url
stringlengths
12
221
text
stringlengths
176
1.03M
encoding
stringclasses
16 values
confidence
float64
0.7
1
license
stringlengths
0
347
copyright
stringlengths
3
31.8k
gamin-0.1.10/python/gamin.c
/* * gamin.c: glue to the gamin library for access from Python * * See Copyright for the status of this software. * * veillard@redhat.com */ #include <Python.h> #include <fam.h> #include "config.h" #ifdef GAMIN_DEBUG_API int FAMDebug(FAMConnection *fc, const char *filename, FAMRequest * fr, void *userData); #endif void init_gamin(void); static FAMConnection **connections = NULL; static int nb_connections = 0; static int max_connections = 0; static FAMRequest **requests = NULL; static int nb_requests = 0; static int max_requests = 0; static int get_connection(void) { int i; if (connections == NULL) { max_connections = 10; connections = (FAMConnection **) malloc(max_connections * sizeof(FAMConnection *)); if (connections == NULL) { max_connections = 0; return(-1); } memset(connections, 0, max_connections * sizeof(FAMConnection *)); } for (i = 0;i < max_connections;i++) if (connections[i] == NULL) break; if (i >= max_connections) { FAMConnection **tmp; tmp = (FAMConnection **) realloc(connections, max_connections * 2 * sizeof(FAMConnection *)); if (tmp == NULL) return(-1); memset(&tmp[max_connections], 0, max_connections * sizeof(FAMConnection *)); max_connections *= 2; connections = tmp; } connections[i] = (FAMConnection *) malloc(sizeof(FAMConnection)); if (connections[i] == NULL) return(-1); nb_connections++; return(i); } static int release_connection(int no) { if ((no < 0) || (no >= max_connections)) return(-1); if (connections[no] == NULL) return(-1); free(connections[no]); connections[no] = NULL; nb_connections--; return(0); } static FAMConnection * check_connection(int no) { if ((no < 0) || (no >= max_connections)) return(NULL); return(connections[no]); } static int get_request(void) { int i; if (requests == NULL) { max_requests = 10; requests = (FAMRequest **) malloc(max_requests * sizeof(FAMRequest *)); if (requests == NULL) { max_requests = 0; return(-1); } memset(requests, 0, max_requests * sizeof(FAMRequest *)); } for (i = 0;i < max_requests;i++) if (requests[i] == NULL) break; if (i >= max_requests) { FAMRequest **tmp; tmp = (FAMRequest **) realloc(requests, max_requests * 2 * sizeof(FAMRequest *)); if (tmp == NULL) return(-1); memset(&tmp[max_requests], 0, max_requests * sizeof(FAMRequest *)); max_requests *= 2; requests = tmp; } requests[i] = (FAMRequest *) malloc(sizeof(FAMRequest)); if (requests[i] == NULL) return(-1); nb_requests++; return(i); } static int release_request(int no) { if ((no < 0) || (no >= max_requests)) return(-1); if (requests[no] == NULL) return(-1); free(requests[no]); requests[no] = NULL; nb_requests--; return(0); } static FAMRequest * check_request(int no) { if ((no < 0) || (no >= max_requests)) return(NULL); return(requests[no]); } static int fam_connect(void) { int ret; int no = get_connection(); FAMConnection *conn; if (no < 0) return(-1); conn = connections[no]; if (conn == NULL) return(-1); ret = FAMOpen2(conn, "gamin-python"); if (ret < 0) { release_connection(no); return(ret); } return(no); } static int call_internal_callback(PyObject *self, const char *filename, FAMCodes event) { PyObject *ret; if ((self == NULL) || (filename == NULL)) return(-1); /* fprintf(stderr, "call_internal_callback(%p)\n", self); */ ret = PyEval_CallMethod(self, (char *) "_internal_callback", (char *) "(zi)", filename, (int) event); if (ret != NULL) { Py_DECREF(ret); #if 0 } else { fprintf(stderr, "call_internal_callback() failed\n"); #endif } return(0); } static PyObject * gamin_Errno(PyObject *self, PyObject * args) { return(PyInt_FromLong(FAMErrno)); } static PyObject * gamin_MonitorConnect(PyObject *self, PyObject * args) { int ret; ret = fam_connect(); if (ret < 0) { return(PyInt_FromLong(-1)); } return(PyInt_FromLong(ret)); } static PyObject * gamin_GetFd(PyObject *self, PyObject * args) { int no; FAMConnection *conn; if (!PyArg_ParseTuple(args, (char *)"i:GetFd", &no)) return(NULL); conn = check_connection(no); if (conn == NULL) { return(PyInt_FromLong(-1)); } return(PyInt_FromLong(FAMCONNECTION_GETFD(conn))); } static PyObject * gamin_MonitorClose(PyObject *self, PyObject * args) { int no; int ret; if (!PyArg_ParseTuple(args, (char *)"i:MonitorClose", &no)) return(NULL); ret = release_connection(no); return(PyInt_FromLong(ret)); } static PyObject * gamin_ProcessOneEvent(PyObject *self, PyObject * args) { int ret; FAMEvent fe; int no; FAMConnection *conn; if (!PyArg_ParseTuple(args, (char *)"i:ProcessOneEvent", &no)) return(NULL); conn = check_connection(no); if (conn == NULL) { return(PyInt_FromLong(-1)); } ret = FAMNextEvent(conn, &fe); if (ret < 0) { return(PyInt_FromLong(-1)); } call_internal_callback(fe.userdata, &fe.filename[0], fe.code); return(PyInt_FromLong(ret)); } static PyObject * gamin_ProcessEvents(PyObject *self, PyObject * args) { int ret; int nb = 0; FAMEvent fe; int no; FAMConnection *conn; if (!PyArg_ParseTuple(args, (char *)"i:ProcessOneEvent", &no)) return(NULL); conn = check_connection(no); if (conn == NULL) { return(PyInt_FromLong(-1)); } do { ret = FAMPending(conn); if (ret < 0) return(PyInt_FromLong(-1)); if (ret == 0) break; ret = FAMNextEvent(conn, &fe); if (ret < 0) return(PyInt_FromLong(-1)); call_internal_callback(fe.userdata, &fe.filename[0], fe.code); nb++; } while (ret >= 0); return(PyInt_FromLong(nb)); } static PyObject * gamin_EventPending(PyObject *self, PyObject * args) { int no; FAMConnection *conn; if (!PyArg_ParseTuple(args, (char *)"i:ProcessOneEvent", &no)) return(NULL); conn = check_connection(no); if (conn == NULL) { return(PyInt_FromLong(-1)); } return(PyInt_FromLong(FAMPending(conn))); } static PyObject * gamin_MonitorNoExists(PyObject *self, PyObject * args) { int no; FAMConnection *conn; if (!PyArg_ParseTuple(args, (char *)"i:MonitorNoExists", &no)) return(NULL); conn = check_connection(no); if (conn == NULL) { return(PyInt_FromLong(-1)); } return(PyInt_FromLong(FAMNoExists(conn))); } static PyObject * gamin_MonitorDirectory(PyObject *self, PyObject * args) { PyObject *userdata; char * filename; int ret; int noreq; int no; FAMConnection *conn; FAMRequest *request; if (!PyArg_ParseTuple(args, (char *)"izO:MonitorDirectory", &no, &filename, &userdata)) return(NULL); conn = check_connection(no); if (conn == NULL) { return(PyInt_FromLong(-1)); } noreq = get_request(); if (noreq < 0) { return(PyInt_FromLong(-1)); } request = check_request(noreq); ret = FAMMonitorDirectory(conn, filename, request, userdata); if (ret < 0) { release_request(noreq); return(PyInt_FromLong(-1)); } return(PyInt_FromLong(noreq)); } static PyObject * gamin_MonitorFile(PyObject *self, PyObject * args) { PyObject *userdata; char * filename; int ret; int noreq; int no; FAMConnection *conn; FAMRequest *request; if (!PyArg_ParseTuple(args, (char *)"izO:MonitorFile", &no, &filename, &userdata)) return(NULL); conn = check_connection(no); if (conn == NULL) { return(PyInt_FromLong(-1)); } noreq = get_request(); if (noreq < 0) { return(PyInt_FromLong(-1)); } request = check_request(noreq); ret = FAMMonitorFile(conn, filename, request, userdata); if (ret < 0) { release_request(noreq); return(PyInt_FromLong(-1)); } return(PyInt_FromLong(noreq)); } static PyObject * gamin_MonitorCancel(PyObject *self, PyObject * args) { int ret; int noreq; int no; FAMConnection *conn; FAMRequest *request; if (!PyArg_ParseTuple(args, (char *)"ii:MonitorCancel", &no, &noreq)) return(NULL); conn = check_connection(no); if (conn == NULL) { return(PyInt_FromLong(-1)); } request = check_request(noreq); if (request == NULL) { return(PyInt_FromLong(-1)); } ret = FAMCancelMonitor(conn, request); if (ret < 0) { release_request(noreq); return(PyInt_FromLong(-1)); } return(PyInt_FromLong(ret)); } #ifdef GAMIN_DEBUG_API static PyObject * gamin_MonitorDebug(PyObject *self, PyObject * args) { PyObject *userdata; char * filename; int ret; int noreq; int no; FAMConnection *conn; FAMRequest *request; if (!PyArg_ParseTuple(args, (char *)"izO:MonitorDebug", &no, &filename, &userdata)) return(NULL); conn = check_connection(no); if (conn == NULL) { return(PyInt_FromLong(-1)); } noreq = get_request(); if (noreq < 0) { return(PyInt_FromLong(-1)); } request = check_request(noreq); ret = FAMDebug(conn, filename, request, userdata); if (ret < 0) { release_request(noreq); return(PyInt_FromLong(-1)); } return(PyInt_FromLong(noreq)); } #endif static PyMethodDef gaminMethods[] = { {(char *)"MonitorConnect", gamin_MonitorConnect, METH_VARARGS, NULL}, {(char *)"MonitorDirectory", gamin_MonitorDirectory, METH_VARARGS, NULL}, {(char *)"MonitorFile", gamin_MonitorFile, METH_VARARGS, NULL}, {(char *)"MonitorCancel", gamin_MonitorCancel, METH_VARARGS, NULL}, {(char *)"MonitorNoExists", gamin_MonitorNoExists, METH_VARARGS, NULL}, {(char *)"EventPending", gamin_EventPending, METH_VARARGS, NULL}, {(char *)"ProcessOneEvent", gamin_ProcessOneEvent, METH_VARARGS, NULL}, {(char *)"ProcessEvents", gamin_ProcessEvents, METH_VARARGS, NULL}, {(char *)"MonitorClose", gamin_MonitorClose, METH_VARARGS, NULL}, {(char *)"GetFd", gamin_GetFd, METH_VARARGS, NULL}, {(char *)"Errno", gamin_Errno, METH_VARARGS, NULL}, #ifdef GAMIN_DEBUG_API {(char *)"MonitorDebug", gamin_MonitorDebug, METH_VARARGS, NULL}, #endif {NULL, NULL, 0, NULL} }; void init_gamin(void) { static int initialized = 0; if (initialized != 0) return; /* intialize the python extension module */ Py_InitModule((char *) "_gamin", gaminMethods); initialized = 1; }
utf-8
1
unknown
unknown
pgbackrest-2.37/src/command/backup/common.h
/*********************************************************************************************************************************** Common Functions and Definitions for Backup and Expire Commands ***********************************************************************************************************************************/ #ifndef COMMAND_BACKUP_COMMON_H #define COMMAND_BACKUP_COMMON_H #include <stdbool.h> #include <time.h> #include "common/type/string.h" #include "info/infoBackup.h" /*********************************************************************************************************************************** Backup constants ***********************************************************************************************************************************/ #define BACKUP_PATH_HISTORY "backup.history" /*********************************************************************************************************************************** Functions ***********************************************************************************************************************************/ // Format a backup label from a type and timestamp with an optional prior label String *backupLabelFormat(BackupType type, const String *backupLabelPrior, time_t timestamp); // Returns an anchored regex string for filtering backups based on the type (at least one type is required to be true) typedef struct BackupRegExpParam { bool full; bool differential; bool incremental; bool noAnchorEnd; } BackupRegExpParam; #define backupRegExpP(...) \ backupRegExp((BackupRegExpParam){__VA_ARGS__}) String *backupRegExp(BackupRegExpParam param); // Create a symlink to the specified backup (if symlinks are supported) void backupLinkLatest(const String *backupLabel, unsigned int repoIdx); #endif
utf-8
1
MIT
2015-2020 The PostgreSQL Global Development Group 2013-2020 David Steele
linux-5.16.7/drivers/media/usb/gspca/m5602/m5602_ov7660.h
/* SPDX-License-Identifier: GPL-2.0-only */ /* * Driver for the ov7660 sensor * * Copyright (C) 2009 Erik Andrén * Copyright (C) 2007 Ilyes Gouta. Based on the m5603x Linux Driver Project. * Copyright (C) 2005 m5603x Linux Driver Project <m5602@x3ng.com.br> * * Portions of code to USB interface and ALi driver software, * Copyright (c) 2006 Willem Duinker * v4l2 interface modeled after the V4L2 driver * for SN9C10x PC Camera Controllers */ #ifndef M5602_OV7660_H_ #define M5602_OV7660_H_ #include "m5602_sensor.h" #define OV7660_GAIN 0x00 #define OV7660_BLUE_GAIN 0x01 #define OV7660_RED_GAIN 0x02 #define OV7660_VREF 0x03 #define OV7660_COM1 0x04 #define OV7660_BAVE 0x05 #define OV7660_GEAVE 0x06 #define OV7660_AECHH 0x07 #define OV7660_RAVE 0x08 #define OV7660_COM2 0x09 #define OV7660_PID 0x0a #define OV7660_VER 0x0b #define OV7660_COM3 0x0c #define OV7660_COM4 0x0d #define OV7660_COM5 0x0e #define OV7660_COM6 0x0f #define OV7660_AECH 0x10 #define OV7660_CLKRC 0x11 #define OV7660_COM7 0x12 #define OV7660_COM8 0x13 #define OV7660_COM9 0x14 #define OV7660_COM10 0x15 #define OV7660_RSVD16 0x16 #define OV7660_HSTART 0x17 #define OV7660_HSTOP 0x18 #define OV7660_VSTART 0x19 #define OV7660_VSTOP 0x1a #define OV7660_PSHFT 0x1b #define OV7660_MIDH 0x1c #define OV7660_MIDL 0x1d #define OV7660_MVFP 0x1e #define OV7660_LAEC 0x1f #define OV7660_BOS 0x20 #define OV7660_GBOS 0x21 #define OV7660_GROS 0x22 #define OV7660_ROS 0x23 #define OV7660_AEW 0x24 #define OV7660_AEB 0x25 #define OV7660_VPT 0x26 #define OV7660_BBIAS 0x27 #define OV7660_GbBIAS 0x28 #define OV7660_RSVD29 0x29 #define OV7660_RBIAS 0x2c #define OV7660_HREF 0x32 #define OV7660_ADC 0x37 #define OV7660_OFON 0x39 #define OV7660_TSLB 0x3a #define OV7660_COM12 0x3c #define OV7660_COM13 0x3d #define OV7660_LCC1 0x62 #define OV7660_LCC2 0x63 #define OV7660_LCC3 0x64 #define OV7660_LCC4 0x65 #define OV7660_LCC5 0x66 #define OV7660_HV 0x69 #define OV7660_RSVDA1 0xa1 #define OV7660_DEFAULT_GAIN 0x0e #define OV7660_DEFAULT_RED_GAIN 0x80 #define OV7660_DEFAULT_BLUE_GAIN 0x80 #define OV7660_DEFAULT_SATURATION 0x00 #define OV7660_DEFAULT_EXPOSURE 0x20 /* Kernel module parameters */ extern int force_sensor; extern bool dump_sensor; int ov7660_probe(struct sd *sd); int ov7660_init(struct sd *sd); int ov7660_init_controls(struct sd *sd); int ov7660_start(struct sd *sd); int ov7660_stop(struct sd *sd); void ov7660_disconnect(struct sd *sd); static const struct m5602_sensor ov7660 = { .name = "ov7660", .i2c_slave_id = 0x42, .i2c_regW = 1, .probe = ov7660_probe, .init = ov7660_init, .init_controls = ov7660_init_controls, .start = ov7660_start, .stop = ov7660_stop, .disconnect = ov7660_disconnect, }; #endif
utf-8
1
GPL-2
1991-2012 Linus Torvalds and many others
barrier-2.4.0+dfsg/src/lib/platform/synwinhk.h
/* * barrier -- mouse and keyboard sharing utility * Copyright (C) 2018 Debauchee Open Source Group * Copyright (C) 2012-2016 Symless Ltd. * Copyright (C) 2002 Chris Schoeneman * * This package is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * found in the file LICENSE that should have accompanied this file. * * This package is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "base/EventTypes.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #if defined(synwinhk_EXPORTS) #define CBARRIERHOOK_API __declspec(dllexport) #else #define CBARRIERHOOK_API __declspec(dllimport) #endif #define BARRIER_MSG_MARK WM_APP + 0x0011 // mark id; <unused> #define BARRIER_MSG_KEY WM_APP + 0x0012 // vk code; key data #define BARRIER_MSG_MOUSE_BUTTON WM_APP + 0x0013 // button msg; <unused> #define BARRIER_MSG_MOUSE_WHEEL WM_APP + 0x0014 // delta; <unused> #define BARRIER_MSG_MOUSE_MOVE WM_APP + 0x0015 // x; y #define BARRIER_MSG_POST_WARP WM_APP + 0x0016 // <unused>; <unused> #define BARRIER_MSG_PRE_WARP WM_APP + 0x0017 // x; y #define BARRIER_MSG_SCREEN_SAVER WM_APP + 0x0018 // activated; <unused> #define BARRIER_MSG_DEBUG WM_APP + 0x0019 // data, data #define BARRIER_MSG_INPUT_FIRST BARRIER_MSG_KEY #define BARRIER_MSG_INPUT_LAST BARRIER_MSG_PRE_WARP #define BARRIER_HOOK_LAST_MSG BARRIER_MSG_DEBUG #define BARRIER_HOOK_FAKE_INPUT_VIRTUAL_KEY VK_CANCEL #define BARRIER_HOOK_FAKE_INPUT_SCANCODE 0 extern "C" { enum EHookMode { kHOOK_DISABLE, kHOOK_WATCH_JUMP_ZONE, kHOOK_RELAY_EVENTS }; /* REMOVED ImmuneKeys for migration of synwinhk out of DLL typedef void (*SetImmuneKeysFunc)(const DWORD*, std::size_t); // do not call setImmuneKeys() while the hooks are active! CBARRIERHOOK_API void setImmuneKeys(const DWORD *list, std::size_t size); */ }
utf-8
1
GPL-2 with OpenSSL exception
2002-2014 Chris Schoeneman <crs23@users.sourceforge.net> 2008-2014 Nick Bolton <nick@symless.com> 2012-2016 Symless Ltd. 2018-2021 Debauchee Open Source Group 2021 Povilas Kanapickas <povilas@radix.lt>
linux-5.16.7/arch/arm/mach-davinci/devices-da8xx.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * DA8XX/OMAP L1XX platform device data * * Copyright (c) 2007-2009, MontaVista Software, Inc. <source@mvista.com> * Derived from code that was: * Copyright (C) 2006 Komal Shah <komal_shah802003@yahoo.com> */ #include <linux/ahci_platform.h> #include <linux/clk-provider.h> #include <linux/clk.h> #include <linux/clkdev.h> #include <linux/dma-map-ops.h> #include <linux/dmaengine.h> #include <linux/init.h> #include <linux/io.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <linux/serial_8250.h> #include <mach/common.h> #include <mach/cputype.h> #include <mach/da8xx.h> #include "asp.h" #include "cpuidle.h" #include "irqs.h" #include "sram.h" #define DA8XX_TPCC_BASE 0x01c00000 #define DA8XX_TPTC0_BASE 0x01c08000 #define DA8XX_TPTC1_BASE 0x01c08400 #define DA8XX_WDOG_BASE 0x01c21000 /* DA8XX_TIMER64P1_BASE */ #define DA8XX_I2C0_BASE 0x01c22000 #define DA8XX_RTC_BASE 0x01c23000 #define DA8XX_PRUSS_MEM_BASE 0x01c30000 #define DA8XX_MMCSD0_BASE 0x01c40000 #define DA8XX_SPI0_BASE 0x01c41000 #define DA830_SPI1_BASE 0x01e12000 #define DA8XX_LCD_CNTRL_BASE 0x01e13000 #define DA850_SATA_BASE 0x01e18000 #define DA850_MMCSD1_BASE 0x01e1b000 #define DA8XX_EMAC_CPPI_PORT_BASE 0x01e20000 #define DA8XX_EMAC_CPGMACSS_BASE 0x01e22000 #define DA8XX_EMAC_CPGMAC_BASE 0x01e23000 #define DA8XX_EMAC_MDIO_BASE 0x01e24000 #define DA8XX_I2C1_BASE 0x01e28000 #define DA850_TPCC1_BASE 0x01e30000 #define DA850_TPTC2_BASE 0x01e38000 #define DA850_SPI1_BASE 0x01f0e000 #define DA8XX_DDR2_CTL_BASE 0xb0000000 #define DA8XX_EMAC_CTRL_REG_OFFSET 0x3000 #define DA8XX_EMAC_MOD_REG_OFFSET 0x2000 #define DA8XX_EMAC_RAM_OFFSET 0x0000 #define DA8XX_EMAC_CTRL_RAM_SIZE SZ_8K void __iomem *da8xx_syscfg0_base; void __iomem *da8xx_syscfg1_base; static struct plat_serial8250_port da8xx_serial0_pdata[] = { { .mapbase = DA8XX_UART0_BASE, .irq = DAVINCI_INTC_IRQ(IRQ_DA8XX_UARTINT0), .flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_IOREMAP, .iotype = UPIO_MEM, .regshift = 2, }, { .flags = 0, } }; static struct plat_serial8250_port da8xx_serial1_pdata[] = { { .mapbase = DA8XX_UART1_BASE, .irq = DAVINCI_INTC_IRQ(IRQ_DA8XX_UARTINT1), .flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_IOREMAP, .iotype = UPIO_MEM, .regshift = 2, }, { .flags = 0, } }; static struct plat_serial8250_port da8xx_serial2_pdata[] = { { .mapbase = DA8XX_UART2_BASE, .irq = DAVINCI_INTC_IRQ(IRQ_DA8XX_UARTINT2), .flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_IOREMAP, .iotype = UPIO_MEM, .regshift = 2, }, { .flags = 0, } }; struct platform_device da8xx_serial_device[] = { { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM, .dev = { .platform_data = da8xx_serial0_pdata, } }, { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM1, .dev = { .platform_data = da8xx_serial1_pdata, } }, { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM2, .dev = { .platform_data = da8xx_serial2_pdata, } }, { } }; static s8 da8xx_queue_priority_mapping[][2] = { /* {event queue no, Priority} */ {0, 3}, {1, 7}, {-1, -1} }; static s8 da850_queue_priority_mapping[][2] = { /* {event queue no, Priority} */ {0, 3}, {-1, -1} }; static struct edma_soc_info da8xx_edma0_pdata = { .queue_priority_mapping = da8xx_queue_priority_mapping, .default_queue = EVENTQ_1, }; static struct edma_soc_info da850_edma1_pdata = { .queue_priority_mapping = da850_queue_priority_mapping, .default_queue = EVENTQ_0, }; static struct resource da8xx_edma0_resources[] = { { .name = "edma3_cc", .start = DA8XX_TPCC_BASE, .end = DA8XX_TPCC_BASE + SZ_32K - 1, .flags = IORESOURCE_MEM, }, { .name = "edma3_tc0", .start = DA8XX_TPTC0_BASE, .end = DA8XX_TPTC0_BASE + SZ_1K - 1, .flags = IORESOURCE_MEM, }, { .name = "edma3_tc1", .start = DA8XX_TPTC1_BASE, .end = DA8XX_TPTC1_BASE + SZ_1K - 1, .flags = IORESOURCE_MEM, }, { .name = "edma3_ccint", .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_CCINT0), .flags = IORESOURCE_IRQ, }, { .name = "edma3_ccerrint", .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_CCERRINT), .flags = IORESOURCE_IRQ, }, }; static struct resource da850_edma1_resources[] = { { .name = "edma3_cc", .start = DA850_TPCC1_BASE, .end = DA850_TPCC1_BASE + SZ_32K - 1, .flags = IORESOURCE_MEM, }, { .name = "edma3_tc0", .start = DA850_TPTC2_BASE, .end = DA850_TPTC2_BASE + SZ_1K - 1, .flags = IORESOURCE_MEM, }, { .name = "edma3_ccint", .start = DAVINCI_INTC_IRQ(IRQ_DA850_CCINT1), .flags = IORESOURCE_IRQ, }, { .name = "edma3_ccerrint", .start = DAVINCI_INTC_IRQ(IRQ_DA850_CCERRINT1), .flags = IORESOURCE_IRQ, }, }; static const struct platform_device_info da8xx_edma0_device __initconst = { .name = "edma", .id = 0, .dma_mask = DMA_BIT_MASK(32), .res = da8xx_edma0_resources, .num_res = ARRAY_SIZE(da8xx_edma0_resources), .data = &da8xx_edma0_pdata, .size_data = sizeof(da8xx_edma0_pdata), }; static const struct platform_device_info da850_edma1_device __initconst = { .name = "edma", .id = 1, .dma_mask = DMA_BIT_MASK(32), .res = da850_edma1_resources, .num_res = ARRAY_SIZE(da850_edma1_resources), .data = &da850_edma1_pdata, .size_data = sizeof(da850_edma1_pdata), }; static const struct dma_slave_map da830_edma_map[] = { { "davinci-mcasp.0", "rx", EDMA_FILTER_PARAM(0, 0) }, { "davinci-mcasp.0", "tx", EDMA_FILTER_PARAM(0, 1) }, { "davinci-mcasp.1", "rx", EDMA_FILTER_PARAM(0, 2) }, { "davinci-mcasp.1", "tx", EDMA_FILTER_PARAM(0, 3) }, { "davinci-mcasp.2", "rx", EDMA_FILTER_PARAM(0, 4) }, { "davinci-mcasp.2", "tx", EDMA_FILTER_PARAM(0, 5) }, { "spi_davinci.0", "rx", EDMA_FILTER_PARAM(0, 14) }, { "spi_davinci.0", "tx", EDMA_FILTER_PARAM(0, 15) }, { "da830-mmc.0", "rx", EDMA_FILTER_PARAM(0, 16) }, { "da830-mmc.0", "tx", EDMA_FILTER_PARAM(0, 17) }, { "spi_davinci.1", "rx", EDMA_FILTER_PARAM(0, 18) }, { "spi_davinci.1", "tx", EDMA_FILTER_PARAM(0, 19) }, }; int __init da830_register_edma(struct edma_rsv_info *rsv) { struct platform_device *edma_pdev; da8xx_edma0_pdata.rsv = rsv; da8xx_edma0_pdata.slave_map = da830_edma_map; da8xx_edma0_pdata.slavecnt = ARRAY_SIZE(da830_edma_map); edma_pdev = platform_device_register_full(&da8xx_edma0_device); return PTR_ERR_OR_ZERO(edma_pdev); } static const struct dma_slave_map da850_edma0_map[] = { { "davinci-mcasp.0", "rx", EDMA_FILTER_PARAM(0, 0) }, { "davinci-mcasp.0", "tx", EDMA_FILTER_PARAM(0, 1) }, { "davinci-mcbsp.0", "rx", EDMA_FILTER_PARAM(0, 2) }, { "davinci-mcbsp.0", "tx", EDMA_FILTER_PARAM(0, 3) }, { "davinci-mcbsp.1", "rx", EDMA_FILTER_PARAM(0, 4) }, { "davinci-mcbsp.1", "tx", EDMA_FILTER_PARAM(0, 5) }, { "spi_davinci.0", "rx", EDMA_FILTER_PARAM(0, 14) }, { "spi_davinci.0", "tx", EDMA_FILTER_PARAM(0, 15) }, { "da830-mmc.0", "rx", EDMA_FILTER_PARAM(0, 16) }, { "da830-mmc.0", "tx", EDMA_FILTER_PARAM(0, 17) }, { "spi_davinci.1", "rx", EDMA_FILTER_PARAM(0, 18) }, { "spi_davinci.1", "tx", EDMA_FILTER_PARAM(0, 19) }, }; static const struct dma_slave_map da850_edma1_map[] = { { "da830-mmc.1", "rx", EDMA_FILTER_PARAM(1, 28) }, { "da830-mmc.1", "tx", EDMA_FILTER_PARAM(1, 29) }, }; int __init da850_register_edma(struct edma_rsv_info *rsv[2]) { struct platform_device *edma_pdev; if (rsv) { da8xx_edma0_pdata.rsv = rsv[0]; da850_edma1_pdata.rsv = rsv[1]; } da8xx_edma0_pdata.slave_map = da850_edma0_map; da8xx_edma0_pdata.slavecnt = ARRAY_SIZE(da850_edma0_map); edma_pdev = platform_device_register_full(&da8xx_edma0_device); if (IS_ERR(edma_pdev)) { pr_warn("%s: Failed to register eDMA0\n", __func__); return PTR_ERR(edma_pdev); } da850_edma1_pdata.slave_map = da850_edma1_map; da850_edma1_pdata.slavecnt = ARRAY_SIZE(da850_edma1_map); edma_pdev = platform_device_register_full(&da850_edma1_device); return PTR_ERR_OR_ZERO(edma_pdev); } static struct resource da8xx_i2c_resources0[] = { { .start = DA8XX_I2C0_BASE, .end = DA8XX_I2C0_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_I2CINT0), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_I2CINT0), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da8xx_i2c_device0 = { .name = "i2c_davinci", .id = 1, .num_resources = ARRAY_SIZE(da8xx_i2c_resources0), .resource = da8xx_i2c_resources0, }; static struct resource da8xx_i2c_resources1[] = { { .start = DA8XX_I2C1_BASE, .end = DA8XX_I2C1_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_I2CINT1), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_I2CINT1), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da8xx_i2c_device1 = { .name = "i2c_davinci", .id = 2, .num_resources = ARRAY_SIZE(da8xx_i2c_resources1), .resource = da8xx_i2c_resources1, }; int __init da8xx_register_i2c(int instance, struct davinci_i2c_platform_data *pdata) { struct platform_device *pdev; if (instance == 0) pdev = &da8xx_i2c_device0; else if (instance == 1) pdev = &da8xx_i2c_device1; else return -EINVAL; pdev->dev.platform_data = pdata; return platform_device_register(pdev); } static struct resource da8xx_watchdog_resources[] = { { .start = DA8XX_WDOG_BASE, .end = DA8XX_WDOG_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, }; static struct platform_device da8xx_wdt_device = { .name = "davinci-wdt", .id = -1, .num_resources = ARRAY_SIZE(da8xx_watchdog_resources), .resource = da8xx_watchdog_resources, }; int __init da8xx_register_watchdog(void) { return platform_device_register(&da8xx_wdt_device); } static struct resource da8xx_emac_resources[] = { { .start = DA8XX_EMAC_CPPI_PORT_BASE, .end = DA8XX_EMAC_CPPI_PORT_BASE + SZ_16K - 1, .flags = IORESOURCE_MEM, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_C0_RX_THRESH_PULSE), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_C0_RX_THRESH_PULSE), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_C0_RX_PULSE), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_C0_RX_PULSE), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_C0_TX_PULSE), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_C0_TX_PULSE), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_C0_MISC_PULSE), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_C0_MISC_PULSE), .flags = IORESOURCE_IRQ, }, }; struct emac_platform_data da8xx_emac_pdata = { .ctrl_reg_offset = DA8XX_EMAC_CTRL_REG_OFFSET, .ctrl_mod_reg_offset = DA8XX_EMAC_MOD_REG_OFFSET, .ctrl_ram_offset = DA8XX_EMAC_RAM_OFFSET, .ctrl_ram_size = DA8XX_EMAC_CTRL_RAM_SIZE, .version = EMAC_VERSION_2, }; static struct platform_device da8xx_emac_device = { .name = "davinci_emac", .id = 1, .dev = { .platform_data = &da8xx_emac_pdata, }, .num_resources = ARRAY_SIZE(da8xx_emac_resources), .resource = da8xx_emac_resources, }; static struct resource da8xx_mdio_resources[] = { { .start = DA8XX_EMAC_MDIO_BASE, .end = DA8XX_EMAC_MDIO_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, }; static struct platform_device da8xx_mdio_device = { .name = "davinci_mdio", .id = 0, .num_resources = ARRAY_SIZE(da8xx_mdio_resources), .resource = da8xx_mdio_resources, }; int __init da8xx_register_emac(void) { int ret; ret = platform_device_register(&da8xx_mdio_device); if (ret < 0) return ret; return platform_device_register(&da8xx_emac_device); } static struct resource da830_mcasp1_resources[] = { { .name = "mpu", .start = DAVINCI_DA830_MCASP1_REG_BASE, .end = DAVINCI_DA830_MCASP1_REG_BASE + (SZ_1K * 12) - 1, .flags = IORESOURCE_MEM, }, /* TX event */ { .name = "tx", .start = DAVINCI_DA830_DMA_MCASP1_AXEVT, .end = DAVINCI_DA830_DMA_MCASP1_AXEVT, .flags = IORESOURCE_DMA, }, /* RX event */ { .name = "rx", .start = DAVINCI_DA830_DMA_MCASP1_AREVT, .end = DAVINCI_DA830_DMA_MCASP1_AREVT, .flags = IORESOURCE_DMA, }, { .name = "common", .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_MCASPINT), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da830_mcasp1_device = { .name = "davinci-mcasp", .id = 1, .num_resources = ARRAY_SIZE(da830_mcasp1_resources), .resource = da830_mcasp1_resources, }; static struct resource da830_mcasp2_resources[] = { { .name = "mpu", .start = DAVINCI_DA830_MCASP2_REG_BASE, .end = DAVINCI_DA830_MCASP2_REG_BASE + (SZ_1K * 12) - 1, .flags = IORESOURCE_MEM, }, /* TX event */ { .name = "tx", .start = DAVINCI_DA830_DMA_MCASP2_AXEVT, .end = DAVINCI_DA830_DMA_MCASP2_AXEVT, .flags = IORESOURCE_DMA, }, /* RX event */ { .name = "rx", .start = DAVINCI_DA830_DMA_MCASP2_AREVT, .end = DAVINCI_DA830_DMA_MCASP2_AREVT, .flags = IORESOURCE_DMA, }, { .name = "common", .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_MCASPINT), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da830_mcasp2_device = { .name = "davinci-mcasp", .id = 2, .num_resources = ARRAY_SIZE(da830_mcasp2_resources), .resource = da830_mcasp2_resources, }; static struct resource da850_mcasp_resources[] = { { .name = "mpu", .start = DAVINCI_DA8XX_MCASP0_REG_BASE, .end = DAVINCI_DA8XX_MCASP0_REG_BASE + (SZ_1K * 12) - 1, .flags = IORESOURCE_MEM, }, /* TX event */ { .name = "tx", .start = DAVINCI_DA8XX_DMA_MCASP0_AXEVT, .end = DAVINCI_DA8XX_DMA_MCASP0_AXEVT, .flags = IORESOURCE_DMA, }, /* RX event */ { .name = "rx", .start = DAVINCI_DA8XX_DMA_MCASP0_AREVT, .end = DAVINCI_DA8XX_DMA_MCASP0_AREVT, .flags = IORESOURCE_DMA, }, { .name = "common", .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_MCASPINT), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da850_mcasp_device = { .name = "davinci-mcasp", .id = 0, .num_resources = ARRAY_SIZE(da850_mcasp_resources), .resource = da850_mcasp_resources, }; void __init da8xx_register_mcasp(int id, struct snd_platform_data *pdata) { struct platform_device *pdev; switch (id) { case 0: /* Valid for DA830/OMAP-L137 or DA850/OMAP-L138 */ pdev = &da850_mcasp_device; break; case 1: /* Valid for DA830/OMAP-L137 only */ if (!cpu_is_davinci_da830()) return; pdev = &da830_mcasp1_device; break; case 2: /* Valid for DA830/OMAP-L137 only */ if (!cpu_is_davinci_da830()) return; pdev = &da830_mcasp2_device; break; default: return; } pdev->dev.platform_data = pdata; platform_device_register(pdev); } static struct resource da8xx_pruss_resources[] = { { .start = DA8XX_PRUSS_MEM_BASE, .end = DA8XX_PRUSS_MEM_BASE + 0xFFFF, .flags = IORESOURCE_MEM, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT0), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT0), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT1), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT1), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT2), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT2), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT3), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT3), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT4), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT4), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT5), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT5), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT6), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT6), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT7), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_EVTOUT7), .flags = IORESOURCE_IRQ, }, }; static struct uio_pruss_pdata da8xx_uio_pruss_pdata = { .pintc_base = 0x4000, }; static struct platform_device da8xx_uio_pruss_dev = { .name = "pruss_uio", .id = -1, .num_resources = ARRAY_SIZE(da8xx_pruss_resources), .resource = da8xx_pruss_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), .platform_data = &da8xx_uio_pruss_pdata, } }; int __init da8xx_register_uio_pruss(void) { da8xx_uio_pruss_pdata.sram_pool = sram_get_gen_pool(); return platform_device_register(&da8xx_uio_pruss_dev); } static struct lcd_ctrl_config lcd_cfg = { .panel_shade = COLOR_ACTIVE, .bpp = 16, }; struct da8xx_lcdc_platform_data sharp_lcd035q3dg01_pdata = { .manu_name = "sharp", .controller_data = &lcd_cfg, .type = "Sharp_LCD035Q3DG01", }; struct da8xx_lcdc_platform_data sharp_lk043t1dg01_pdata = { .manu_name = "sharp", .controller_data = &lcd_cfg, .type = "Sharp_LK043T1DG01", }; static struct resource da8xx_lcdc_resources[] = { [0] = { /* registers */ .start = DA8XX_LCD_CNTRL_BASE, .end = DA8XX_LCD_CNTRL_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, [1] = { /* interrupt */ .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_LCDINT), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_LCDINT), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da8xx_lcdc_device = { .name = "da8xx_lcdc", .id = 0, .num_resources = ARRAY_SIZE(da8xx_lcdc_resources), .resource = da8xx_lcdc_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), } }; int __init da8xx_register_lcdc(struct da8xx_lcdc_platform_data *pdata) { da8xx_lcdc_device.dev.platform_data = pdata; return platform_device_register(&da8xx_lcdc_device); } static struct resource da8xx_gpio_resources[] = { { /* registers */ .start = DA8XX_GPIO_BASE, .end = DA8XX_GPIO_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { /* interrupt */ .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO0), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO0), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO1), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO1), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO2), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO2), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO3), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO3), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO4), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO4), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO5), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO5), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO6), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO6), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO7), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO7), .flags = IORESOURCE_IRQ, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO8), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_GPIO8), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da8xx_gpio_device = { .name = "davinci_gpio", .id = -1, .num_resources = ARRAY_SIZE(da8xx_gpio_resources), .resource = da8xx_gpio_resources, }; int __init da8xx_register_gpio(void *pdata) { da8xx_gpio_device.dev.platform_data = pdata; return platform_device_register(&da8xx_gpio_device); } static struct resource da8xx_mmcsd0_resources[] = { { /* registers */ .start = DA8XX_MMCSD0_BASE, .end = DA8XX_MMCSD0_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { /* interrupt */ .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_MMCSDINT0), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_MMCSDINT0), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da8xx_mmcsd0_device = { .name = "da830-mmc", .id = 0, .num_resources = ARRAY_SIZE(da8xx_mmcsd0_resources), .resource = da8xx_mmcsd0_resources, }; int __init da8xx_register_mmcsd0(struct davinci_mmc_config *config) { da8xx_mmcsd0_device.dev.platform_data = config; return platform_device_register(&da8xx_mmcsd0_device); } #ifdef CONFIG_ARCH_DAVINCI_DA850 static struct resource da850_mmcsd1_resources[] = { { /* registers */ .start = DA850_MMCSD1_BASE, .end = DA850_MMCSD1_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { /* interrupt */ .start = DAVINCI_INTC_IRQ(IRQ_DA850_MMCSDINT0_1), .end = DAVINCI_INTC_IRQ(IRQ_DA850_MMCSDINT0_1), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da850_mmcsd1_device = { .name = "da830-mmc", .id = 1, .num_resources = ARRAY_SIZE(da850_mmcsd1_resources), .resource = da850_mmcsd1_resources, }; int __init da850_register_mmcsd1(struct davinci_mmc_config *config) { da850_mmcsd1_device.dev.platform_data = config; return platform_device_register(&da850_mmcsd1_device); } #endif static struct resource da8xx_rproc_resources[] = { { /* DSP boot address */ .name = "host1cfg", .start = DA8XX_SYSCFG0_BASE + DA8XX_HOST1CFG_REG, .end = DA8XX_SYSCFG0_BASE + DA8XX_HOST1CFG_REG + 3, .flags = IORESOURCE_MEM, }, { /* DSP interrupt registers */ .name = "chipsig", .start = DA8XX_SYSCFG0_BASE + DA8XX_CHIPSIG_REG, .end = DA8XX_SYSCFG0_BASE + DA8XX_CHIPSIG_REG + 7, .flags = IORESOURCE_MEM, }, { /* DSP L2 RAM */ .name = "l2sram", .start = DA8XX_DSP_L2_RAM_BASE, .end = DA8XX_DSP_L2_RAM_BASE + SZ_256K - 1, .flags = IORESOURCE_MEM, }, { /* DSP L1P RAM */ .name = "l1pram", .start = DA8XX_DSP_L1P_RAM_BASE, .end = DA8XX_DSP_L1P_RAM_BASE + SZ_32K - 1, .flags = IORESOURCE_MEM, }, { /* DSP L1D RAM */ .name = "l1dram", .start = DA8XX_DSP_L1D_RAM_BASE, .end = DA8XX_DSP_L1D_RAM_BASE + SZ_32K - 1, .flags = IORESOURCE_MEM, }, { /* dsp irq */ .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_CHIPINT0), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_CHIPINT0), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da8xx_dsp = { .name = "davinci-rproc", .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), }, .num_resources = ARRAY_SIZE(da8xx_rproc_resources), .resource = da8xx_rproc_resources, }; static bool rproc_mem_inited __initdata; #if IS_ENABLED(CONFIG_DA8XX_REMOTEPROC) static phys_addr_t rproc_base __initdata; static unsigned long rproc_size __initdata; static int __init early_rproc_mem(char *p) { char *endp; if (p == NULL) return 0; rproc_size = memparse(p, &endp); if (*endp == '@') rproc_base = memparse(endp + 1, NULL); return 0; } early_param("rproc_mem", early_rproc_mem); void __init da8xx_rproc_reserve_cma(void) { struct cma *cma; int ret; if (!rproc_base || !rproc_size) { pr_err("%s: 'rproc_mem=nn@address' badly specified\n" " 'nn' and 'address' must both be non-zero\n", __func__); return; } pr_info("%s: reserving 0x%lx @ 0x%lx...\n", __func__, rproc_size, (unsigned long)rproc_base); ret = dma_contiguous_reserve_area(rproc_size, rproc_base, 0, &cma, true); if (ret) { pr_err("%s: dma_contiguous_reserve_area failed %d\n", __func__, ret); return; } da8xx_dsp.dev.cma_area = cma; rproc_mem_inited = true; } #else void __init da8xx_rproc_reserve_cma(void) { } #endif int __init da8xx_register_rproc(void) { int ret; if (!rproc_mem_inited) { pr_warn("%s: memory not reserved for DSP, not registering DSP device\n", __func__); return -ENOMEM; } ret = platform_device_register(&da8xx_dsp); if (ret) pr_err("%s: can't register DSP device: %d\n", __func__, ret); return ret; }; static struct resource da8xx_rtc_resources[] = { { .start = DA8XX_RTC_BASE, .end = DA8XX_RTC_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { /* timer irq */ .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_RTC), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_RTC), .flags = IORESOURCE_IRQ, }, { /* alarm irq */ .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_RTC), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_RTC), .flags = IORESOURCE_IRQ, }, }; static struct platform_device da8xx_rtc_device = { .name = "da830-rtc", .id = -1, .num_resources = ARRAY_SIZE(da8xx_rtc_resources), .resource = da8xx_rtc_resources, }; int da8xx_register_rtc(void) { return platform_device_register(&da8xx_rtc_device); } static void __iomem *da8xx_ddr2_ctlr_base; void __iomem * __init da8xx_get_mem_ctlr(void) { if (da8xx_ddr2_ctlr_base) return da8xx_ddr2_ctlr_base; da8xx_ddr2_ctlr_base = ioremap(DA8XX_DDR2_CTL_BASE, SZ_32K); if (!da8xx_ddr2_ctlr_base) pr_warn("%s: Unable to map DDR2 controller", __func__); return da8xx_ddr2_ctlr_base; } static struct resource da8xx_cpuidle_resources[] = { { .start = DA8XX_DDR2_CTL_BASE, .end = DA8XX_DDR2_CTL_BASE + SZ_32K - 1, .flags = IORESOURCE_MEM, }, }; /* DA8XX devices support DDR2 power down */ static struct davinci_cpuidle_config da8xx_cpuidle_pdata = { .ddr2_pdown = 1, }; static struct platform_device da8xx_cpuidle_device = { .name = "cpuidle-davinci", .num_resources = ARRAY_SIZE(da8xx_cpuidle_resources), .resource = da8xx_cpuidle_resources, .dev = { .platform_data = &da8xx_cpuidle_pdata, }, }; int __init da8xx_register_cpuidle(void) { da8xx_cpuidle_pdata.ddr2_ctlr_base = da8xx_get_mem_ctlr(); return platform_device_register(&da8xx_cpuidle_device); } static struct resource da8xx_spi0_resources[] = { [0] = { .start = DA8XX_SPI0_BASE, .end = DA8XX_SPI0_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_SPINT0), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_SPINT0), .flags = IORESOURCE_IRQ, }, }; static struct resource da8xx_spi1_resources[] = { [0] = { .start = DA830_SPI1_BASE, .end = DA830_SPI1_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = DAVINCI_INTC_IRQ(IRQ_DA8XX_SPINT1), .end = DAVINCI_INTC_IRQ(IRQ_DA8XX_SPINT1), .flags = IORESOURCE_IRQ, }, }; static struct davinci_spi_platform_data da8xx_spi_pdata[] = { [0] = { .version = SPI_VERSION_2, .intr_line = 1, .dma_event_q = EVENTQ_0, .prescaler_limit = 2, }, [1] = { .version = SPI_VERSION_2, .intr_line = 1, .dma_event_q = EVENTQ_0, .prescaler_limit = 2, }, }; static struct platform_device da8xx_spi_device[] = { [0] = { .name = "spi_davinci", .id = 0, .num_resources = ARRAY_SIZE(da8xx_spi0_resources), .resource = da8xx_spi0_resources, .dev = { .platform_data = &da8xx_spi_pdata[0], }, }, [1] = { .name = "spi_davinci", .id = 1, .num_resources = ARRAY_SIZE(da8xx_spi1_resources), .resource = da8xx_spi1_resources, .dev = { .platform_data = &da8xx_spi_pdata[1], }, }, }; int __init da8xx_register_spi_bus(int instance, unsigned num_chipselect) { if (instance < 0 || instance > 1) return -EINVAL; da8xx_spi_pdata[instance].num_chipselect = num_chipselect; if (instance == 1 && cpu_is_davinci_da850()) { da8xx_spi1_resources[0].start = DA850_SPI1_BASE; da8xx_spi1_resources[0].end = DA850_SPI1_BASE + SZ_4K - 1; } return platform_device_register(&da8xx_spi_device[instance]); } #ifdef CONFIG_ARCH_DAVINCI_DA850 int __init da850_register_sata_refclk(int rate) { struct clk *clk; clk = clk_register_fixed_rate(NULL, "sata_refclk", NULL, 0, rate); if (IS_ERR(clk)) return PTR_ERR(clk); return clk_register_clkdev(clk, "refclk", "ahci_da850"); } static struct resource da850_sata_resources[] = { { .start = DA850_SATA_BASE, .end = DA850_SATA_BASE + 0x1fff, .flags = IORESOURCE_MEM, }, { .start = DA8XX_SYSCFG1_BASE + DA8XX_PWRDN_REG, .end = DA8XX_SYSCFG1_BASE + DA8XX_PWRDN_REG + 0x3, .flags = IORESOURCE_MEM, }, { .start = DAVINCI_INTC_IRQ(IRQ_DA850_SATAINT), .flags = IORESOURCE_IRQ, }, }; static u64 da850_sata_dmamask = DMA_BIT_MASK(32); static struct platform_device da850_sata_device = { .name = "ahci_da850", .id = -1, .dev = { .dma_mask = &da850_sata_dmamask, .coherent_dma_mask = DMA_BIT_MASK(32), }, .num_resources = ARRAY_SIZE(da850_sata_resources), .resource = da850_sata_resources, }; int __init da850_register_sata(unsigned long refclkpn) { int ret; ret = da850_register_sata_refclk(refclkpn); if (ret) return ret; return platform_device_register(&da850_sata_device); } #endif static struct regmap *da8xx_cfgchip; static const struct regmap_config da8xx_cfgchip_config __initconst = { .name = "cfgchip", .reg_bits = 32, .val_bits = 32, .reg_stride = 4, .max_register = DA8XX_CFGCHIP4_REG - DA8XX_CFGCHIP0_REG, }; /** * da8xx_get_cfgchip - Lazy gets CFGCHIP as regmap * * This is for use on non-DT boards only. For DT boards, use * syscon_regmap_lookup_by_compatible("ti,da830-cfgchip") * * Returns: Pointer to the CFGCHIP regmap or negative error code. */ struct regmap * __init da8xx_get_cfgchip(void) { if (IS_ERR_OR_NULL(da8xx_cfgchip)) da8xx_cfgchip = regmap_init_mmio(NULL, DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP0_REG), &da8xx_cfgchip_config); return da8xx_cfgchip; }
utf-8
1
GPL-2
1991-2012 Linus Torvalds and many others
linux-5.16.7/arch/arm/mach-s3c/regs-irqtype.h
/* SPDX-License-Identifier: GPL-2.0 */ /* * Copyright 2008 Simtec Electronics * Ben Dooks <ben@simtec.co.uk> * http://armlinux.simtec.co.uk/ * * S3C - IRQ detection types. */ /* values for S3C2410_EXTINT0/1/2 and other cpus in the series, including * the S3C64XX */ #define S3C2410_EXTINT_LOWLEV (0x00) #define S3C2410_EXTINT_HILEV (0x01) #define S3C2410_EXTINT_FALLEDGE (0x02) #define S3C2410_EXTINT_RISEEDGE (0x04) #define S3C2410_EXTINT_BOTHEDGE (0x06)
utf-8
1
GPL-2
1991-2012 Linus Torvalds and many others
allegro4.4-4.4.3.1/src/x/xmouse.c
/* ______ ___ ___ * /\ _ \ /\_ \ /\_ \ * \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___ * \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\ * \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \ * \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/ * \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/ * /\____/ * \_/__/ * * X-Windows mouse module. * * By Michael Bukin. * * See readme.txt for copyright information. */ #include "allegro.h" #include "allegro/internal/aintern.h" #include "allegro/platform/aintunix.h" #include "xwin.h" #include <X11/cursorfont.h> /* TRUE if the requested mouse range extends beyond the regular * (0, 0, SCREEN_W-1, SCREEN_H-1) range. This is aimed at detecting * whether the user mouse coordinates are relative to the 'screen' * bitmap (semantics associated with scrolling) or to the video page * currently being displayed (semantics associated with page flipping). * We cannot differentiate them properly because both use the same * scroll_screen() method. */ int _xwin_mouse_extended_range = FALSE; static int mouse_minx = 0; static int mouse_miny = 0; static int mouse_maxx = 319; static int mouse_maxy = 199; static int mymickey_x = 0; static int mymickey_y = 0; static int mouse_mult = -1; /* mouse acceleration multiplier */ static int mouse_div = -1; /* mouse acceleration divisor */ static int mouse_threshold = -1; /* mouse acceleration threshold */ static int last_xspeed = -1; /* latest set_mouse_speed() settings */ static int last_yspeed = -1; static int _xwin_mousedrv_init(void); static void _xwin_mousedrv_exit(void); static void _xwin_mousedrv_position(int x, int y); static void _xwin_mousedrv_set_range(int x1, int y1, int x2, int y2); static void _xwin_mousedrv_set_speed(int xspeed, int yspeed); static void _xwin_mousedrv_get_mickeys(int *mickeyx, int *mickeyy); static int _xwin_select_system_cursor(AL_CONST int cursor); static void _xwin_set_mouse_speed(int xspeed, int yspeed); static MOUSE_DRIVER mouse_xwin = { MOUSE_XWINDOWS, empty_string, empty_string, "X-Windows mouse", _xwin_mousedrv_init, _xwin_mousedrv_exit, NULL, NULL, _xwin_mousedrv_position, _xwin_mousedrv_set_range, _xwin_mousedrv_set_speed, _xwin_mousedrv_get_mickeys, NULL, _xwin_enable_hardware_cursor, _xwin_select_system_cursor }; /* list the available drivers */ _DRIVER_INFO _xwin_mouse_driver_list[] = { { MOUSE_XWINDOWS, &mouse_xwin, TRUE }, { 0, NULL, 0 } }; /* _xwin_mousedrv_handler: * Mouse "interrupt" handler for mickey-mode driver. */ static void _xwin_mousedrv_handler(int x, int y, int z, int w, int buttons) { _mouse_b = buttons; mymickey_x += x; mymickey_y += y; _mouse_x += x; _mouse_y += y; _mouse_z += z; _mouse_w += w; if ((_mouse_x < mouse_minx) || (_mouse_x > mouse_maxx) || (_mouse_y < mouse_miny) || (_mouse_y > mouse_maxy)) { _mouse_x = CLAMP(mouse_minx, _mouse_x, mouse_maxx); _mouse_y = CLAMP(mouse_miny, _mouse_y, mouse_maxy); } _handle_mouse_input(); } /* _xwin_mousedrv_init: * Initializes the mickey-mode driver. */ static int _xwin_mousedrv_init(void) { int num_buttons; unsigned char map[8]; num_buttons = _xwin_get_pointer_mapping(map, sizeof(map)); num_buttons = CLAMP(2, num_buttons, 3); last_xspeed = -1; last_yspeed = -1; XLOCK(); _xwin_mouse_interrupt = _xwin_mousedrv_handler; XUNLOCK(); return num_buttons; } /* _xwin_mousedrv_exit: * Shuts down the mickey-mode driver. */ static void _xwin_mousedrv_exit(void) { XLOCK(); if (mouse_mult >= 0) XChangePointerControl(_xwin.display, 1, 1, mouse_mult, mouse_div, mouse_threshold); _xwin_mouse_interrupt = 0; XUNLOCK(); } /* _xwin_mousedrv_position: * Sets the position of the mickey-mode mouse. */ static void _xwin_mousedrv_position(int x, int y) { XLOCK(); _mouse_x = x; _mouse_y = y; mymickey_x = mymickey_y = 0; if (_xwin.hw_cursor_ok) XWarpPointer(_xwin.display, _xwin.window, _xwin.window, 0, 0, _xwin.window_width, _xwin.window_height, x, y); XUNLOCK(); _xwin_set_warped_mouse_mode(FALSE); } /* _xwin_mousedrv_set_range: * Sets the range of the mickey-mode mouse. */ static void _xwin_mousedrv_set_range(int x1, int y1, int x2, int y2) { mouse_minx = x1; mouse_miny = y1; mouse_maxx = x2; mouse_maxy = y2; if ((mouse_maxx >= SCREEN_W) || (mouse_maxy >= SCREEN_H)) _xwin_mouse_extended_range = TRUE; else _xwin_mouse_extended_range = FALSE; XLOCK(); _mouse_x = CLAMP(mouse_minx, _mouse_x, mouse_maxx); _mouse_y = CLAMP(mouse_miny, _mouse_y, mouse_maxy); XUNLOCK(); } /* _xwin_mousedrv_set_speed: * Sets the speed of the mouse cursor. We don't set the speed if the cursor * isn't in the window, but we remember the setting so it will be set the * next time the cursor enters the window. */ static void _xwin_mousedrv_set_speed(int xspeed, int yspeed) { if (_mouse_on) { _xwin_set_mouse_speed(xspeed, yspeed); } last_xspeed = xspeed; last_yspeed = yspeed; } /* _xwin_mousedrv_get_mickeys: * Reads the mickey-mode count. */ static void _xwin_mousedrv_get_mickeys(int *mickeyx, int *mickeyy) { int temp_x = mymickey_x; int temp_y = mymickey_y; mymickey_x -= temp_x; mymickey_y -= temp_y; *mickeyx = temp_x; *mickeyy = temp_y; _xwin_set_warped_mouse_mode(TRUE); } /* _xwin_select_system_cursor: * Select an OS native cursor */ static int _xwin_select_system_cursor(AL_CONST int cursor) { switch(cursor) { case MOUSE_CURSOR_ARROW: _xwin.cursor_shape = XC_left_ptr; break; case MOUSE_CURSOR_BUSY: _xwin.cursor_shape = XC_watch; break; case MOUSE_CURSOR_QUESTION: _xwin.cursor_shape = XC_question_arrow; break; case MOUSE_CURSOR_EDIT: _xwin.cursor_shape = XC_xterm; break; default: return 0; } XLOCK(); if (_xwin.cursor != None) { XUndefineCursor(_xwin.display, _xwin.window); XFreeCursor(_xwin.display, _xwin.cursor); } _xwin.cursor = XCreateFontCursor(_xwin.display, _xwin.cursor_shape); XDefineCursor(_xwin.display, _xwin.window, _xwin.cursor); XUNLOCK(); return cursor; } /* _xwin_set_mouse_speed: * The actual function that sets the speed of the mouse cursor. * Each step slows down or speeds the mouse up by 0.5x. */ static void _xwin_set_mouse_speed(int xspeed, int yspeed) { int speed; int hundredths; XLOCK(); if (mouse_mult < 0) XGetPointerControl(_xwin.display, &mouse_mult, &mouse_div, &mouse_threshold); speed = MAX(1, (xspeed + yspeed) / 2); if (mouse_div == 0) hundredths = mouse_mult * 100; else hundredths = (mouse_mult * 100 / mouse_div); hundredths -= (speed - 2) * 50; if (hundredths < 0) hundredths = 0; XChangePointerControl(_xwin.display, 1, 1, hundredths, 100, mouse_threshold); XUNLOCK(); } /* _xwin_mouse_leave_notify: * Reset the mouse speed to its original value when the cursor leave the * Allegro window. */ void _xwin_mouse_leave_notify(void) { if (mouse_mult >= 0) { XLOCK(); XChangePointerControl(_xwin.display, 1, 1, mouse_mult, mouse_div, mouse_threshold); XUNLOCK(); } } /* _xwin_mouse_enter_notify: * Restore the mouse speed setting when the mouse cursor re-enters the * Allegro window. */ void _xwin_mouse_enter_notify(void) { if (last_xspeed >= 0) { _xwin_set_mouse_speed(last_xspeed, last_yspeed); } }
utf-8
1
Allegro-gift-ware
1996-2011 Shawn Hargreaves and the Allegro developers.
thunderbird-91.6.0/dom/media/MediaQueue.h
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et cindent: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #if !defined(MediaQueue_h_) # define MediaQueue_h_ # include <type_traits> # include "mozilla/RecursiveMutex.h" # include "mozilla/TaskQueue.h" # include "nsDeque.h" # include "MediaEventSource.h" # include "TimeUnits.h" namespace mozilla { class AudioData; template <class T> class MediaQueue : private nsRefPtrDeque<T> { public: MediaQueue() : nsRefPtrDeque<T>(), mRecursiveMutex("mediaqueue"), mEndOfStream(false) {} ~MediaQueue() { Reset(); } inline size_t GetSize() const { RecursiveMutexAutoLock lock(mRecursiveMutex); return nsRefPtrDeque<T>::GetSize(); } inline void PushFront(T* aItem) { RecursiveMutexAutoLock lock(mRecursiveMutex); nsRefPtrDeque<T>::PushFront(aItem); } inline void Push(T* aItem) { MOZ_DIAGNOSTIC_ASSERT(aItem); Push(do_AddRef(aItem)); } inline void Push(already_AddRefed<T> aItem) { RecursiveMutexAutoLock lock(mRecursiveMutex); T* item = aItem.take(); MOZ_DIAGNOSTIC_ASSERT(item); MOZ_DIAGNOSTIC_ASSERT(item->GetEndTime() >= item->mTime); nsRefPtrDeque<T>::Push(dont_AddRef(item)); mPushEvent.Notify(RefPtr<T>(item)); // Pushing new data after queue has ended means that the stream is active // again, so we should not mark it as ended. if (mEndOfStream) { mEndOfStream = false; } } inline already_AddRefed<T> PopFront() { RecursiveMutexAutoLock lock(mRecursiveMutex); RefPtr<T> rv = nsRefPtrDeque<T>::PopFront(); if (rv) { MOZ_DIAGNOSTIC_ASSERT(rv->GetEndTime() >= rv->mTime); mPopFrontEvent.Notify(RefPtr<T>(rv)); } return rv.forget(); } inline already_AddRefed<T> PopBack() { RecursiveMutexAutoLock lock(mRecursiveMutex); return nsRefPtrDeque<T>::Pop(); } inline RefPtr<T> PeekFront() const { RecursiveMutexAutoLock lock(mRecursiveMutex); return nsRefPtrDeque<T>::PeekFront(); } inline RefPtr<T> PeekBack() const { RecursiveMutexAutoLock lock(mRecursiveMutex); return nsRefPtrDeque<T>::Peek(); } void Reset() { RecursiveMutexAutoLock lock(mRecursiveMutex); nsRefPtrDeque<T>::Erase(); mEndOfStream = false; } bool AtEndOfStream() const { RecursiveMutexAutoLock lock(mRecursiveMutex); return GetSize() == 0 && mEndOfStream; } // Returns true if the media queue has had its last item added to it. // This happens when the media stream has been completely decoded. Note this // does not mean that the corresponding stream has finished playback. bool IsFinished() const { RecursiveMutexAutoLock lock(mRecursiveMutex); return mEndOfStream; } // Informs the media queue that it won't be receiving any more items. void Finish() { RecursiveMutexAutoLock lock(mRecursiveMutex); if (!mEndOfStream) { mEndOfStream = true; mFinishEvent.Notify(); } } // Returns the approximate number of microseconds of items in the queue. int64_t Duration() const { RecursiveMutexAutoLock lock(mRecursiveMutex); if (GetSize() == 0) { return 0; } T* last = nsRefPtrDeque<T>::Peek(); T* first = nsRefPtrDeque<T>::PeekFront(); return (last->GetEndTime() - first->mTime).ToMicroseconds(); } void LockedForEach(nsDequeFunctor<T>& aFunctor) const { RecursiveMutexAutoLock lock(mRecursiveMutex); nsRefPtrDeque<T>::ForEach(aFunctor); } // Fill aResult with the elements which end later than the given time aTime. void GetElementsAfter(const media::TimeUnit& aTime, nsTArray<RefPtr<T>>* aResult) { GetElementsAfterStrict(aTime.ToMicroseconds(), aResult); } void GetFirstElements(uint32_t aMaxElements, nsTArray<RefPtr<T>>* aResult) { RecursiveMutexAutoLock lock(mRecursiveMutex); for (size_t i = 0; i < aMaxElements && i < GetSize(); ++i) { *aResult->AppendElement() = nsRefPtrDeque<T>::ObjectAt(i); } } uint32_t AudioFramesCount() { static_assert(std::is_same_v<T, AudioData>, "Only usable with MediaQueue<AudioData>"); RecursiveMutexAutoLock lock(mRecursiveMutex); uint32_t frames = 0; for (size_t i = 0; i < GetSize(); ++i) { T* v = nsRefPtrDeque<T>::ObjectAt(i); frames += v->Frames(); } return frames; } MediaEventSource<RefPtr<T>>& PopFrontEvent() { return mPopFrontEvent; } MediaEventSource<RefPtr<T>>& PushEvent() { return mPushEvent; } MediaEventSource<void>& FinishEvent() { return mFinishEvent; } private: // Extracts elements from the queue into aResult, in order. // Elements whose end time is before or equal to aTime are ignored. void GetElementsAfterStrict(int64_t aTime, nsTArray<RefPtr<T>>* aResult) { RecursiveMutexAutoLock lock(mRecursiveMutex); if (GetSize() == 0) return; size_t i; for (i = GetSize() - 1; i > 0; --i) { T* v = nsRefPtrDeque<T>::ObjectAt(i); if (v->GetEndTime().ToMicroseconds() < aTime) break; } for (; i < GetSize(); ++i) { RefPtr<T> elem = nsRefPtrDeque<T>::ObjectAt(i); if (elem->GetEndTime().ToMicroseconds() > aTime) { aResult->AppendElement(elem); } } } mutable RecursiveMutex mRecursiveMutex; MediaEventProducer<RefPtr<T>> mPopFrontEvent; MediaEventProducer<RefPtr<T>> mPushEvent; MediaEventProducer<void> mFinishEvent; // True when we've decoded the last frame of data in the // bitstream for which we're queueing frame data. bool mEndOfStream; }; } // namespace mozilla #endif
utf-8
1
MPL-2.0 or GPL-2 or LGPL-2.1
1998-2016, Mozilla Project
libreoffice-7.3.1~rc1/sw/inc/unotbl.hxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #ifndef INCLUDED_SW_INC_UNOTBL_HXX #define INCLUDED_SW_INC_UNOTBL_HXX #include <com/sun/star/container/XNamed.hpp> #include <com/sun/star/container/XEnumerationAccess.hpp> #include <com/sun/star/util/XSortable.hpp> #include <com/sun/star/chart/XChartDataArray.hpp> #include <com/sun/star/text/XTextTableCursor.hpp> #include <com/sun/star/text/XTextTable.hpp> #include <com/sun/star/table/XCellRange.hpp> #include <com/sun/star/sheet/XCellRangeData.hpp> #include <com/sun/star/table/XAutoFormattable.hpp> #include <cppuhelper/implbase.hxx> #include <comphelper/uno3.hxx> #include <svl/listener.hxx> #include "TextCursorHelper.hxx" #include "unotext.hxx" #include "frmfmt.hxx" #include "unocrsr.hxx" class SwTable; class SwTableBox; class SwTableLine; class SwTableCursor; class SfxItemPropertySet; typedef cppu::WeakImplHelper < css::table::XCell, css::lang::XServiceInfo, css::beans::XPropertySet, css::container::XEnumerationAccess > SwXCellBaseClass; class SwXCell final : public SwXCellBaseClass, public SwXText, public SvtListener { friend void sw_setString( SwXCell &rCell, const OUString &rText, bool bKeepNumberFormat ); friend void sw_setValue( SwXCell &rCell, double nVal ); const SfxItemPropertySet* m_pPropSet; SwTableBox* m_pBox; // only set in non-XML import const SwStartNode* m_pStartNode; // only set in XML import SwFrameFormat* m_pTableFormat; // table position where pBox was found last size_t m_nFndPos; css::uno::Reference<css::text::XText> m_xParentText; static size_t const NOTFOUND = SAL_MAX_SIZE; virtual const SwStartNode *GetStartNode() const override; virtual css::uno::Reference< css::text::XTextCursor > CreateCursor() override; bool IsValid() const; virtual ~SwXCell() override; virtual void Notify(const SfxHint&) override; public: SwXCell(SwFrameFormat* pTableFormat, SwTableBox* pBox, size_t nPos); SwXCell(SwFrameFormat* pTableFormat, const SwStartNode& rStartNode); // XML import interface static const css::uno::Sequence< sal_Int8 > & getUnoTunnelId(); //XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& aType ) override; virtual void SAL_CALL acquire( ) noexcept override; virtual void SAL_CALL release( ) noexcept override; //XTypeProvider virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes( ) override; virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) override; //XCell virtual OUString SAL_CALL getFormula( ) override; virtual void SAL_CALL setFormula( const OUString& aFormula ) override; virtual double SAL_CALL getValue( ) override; /// @throws css::uno::RuntimeException double getValue( ) const { return const_cast<SwXCell*>(this)->getValue(); }; virtual void SAL_CALL setValue( double nValue ) override; virtual css::table::CellContentType SAL_CALL getType( ) override; virtual sal_Int32 SAL_CALL getError( ) override; //XText virtual css::uno::Reference< css::text::XTextCursor > SAL_CALL createTextCursor() override; virtual css::uno::Reference< css::text::XTextCursor > SAL_CALL createTextCursorByRange(const css::uno::Reference< css::text::XTextRange > & aTextPosition) override; virtual void SAL_CALL setString(const OUString& aString) override; //XPropertySet virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; //XServiceInfo virtual OUString SAL_CALL getImplementationName() override; virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; //XEnumerationAccess - was: XParagraphEnumerationAccess virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL createEnumeration() override; //XElementAccess virtual css::uno::Type SAL_CALL getElementType( ) override; virtual sal_Bool SAL_CALL hasElements( ) override; SwTableBox* GetTableBox() const { return m_pBox; } static rtl::Reference<SwXCell> CreateXCell(SwFrameFormat* pTableFormat, SwTableBox* pBox, SwTable *pTable = nullptr ); SwTableBox* FindBox(SwTable* pTable, SwTableBox* pBox); SwFrameFormat* GetFrameFormat() const { return m_pTableFormat; } double GetForcedNumericalValue() const; css::uno::Any GetAny() const; }; class SwXTextTableRow final : public cppu::WeakImplHelper<css::beans::XPropertySet, css::lang::XServiceInfo> , public SvtListener { SwFrameFormat* m_pFormat; SwTableLine* m_pLine; const SfxItemPropertySet* m_pPropSet; SwFrameFormat* GetFrameFormat() { return m_pFormat; } const SwFrameFormat* GetFrameFormat() const { return m_pFormat; } virtual ~SwXTextTableRow() override; public: SwXTextTableRow(SwFrameFormat* pFormat, SwTableLine* pLine); //XPropertySet virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; //XServiceInfo virtual OUString SAL_CALL getImplementationName() override; virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; static SwTableLine* FindLine(SwTable* pTable, SwTableLine const * pLine); void Notify(const SfxHint&) override; }; typedef cppu::WeakImplHelper< css::text::XTextTableCursor, css::lang::XServiceInfo, css::beans::XPropertySet> SwXTextTableCursor_Base; class SW_DLLPUBLIC SwXTextTableCursor final : public SwXTextTableCursor_Base , public SvtListener , public OTextCursorHelper { SwFrameFormat* m_pFrameFormat; const SfxItemPropertySet* m_pPropSet; public: SwXTextTableCursor(SwFrameFormat* pFormat, SwTableBox const* pBox); SwXTextTableCursor(SwFrameFormat& rTableFormat, const SwTableCursor* pTableSelection); DECLARE_XINTERFACE() //XTextTableCursor virtual OUString SAL_CALL getRangeName() override; virtual sal_Bool SAL_CALL gotoCellByName( const OUString& aCellName, sal_Bool bExpand ) override; virtual sal_Bool SAL_CALL goLeft( sal_Int16 nCount, sal_Bool bExpand ) override; virtual sal_Bool SAL_CALL goRight( sal_Int16 nCount, sal_Bool bExpand ) override; virtual sal_Bool SAL_CALL goUp( sal_Int16 nCount, sal_Bool bExpand ) override; virtual sal_Bool SAL_CALL goDown( sal_Int16 nCount, sal_Bool bExpand ) override; virtual void SAL_CALL gotoStart( sal_Bool bExpand ) override; virtual void SAL_CALL gotoEnd( sal_Bool bExpand ) override; virtual sal_Bool SAL_CALL mergeRange() override; virtual sal_Bool SAL_CALL splitRange( sal_Int16 Count, sal_Bool Horizontal ) override; //XPropertySet virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; //XServiceInfo virtual OUString SAL_CALL getImplementationName() override; virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; // ITextCursorHelper virtual const SwPaM* GetPaM() const override; virtual SwPaM* GetPaM() override; virtual const SwDoc* GetDoc() const override; virtual SwDoc* GetDoc() override; virtual void Notify( const SfxHint& ) override; const SwUnoCursor& GetCursor() const; SwUnoCursor& GetCursor(); sw::UnoCursorPointer m_pUnoCursor; SwFrameFormat* GetFrameFormat() const { return m_pFrameFormat; } }; struct SwRangeDescriptor { sal_Int32 nTop; sal_Int32 nLeft; sal_Int32 nBottom; sal_Int32 nRight; void Normalize(); }; class SAL_DLLPUBLIC_RTTI SwXTextTable final : public cppu::WeakImplHelper < css::text::XTextTable, css::lang::XServiceInfo, css::table::XCellRange, css::chart::XChartDataArray, css::beans::XPropertySet, css::container::XNamed, css::table::XAutoFormattable, css::util::XSortable, css::lang::XUnoTunnel, css::sheet::XCellRangeData > { private: class Impl; ::sw::UnoImplPtr<Impl> m_pImpl; SwXTextTable(); SwXTextTable(SwFrameFormat& rFrameFormat); virtual ~SwXTextTable() override; public: static css::uno::Reference<css::text::XTextTable> CreateXTextTable(SwFrameFormat * pFrameFormat); SW_DLLPUBLIC static const css::uno::Sequence< sal_Int8 > & getUnoTunnelId(); SW_DLLPUBLIC static void GetCellPosition(const OUString& rCellName, sal_Int32& o_rColumn, sal_Int32& o_rRow); SW_DLLPUBLIC SwFrameFormat* GetFrameFormat(); //XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; //XTextTable virtual void SAL_CALL initialize( sal_Int32 nRows, sal_Int32 nColumns ) override; virtual css::uno::Reference< css::table::XTableRows > SAL_CALL getRows( ) override; virtual css::uno::Reference< css::table::XTableColumns > SAL_CALL getColumns( ) override; virtual css::uno::Reference< css::table::XCell > SAL_CALL getCellByName( const OUString& aCellName ) override; virtual css::uno::Sequence< OUString > SAL_CALL getCellNames( ) override; virtual css::uno::Reference< css::text::XTextTableCursor > SAL_CALL createCursorByCellName( const OUString& aCellName ) override; //XTextContent virtual void SAL_CALL attach(const css::uno::Reference< css::text::XTextRange > & xTextRange) override; virtual css::uno::Reference< css::text::XTextRange > SAL_CALL getAnchor( ) override; //XComponent virtual void SAL_CALL dispose() override; virtual void SAL_CALL addEventListener(const css::uno::Reference< css::lang::XEventListener > & aListener) override; virtual void SAL_CALL removeEventListener(const css::uno::Reference< css::lang::XEventListener > & aListener) override; //XCellRange virtual css::uno::Reference< css::table::XCell > SAL_CALL getCellByPosition( sal_Int32 nColumn, sal_Int32 nRow ) override; virtual css::uno::Reference< css::table::XCellRange > SAL_CALL getCellRangeByPosition( sal_Int32 nLeft, sal_Int32 nTop, sal_Int32 nRight, sal_Int32 nBottom ) override; virtual css::uno::Reference< css::table::XCellRange > SAL_CALL getCellRangeByName( const OUString& aRange ) override; //XChartDataArray virtual css::uno::Sequence< css::uno::Sequence< double > > SAL_CALL getData( ) override; virtual void SAL_CALL setData( const css::uno::Sequence< css::uno::Sequence< double > >& aData ) override; virtual css::uno::Sequence< OUString > SAL_CALL getRowDescriptions( ) override; virtual void SAL_CALL setRowDescriptions( const css::uno::Sequence< OUString >& aRowDescriptions ) override; virtual css::uno::Sequence< OUString > SAL_CALL getColumnDescriptions( ) override; virtual void SAL_CALL setColumnDescriptions( const css::uno::Sequence< OUString >& aColumnDescriptions ) override; //XChartData virtual void SAL_CALL addChartDataChangeEventListener( const css::uno::Reference< css::chart::XChartDataChangeEventListener >& aListener ) override; virtual void SAL_CALL removeChartDataChangeEventListener( const css::uno::Reference< css::chart::XChartDataChangeEventListener >& aListener ) override; virtual double SAL_CALL getNotANumber( ) override; virtual sal_Bool SAL_CALL isNotANumber( double nNumber ) override; //XSortable virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL createSortDescriptor() override; virtual void SAL_CALL sort(const css::uno::Sequence< css::beans::PropertyValue >& xDescriptor) override; //XAutoFormattable virtual void SAL_CALL autoFormat(const OUString& aName) override; //XPropertySet virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; virtual void SAL_CALL setPropertyValue( const OUString& aPropertyName, const css::uno::Any& aValue ) override; virtual css::uno::Any SAL_CALL getPropertyValue( const OUString& PropertyName ) override; virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; //XNamed virtual OUString SAL_CALL getName() override; virtual void SAL_CALL setName(const OUString& Name_) override; //XCellRangeData virtual css::uno::Sequence< css::uno::Sequence< css::uno::Any > > SAL_CALL getDataArray( ) override; virtual void SAL_CALL setDataArray( const css::uno::Sequence< css::uno::Sequence< css::uno::Any > >& aArray ) override; //XServiceInfo virtual OUString SAL_CALL getImplementationName() override; virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; }; class SwXCellRange final : public cppu::WeakImplHelper < css::table::XCellRange, css::lang::XServiceInfo, css::lang::XUnoTunnel, css::beans::XPropertySet, css::chart::XChartDataArray, css::util::XSortable, css::sheet::XCellRangeData > { private: class Impl; ::sw::UnoImplPtr<Impl> m_pImpl; SwXCellRange(const sw::UnoCursorPointer& pCursor, SwFrameFormat& rFrameFormat, SwRangeDescriptor const & rDesc); virtual ~SwXCellRange() override; public: static ::rtl::Reference<SwXCellRange> CreateXCellRange( const sw::UnoCursorPointer& pCursor, SwFrameFormat& rFrameFormat, SwRangeDescriptor const & rDesc); static const css::uno::Sequence< sal_Int8 > & getUnoTunnelId(); void SetLabels(bool bFirstRowAsLabel, bool bFirstColumnAsLabel); std::vector<css::uno::Reference<css::table::XCell>> GetCells(); const SwUnoCursor* GetTableCursor() const; //XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const css::uno::Sequence< sal_Int8 >& aIdentifier ) override; //XCellRange virtual css::uno::Reference< css::table::XCell > SAL_CALL getCellByPosition( sal_Int32 nColumn, sal_Int32 nRow ) override; virtual css::uno::Reference< css::table::XCellRange > SAL_CALL getCellRangeByPosition( sal_Int32 nLeft, sal_Int32 nTop, sal_Int32 nRight, sal_Int32 nBottom ) override; virtual css::uno::Reference< css::table::XCellRange > SAL_CALL getCellRangeByName( const OUString& aRange ) override; //XPropertySet virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) override; virtual void SAL_CALL setPropertyValue(const OUString& aPropertyName, const css::uno::Any& aValue) override; virtual css::uno::Any SAL_CALL getPropertyValue(const OUString& PropertyName) override; virtual void SAL_CALL addPropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener ) override; virtual void SAL_CALL removePropertyChangeListener( const OUString& aPropertyName, const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener ) override; virtual void SAL_CALL addVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; virtual void SAL_CALL removeVetoableChangeListener( const OUString& PropertyName, const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener ) override; //XChartData virtual void SAL_CALL addChartDataChangeEventListener( const css::uno::Reference< css::chart::XChartDataChangeEventListener >& aListener ) override; virtual void SAL_CALL removeChartDataChangeEventListener( const css::uno::Reference< css::chart::XChartDataChangeEventListener >& aListener ) override; virtual double SAL_CALL getNotANumber( ) override; virtual sal_Bool SAL_CALL isNotANumber( double nNumber ) override; //XChartDataArray virtual css::uno::Sequence< css::uno::Sequence< double > > SAL_CALL getData( ) override; virtual void SAL_CALL setData( const css::uno::Sequence< css::uno::Sequence< double > >& aData ) override; virtual css::uno::Sequence< OUString > SAL_CALL getRowDescriptions( ) override; virtual void SAL_CALL setRowDescriptions( const css::uno::Sequence< OUString >& aRowDescriptions ) override; virtual css::uno::Sequence< OUString > SAL_CALL getColumnDescriptions( ) override; virtual void SAL_CALL setColumnDescriptions( const css::uno::Sequence< OUString >& aColumnDescriptions ) override; //XSortable virtual css::uno::Sequence< css::beans::PropertyValue > SAL_CALL createSortDescriptor() override; virtual void SAL_CALL sort(const css::uno::Sequence< css::beans::PropertyValue >& xDescriptor) override; //XCellRangeData virtual css::uno::Sequence< css::uno::Sequence< css::uno::Any > > SAL_CALL getDataArray( ) override; virtual void SAL_CALL setDataArray( const css::uno::Sequence< css::uno::Sequence< css::uno::Any > >& aArray ) override; //XServiceInfo virtual OUString SAL_CALL getImplementationName() override; virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; }; class SwXTableRows final : public cppu::WeakImplHelper < css::table::XTableRows, css::lang::XServiceInfo > { class Impl; ::sw::UnoImplPtr<Impl> m_pImpl; SwFrameFormat* GetFrameFormat(); const SwFrameFormat* GetFrameFormat() const { return const_cast<SwXTableRows*>(this)->GetFrameFormat(); } virtual ~SwXTableRows() override; public: SwXTableRows(SwFrameFormat& rFrameFormat); //XIndexAccess virtual sal_Int32 SAL_CALL getCount() override; virtual css::uno::Any SAL_CALL getByIndex(sal_Int32 nIndex) override; //XElementAccess virtual css::uno::Type SAL_CALL getElementType( ) override; virtual sal_Bool SAL_CALL hasElements( ) override; //XTableRows virtual void SAL_CALL insertByIndex(sal_Int32 nIndex, sal_Int32 nCount) override; virtual void SAL_CALL removeByIndex(sal_Int32 nIndex, sal_Int32 nCount) override; //XServiceInfo virtual OUString SAL_CALL getImplementationName() override; virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; }; class SwXTableColumns final : public cppu::WeakImplHelper < css::table::XTableColumns, css::lang::XServiceInfo > { private: class Impl; ::sw::UnoImplPtr<Impl> m_pImpl; SwFrameFormat* GetFrameFormat() const; virtual ~SwXTableColumns() override; public: SwXTableColumns(SwFrameFormat& rFrameFormat); //XIndexAccess virtual sal_Int32 SAL_CALL getCount() override; virtual css::uno::Any SAL_CALL getByIndex(sal_Int32 nIndex) override; //XElementAccess virtual css::uno::Type SAL_CALL getElementType( ) override; virtual sal_Bool SAL_CALL hasElements( ) override; //XTableColumns virtual void SAL_CALL insertByIndex(sal_Int32 nIndex, sal_Int32 nCount) override; virtual void SAL_CALL removeByIndex(sal_Int32 nIndex, sal_Int32 nCount) override; //XServiceInfo virtual OUString SAL_CALL getImplementationName() override; virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override; virtual css::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() override; }; int sw_CompareCellRanges( const OUString &rRange1StartCell, const OUString &rRange1EndCell, const OUString &rRange2StartCell, const OUString &rRange2EndCell, bool bCmpColsFirst ); void sw_NormalizeRange( OUString &rCell1, OUString &rCell2 ); OUString sw_GetCellName( sal_Int32 nColumn, sal_Int32 nRow ); int sw_CompareCellsByColFirst( const OUString &rCellName1, const OUString &rCellName2 ); int sw_CompareCellsByRowFirst( const OUString &rCellName1, const OUString &rCellName2 ); #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
utf-8
1
MPL-2.0
Copyright 2000, 2010 Oracle and/or its affiliates. Copyright (c) 2000, 2010 LibreOffice contributors and/or their affiliates.
android-platform-frameworks-native-10.0.0+r36/opengl/tools/glgen/stubs/egl/eglCreatePbufferFromClientBuffer.cpp
/* EGLSurface eglCreatePbufferFromClientBuffer ( EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list ) */ static jobject android_eglCreatePbufferFromClientBuffer (JNIEnv *_env, jobject _this, jobject dpy, jint buftype, jlong buffer, jobject config, jintArray attrib_list_ref, jint offset) { jint _exception = 0; const char * _exceptionType = NULL; const char * _exceptionMessage = NULL; EGLSurface _returnValue = (EGLSurface) 0; EGLDisplay dpy_native = (EGLDisplay) fromEGLHandle(_env, egldisplayGetHandleID, dpy); EGLConfig config_native = (EGLConfig) fromEGLHandle(_env, eglconfigGetHandleID, config); bool attrib_list_sentinel = false; EGLint *attrib_list_base = (EGLint *) 0; jint _remaining; EGLint *attrib_list = (EGLint *) 0; if (attrib_list_ref) { if (offset < 0) { _exception = 1; _exceptionType = "java/lang/IllegalArgumentException"; _exceptionMessage = "offset < 0"; goto exit; } _remaining = _env->GetArrayLength(attrib_list_ref) - offset; attrib_list_base = (EGLint *) _env->GetIntArrayElements(attrib_list_ref, (jboolean *)0); attrib_list = attrib_list_base + offset; attrib_list_sentinel = false; for (int i = _remaining - 1; i >= 0; i--) { if (attrib_list[i] == EGL_NONE){ attrib_list_sentinel = true; break; } } if (attrib_list_sentinel == false) { _exception = 1; _exceptionType = "java/lang/IllegalArgumentException"; _exceptionMessage = "attrib_list must contain EGL_NONE!"; goto exit; } } _returnValue = eglCreatePbufferFromClientBuffer( (EGLDisplay)dpy_native, (EGLenum)buftype, reinterpret_cast<EGLClientBuffer>(buffer), (EGLConfig)config_native, (EGLint *)attrib_list ); exit: if (attrib_list_base) { _env->ReleaseIntArrayElements(attrib_list_ref, attrib_list_base, JNI_ABORT); } if (_exception) { jniThrowException(_env, _exceptionType, _exceptionMessage); return nullptr; } return toEGLHandle(_env, eglsurfaceClass, eglsurfaceConstructor, _returnValue); } static jobject android_eglCreatePbufferFromClientBufferInt (JNIEnv *_env, jobject _this, jobject dpy, jint buftype, jint buffer, jobject config, jintArray attrib_list_ref, jint offset) { if(sizeof(void*) != sizeof(uint32_t)) { jniThrowException(_env, "java/lang/UnsupportedOperationException", "eglCreatePbufferFromClientBuffer"); return 0; } return android_eglCreatePbufferFromClientBuffer(_env, _this, dpy, buftype, buffer, config, attrib_list_ref, offset); }
utf-8
1
Apache-2.0
2005-2019, The Android Open Source Project
tracker-3.1.2/src/libtracker-sparql/tracker-serializer-xml.h
/* * Copyright (C) 2020, Red Hat, 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. * * Author: Carlos Garnacho <carlosg@gnome.org> */ #ifndef TRACKER_SERIALIZER_XML_H #define TRACKER_SERIALIZER_XML_H #include <libtracker-sparql/tracker-sparql.h> #include <libtracker-sparql/tracker-private.h> #include <libtracker-sparql/tracker-serializer.h> #define TRACKER_TYPE_SERIALIZER_XML (tracker_serializer_xml_get_type()) G_DECLARE_FINAL_TYPE (TrackerSerializerXml, tracker_serializer_xml, TRACKER, SERIALIZER_XML, TrackerSerializer); #endif /* TRACKER_SERIALIZER_XML_H */
utf-8
1
GPL-2.0+
2008-2011 Nokia <ivan.frade@nokia.com> 2006 Jamie McCracken <jamiemcc@gnome.org> 2012-2013 Martyn Russell <martyn@lanedo.com> 2012-2020 Sam Thursfield <sam@afuera.me.uk> 2014 Lanedo <martyn@lanedo.com> 2014, Softathome <philippe.judge@softathome.com> 2014-2020 Red Hat Inc. 2019 Sam Thursfield <sam@afuera.me.uk> 2020 Carlos Garnacho <carlosg@gnome.org>
samba-4.13.14+dfsg/auth/credentials/credentials.c
/* Unix SMB/CIFS implementation. User credentials handling Copyright (C) Jelmer Vernooij 2005 Copyright (C) Tim Potter 2001 Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "includes.h" #include "librpc/gen_ndr/samr.h" /* for struct samrPassword */ #include "auth/credentials/credentials.h" #include "auth/credentials/credentials_internal.h" #include "auth/gensec/gensec.h" #include "libcli/auth/libcli_auth.h" #include "tevent.h" #include "param/param.h" #include "system/filesys.h" /** * Create a new credentials structure * @param mem_ctx TALLOC_CTX parent for credentials structure */ _PUBLIC_ struct cli_credentials *cli_credentials_init(TALLOC_CTX *mem_ctx) { struct cli_credentials *cred = talloc_zero(mem_ctx, struct cli_credentials); if (cred == NULL) { return cred; } cred->winbind_separator = '\\'; return cred; } _PUBLIC_ void cli_credentials_set_callback_data(struct cli_credentials *cred, void *callback_data) { cred->priv_data = callback_data; } _PUBLIC_ void *_cli_credentials_callback_data(struct cli_credentials *cred) { return cred->priv_data; } /** * Create a new anonymous credential * @param mem_ctx TALLOC_CTX parent for credentials structure */ _PUBLIC_ struct cli_credentials *cli_credentials_init_anon(TALLOC_CTX *mem_ctx) { struct cli_credentials *anon_credentials; anon_credentials = cli_credentials_init(mem_ctx); cli_credentials_set_anonymous(anon_credentials); return anon_credentials; } _PUBLIC_ void cli_credentials_set_kerberos_state(struct cli_credentials *creds, enum credentials_use_kerberos use_kerberos) { creds->use_kerberos = use_kerberos; } _PUBLIC_ void cli_credentials_set_forced_sasl_mech(struct cli_credentials *creds, const char *sasl_mech) { TALLOC_FREE(creds->forced_sasl_mech); creds->forced_sasl_mech = talloc_strdup(creds, sasl_mech); } _PUBLIC_ void cli_credentials_set_krb_forwardable(struct cli_credentials *creds, enum credentials_krb_forwardable krb_forwardable) { creds->krb_forwardable = krb_forwardable; } _PUBLIC_ enum credentials_use_kerberos cli_credentials_get_kerberos_state(struct cli_credentials *creds) { return creds->use_kerberos; } _PUBLIC_ const char *cli_credentials_get_forced_sasl_mech(struct cli_credentials *creds) { return creds->forced_sasl_mech; } _PUBLIC_ enum credentials_krb_forwardable cli_credentials_get_krb_forwardable(struct cli_credentials *creds) { return creds->krb_forwardable; } _PUBLIC_ void cli_credentials_set_gensec_features(struct cli_credentials *creds, uint32_t gensec_features) { creds->gensec_features = gensec_features; } _PUBLIC_ uint32_t cli_credentials_get_gensec_features(struct cli_credentials *creds) { return creds->gensec_features; } /** * Obtain the username for this credentials context. * @param cred credentials context * @retval The username set on this context. * @note Return value will never be NULL except by programmer error. */ _PUBLIC_ const char *cli_credentials_get_username(struct cli_credentials *cred) { if (cred->machine_account_pending) { cli_credentials_set_machine_account(cred, cred->machine_account_pending_lp_ctx); } if (cred->username_obtained == CRED_CALLBACK && !cred->callback_running) { cred->callback_running = true; cred->username = cred->username_cb(cred); cred->callback_running = false; if (cred->username_obtained == CRED_CALLBACK) { cred->username_obtained = CRED_CALLBACK_RESULT; cli_credentials_invalidate_ccache(cred, cred->username_obtained); } } return cred->username; } _PUBLIC_ bool cli_credentials_set_username(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained) { if (obtained >= cred->username_obtained) { cred->username = talloc_strdup(cred, val); cred->username_obtained = obtained; cli_credentials_invalidate_ccache(cred, cred->username_obtained); return true; } return false; } _PUBLIC_ bool cli_credentials_set_username_callback(struct cli_credentials *cred, const char *(*username_cb) (struct cli_credentials *)) { if (cred->username_obtained < CRED_CALLBACK) { cred->username_cb = username_cb; cred->username_obtained = CRED_CALLBACK; return true; } return false; } _PUBLIC_ bool cli_credentials_set_bind_dn(struct cli_credentials *cred, const char *bind_dn) { cred->bind_dn = talloc_strdup(cred, bind_dn); return true; } /** * Obtain the BIND DN for this credentials context. * @param cred credentials context * @retval The username set on this context. * @note Return value will be NULL if not specified explictly */ _PUBLIC_ const char *cli_credentials_get_bind_dn(struct cli_credentials *cred) { return cred->bind_dn; } /** * Obtain the client principal for this credentials context. * @param cred credentials context * @retval The username set on this context. * @note Return value will never be NULL except by programmer error. */ _PUBLIC_ char *cli_credentials_get_principal_and_obtained(struct cli_credentials *cred, TALLOC_CTX *mem_ctx, enum credentials_obtained *obtained) { if (cred->machine_account_pending) { cli_credentials_set_machine_account(cred, cred->machine_account_pending_lp_ctx); } if (cred->principal_obtained == CRED_CALLBACK && !cred->callback_running) { cred->callback_running = true; cred->principal = cred->principal_cb(cred); cred->callback_running = false; if (cred->principal_obtained == CRED_CALLBACK) { cred->principal_obtained = CRED_CALLBACK_RESULT; cli_credentials_invalidate_ccache(cred, cred->principal_obtained); } } if (cred->principal_obtained < cred->username_obtained || cred->principal_obtained < MAX(cred->domain_obtained, cred->realm_obtained)) { const char *effective_username = NULL; const char *effective_realm = NULL; enum credentials_obtained effective_obtained; effective_username = cli_credentials_get_username(cred); if (effective_username == NULL || strlen(effective_username) == 0) { *obtained = cred->username_obtained; return NULL; } if (cred->domain_obtained > cred->realm_obtained) { effective_realm = cli_credentials_get_domain(cred); effective_obtained = MIN(cred->domain_obtained, cred->username_obtained); } else { effective_realm = cli_credentials_get_realm(cred); effective_obtained = MIN(cred->realm_obtained, cred->username_obtained); } if (effective_realm == NULL || strlen(effective_realm) == 0) { effective_realm = cli_credentials_get_domain(cred); effective_obtained = MIN(cred->domain_obtained, cred->username_obtained); } if (effective_realm != NULL && strlen(effective_realm) != 0) { *obtained = effective_obtained; return talloc_asprintf(mem_ctx, "%s@%s", effective_username, effective_realm); } } *obtained = cred->principal_obtained; return talloc_strdup(mem_ctx, cred->principal); } /** * Obtain the client principal for this credentials context. * @param cred credentials context * @retval The username set on this context. * @note Return value will never be NULL except by programmer error. */ _PUBLIC_ char *cli_credentials_get_principal(struct cli_credentials *cred, TALLOC_CTX *mem_ctx) { enum credentials_obtained obtained; return cli_credentials_get_principal_and_obtained(cred, mem_ctx, &obtained); } _PUBLIC_ bool cli_credentials_set_principal(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained) { if (obtained >= cred->principal_obtained) { cred->principal = talloc_strdup(cred, val); if (cred->principal == NULL) { return false; } cred->principal_obtained = obtained; cli_credentials_invalidate_ccache(cred, cred->principal_obtained); return true; } return false; } /* Set a callback to get the principal. This could be a popup dialog, * a terminal prompt or similar. */ _PUBLIC_ bool cli_credentials_set_principal_callback(struct cli_credentials *cred, const char *(*principal_cb) (struct cli_credentials *)) { if (cred->principal_obtained < CRED_CALLBACK) { cred->principal_cb = principal_cb; cred->principal_obtained = CRED_CALLBACK; return true; } return false; } /* Some of our tools are 'anonymous by default'. This is a single * function to determine if authentication has been explicitly * requested */ _PUBLIC_ bool cli_credentials_authentication_requested(struct cli_credentials *cred) { uint32_t gensec_features = 0; if (cred->bind_dn) { return true; } /* * If we forced the mech we clearly want authentication. E.g. to use * SASL/EXTERNAL which has no credentials. */ if (cred->forced_sasl_mech) { return true; } if (cli_credentials_is_anonymous(cred)){ return false; } if (cred->principal_obtained >= CRED_SPECIFIED) { return true; } if (cred->username_obtained >= CRED_SPECIFIED) { return true; } if (cli_credentials_get_kerberos_state(cred) == CRED_MUST_USE_KERBEROS) { return true; } gensec_features = cli_credentials_get_gensec_features(cred); if (gensec_features & GENSEC_FEATURE_NTLM_CCACHE) { return true; } if (gensec_features & GENSEC_FEATURE_SIGN) { return true; } if (gensec_features & GENSEC_FEATURE_SEAL) { return true; } return false; } /** * Obtain the password for this credentials context. * @param cred credentials context * @retval If set, the cleartext password, otherwise NULL */ _PUBLIC_ const char *cli_credentials_get_password(struct cli_credentials *cred) { if (cred->machine_account_pending) { cli_credentials_set_machine_account(cred, cred->machine_account_pending_lp_ctx); } if (cred->password_obtained == CRED_CALLBACK && !cred->callback_running && !cred->password_will_be_nt_hash) { cred->callback_running = true; cred->password = cred->password_cb(cred); cred->callback_running = false; if (cred->password_obtained == CRED_CALLBACK) { cred->password_obtained = CRED_CALLBACK_RESULT; cli_credentials_invalidate_ccache(cred, cred->password_obtained); } } return cred->password; } /* Set a password on the credentials context, including an indication * of 'how' the password was obtained */ _PUBLIC_ bool cli_credentials_set_password(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained) { if (obtained >= cred->password_obtained) { cred->lm_response = data_blob_null; cred->nt_response = data_blob_null; cred->nt_hash = NULL; cred->password = NULL; cli_credentials_invalidate_ccache(cred, obtained); cred->password_tries = 0; if (val == NULL) { cred->password_obtained = obtained; return true; } if (cred->password_will_be_nt_hash) { struct samr_Password *nt_hash = NULL; size_t val_len = strlen(val); size_t converted; nt_hash = talloc(cred, struct samr_Password); if (nt_hash == NULL) { return false; } converted = strhex_to_str((char *)nt_hash->hash, sizeof(nt_hash->hash), val, val_len); if (converted != sizeof(nt_hash->hash)) { TALLOC_FREE(nt_hash); return false; } cred->nt_hash = nt_hash; cred->password_obtained = obtained; return true; } cred->password = talloc_strdup(cred, val); if (cred->password == NULL) { return false; } /* Don't print the actual password in talloc memory dumps */ talloc_set_name_const(cred->password, "password set via cli_credentials_set_password"); cred->password_obtained = obtained; return true; } return false; } _PUBLIC_ bool cli_credentials_set_password_callback(struct cli_credentials *cred, const char *(*password_cb) (struct cli_credentials *)) { if (cred->password_obtained < CRED_CALLBACK) { cred->password_tries = 3; cred->password_cb = password_cb; cred->password_obtained = CRED_CALLBACK; cli_credentials_invalidate_ccache(cred, cred->password_obtained); return true; } return false; } /** * Obtain the 'old' password for this credentials context (used for join accounts). * @param cred credentials context * @retval If set, the cleartext password, otherwise NULL */ _PUBLIC_ const char *cli_credentials_get_old_password(struct cli_credentials *cred) { if (cred->machine_account_pending) { cli_credentials_set_machine_account(cred, cred->machine_account_pending_lp_ctx); } return cred->old_password; } _PUBLIC_ bool cli_credentials_set_old_password(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained) { cred->old_password = talloc_strdup(cred, val); if (cred->old_password) { /* Don't print the actual password in talloc memory dumps */ talloc_set_name_const(cred->old_password, "password set via cli_credentials_set_old_password"); } cred->old_nt_hash = NULL; return true; } /** * Obtain the password, in the form MD4(unicode(password)) for this credentials context. * * Sometimes we only have this much of the password, while the rest of * the time this call avoids calling E_md4hash themselves. * * @param cred credentials context * @retval If set, the cleartext password, otherwise NULL */ _PUBLIC_ struct samr_Password *cli_credentials_get_nt_hash(struct cli_credentials *cred, TALLOC_CTX *mem_ctx) { enum credentials_obtained password_obtained; enum credentials_obtained ccache_threshold; enum credentials_obtained client_gss_creds_threshold; bool password_is_nt_hash; const char *password = NULL; struct samr_Password *nt_hash = NULL; if (cred->nt_hash != NULL) { /* * If we already have a hash it's easy. */ goto return_hash; } /* * This is a bit tricky, with password_will_be_nt_hash * we still need to get the value via the password_callback * but if we did that we should not remember it's state * in the long run so we need to undo it. */ password_obtained = cred->password_obtained; ccache_threshold = cred->ccache_threshold; client_gss_creds_threshold = cred->client_gss_creds_threshold; password_is_nt_hash = cred->password_will_be_nt_hash; cred->password_will_be_nt_hash = false; password = cli_credentials_get_password(cred); cred->password_will_be_nt_hash = password_is_nt_hash; if (password_is_nt_hash && password_obtained == CRED_CALLBACK) { /* * We got the nt_hash as string via the callback, * so we need to undo the state change. * * And also don't remember it as plaintext password. */ cred->client_gss_creds_threshold = client_gss_creds_threshold; cred->ccache_threshold = ccache_threshold; cred->password_obtained = password_obtained; cred->password = NULL; } if (password == NULL) { return NULL; } nt_hash = talloc(cred, struct samr_Password); if (nt_hash == NULL) { return NULL; } if (password_is_nt_hash) { size_t password_len = strlen(password); size_t converted; converted = strhex_to_str((char *)nt_hash->hash, sizeof(nt_hash->hash), password, password_len); if (converted != sizeof(nt_hash->hash)) { TALLOC_FREE(nt_hash); return NULL; } } else { E_md4hash(password, nt_hash->hash); } cred->nt_hash = nt_hash; nt_hash = NULL; return_hash: nt_hash = talloc(mem_ctx, struct samr_Password); if (nt_hash == NULL) { return NULL; } *nt_hash = *cred->nt_hash; return nt_hash; } /** * Obtain the old password, in the form MD4(unicode(password)) for this credentials context. * * Sometimes we only have this much of the password, while the rest of * the time this call avoids calling E_md4hash themselves. * * @param cred credentials context * @retval If set, the cleartext password, otherwise NULL */ _PUBLIC_ struct samr_Password *cli_credentials_get_old_nt_hash(struct cli_credentials *cred, TALLOC_CTX *mem_ctx) { const char *old_password = NULL; if (cred->old_nt_hash != NULL) { struct samr_Password *nt_hash = talloc(mem_ctx, struct samr_Password); if (!nt_hash) { return NULL; } *nt_hash = *cred->old_nt_hash; return nt_hash; } old_password = cli_credentials_get_old_password(cred); if (old_password) { struct samr_Password *nt_hash = talloc(mem_ctx, struct samr_Password); if (!nt_hash) { return NULL; } E_md4hash(old_password, nt_hash->hash); return nt_hash; } return NULL; } /** * Obtain the 'short' or 'NetBIOS' domain for this credentials context. * @param cred credentials context * @retval The domain set on this context. * @note Return value will never be NULL except by programmer error. */ _PUBLIC_ const char *cli_credentials_get_domain(struct cli_credentials *cred) { if (cred->machine_account_pending) { cli_credentials_set_machine_account(cred, cred->machine_account_pending_lp_ctx); } if (cred->domain_obtained == CRED_CALLBACK && !cred->callback_running) { cred->callback_running = true; cred->domain = cred->domain_cb(cred); cred->callback_running = false; if (cred->domain_obtained == CRED_CALLBACK) { cred->domain_obtained = CRED_CALLBACK_RESULT; cli_credentials_invalidate_ccache(cred, cred->domain_obtained); } } return cred->domain; } _PUBLIC_ bool cli_credentials_set_domain(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained) { if (obtained >= cred->domain_obtained) { /* it is important that the domain be in upper case, * particularly for the sensitive NTLMv2 * calculations */ cred->domain = strupper_talloc(cred, val); cred->domain_obtained = obtained; /* setting domain does not mean we have to invalidate ccache * because domain in not used for Kerberos operations. * If ccache invalidation is required, one will anyway specify * a password to kinit, and that will force invalidation of the ccache */ return true; } return false; } bool cli_credentials_set_domain_callback(struct cli_credentials *cred, const char *(*domain_cb) (struct cli_credentials *)) { if (cred->domain_obtained < CRED_CALLBACK) { cred->domain_cb = domain_cb; cred->domain_obtained = CRED_CALLBACK; return true; } return false; } /** * Obtain the Kerberos realm for this credentials context. * @param cred credentials context * @retval The realm set on this context. * @note Return value will never be NULL except by programmer error. */ _PUBLIC_ const char *cli_credentials_get_realm(struct cli_credentials *cred) { if (cred->machine_account_pending) { cli_credentials_set_machine_account(cred, cred->machine_account_pending_lp_ctx); } if (cred->realm_obtained == CRED_CALLBACK && !cred->callback_running) { cred->callback_running = true; cred->realm = cred->realm_cb(cred); cred->callback_running = false; if (cred->realm_obtained == CRED_CALLBACK) { cred->realm_obtained = CRED_CALLBACK_RESULT; cli_credentials_invalidate_ccache(cred, cred->realm_obtained); } } return cred->realm; } /** * Set the realm for this credentials context, and force it to * uppercase for the sanity of our local kerberos libraries */ _PUBLIC_ bool cli_credentials_set_realm(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained) { if (obtained >= cred->realm_obtained) { cred->realm = strupper_talloc(cred, val); cred->realm_obtained = obtained; cli_credentials_invalidate_ccache(cred, cred->realm_obtained); return true; } return false; } bool cli_credentials_set_realm_callback(struct cli_credentials *cred, const char *(*realm_cb) (struct cli_credentials *)) { if (cred->realm_obtained < CRED_CALLBACK) { cred->realm_cb = realm_cb; cred->realm_obtained = CRED_CALLBACK; return true; } return false; } /** * Obtain the 'short' or 'NetBIOS' workstation name for this credentials context. * * @param cred credentials context * @retval The workstation name set on this context. * @note Return value will never be NULL except by programmer error. */ _PUBLIC_ const char *cli_credentials_get_workstation(struct cli_credentials *cred) { if (cred->workstation_obtained == CRED_CALLBACK && !cred->callback_running) { cred->callback_running = true; cred->workstation = cred->workstation_cb(cred); cred->callback_running = false; if (cred->workstation_obtained == CRED_CALLBACK) { cred->workstation_obtained = CRED_CALLBACK_RESULT; } } return cred->workstation; } _PUBLIC_ bool cli_credentials_set_workstation(struct cli_credentials *cred, const char *val, enum credentials_obtained obtained) { if (obtained >= cred->workstation_obtained) { cred->workstation = talloc_strdup(cred, val); cred->workstation_obtained = obtained; return true; } return false; } bool cli_credentials_set_workstation_callback(struct cli_credentials *cred, const char *(*workstation_cb) (struct cli_credentials *)) { if (cred->workstation_obtained < CRED_CALLBACK) { cred->workstation_cb = workstation_cb; cred->workstation_obtained = CRED_CALLBACK; return true; } return false; } /** * Given a string, typically obtained from a -U argument, parse it into domain, username, realm and password fields * * The format accepted is [domain\\]user[%password] or user[@realm][%password] * * @param credentials Credentials structure on which to set the password * @param data the string containing the username, password etc * @param obtained This enum describes how 'specified' this password is */ _PUBLIC_ void cli_credentials_parse_string(struct cli_credentials *credentials, const char *data, enum credentials_obtained obtained) { char *uname, *p; if (strcmp("%",data) == 0) { cli_credentials_set_anonymous(credentials); return; } uname = talloc_strdup(credentials, data); if ((p = strchr_m(uname,'%'))) { *p = 0; cli_credentials_set_password(credentials, p+1, obtained); } if ((p = strchr_m(uname,'@'))) { /* * We also need to set username and domain * in order to undo the effect of * cli_credentials_guess(). */ cli_credentials_set_username(credentials, uname, obtained); cli_credentials_set_domain(credentials, "", obtained); cli_credentials_set_principal(credentials, uname, obtained); *p = 0; cli_credentials_set_realm(credentials, p+1, obtained); return; } else if ((p = strchr_m(uname,'\\')) || (p = strchr_m(uname, '/')) || (p = strchr_m(uname, credentials->winbind_separator))) { const char *domain = NULL; domain = uname; *p = 0; uname = p+1; if (obtained == credentials->realm_obtained && !strequal_m(credentials->domain, domain)) { /* * We need to undo a former set with the same level * in order to get the expected result from * cli_credentials_get_principal(). * * But we only need to do that if the domain * actually changes. */ cli_credentials_set_realm(credentials, domain, obtained); } cli_credentials_set_domain(credentials, domain, obtained); } if (obtained == credentials->principal_obtained && !strequal_m(credentials->username, uname)) { /* * We need to undo a former set with the same level * in order to get the expected result from * cli_credentials_get_principal(). * * But we only need to do that if the username * actually changes. */ credentials->principal_obtained = CRED_UNINITIALISED; credentials->principal = NULL; } cli_credentials_set_username(credentials, uname, obtained); } /** * Given a a credentials structure, print it as a string * * The format output is [domain\\]user[%password] or user[@realm][%password] * * @param credentials Credentials structure on which to set the password * @param mem_ctx The memory context to place the result on */ _PUBLIC_ char *cli_credentials_get_unparsed_name(struct cli_credentials *credentials, TALLOC_CTX *mem_ctx) { const char *bind_dn = cli_credentials_get_bind_dn(credentials); const char *domain = NULL; const char *username = NULL; char *name = NULL; if (bind_dn) { name = talloc_strdup(mem_ctx, bind_dn); } else { cli_credentials_get_ntlm_username_domain(credentials, mem_ctx, &username, &domain); if (domain && domain[0]) { name = talloc_asprintf(mem_ctx, "%s\\%s", domain, username); } else { name = talloc_asprintf(mem_ctx, "%s", username); } } return name; } /** * Specifies default values for domain, workstation and realm * from the smb.conf configuration file * * @param cred Credentials structure to fill in */ _PUBLIC_ void cli_credentials_set_conf(struct cli_credentials *cred, struct loadparm_context *lp_ctx) { const char *sep = NULL; const char *realm = lpcfg_realm(lp_ctx); cli_credentials_set_username(cred, "", CRED_UNINITIALISED); if (lpcfg_parm_is_cmdline(lp_ctx, "workgroup")) { cli_credentials_set_domain(cred, lpcfg_workgroup(lp_ctx), CRED_SPECIFIED); } else { cli_credentials_set_domain(cred, lpcfg_workgroup(lp_ctx), CRED_UNINITIALISED); } if (lpcfg_parm_is_cmdline(lp_ctx, "netbios name")) { cli_credentials_set_workstation(cred, lpcfg_netbios_name(lp_ctx), CRED_SPECIFIED); } else { cli_credentials_set_workstation(cred, lpcfg_netbios_name(lp_ctx), CRED_UNINITIALISED); } if (realm != NULL && strlen(realm) == 0) { realm = NULL; } if (lpcfg_parm_is_cmdline(lp_ctx, "realm")) { cli_credentials_set_realm(cred, realm, CRED_SPECIFIED); } else { cli_credentials_set_realm(cred, realm, CRED_UNINITIALISED); } sep = lpcfg_winbind_separator(lp_ctx); if (sep != NULL && sep[0] != '\0') { cred->winbind_separator = *lpcfg_winbind_separator(lp_ctx); } } /** * Guess defaults for credentials from environment variables, * and from the configuration file * * @param cred Credentials structure to fill in */ _PUBLIC_ void cli_credentials_guess(struct cli_credentials *cred, struct loadparm_context *lp_ctx) { char *p; const char *error_string; if (lp_ctx != NULL) { cli_credentials_set_conf(cred, lp_ctx); } if (getenv("LOGNAME")) { cli_credentials_set_username(cred, getenv("LOGNAME"), CRED_GUESS_ENV); } if (getenv("USER")) { cli_credentials_parse_string(cred, getenv("USER"), CRED_GUESS_ENV); if ((p = strchr_m(getenv("USER"),'%'))) { memset(p,0,strlen(cred->password)); } } if (getenv("PASSWD")) { cli_credentials_set_password(cred, getenv("PASSWD"), CRED_GUESS_ENV); } if (getenv("PASSWD_FD")) { cli_credentials_parse_password_fd(cred, atoi(getenv("PASSWD_FD")), CRED_GUESS_FILE); } p = getenv("PASSWD_FILE"); if (p && p[0]) { cli_credentials_parse_password_file(cred, p, CRED_GUESS_FILE); } if (lp_ctx != NULL && cli_credentials_get_kerberos_state(cred) != CRED_DONT_USE_KERBEROS) { cli_credentials_set_ccache(cred, lp_ctx, NULL, CRED_GUESS_FILE, &error_string); } } /** * Attach NETLOGON credentials for use with SCHANNEL */ _PUBLIC_ void cli_credentials_set_netlogon_creds( struct cli_credentials *cred, const struct netlogon_creds_CredentialState *netlogon_creds) { TALLOC_FREE(cred->netlogon_creds); if (netlogon_creds == NULL) { return; } cred->netlogon_creds = netlogon_creds_copy(cred, netlogon_creds); } /** * Return attached NETLOGON credentials */ _PUBLIC_ struct netlogon_creds_CredentialState *cli_credentials_get_netlogon_creds(struct cli_credentials *cred) { return cred->netlogon_creds; } /** * Set NETLOGON secure channel type */ _PUBLIC_ void cli_credentials_set_secure_channel_type(struct cli_credentials *cred, enum netr_SchannelType secure_channel_type) { cred->secure_channel_type = secure_channel_type; } /** * Return NETLOGON secure chanel type */ _PUBLIC_ time_t cli_credentials_get_password_last_changed_time(struct cli_credentials *cred) { return cred->password_last_changed_time; } /** * Set NETLOGON secure channel type */ _PUBLIC_ void cli_credentials_set_password_last_changed_time(struct cli_credentials *cred, time_t last_changed_time) { cred->password_last_changed_time = last_changed_time; } /** * Return NETLOGON secure chanel type */ _PUBLIC_ enum netr_SchannelType cli_credentials_get_secure_channel_type(struct cli_credentials *cred) { return cred->secure_channel_type; } /** * Fill in a credentials structure as the anonymous user */ _PUBLIC_ void cli_credentials_set_anonymous(struct cli_credentials *cred) { cli_credentials_set_username(cred, "", CRED_SPECIFIED); cli_credentials_set_domain(cred, "", CRED_SPECIFIED); cli_credentials_set_password(cred, NULL, CRED_SPECIFIED); cli_credentials_set_principal(cred, NULL, CRED_SPECIFIED); cli_credentials_set_realm(cred, NULL, CRED_SPECIFIED); cli_credentials_set_workstation(cred, "", CRED_UNINITIALISED); cli_credentials_set_kerberos_state(cred, CRED_DONT_USE_KERBEROS); } /** * Describe a credentials context as anonymous or authenticated * @retval true if anonymous, false if a username is specified */ _PUBLIC_ bool cli_credentials_is_anonymous(struct cli_credentials *cred) { const char *username; /* if bind dn is set it's not anonymous */ if (cred->bind_dn) { return false; } if (cred->machine_account_pending) { cli_credentials_set_machine_account(cred, cred->machine_account_pending_lp_ctx); } /* if principal is set, it's not anonymous */ if ((cred->principal != NULL) && cred->principal_obtained >= cred->username_obtained) { return false; } username = cli_credentials_get_username(cred); /* Yes, it is deliberate that we die if we have a NULL pointer * here - anonymous is "", not NULL, which is 'never specified, * never guessed', ie programmer bug */ if (!username[0]) { return true; } return false; } /** * Mark the current password for a credentials struct as wrong. This will * cause the password to be prompted again (if a callback is set). * * This will decrement the number of times the password can be tried. * * @retval whether the credentials struct is finished */ _PUBLIC_ bool cli_credentials_wrong_password(struct cli_credentials *cred) { if (cred->password_obtained != CRED_CALLBACK_RESULT) { return false; } if (cred->password_tries == 0) { return false; } cred->password_tries--; if (cred->password_tries == 0) { return false; } cred->password_obtained = CRED_CALLBACK; return true; } _PUBLIC_ void cli_credentials_get_ntlm_username_domain(struct cli_credentials *cred, TALLOC_CTX *mem_ctx, const char **username, const char **domain) { if (cred->principal_obtained >= cred->username_obtained) { *domain = talloc_strdup(mem_ctx, ""); *username = cli_credentials_get_principal(cred, mem_ctx); } else { *domain = cli_credentials_get_domain(cred); *username = cli_credentials_get_username(cred); } } /** * Read a named file, and parse it for username, domain, realm and password * * @param credentials Credentials structure on which to set the password * @param file a named file to read the details from * @param obtained This enum describes how 'specified' this password is */ _PUBLIC_ bool cli_credentials_parse_file(struct cli_credentials *cred, const char *file, enum credentials_obtained obtained) { uint16_t len = 0; char *ptr, *val, *param; char **lines; int i, numlines; const char *realm = NULL; const char *domain = NULL; const char *password = NULL; const char *username = NULL; lines = file_lines_load(file, &numlines, 0, NULL); if (lines == NULL) { /* fail if we can't open the credentials file */ d_printf("ERROR: Unable to open credentials file!\n"); return false; } for (i = 0; i < numlines; i++) { len = strlen(lines[i]); if (len == 0) continue; /* break up the line into parameter & value. * will need to eat a little whitespace possibly */ param = lines[i]; if (!(ptr = strchr_m (lines[i], '='))) continue; val = ptr+1; *ptr = '\0'; /* eat leading white space */ while ((*val!='\0') && ((*val==' ') || (*val=='\t'))) val++; if (strwicmp("password", param) == 0) { password = val; } else if (strwicmp("username", param) == 0) { username = val; } else if (strwicmp("domain", param) == 0) { domain = val; } else if (strwicmp("realm", param) == 0) { realm = val; } /* * We need to readd '=' in order to let * the strlen() work in the last loop * that clears the memory. */ *ptr = '='; } if (realm != NULL && strlen(realm) != 0) { /* * only overwrite with a valid string */ cli_credentials_set_realm(cred, realm, obtained); } if (domain != NULL && strlen(domain) != 0) { /* * only overwrite with a valid string */ cli_credentials_set_domain(cred, domain, obtained); } if (password != NULL) { /* * Here we allow "". */ cli_credentials_set_password(cred, password, obtained); } if (username != NULL) { /* * The last "username" line takes preference * if the string also contains domain, realm or * password. */ cli_credentials_parse_string(cred, username, obtained); } for (i = 0; i < numlines; i++) { len = strlen(lines[i]); memset(lines[i], 0, len); } talloc_free(lines); return true; } /** * Read a named file, and parse it for a password * * @param credentials Credentials structure on which to set the password * @param file a named file to read the password from * @param obtained This enum describes how 'specified' this password is */ _PUBLIC_ bool cli_credentials_parse_password_file(struct cli_credentials *credentials, const char *file, enum credentials_obtained obtained) { int fd = open(file, O_RDONLY, 0); bool ret; if (fd < 0) { fprintf(stderr, "Error opening password file %s: %s\n", file, strerror(errno)); return false; } ret = cli_credentials_parse_password_fd(credentials, fd, obtained); close(fd); return ret; } /** * Read a file descriptor, and parse it for a password (eg from a file or stdin) * * @param credentials Credentials structure on which to set the password * @param fd open file descriptor to read the password from * @param obtained This enum describes how 'specified' this password is */ _PUBLIC_ bool cli_credentials_parse_password_fd(struct cli_credentials *credentials, int fd, enum credentials_obtained obtained) { char *p; char pass[128]; for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */ p && p - pass < sizeof(pass);) { switch (read(fd, p, 1)) { case 1: if (*p != '\n' && *p != '\0') { *++p = '\0'; /* advance p, and null-terminate pass */ break; } FALL_THROUGH; case 0: if (p - pass) { *p = '\0'; /* null-terminate it, just in case... */ p = NULL; /* then force the loop condition to become false */ break; } fprintf(stderr, "Error reading password from file descriptor " "%d: empty password\n", fd); return false; default: fprintf(stderr, "Error reading password from file descriptor %d: %s\n", fd, strerror(errno)); return false; } } cli_credentials_set_password(credentials, pass, obtained); return true; } /** * Encrypt a data blob using the session key and the negotiated encryption * algorithm * * @param state Credential state, contains the session key and algorithm * @param data Data blob containing the data to be encrypted. * */ _PUBLIC_ NTSTATUS netlogon_creds_session_encrypt( struct netlogon_creds_CredentialState *state, DATA_BLOB data) { NTSTATUS status; if (data.data == NULL || data.length == 0) { DBG_ERR("Nothing to encrypt " "data.data == NULL or data.length == 0"); return NT_STATUS_INVALID_PARAMETER; } /* * Don't crypt an all-zero password it will give away the * NETLOGON pipe session key . */ if (all_zero(data.data, data.length)) { DBG_ERR("Supplied data all zeros, could leak session key"); return NT_STATUS_INVALID_PARAMETER; } if (state->negotiate_flags & NETLOGON_NEG_SUPPORTS_AES) { status = netlogon_creds_aes_encrypt(state, data.data, data.length); } else if (state->negotiate_flags & NETLOGON_NEG_ARCFOUR) { status = netlogon_creds_arcfour_crypt(state, data.data, data.length); } else { DBG_ERR("Unsupported encryption option negotiated"); status = NT_STATUS_NOT_SUPPORTED; } if (!NT_STATUS_IS_OK(status)) { return status; } return NT_STATUS_OK; }
utf-8
1
GPL-3.0+
1992-2012 Andrew Tridgell and the Samba Team
liquid-dsp-1.3.2/examples/windowf_example.c
// // windowf_example.c // // This example demonstrates the functionality of a window buffer (also // known as a circular or ring buffer) of floating-point values. Values // are written to and read from the buffer using several different // methods. // // SEE ALSO: bufferf_example.c // wdelayf_example.c // #include <stdio.h> #include "liquid.h" int main() { // initialize vector of data for testing float v[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; float *r; // reader unsigned int i; // create window: 10 elements, initialized to 0 // w: 0 0 0 0 0 0 0 0 0 0 windowf w = windowf_create(10); // push 4 elements // w: 0 0 0 0 0 0 1 1 1 1 windowf_push(w, 1); windowf_push(w, 1); windowf_push(w, 1); windowf_push(w, 1); // push 4 more elements // w: 0 0 1 1 1 1 9 8 7 6 windowf_write(w, v, 4); // push 4 more elements // w: 1 1 9 8 7 6 3 3 3 3 windowf_push(w, 3); windowf_push(w, 3); windowf_push(w, 3); windowf_push(w, 3); // read the buffer by assigning the pointer // appropriately windowf_read(w, &r); // manual print printf("manual output:\n"); for (i=0; i<10; i++) printf("%6u : %f\n", i, r[i]); windowf_debug_print(w); // clean it up windowf_destroy(w); printf("done.\n"); return 0; }
utf-8
1
Expat
2007-2017 Joseph Gaeddert
squid-5.2/lib/ntlmauth/support_endian.h
/* * Copyright (C) 1996-2021 The Squid Software Foundation and contributors * * Squid software is distributed under GPLv2+ license and includes * contributions from numerous individuals and organizations. * Please see the COPYING and CONTRIBUTORS files for details. */ #ifndef SQUID_LIB_NTLMAUTH_SUPPORT_ENDIAN_H #define SQUID_LIB_NTLMAUTH_SUPPORT_ENDIAN_H #if HAVE_BYTESWAP_H #include <byteswap.h> #endif #if HAVE_MACHINE_BYTE_SWAP_H #include <machine/byte_swap.h> #endif #if HAVE_SYS_BSWAP_H #include <sys/bswap.h> #endif #if HAVE_ENDIAN_H #include <endian.h> #endif #if HAVE_SYS_ENDIAN_H #include <sys/endian.h> #endif /* * Macros to deal with byte swapping. These macros provide * the following interface: * * // Byte-swap * uint16_t bswap16(uint16_t); * uint32_t bswap32(uint32_t); * * // Convert from host byte order to little-endian, and vice versa. * uint16_t htole16(uint16_t); * uint32_t htole32(uint32_t); * uint16_t le16toh(uint16_t); * uint32_t le32toh(uint32_t); * * XXX: What about unusual byte orders like 3412 or 2143 ? * Never had any problems reported, so we do not worry about them. */ #if !HAVE_HTOLE16 && !defined(htole16) /* Define bswap16() in terms of bswap_16() or the hard way. */ #if !HAVE_BSWAP16 && !defined(bswap16) # if HAVE_BSWAP_16 || defined(bswap_16) # define bswap16(x) bswap_16(x) # else // 'hard way' # define bswap16(x) \ (((((uint16_t)(x)) >> 8) & 0xff) | ((((uint16_t)(x)) & 0xff) << 8)) # endif #endif /* Define htole16() in terms of bswap16(). */ # if defined(WORDS_BIGENDIAN) # define htole16(x) bswap16(x) # else # define htole16(x) (x) # endif #endif #if !HAVE_HTOLE32 && !defined(htole32) #if ! HAVE_BSWAP32 && ! defined(bswap32) /* Define bswap32() in terms of bswap_32() or the hard way. */ # if HAVE_BSWAP_32 || defined(bswap_32) # define bswap32(x) bswap_32(x) # else // 'hard way' # define bswap32(x) \ (((((uint32_t)(x)) & 0xff000000) >> 24) | \ ((((uint32_t)(x)) & 0x00ff0000) >> 8) | \ ((((uint32_t)(x)) & 0x0000ff00) << 8) | \ ((((uint32_t)(x)) & 0x000000ff) << 24)) # endif /* Define htole32() in terms of bswap32(). */ #endif # if defined(WORDS_BIGENDIAN) # define htole32(x) bswap32(x) # else # define htole32(x) (x) # endif #endif /* Define letoh*() in terms of htole*(). The swap is symmetrical. */ #if !HAVE_LE16TOH && !defined(le16toh) #define le16toh(x) htole16(x) #endif #if !HAVE_LE32TOH && !defined(le32toh) #define le32toh(x) htole32(x) #endif #endif /* SQUID_LIB_NTLMAUTH_SUPPORT_ENDIAN_H */
utf-8
1
unknown
unknown
paraview-5.10.0~rc1/VTK/ThirdParty/vtkm/vtkvtkm/vtk-m/vtkm/cont/CellSetExtrude.h
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #ifndef vtk_m_cont_CellSetExtrude_h #define vtk_m_cont_CellSetExtrude_h #include <vtkm/TopologyElementTag.h> #include <vtkm/cont/ArrayHandle.h> #include <vtkm/cont/ArrayHandleCounting.h> #include <vtkm/cont/ArrayHandleXGCCoordinates.h> #include <vtkm/cont/CellSet.h> #include <vtkm/cont/Invoker.h> #include <vtkm/exec/ConnectivityExtrude.h> #include <vtkm/exec/arg/ThreadIndicesExtrude.h> namespace vtkm { namespace cont { namespace detail { template <typename VisitTopology, typename IncidentTopology> struct CellSetExtrudeConnectivityChooser; template <> struct CellSetExtrudeConnectivityChooser<vtkm::TopologyElementTagCell, vtkm::TopologyElementTagPoint> { using ExecConnectivityType = vtkm::exec::ConnectivityExtrude; }; template <> struct CellSetExtrudeConnectivityChooser<vtkm::TopologyElementTagPoint, vtkm::TopologyElementTagCell> { using ExecConnectivityType = vtkm::exec::ReverseConnectivityExtrude; }; } // namespace detail class VTKM_CONT_EXPORT CellSetExtrude : public CellSet { public: VTKM_CONT CellSetExtrude(); VTKM_CONT CellSetExtrude(const vtkm::cont::ArrayHandle<vtkm::Int32>& conn, vtkm::Int32 numberOfPointsPerPlane, vtkm::Int32 numberOfPlanes, const vtkm::cont::ArrayHandle<vtkm::Int32>& nextNode, bool periodic); VTKM_CONT CellSetExtrude(const CellSetExtrude& src); VTKM_CONT CellSetExtrude(CellSetExtrude&& src) noexcept; VTKM_CONT CellSetExtrude& operator=(const CellSetExtrude& src); VTKM_CONT CellSetExtrude& operator=(CellSetExtrude&& src) noexcept; virtual ~CellSetExtrude() override; vtkm::Int32 GetNumberOfPlanes() const; vtkm::Id GetNumberOfCells() const override; vtkm::Id GetNumberOfPoints() const override; vtkm::Id GetNumberOfFaces() const override; vtkm::Id GetNumberOfEdges() const override; VTKM_CONT vtkm::Id2 GetSchedulingRange(vtkm::TopologyElementTagCell) const; VTKM_CONT vtkm::Id2 GetSchedulingRange(vtkm::TopologyElementTagPoint) const; vtkm::UInt8 GetCellShape(vtkm::Id id) const override; vtkm::IdComponent GetNumberOfPointsInCell(vtkm::Id id) const override; void GetCellPointIds(vtkm::Id id, vtkm::Id* ptids) const override; std::shared_ptr<CellSet> NewInstance() const override; void DeepCopy(const CellSet* src) override; void PrintSummary(std::ostream& out) const override; void ReleaseResourcesExecution() override; const vtkm::cont::ArrayHandle<vtkm::Int32>& GetConnectivityArray() const { return this->Connectivity; } vtkm::Int32 GetNumberOfPointsPerPlane() const { return this->NumberOfPointsPerPlane; } const vtkm::cont::ArrayHandle<vtkm::Int32>& GetNextNodeArray() const { return this->NextNode; } bool GetIsPeriodic() const { return this->IsPeriodic; } template <vtkm::IdComponent NumIndices> VTKM_CONT void GetIndices(vtkm::Id index, vtkm::Vec<vtkm::Id, NumIndices>& ids) const; VTKM_CONT void GetIndices(vtkm::Id index, vtkm::cont::ArrayHandle<vtkm::Id>& ids) const; template <typename VisitTopology, typename IncidentTopology> using ExecConnectivityType = typename detail::CellSetExtrudeConnectivityChooser<VisitTopology, IncidentTopology>::ExecConnectivityType; template <typename DeviceAdapter, typename VisitTopology, typename IncidentTopology> struct VTKM_DEPRECATED( 1.6, "Replace ExecutionTypes<D, V, I>::ExecObjectType with ExecConnectivityType<V, I>.") ExecutionTypes { using ExecObjectType = ExecConnectivityType<VisitTopology, IncidentTopology>; }; vtkm::exec::ConnectivityExtrude PrepareForInput(vtkm::cont::DeviceAdapterId, vtkm::TopologyElementTagCell, vtkm::TopologyElementTagPoint, vtkm::cont::Token&) const; vtkm::exec::ReverseConnectivityExtrude PrepareForInput(vtkm::cont::DeviceAdapterId, vtkm::TopologyElementTagPoint, vtkm::TopologyElementTagCell, vtkm::cont::Token&) const; VTKM_DEPRECATED(1.6, "Provide a vtkm::cont::Token object when calling PrepareForInput.") vtkm::exec::ConnectivityExtrude PrepareForInput( vtkm::cont::DeviceAdapterId device, vtkm::TopologyElementTagCell visitTopology, vtkm::TopologyElementTagPoint incidentTopology) const { vtkm::cont::Token token; return this->PrepareForInput(device, visitTopology, incidentTopology, token); } VTKM_DEPRECATED(1.6, "Provide a vtkm::cont::Token object when calling PrepareForInput.") vtkm::exec::ReverseConnectivityExtrude PrepareForInput( vtkm::cont::DeviceAdapterId device, vtkm::TopologyElementTagPoint visitTopology, vtkm::TopologyElementTagCell incidentTopology) const { vtkm::cont::Token token; return this->PrepareForInput(device, visitTopology, incidentTopology, token); } private: void BuildReverseConnectivity(); bool IsPeriodic; vtkm::Int32 NumberOfPointsPerPlane; vtkm::Int32 NumberOfCellsPerPlane; vtkm::Int32 NumberOfPlanes; vtkm::cont::ArrayHandle<vtkm::Int32> Connectivity; vtkm::cont::ArrayHandle<vtkm::Int32> NextNode; bool ReverseConnectivityBuilt; vtkm::cont::ArrayHandle<vtkm::Int32> RConnectivity; vtkm::cont::ArrayHandle<vtkm::Int32> ROffsets; vtkm::cont::ArrayHandle<vtkm::Int32> RCounts; vtkm::cont::ArrayHandle<vtkm::Int32> PrevNode; }; template <typename T> CellSetExtrude make_CellSetExtrude(const vtkm::cont::ArrayHandle<vtkm::Int32>& conn, const vtkm::cont::ArrayHandleXGCCoordinates<T>& coords, const vtkm::cont::ArrayHandle<vtkm::Int32>& nextNode, bool periodic = true) { return CellSetExtrude{ conn, coords.GetNumberOfPointsPerPlane(), coords.GetNumberOfPlanes(), nextNode, periodic }; } template <typename T> CellSetExtrude make_CellSetExtrude(const std::vector<vtkm::Int32>& conn, const vtkm::cont::ArrayHandleXGCCoordinates<T>& coords, const std::vector<vtkm::Int32>& nextNode, bool periodic = true) { return CellSetExtrude{ vtkm::cont::make_ArrayHandle(conn, vtkm::CopyFlag::On), static_cast<vtkm::Int32>(coords.GetNumberOfPointsPerPlane()), static_cast<vtkm::Int32>(coords.GetNumberOfPlanes()), vtkm::cont::make_ArrayHandle(nextNode, vtkm::CopyFlag::On), periodic }; } template <typename T> CellSetExtrude make_CellSetExtrude(std::vector<vtkm::Int32>&& conn, const vtkm::cont::ArrayHandleXGCCoordinates<T>& coords, std::vector<vtkm::Int32>&& nextNode, bool periodic = true) { return CellSetExtrude{ vtkm::cont::make_ArrayHandleMove(std::move(conn)), static_cast<vtkm::Int32>(coords.GetNumberOfPointsPerPlane()), static_cast<vtkm::Int32>(coords.GetNumberOfPlanes()), vtkm::cont::make_ArrayHandleMove(std::move(nextNode)), periodic }; } } } // vtkm::cont //============================================================================= // Specializations of serialization related classes /// @cond SERIALIZATION namespace vtkm { namespace cont { template <> struct SerializableTypeString<vtkm::cont::CellSetExtrude> { static VTKM_CONT const std::string& Get() { static std::string name = "CS_Extrude"; return name; } }; } } // vtkm::cont namespace mangled_diy_namespace { template <> struct Serialization<vtkm::cont::CellSetExtrude> { private: using Type = vtkm::cont::CellSetExtrude; public: static VTKM_CONT void save(BinaryBuffer& bb, const Type& cs) { vtkmdiy::save(bb, cs.GetNumberOfPointsPerPlane()); vtkmdiy::save(bb, cs.GetNumberOfPlanes()); vtkmdiy::save(bb, cs.GetIsPeriodic()); vtkmdiy::save(bb, cs.GetConnectivityArray()); vtkmdiy::save(bb, cs.GetNextNodeArray()); } static VTKM_CONT void load(BinaryBuffer& bb, Type& cs) { vtkm::Int32 numberOfPointsPerPlane; vtkm::Int32 numberOfPlanes; bool isPeriodic; vtkm::cont::ArrayHandle<vtkm::Int32> conn; vtkm::cont::ArrayHandle<vtkm::Int32> nextNode; vtkmdiy::load(bb, numberOfPointsPerPlane); vtkmdiy::load(bb, numberOfPlanes); vtkmdiy::load(bb, isPeriodic); vtkmdiy::load(bb, conn); vtkmdiy::load(bb, nextNode); cs = Type{ conn, numberOfPointsPerPlane, numberOfPlanes, nextNode, isPeriodic }; } }; } // diy /// @endcond SERIALIZATION #endif // vtk_m_cont_CellSetExtrude.h
utf-8
1
BSD-3-clause
2000-2005 Kitware Inc. 28 Corporate Drive, Suite 204, Clifton Park, NY, 12065, USA. 2000-2005 Kitware Inc. 28 Corporate Drive, Suite 204, Clifton Park, NY, 12065, USA.
cc65-2.19/src/sim65/paravirt.h
/*****************************************************************************/ /* */ /* paravirt.h */ /* */ /* Paravirtualization for the sim65 6502 simulator */ /* */ /* */ /* */ /* (C) 2013-2013 Ullrich von Bassewitz */ /* Römerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #ifndef PARAVIRT_H #define PARAVIRT_H /*****************************************************************************/ /* Data */ /*****************************************************************************/ #define PARAVIRT_BASE 0xFFF4 /* Lowest address used by a paravirtualization hook */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void ParaVirtInit (unsigned aArgStart, unsigned char aSPAddr); /* Initialize the paravirtualization subsystem */ void ParaVirtHooks (CPURegs* Regs); /* Potentially execute paravirtualization hooks */ /* End of paravirt.h */ #endif
ISO-8859-1
0.73
BSD-3-zlib
2004- Oliver Schmidt <ol.sc@web.de>, 1999-2015 Ullrich von Bassewitz <uz@cc65.org>, 1989 John R. Dunning <jrd@jrd.org>
eqonomize-1.5.3/src/recurrenceeditwidget.cpp
/*************************************************************************** * Copyright (C) 2006-2008, 2014, 2016 by Hanna Knutsson * * hanna.knutsson@protonmail.com * * * * This file is part of Eqonomize!. * * * * Eqonomize! is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * Eqonomize! 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 Eqonomize!. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <QButtonGroup> #include <QBoxLayout> #include <QCheckBox> #include <QComboBox> #include <QGridLayout> #include <QGroupBox> #include <QHBoxLayout> #include <QLabel> #include <QLayout> #include <QListWidget> #include <QLineEdit> #include <QObject> #include <QPushButton> #include <QRadioButton> #include <QSpinBox> #include <QStackedWidget> #include <QVBoxLayout> #include <QDialogButtonBox> #include <QDateEdit> #include <QMessageBox> #include "budget.h" #include "eqonomizevalueedit.h" #include "recurrence.h" #include "recurrenceeditwidget.h" EditExceptionsDialog::EditExceptionsDialog(QWidget *parent) : QDialog(parent) { setWindowTitle(tr("Edit Exceptions")); setModal(true); QVBoxLayout *box1 = new QVBoxLayout(this); QGridLayout *layout = new QGridLayout(); box1->addLayout(layout); layout->addWidget(new QLabel(tr("Occurrences:"), this), 0, 0); occurrencesList = new QListWidget(this); occurrencesList->setSelectionMode(QListWidget::ExtendedSelection); layout->addWidget(occurrencesList, 1, 0); QVBoxLayout *buttonsLayout = new QVBoxLayout(); layout->addLayout(buttonsLayout, 0, 1, -1, 1); buttonsLayout->addStretch(1); addButton = new QPushButton(tr("Add Exception"), this); addButton->setEnabled(false); buttonsLayout->addWidget(addButton); deleteButton = new QPushButton(tr("Remove Exception"), this); deleteButton->setEnabled(false); buttonsLayout->addWidget(deleteButton); buttonsLayout->addStretch(1); layout->addWidget(new QLabel(tr("Exceptions:"), this), 0, 2); exceptionsList = new QListWidget(this); exceptionsList->setSelectionMode(QListWidget::ExtendedSelection); layout->addWidget(exceptionsList, 1, 2); infoLabel = new QLabel(QString("<i>") + tr("Only the first fifty occurrences are shown.") + QString("</i>"), this); infoLabel->hide(); layout->addWidget(infoLabel, 2, 0, 1, -1); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this); buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); buttonBox->button(QDialogButtonBox::Cancel)->setAutoDefault(false); buttonBox->button(QDialogButtonBox::Ok)->setShortcut(Qt::CTRL | Qt::Key_Return); connect(buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), this, SLOT(reject())); connect(buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(accept())); box1->addWidget(buttonBox); connect(occurrencesList, SIGNAL(itemSelectionChanged()), this, SLOT(onSelectionChanged())); connect(exceptionsList, SIGNAL(itemSelectionChanged()), this, SLOT(onSelectionChanged())); connect(addButton, SIGNAL(clicked()), this, SLOT(addException())); connect(deleteButton, SIGNAL(clicked()), this, SLOT(deleteException())); } EditExceptionsDialog::~EditExceptionsDialog() { } void EditExceptionsDialog::setRecurrence(Recurrence *rec) { occurrencesList->clear(); exceptionsList->clear(); if(rec) { QDate next_date = rec->firstOccurrence(); int i = 0; for(; i < 50 && next_date.isValid(); i++) { occurrencesList->addItem(QLocale().toString(next_date, QLocale::ShortFormat)); next_date = rec->nextOccurrence(next_date); } if(i == 50) { infoLabel->show(); } else { infoLabel->hide(); } for(QVector<QDate>::size_type i = 0; i < rec->exceptions.size(); i++) { exceptionsList->addItem(QLocale().toString(rec->exceptions[i], QLocale::ShortFormat)); } exceptionsList->sortItems(); } o_rec = rec; saveValues(); } void EditExceptionsDialog::modifyExceptions(Recurrence *rec) { for(int i = 0; i < exceptionsList->count(); i++) { rec->addException(QLocale().toDate(exceptionsList->item(i)->text(), QLocale::ShortFormat)); } } bool EditExceptionsDialog::validValues() { return true; } void EditExceptionsDialog::saveValues() { savedExceptions.clear(); for(int i = 0; i < exceptionsList->count(); i++) { savedExceptions.append(exceptionsList->item(i)->text()); } } void EditExceptionsDialog::restoreValues() { exceptionsList->clear(); exceptionsList->addItems(savedExceptions); } void EditExceptionsDialog::accept() { if(!validValues()) return; saveValues(); QDialog::accept(); } void EditExceptionsDialog::reject() { restoreValues(); QDialog::reject(); } void EditExceptionsDialog::onSelectionChanged() { QList<QListWidgetItem*> list = exceptionsList->selectedItems(); deleteButton->setEnabled(!list.isEmpty()); list = occurrencesList->selectedItems(); if(!list.isEmpty() && list.first() == occurrencesList->item(0)) { occurrencesList->item(0)->setSelected(false); list.removeFirst(); } addButton->setEnabled(!list.isEmpty()); } void EditExceptionsDialog::addException() { QList<QListWidgetItem*> list = occurrencesList->selectedItems(); for(int i = 0; i < list.count(); i++) { exceptionsList->addItem(list[i]->text()); delete list[i]; } exceptionsList->sortItems(); } void EditExceptionsDialog::deleteException() { QList<QListWidgetItem*> list = exceptionsList->selectedItems(); for(int i = 0; i < list.count(); i++) { delete list[i]; } modifyExceptions(o_rec); occurrencesList->clear(); QDate next_date = o_rec->firstOccurrence(); for(int i = 0; i < 50 && next_date.isValid(); i++) { occurrencesList->addItem(QLocale().toString(next_date, QLocale::ShortFormat)); next_date = o_rec->nextOccurrence(next_date); } } EditRangeDialog::EditRangeDialog(const QDate &startdate, QWidget *parent) : QDialog(parent), date(startdate) { setWindowTitle(tr("Edit Recurrence Range")); setModal(true); QVBoxLayout *box1 = new QVBoxLayout(this); QGridLayout *rangeLayout = new QGridLayout(); box1->addLayout(rangeLayout); startLabel = new QLabel(tr("Begins on: %1").arg(QLocale().toString(startdate)), this); rangeLayout->addWidget(startLabel, 0, 0, 1, 3); rangeButtonGroup = new QButtonGroup(this); foreverButton = new QRadioButton(tr("No ending date"), this); rangeButtonGroup->addButton(foreverButton); rangeLayout->addWidget(foreverButton, 1, 0, 1, 3); fixedCountButton = new QRadioButton(tr("End after"), this); rangeButtonGroup->addButton(fixedCountButton); rangeLayout->addWidget(fixedCountButton, 2, 0); fixedCountEdit = new QSpinBox(this); fixedCountEdit->setRange(1, 9999); rangeLayout->addWidget(fixedCountEdit, 2, 1); rangeLayout ->addWidget(new QLabel(tr("occurrence(s)"), this), 2, 2); endDateButton = new QRadioButton(tr("End on"), this); rangeButtonGroup->addButton(endDateButton); rangeLayout->addWidget(endDateButton, 3, 0); endDateEdit = new EqonomizeDateEdit(startdate, this); endDateEdit->setCalendarPopup(true); rangeLayout->addWidget(endDateEdit, 3, 1, 1, 2); setRecurrence(NULL); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this); buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); buttonBox->button(QDialogButtonBox::Cancel)->setAutoDefault(false); buttonBox->button(QDialogButtonBox::Ok)->setShortcut(Qt::CTRL | Qt::Key_Return); connect(buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), this, SLOT(reject())); connect(buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(accept())); box1->addWidget(buttonBox); connect(fixedCountButton, SIGNAL(toggled(bool)), fixedCountEdit, SLOT(setEnabled(bool))); connect(endDateButton, SIGNAL(toggled(bool)), endDateEdit, SLOT(setEnabled(bool))); } EditRangeDialog::~EditRangeDialog() { } void EditRangeDialog::setStartDate(const QDate &startdate) { startLabel->setText(tr("Begins on: %1").arg(QLocale().toString(startdate))); date = startdate; if(!endDateButton->isChecked() && date > endDateEdit->date()) { endDateEdit->setDate(date); } } void EditRangeDialog::setRecurrence(Recurrence *rec) { if(rec && rec->fixedOccurrenceCount() > 0) { fixedCountButton->setChecked(true); fixedCountEdit->setValue(rec->fixedOccurrenceCount()); endDateEdit->setEnabled(false); fixedCountEdit->setEnabled(true); endDateEdit->setDate(date); } else if(rec && !rec->endDate().isNull()) { endDateButton->setChecked(true); endDateEdit->setDate(rec->endDate()); endDateEdit->setEnabled(true); fixedCountEdit->setEnabled(false); fixedCountEdit->setValue(1); } else { foreverButton->setChecked(true); endDateEdit->setEnabled(false); fixedCountEdit->setEnabled(false); endDateEdit->setDate(date); fixedCountEdit->setValue(1); } saveValues(); } int EditRangeDialog::fixedCount() { if(fixedCountButton->isChecked()) { return fixedCountEdit->value(); } return -1; } QDate EditRangeDialog::endDate() { if(endDateButton->isChecked()) { return endDateEdit->date(); } return QDate(); } void EditRangeDialog::accept() { if(!validValues()) return; saveValues(); QDialog::accept(); } void EditRangeDialog::reject() { restoreValues(); QDialog::reject(); } void EditRangeDialog::saveValues() { fixedCountEdit_value = fixedCountEdit->value(); endDateEdit_value = endDateEdit->date(); if(foreverButton->isChecked()) checkedButton = foreverButton; else if(endDateButton->isChecked()) checkedButton = endDateButton; else checkedButton = fixedCountButton; } void EditRangeDialog::restoreValues() { fixedCountEdit->setValue(fixedCountEdit_value); endDateEdit->setDate(endDateEdit_value); checkedButton->setChecked(true); } bool EditRangeDialog::validValues() { if(endDateButton->isChecked()) { if(!endDateEdit->date().isValid()) { QMessageBox::critical(this, tr("Error"), tr("Invalid date.")); endDateEdit->setFocus(); endDateEdit->setCurrentSection(QDateTimeEdit::DaySection); return false; } if(endDateEdit->date() < date) { QMessageBox::critical(this, tr("Error"), tr("End date before start date.")); endDateEdit->setFocus(); endDateEdit->setCurrentSection(QDateTimeEdit::DaySection); return false; } } return true; } RecurrenceEditWidget::RecurrenceEditWidget(const QDate &startdate, Budget *budg, QWidget *parent) : QWidget(parent), date(startdate), budget(budg) { QVBoxLayout *recurrenceLayout = new QVBoxLayout(this); //recurrenceLayout->setContentsMargins(0, 0, 0, 0); recurrenceButton = new QCheckBox(tr("Enable recurrence"), this); recurrenceLayout->addWidget(recurrenceButton); ruleGroup = new QGroupBox(tr("Recurrence Rule"), this); QVBoxLayout *ruleGroup_layout = new QVBoxLayout(ruleGroup); typeCombo = new QComboBox(ruleGroup); typeCombo->setEditable(false); typeCombo->addItem(tr("Daily")); typeCombo->addItem(tr("Weekly")); typeCombo->addItem(tr("Monthly")); typeCombo->addItem(tr("Yearly")); typeCombo->setCurrentIndex(2); ruleGroup_layout->addWidget(typeCombo); ruleStack = new QStackedWidget(ruleGroup); ruleGroup_layout->addWidget(ruleStack); QWidget *dailyRuleWidget = new QWidget(ruleStack); ruleStack->addWidget(dailyRuleWidget); QWidget *weeklyRuleWidget = new QWidget(ruleStack); ruleStack->addWidget(weeklyRuleWidget); QWidget *monthlyRuleWidget = new QWidget(ruleStack); ruleStack->addWidget(monthlyRuleWidget); QWidget *yearlyRuleWidget = new QWidget(ruleStack); ruleStack->addWidget(yearlyRuleWidget); QVBoxLayout *dailyRuleLayout = new QVBoxLayout(dailyRuleWidget); QHBoxLayout *dailyFrequencyLayout = new QHBoxLayout(); dailyRuleLayout->addLayout(dailyFrequencyLayout); dailyFrequencyLayout->addWidget(new QLabel(tr("Recur every"), dailyRuleWidget)); dailyFrequencyEdit = new QSpinBox(dailyRuleWidget); dailyFrequencyEdit->setRange(1, 9999); dailyFrequencyLayout->addWidget(dailyFrequencyEdit); dailyFrequencyLayout->addWidget(new QLabel(tr("day(s)"), dailyRuleWidget)); dailyFrequencyLayout->addStretch(1); dailyRuleLayout->addStretch(1); QVBoxLayout *weeklyRuleLayout = new QVBoxLayout(weeklyRuleWidget); QHBoxLayout *weeklyFrequencyLayout = new QHBoxLayout(); weeklyRuleLayout->addLayout(weeklyFrequencyLayout); weeklyFrequencyLayout->addWidget(new QLabel(tr("Recur every"), weeklyRuleWidget)); weeklyFrequencyEdit = new QSpinBox(weeklyRuleWidget); weeklyFrequencyEdit->setRange(1, 9999); weeklyFrequencyLayout->addWidget(weeklyFrequencyEdit); weeklyFrequencyLayout->addWidget(new QLabel(tr("week(s) on:"), weeklyRuleWidget)); weeklyFrequencyLayout->addStretch(1); QHBoxLayout *weeklyDaysLayout = new QHBoxLayout(); weeklyRuleLayout->addLayout(weeklyDaysLayout); int weekStart = QLocale().firstDayOfWeek(); for(int i = 0; i < 7; ++i ) { weeklyButtons[i] = new QCheckBox(QLocale().standaloneDayName(i + 1, QLocale::ShortFormat), weeklyRuleWidget); } for(int i = weekStart - 1; i < 7; ++i ) { weeklyDaysLayout->addWidget(weeklyButtons[i]); } for(int i = 0; i < weekStart - 1; ++i ) { weeklyDaysLayout->addWidget(weeklyButtons[i]); } weeklyRuleLayout->addStretch(1); QVBoxLayout *monthlyRuleLayout = new QVBoxLayout(monthlyRuleWidget); QHBoxLayout *monthlyFrequencyLayout = new QHBoxLayout(); monthlyRuleLayout->addLayout(monthlyFrequencyLayout); monthlyFrequencyLayout->addWidget(new QLabel(tr("Recur every"), monthlyRuleWidget)); monthlyFrequencyEdit = new QSpinBox(monthlyRuleWidget); monthlyFrequencyEdit->setRange(1, 9999); monthlyFrequencyLayout->addWidget(monthlyFrequencyEdit); monthlyFrequencyLayout->addWidget(new QLabel(tr("month(s), after the start month"), monthlyRuleWidget)); monthlyFrequencyLayout->addStretch(1); QButtonGroup *monthlyButtonGroup = new QButtonGroup(this); QGridLayout *monthlyButtonLayout = new QGridLayout(); monthlyRuleLayout->addLayout(monthlyButtonLayout, 1); monthlyOnDayButton = new QRadioButton(tr("Recur on the"), monthlyRuleWidget); monthlyOnDayButton->setChecked(true); monthlyButtonGroup->addButton(monthlyOnDayButton); monthlyButtonLayout->addWidget(monthlyOnDayButton, 0, 0); QBoxLayout *monthlyDayLayout = new QHBoxLayout(); monthlyDayCombo = new QComboBox(monthlyRuleWidget); monthlyDayCombo->addItem(tr("1st")); monthlyDayCombo->addItem(tr("2nd")); monthlyDayCombo->addItem(tr("3rd")); monthlyDayCombo->addItem(tr("4th")); monthlyDayCombo->addItem(tr("5th")); monthlyDayCombo->addItem(tr("6th")); monthlyDayCombo->addItem(tr("7th")); monthlyDayCombo->addItem(tr("8th")); monthlyDayCombo->addItem(tr("9th")); monthlyDayCombo->addItem(tr("10th")); monthlyDayCombo->addItem(tr("11th")); monthlyDayCombo->addItem(tr("12th")); monthlyDayCombo->addItem(tr("13th")); monthlyDayCombo->addItem(tr("14th")); monthlyDayCombo->addItem(tr("15th")); monthlyDayCombo->addItem(tr("16th")); monthlyDayCombo->addItem(tr("17th")); monthlyDayCombo->addItem(tr("18th")); monthlyDayCombo->addItem(tr("19th")); monthlyDayCombo->addItem(tr("20th")); monthlyDayCombo->addItem(tr("21st")); monthlyDayCombo->addItem(tr("22nd")); monthlyDayCombo->addItem(tr("23rd")); monthlyDayCombo->addItem(tr("24th")); monthlyDayCombo->addItem(tr("25th")); monthlyDayCombo->addItem(tr("26th")); monthlyDayCombo->addItem(tr("27th")); monthlyDayCombo->addItem(tr("28th")); monthlyDayCombo->addItem(tr("29th")); monthlyDayCombo->addItem(tr("30th")); monthlyDayCombo->addItem(tr("31st")); monthlyDayCombo->addItem(tr("Last")); monthlyDayCombo->addItem(tr("2nd Last")); monthlyDayCombo->addItem(tr("3rd Last")); monthlyDayCombo->addItem(tr("4th Last")); monthlyDayCombo->addItem(tr("5th Last")); monthlyDayLayout->addWidget(monthlyDayCombo); monthlyDayLayout->addWidget(new QLabel(tr("day"), monthlyRuleWidget)); monthlyWeekendCombo = new QComboBox(monthlyRuleWidget); monthlyWeekendCombo->addItem(tr("possibly on weekend")); monthlyWeekendCombo->addItem(tr("but before weekend")); monthlyWeekendCombo->addItem(tr("but after weekend")); monthlyWeekendCombo->addItem(tr("on nearest weekday")); monthlyDayLayout->addWidget(monthlyWeekendCombo); monthlyDayLayout->addStretch(1); monthlyButtonLayout->addLayout(monthlyDayLayout, 0, 1); monthlyOnDayOfWeekButton = new QRadioButton(tr("Recur on the"), monthlyRuleWidget); monthlyButtonGroup->addButton(monthlyOnDayOfWeekButton); monthlyButtonLayout->addWidget(monthlyOnDayOfWeekButton, 1, 0); QBoxLayout *monthlyWeekLayout = new QHBoxLayout(); monthlyWeekCombo = new QComboBox(monthlyRuleWidget); monthlyWeekCombo->addItem(tr("1st")); monthlyWeekCombo->addItem(tr("2nd")); monthlyWeekCombo->addItem(tr("3rd")); monthlyWeekCombo->addItem(tr("4th")); monthlyWeekCombo->addItem(tr("5th")); monthlyWeekCombo->addItem(tr("Last")); monthlyWeekCombo->addItem(tr("2nd Last")); monthlyWeekCombo->addItem(tr("3rd Last")); monthlyWeekCombo->addItem(tr("4th Last")); monthlyWeekLayout->addWidget(monthlyWeekCombo); monthlyDayOfWeekCombo = new QComboBox(monthlyRuleWidget); monthlyWeekLayout->addWidget(monthlyDayOfWeekCombo); monthlyWeekLayout->addStretch(1); monthlyButtonLayout->addLayout(monthlyWeekLayout, 1, 1); monthlyRuleLayout->addStretch(1); QVBoxLayout *yearlyRuleLayout = new QVBoxLayout(yearlyRuleWidget); QHBoxLayout *yearlyFrequencyLayout = new QHBoxLayout(); yearlyRuleLayout->addLayout(yearlyFrequencyLayout); yearlyFrequencyLayout->addWidget(new QLabel(tr("Recur every"), yearlyRuleWidget)); yearlyFrequencyEdit = new QSpinBox(yearlyRuleWidget); yearlyFrequencyEdit->setRange(1, 9999); yearlyFrequencyLayout->addWidget(yearlyFrequencyEdit); yearlyFrequencyLayout->addWidget(new QLabel(tr("year(s), after the start year"), yearlyRuleWidget)); yearlyFrequencyLayout->addStretch(1); QButtonGroup *yearlyButtonGroup = new QButtonGroup(this); QGridLayout *yearlyButtonLayout = new QGridLayout(); yearlyRuleLayout->addLayout(yearlyButtonLayout, 1); yearlyOnDayOfMonthButton = new QRadioButton(tr("Recur on day", "part before XXX of 'Recur on day XXX of month YYY'"), yearlyRuleWidget); yearlyButtonGroup->addButton(yearlyOnDayOfMonthButton); yearlyOnDayOfMonthButton->setChecked(true); yearlyButtonLayout->addWidget(yearlyOnDayOfMonthButton, 0, 0); QBoxLayout *yearlyMonthLayout = new QHBoxLayout(); yearlyDayOfMonthEdit = new QSpinBox(yearlyRuleWidget); yearlyDayOfMonthEdit->setRange(1, 31); yearlyMonthLayout->addWidget(yearlyDayOfMonthEdit); yearlyMonthLayout->addWidget(new QLabel(tr("of", "part between XXX and YYY of 'Recur on day XXX of month YYY'"), yearlyRuleWidget)); yearlyMonthCombo = new QComboBox(yearlyRuleWidget); yearlyMonthLayout->addWidget(yearlyMonthCombo); yearlyWeekendCombo_month = new QComboBox(yearlyRuleWidget); yearlyWeekendCombo_month->addItem(tr("possibly on weekend")); yearlyWeekendCombo_month->addItem(tr("but before weekend")); yearlyWeekendCombo_month->addItem(tr("but after weekend")); yearlyWeekendCombo_month->addItem(tr("nearest weekend day")); yearlyMonthLayout->addWidget(yearlyWeekendCombo_month); yearlyMonthLayout->addStretch(1); yearlyButtonLayout->addLayout(yearlyMonthLayout, 0, 1); yearlyOnDayOfWeekButton = new QRadioButton(tr("On the", "Part before NNN in 'Recur on the NNN. WEEKDAY of MONTH'"), yearlyRuleWidget); yearlyButtonGroup->addButton(yearlyOnDayOfWeekButton); yearlyButtonLayout->addWidget(yearlyOnDayOfWeekButton, 1, 0); QBoxLayout *yearlyWeekLayout = new QHBoxLayout(); yearlyWeekCombo = new QComboBox(yearlyRuleWidget); yearlyWeekCombo->addItem(tr("1st")); yearlyWeekCombo->addItem(tr("2nd")); yearlyWeekCombo->addItem(tr("3rd")); yearlyWeekCombo->addItem(tr("4th")); yearlyWeekCombo->addItem(tr("5th")); yearlyWeekCombo->addItem(tr("Last")); yearlyWeekCombo->addItem(tr("2nd Last")); yearlyWeekCombo->addItem(tr("3rd Last")); yearlyWeekCombo->addItem(tr("4th Last")); yearlyWeekCombo->addItem(tr("5th Last")); yearlyWeekLayout->addWidget(yearlyWeekCombo); yearlyDayOfWeekCombo = new QComboBox(yearlyRuleWidget); yearlyWeekLayout->addWidget(yearlyDayOfWeekCombo); yearlyWeekLayout->addWidget(new QLabel(tr("of", "part between WEEKDAY and MONTH in 'Recur on NNN. WEEKDAY of MONTH'"), yearlyRuleWidget)); yearlyMonthCombo_week = new QComboBox(yearlyRuleWidget); yearlyWeekLayout->addWidget(yearlyMonthCombo_week); yearlyWeekLayout->addStretch(1); yearlyButtonLayout->addLayout(yearlyWeekLayout, 1, 1); yearlyOnDayOfYearButton = new QRadioButton(tr("Recur on day #"), yearlyRuleWidget); yearlyButtonGroup->addButton(yearlyOnDayOfYearButton); yearlyButtonLayout->addWidget(yearlyOnDayOfYearButton, 2, 0); QBoxLayout *yearlyDayLayout = new QHBoxLayout(); yearlyDayOfYearEdit = new QSpinBox(yearlyRuleWidget); yearlyDayOfYearEdit->setRange(1, 366); yearlyDayLayout->addWidget(yearlyDayOfYearEdit); yearlyDayLayout->addWidget(new QLabel(tr(" of the year", "part after NNN of 'Recur on day #NNN of the year'"), yearlyRuleWidget)); yearlyWeekendCombo_day = new QComboBox(yearlyRuleWidget); yearlyWeekendCombo_day->addItem(tr("possibly on weekend")); yearlyWeekendCombo_day->addItem(tr("but before weekend")); yearlyWeekendCombo_day->addItem(tr("but after weekend")); yearlyWeekendCombo_day->addItem(tr("nearest weekend day")); yearlyDayLayout->addWidget(yearlyWeekendCombo_day); yearlyDayLayout->addStretch(1); yearlyButtonLayout->addLayout(yearlyDayLayout, 2, 1); yearlyRuleLayout->addStretch(1); recurrenceLayout->addWidget(ruleGroup); QHBoxLayout *buttonLayout = new QHBoxLayout(); recurrenceLayout->addLayout(buttonLayout); rangeButton = new QPushButton(tr("Range…"), this); buttonLayout->addWidget(rangeButton); exceptionsButton = new QPushButton(tr("Occurrences/Exceptions…"), this); buttonLayout->addWidget(exceptionsButton); recurrenceLayout->addStretch(1); ruleStack->setCurrentIndex(2); recurrenceButton->setChecked(false); ruleGroup->setEnabled(false); rangeButton->setEnabled(false); exceptionsButton->setEnabled(false); rangeDialog = new EditRangeDialog(date, this); rangeDialog->hide(); exceptionsDialog = new EditExceptionsDialog(this); exceptionsDialog->hide(); int months = 0; QDate date = QDate::currentDate(); for(int i = 0; i < 10; i++) { int months2 = 12; if(months2 > months) { for(int i2 = months + 1; i2 <= months2; i2++) { yearlyMonthCombo_week->addItem(QLocale().monthName(i2, QLocale::LongFormat)); yearlyMonthCombo->addItem(QLocale().monthName(i2, QLocale::LongFormat)); } months = months2; } date = date.addYears(1); } for(int i = 1; i <= 7; i++) { yearlyDayOfWeekCombo->addItem(QLocale().standaloneDayName(i)); monthlyDayOfWeekCombo->addItem(QLocale().standaloneDayName(i)); } connect(typeCombo, SIGNAL(activated(int)), ruleStack, SLOT(setCurrentIndex(int))); connect(rangeButton, SIGNAL(clicked()), this, SLOT(editRange())); connect(exceptionsButton, SIGNAL(clicked()), this, SLOT(editExceptions())); connect(recurrenceButton, SIGNAL(toggled(bool)), ruleGroup, SLOT(setEnabled(bool))); connect(recurrenceButton, SIGNAL(toggled(bool)), rangeButton, SLOT(setEnabled(bool))); connect(recurrenceButton, SIGNAL(toggled(bool)), exceptionsButton, SLOT(setEnabled(bool))); } RecurrenceEditWidget::~RecurrenceEditWidget() { } void RecurrenceEditWidget::editExceptions() { Recurrence *rec = createRecurrence(); exceptionsDialog->setRecurrence(rec); exceptionsDialog->exec(); exceptionsDialog->hide(); delete rec; } void RecurrenceEditWidget::editRange() { rangeDialog->exec(); rangeDialog->hide(); } void RecurrenceEditWidget::setRecurrence(Recurrence *rec) { rangeDialog->setRecurrence(rec); exceptionsDialog->setRecurrence(rec); if(!rec) { recurrenceButton->setChecked(false); recurrenceButton->setChecked(false); ruleGroup->setEnabled(false); rangeButton->setEnabled(false); exceptionsButton->setEnabled(false); return; } switch(rec->type()) { case RECURRENCE_TYPE_DAILY: { DailyRecurrence *drec = (DailyRecurrence*) rec; dailyFrequencyEdit->setValue(drec->frequency()); typeCombo->setCurrentIndex(0); break; } case RECURRENCE_TYPE_WEEKLY: { WeeklyRecurrence *wrec = (WeeklyRecurrence*) rec; weeklyFrequencyEdit->setValue(wrec->frequency()); for(int i = 0; i < 7; i++) { weeklyButtons[i]->setChecked(wrec->dayOfWeek(i + 1)); } typeCombo->setCurrentIndex(1); break; } case RECURRENCE_TYPE_MONTHLY: { MonthlyRecurrence *mrec = (MonthlyRecurrence*) rec; monthlyFrequencyEdit->setValue(mrec->frequency()); if(mrec->dayOfWeek() > 0) { monthlyOnDayOfWeekButton->setChecked(true); monthlyDayOfWeekCombo->setCurrentIndex(mrec->dayOfWeek() - 1); int week = mrec->week(); if(week <= 0) week = 6 - week; monthlyWeekCombo->setCurrentIndex(week - 1); } else { monthlyOnDayButton->setChecked(true); int day = mrec->day(); if(day <= 0) day = 32 - day; monthlyDayCombo->setCurrentIndex(day - 1); monthlyWeekendCombo->setCurrentIndex(mrec->weekendHandling()); } typeCombo->setCurrentIndex(2); break; } case RECURRENCE_TYPE_YEARLY: { YearlyRecurrence *yrec = (YearlyRecurrence*) rec; yearlyFrequencyEdit->setValue(yrec->frequency()); if(yrec->dayOfYear() > 0) { yearlyOnDayOfYearButton->setChecked(true); yearlyDayOfYearEdit->setValue(yrec->dayOfYear()); yearlyWeekendCombo_day->setCurrentIndex(yrec->weekendHandling()); yearlyWeekendCombo_month->setCurrentIndex(yrec->weekendHandling()); } else if(yrec->dayOfWeek() > 0) { yearlyOnDayOfWeekButton->setChecked(true); yearlyDayOfWeekCombo->setCurrentIndex(yrec->dayOfWeek() - 1); int week = yrec->week(); if(week <= 0) week = 6 - week; yearlyWeekCombo->setCurrentIndex(week - 1); yearlyMonthCombo_week->setCurrentIndex(yrec->month() - 1); } else { yearlyOnDayOfMonthButton->setChecked(true); yearlyDayOfMonthEdit->setValue(yrec->dayOfMonth()); yearlyMonthCombo->setCurrentIndex(yrec->month() - 1); yearlyWeekendCombo_day->setCurrentIndex(yrec->weekendHandling()); yearlyWeekendCombo_month->setCurrentIndex(yrec->weekendHandling()); } typeCombo->setCurrentIndex(3); break; } } ruleStack->setCurrentIndex(typeCombo->currentIndex()); recurrenceButton->setChecked(true); ruleGroup->setEnabled(true); rangeButton->setEnabled(true); exceptionsButton->setEnabled(true); } Recurrence *RecurrenceEditWidget::createRecurrence() { if(!recurrenceButton->isChecked() || !validValues()) return NULL; switch(typeCombo->currentIndex()) { case 0: { DailyRecurrence *rec = new DailyRecurrence(budget); rec->set(date, rangeDialog->endDate(), dailyFrequencyEdit->value(), rangeDialog->fixedCount()); exceptionsDialog->modifyExceptions(rec); return rec; } case 1: { WeeklyRecurrence *rec = new WeeklyRecurrence(budget); rec->set(date, rangeDialog->endDate(), weeklyButtons[0]->isChecked(), weeklyButtons[1]->isChecked(), weeklyButtons[2]->isChecked(), weeklyButtons[3]->isChecked(), weeklyButtons[4]->isChecked(), weeklyButtons[5]->isChecked(), weeklyButtons[6]->isChecked(), weeklyFrequencyEdit->value(), rangeDialog->fixedCount()); exceptionsDialog->modifyExceptions(rec); return rec; } case 2: { MonthlyRecurrence *rec = new MonthlyRecurrence(budget); if(monthlyOnDayButton->isChecked()) { int day = monthlyDayCombo->currentIndex() + 1; if(day > 31) day = 32 - day; rec->setOnDay(date, rangeDialog->endDate(), day, (WeekendHandling) monthlyWeekendCombo->currentIndex(), monthlyFrequencyEdit->value(), rangeDialog->fixedCount()); } else { int week = monthlyWeekCombo->currentIndex() + 1; if(week > 5) week = 6 - week; rec->setOnDayOfWeek(date, rangeDialog->endDate(), monthlyDayOfWeekCombo->currentIndex() + 1, week, monthlyFrequencyEdit->value(), rangeDialog->fixedCount()); } exceptionsDialog->modifyExceptions(rec); return rec; } case 3: { YearlyRecurrence *rec = new YearlyRecurrence(budget); if(yearlyOnDayOfMonthButton->isChecked()) { rec->setOnDayOfMonth(date, rangeDialog->endDate(), yearlyMonthCombo->currentIndex() + 1, yearlyDayOfMonthEdit->value(), (WeekendHandling) yearlyWeekendCombo_month->currentIndex(), yearlyFrequencyEdit->value(), rangeDialog->fixedCount()); } else if(yearlyOnDayOfWeekButton->isChecked()) { int week = yearlyWeekCombo->currentIndex() + 1; if(week > 5) week = 6 - week; rec->setOnDayOfWeek(date, rangeDialog->endDate(), yearlyMonthCombo_week->currentIndex() + 1, yearlyDayOfWeekCombo->currentIndex() + 1, week, yearlyFrequencyEdit->value(), rangeDialog->fixedCount()); } else { rec->setOnDayOfYear(date, rangeDialog->endDate(), yearlyDayOfYearEdit->value(), (WeekendHandling) yearlyWeekendCombo_day->currentIndex(), yearlyFrequencyEdit->value(), rangeDialog->fixedCount()); } exceptionsDialog->modifyExceptions(rec); return rec; } } return NULL; } bool RecurrenceEditWidget::validValues() { if(!recurrenceButton->isChecked()) return true; switch(typeCombo->currentIndex()) { case 0: { break; } case 1: { bool b = false; for(int i = 0; i < 7; i++) { if(weeklyButtons[i]->isChecked()) { b = true; break; } } if(!b) { QMessageBox::critical(this, tr("Error"), tr("No day of week selected for weekly recurrence.")); weeklyButtons[0]->setFocus(); return false; } break; } case 2: { int i_frequency = monthlyFrequencyEdit->value(); if(i_frequency % 12 == 0) { int i_dayofmonth = monthlyDayCombo->currentIndex() + 1; int i_month = date.month(); if(i_dayofmonth <= 31 && ((i_month == 2 && i_dayofmonth > 29) || (i_dayofmonth > 30 && (i_month == 4 || i_month == 6 || i_month == 9 || i_month == 11)))) { QMessageBox::critical(this, tr("Error"), tr("Selected day will never occur with selected frequency and start date.")); monthlyDayCombo->setFocus(); return false; } } break; } case 3: { if(yearlyOnDayOfMonthButton->isChecked()) { int i_frequency = yearlyFrequencyEdit->value(); int i_dayofmonth = yearlyDayOfMonthEdit->value(); int i_month = yearlyMonthCombo->currentIndex() + 1; if(IS_GREGORIAN_CALENDAR) { if((i_month == 2 && i_dayofmonth > 29) || (i_dayofmonth > 30 && (i_month == 4 || i_month == 6 || i_month == 9 || i_month == 11))) { QMessageBox::critical(this, tr("Error"), tr("Selected day does not exist in selected month.")); yearlyDayOfMonthEdit->setFocus(); return false; } else if(i_month != 2 || i_dayofmonth < 29) { break; } } QDate nextdate; nextdate.setDate(date.year(), i_month, 1); if(i_dayofmonth > nextdate.daysInMonth()) { int i = 10; do { if(i == 0) { QMessageBox::critical(this, tr("Error"), tr("Selected day will never occur with selected frequency and start date.")); yearlyDayOfMonthEdit->setFocus(); return false; } nextdate = nextdate.addYears(i_frequency); nextdate.setDate(nextdate.year(), i_month, 1); i--; } while(i_dayofmonth > nextdate.daysInMonth()); } } else if(yearlyOnDayOfYearButton->isChecked()) { int i_frequency = yearlyFrequencyEdit->value(); int i_dayofyear = yearlyDayOfYearEdit->value(); if(i_dayofyear > date.daysInYear()) { QDate nextdate = date; int i = 10; do { if(i == 0) { QMessageBox::critical(this, tr("Error"), tr("Selected day will never occur with selected frequency and start date.")); yearlyDayOfYearEdit->setFocus(); return false; } nextdate = nextdate.addYears(i_frequency); i--; } while(i_dayofyear > nextdate.daysInYear()); } } break; } } if(!rangeDialog->validValues()) return false; if(!exceptionsDialog->validValues()) return false; return true; } void RecurrenceEditWidget::setStartDate(const QDate &startdate) { if(!startdate.isValid()) return; date = startdate; rangeDialog->setStartDate(date); }
utf-8
1
GPL-3+
2006-2022 Hanna Knutsson <hanna.knutsson@protonmail.com>
grpc-1.30.2/src/core/lib/iomgr/poller/eventmanager_interface.h
/* * * Copyright 2019 gRPC authors. * * 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. * */ #ifndef GRPC_CORE_LIB_IOMGR_POLLER_EVENTMANAGER_INTERFACE_H #define GRPC_CORE_LIB_IOMGR_POLLER_EVENTMANAGER_INTERFACE_H namespace grpc { namespace experimental { class BaseEventManagerInterface { public: virtual ~BaseEventManagerInterface() {} }; class EpollEventManagerInterface : public BaseEventManagerInterface {}; } // namespace experimental } // namespace grpc #endif /* GRPC_CORE_LIB_IOMGR_POLLER_EVENTMANAGER_INTERFACE_H */
utf-8
1
Apache-2.0
2008, Google Inc. 2015, Google Inc. 2015-2016, Google Inc. 2016, Google Inc. 2017, Google Inc. Esben Mose Hansen, Ange Optimization ApS 2009, Kitware, Inc. 2009-2011, Philip Lowman <philip@yhbt.com> 2016 The Chromium Authors. All rights reserved.
gecode-6.2.0/gecode/int/branch/cbs.hpp
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Samuel Gagnon <samuel.gagnon92@gmail.com> * * Copyright: * Samuel Gagnon, 2018 * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.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 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. * */ #ifdef GECODE_HAS_CBS namespace Gecode { namespace Int { namespace Branch { template<class View> forceinline void CBSBrancher<View>::VarIdToPos::init() { assert(object() == nullptr); object(new VarIdToPosO()); } template<class View> forceinline bool CBSBrancher<View>::VarIdToPos::isIn(unsigned int var_id) const { auto *hm = &static_cast<VarIdToPosO*>(object())->_varIdToPos; return hm->find(var_id) != hm->end(); } template<class View> forceinline int CBSBrancher<View>::VarIdToPos::operator[](unsigned int i) const { return static_cast<VarIdToPosO*>(object())->_varIdToPos.at(i); } template<class View> forceinline void CBSBrancher<View>::VarIdToPos::insert(unsigned int var_id, unsigned int pos) { static_cast<VarIdToPosO*>(object()) ->_varIdToPos.insert(std::make_pair(var_id, pos)); } template<class View> CBSBrancher<View>::CBSBrancher(Home home, ViewArray<View>& x0) : Brancher(home), x(x0), logProp(typename decltype(logProp)::size_type(), typename decltype(logProp)::hasher(), typename decltype(logProp)::key_equal(), typename decltype(logProp)::allocator_type(home)) { home.notice(*this, AP_DISPOSE); varIdToPos.init(); for (int i=0; i<x.size(); i++) varIdToPos.insert(x[i].id(), i); } template<class View> forceinline void CBSBrancher<View>::post(Home home, ViewArray<View>& x) { (void) new (home) CBSBrancher(home,x); } template<class View> Actor* CBSBrancher<View>::copy(Space& home) { return new (home) CBSBrancher(home,*this); } template<class View> forceinline size_t CBSBrancher<View>::dispose(Space& home) { home.ignore(*this, AP_DISPOSE); varIdToPos.~VarIdToPos(); (void) Brancher::dispose(home); return sizeof(*this); } template<class View> CBSBrancher<View>::CBSBrancher(Space& home, CBSBrancher& b) : Brancher(home,b), varIdToPos(b.varIdToPos), logProp(b.logProp.begin(), b.logProp.end(), typename decltype(logProp)::size_type(), typename decltype(logProp)::hasher(), typename decltype(logProp)::key_equal(), typename decltype(logProp)::allocator_type(home)) { x.update(home,b.x); } template<class View> bool CBSBrancher<View>::status(const Space& home) const { for (Propagators p(home, PropagatorGroup::all); p(); ++p) { // Sum of domains of all variable in propagator unsigned int domsum; // Same, but for variables that are also in this brancher. unsigned int domsum_b; // If the propagator doesn't support counting-based search, domsum and // domsum_b are going to be equal to 0. p.propagator().domainsizesum([this](unsigned int var_id) { return inbrancher(var_id); }, domsum, domsum_b); if (domsum_b > 0) return true; } return false; } template<class View> forceinline bool CBSBrancher<View>::inbrancher(unsigned int varId) const { return varIdToPos.isIn(varId); } template<class View> const Choice* CBSBrancher<View>::choice(Space& home) { // Structure for keeping the maximum solution density assignment struct { unsigned int var_id; int val; double dens; } maxSD{0, 0, -1}; // Lambda we pass to propagators via solndistrib to query solution densities auto SendMarginal = [this](unsigned int prop_id, unsigned int var_id, int val, double dens) { if (logProp[prop_id].dens < dens) { logProp[prop_id].var_id = var_id; logProp[prop_id].val = val; logProp[prop_id].dens = dens; } }; for (auto& kv : logProp) kv.second.visited = false; for (Propagators p(home, PropagatorGroup::all); p(); ++p) { unsigned int prop_id = p.propagator().id(); unsigned int domsum; unsigned int domsum_b; p.propagator().domainsizesum([this](unsigned int var_id) { return inbrancher(var_id); }, domsum, domsum_b); // If the propagator doesn't share any unasigned variables with this // brancher, we continue and it will be deleted from the log afterwards. if (domsum_b == 0) continue; // New propagators can be created as we solve the problem. If this is the // case we create a new entry in the log. if (logProp.find(prop_id) == logProp.end()) logProp.insert(std::make_pair(prop_id, PropInfo{0, 0, 0, -1, true})); else logProp[prop_id].visited = true; // If the domain size sum of all variables in the propagator has changed // since the last time we called this function, we need to recompute // solution densities. Otherwise, we can reuse them. if (logProp[prop_id].domsum != domsum) { logProp[prop_id].dens = -1; // Solution density computation p.propagator().solndistrib(home, SendMarginal); logProp[prop_id].domsum = domsum; } } // We delete unvisited propagators from the log and look for the highest // solution density across all propagators. for (const auto& kv : logProp) { unsigned int prop_id = kv.first; const PropInfo& info = kv.second; if (!info.visited) logProp.erase(prop_id); else if (info.dens > maxSD.dens) maxSD = {info.var_id, info.val, info.dens}; } assert(maxSD.dens != -1); assert(!x[varIdToPos[maxSD.var_id]].assigned()); return new PosValChoice<int>(*this, 2, varIdToPos[maxSD.var_id], maxSD.val); } template<class View> forceinline const Choice* CBSBrancher<View>::choice(const Space&, Archive& e) { int pos, val; e >> pos >> val; return new PosValChoice<int>(*this, 2, pos, val); } template<class View> forceinline ExecStatus CBSBrancher<View>::commit(Space& home, const Choice& c, unsigned int a) { const auto& pvc = static_cast<const PosValChoice<int>&>(c); int pos = pvc.pos().pos; int val = pvc.val(); if (a == 0) return me_failed(x[pos].eq(home, val)) ? ES_FAILED : ES_OK; else return me_failed(x[pos].nq(home, val)) ? ES_FAILED : ES_OK; } template<class View> forceinline void CBSBrancher<View>::print(const Space&, const Choice& c, unsigned int a, std::ostream& o) const { const auto& pvc = static_cast<const PosValChoice<int>&>(c); int pos=pvc.pos().pos, val=pvc.val(); if (a == 0) o << "x[" << pos << "] = " << val; else o << "x[" << pos << "] != " << val; } }}} #endif // STATISTICS: int-branch
utf-8
1
unknown
unknown
proj-8.2.1/src/projections/nell.cpp
#define PJ_LIB__ #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(nell, "Nell") "\n\tPCyl, Sph"; #define MAX_ITER 10 #define LOOP_TOL 1e-7 static PJ_XY nell_s_forward (PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0,0.0}; int i; (void) P; const double k = 2. * sin(lp.phi); const double phi_pow_2 = lp.phi * lp.phi; lp.phi *= 1.00371 + phi_pow_2 * (-0.0935382 + phi_pow_2 * -0.011412); for (i = MAX_ITER; i ; --i) { const double V = (lp.phi + sin(lp.phi) - k) / (1. + cos(lp.phi)); lp.phi -= V; if (fabs(V) < LOOP_TOL) break; } xy.x = 0.5 * lp.lam * (1. + cos(lp.phi)); xy.y = lp.phi; return xy; } static PJ_LP nell_s_inverse (PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0,0.0}; lp.lam = 2. * xy.x / (1. + cos(xy.y)); lp.phi = aasin(P->ctx,0.5 * (xy.y + sin(xy.y))); return lp; } PJ *PROJECTION(nell) { P->es = 0; P->inv = nell_s_inverse; P->fwd = nell_s_forward; return P; }
utf-8
1
Expat
2008-2021, Even Rouault <even dot rouault at mines-paris dot org> 2012-2021, Charles Karney <charles@karney.com> 2021, Marcus Elia <marcus at geopi.pe> 2021, Toby C Wilkinson 2016-2020, Kristian Evers 2016-2018, Thomas Knudsen 2016-2018, SDFE 2011-2018, Open Geospatial Consortium, Inc 2018, Google Inc. 2017, Lukasz Komsta 2016, Karsten Engsager 2015, Drazen Tutic 2015, Lovro Gradiser 2000-2002, 2009-2010, 2012-2013, Frank Warmerdam <warmerdam@pobox.com> 2011-2012, Martin Lambers <marlam@marlam.de> 2012, Martin Raspaud 2011, Martin Desruisseaux 1995, 2003-2004, 2006, Gerald I. Evenden 2006, Andrey Kiselev 2005, Andrea Antonello 2001, Thomas Flemming <tf@ttqv.com>
thunderbird-91.6.0/layout/mathml/nsMathMLContainerFrame.cpp
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsMathMLContainerFrame.h" #include "gfxContext.h" #include "gfxUtils.h" #include "mozilla/Likely.h" #include "mozilla/PresShell.h" #include "mozilla/dom/MutationEventBinding.h" #include "mozilla/gfx/2D.h" #include "nsLayoutUtils.h" #include "nsPresContext.h" #include "nsNameSpaceManager.h" #include "nsGkAtoms.h" #include "nsDisplayList.h" #include "nsIScriptError.h" #include "nsContentUtils.h" #include "mozilla/dom/MathMLElement.h" using namespace mozilla; using namespace mozilla::gfx; // // nsMathMLContainerFrame implementation // NS_QUERYFRAME_HEAD(nsMathMLContainerFrame) NS_QUERYFRAME_ENTRY(nsIMathMLFrame) NS_QUERYFRAME_ENTRY(nsMathMLContainerFrame) NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame) // ============================================================================= // error handlers // provide a feedback to the user when a frame with bad markup can not be // rendered nsresult nsMathMLContainerFrame::ReflowError(DrawTarget* aDrawTarget, ReflowOutput& aDesiredSize) { // clear all other flags and record that there is an error with this frame mEmbellishData.flags = 0; mPresentationData.flags = NS_MATHML_ERROR; /////////////// // Set font RefPtr<nsFontMetrics> fm = nsLayoutUtils::GetInflatedFontMetricsForFrame(this); // bounding metrics nsAutoString errorMsg; errorMsg.AssignLiteral("invalid-markup"); mBoundingMetrics = nsLayoutUtils::AppUnitBoundsOfString( errorMsg.get(), errorMsg.Length(), *fm, aDrawTarget); // reflow metrics WritingMode wm = aDesiredSize.GetWritingMode(); aDesiredSize.SetBlockStartAscent(fm->MaxAscent()); nscoord descent = fm->MaxDescent(); aDesiredSize.BSize(wm) = aDesiredSize.BlockStartAscent() + descent; aDesiredSize.ISize(wm) = mBoundingMetrics.width; // Also return our bounding metrics aDesiredSize.mBoundingMetrics = mBoundingMetrics; return NS_OK; } class nsDisplayMathMLError : public nsPaintedDisplayItem { public: nsDisplayMathMLError(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame) : nsPaintedDisplayItem(aBuilder, aFrame) { MOZ_COUNT_CTOR(nsDisplayMathMLError); } MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayMathMLError) virtual void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override; NS_DISPLAY_DECL_NAME("MathMLError", TYPE_MATHML_ERROR) }; void nsDisplayMathMLError::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) { // Set color and font ... RefPtr<nsFontMetrics> fm = nsLayoutUtils::GetFontMetricsForFrame(mFrame, 1.0f); nsPoint pt = ToReferenceFrame(); int32_t appUnitsPerDevPixel = mFrame->PresContext()->AppUnitsPerDevPixel(); DrawTarget* drawTarget = aCtx->GetDrawTarget(); Rect rect = NSRectToSnappedRect(nsRect(pt, mFrame->GetSize()), appUnitsPerDevPixel, *drawTarget); ColorPattern red(ToDeviceColor(sRGBColor(1.f, 0.f, 0.f, 1.f))); drawTarget->FillRect(rect, red); aCtx->SetColor(sRGBColor::OpaqueWhite()); nscoord ascent = fm->MaxAscent(); constexpr auto errorMsg = u"invalid-markup"_ns; nsLayoutUtils::DrawUniDirString(errorMsg.get(), uint32_t(errorMsg.Length()), nsPoint(pt.x, pt.y + ascent), *fm, *aCtx); } /* ///////////// * nsIMathMLFrame - support methods for stretchy elements * ============================================================================= */ static bool IsForeignChild(const nsIFrame* aFrame) { // This counts nsMathMLmathBlockFrame as a foreign child, because it // uses block reflow return !(aFrame->IsFrameOfType(nsIFrame::eMathML)) || aFrame->IsBlockFrame(); } NS_DECLARE_FRAME_PROPERTY_DELETABLE(HTMLReflowOutputProperty, ReflowOutput) /* static */ void nsMathMLContainerFrame::SaveReflowAndBoundingMetricsFor( nsIFrame* aFrame, const ReflowOutput& aReflowOutput, const nsBoundingMetrics& aBoundingMetrics) { ReflowOutput* reflowOutput = new ReflowOutput(aReflowOutput); reflowOutput->mBoundingMetrics = aBoundingMetrics; aFrame->SetProperty(HTMLReflowOutputProperty(), reflowOutput); } // helper method to facilitate getting the reflow and bounding metrics /* static */ void nsMathMLContainerFrame::GetReflowAndBoundingMetricsFor( nsIFrame* aFrame, ReflowOutput& aReflowOutput, nsBoundingMetrics& aBoundingMetrics, eMathMLFrameType* aMathMLFrameType) { MOZ_ASSERT(aFrame, "null arg"); ReflowOutput* reflowOutput = aFrame->GetProperty(HTMLReflowOutputProperty()); // IMPORTANT: This function is only meant to be called in Place() methods // where it is assumed that SaveReflowAndBoundingMetricsFor has recorded the // information. NS_ASSERTION(reflowOutput, "Didn't SaveReflowAndBoundingMetricsFor frame!"); if (reflowOutput) { aReflowOutput = *reflowOutput; aBoundingMetrics = reflowOutput->mBoundingMetrics; } if (aMathMLFrameType) { if (!IsForeignChild(aFrame)) { nsIMathMLFrame* mathMLFrame = do_QueryFrame(aFrame); if (mathMLFrame) { *aMathMLFrameType = mathMLFrame->GetMathMLFrameType(); return; } } *aMathMLFrameType = eMathMLFrameType_UNKNOWN; } } void nsMathMLContainerFrame::ClearSavedChildMetrics() { nsIFrame* childFrame = mFrames.FirstChild(); while (childFrame) { childFrame->RemoveProperty(HTMLReflowOutputProperty()); childFrame = childFrame->GetNextSibling(); } } // helper to get the preferred size that a container frame should use to fire // the stretch on its stretchy child frames. void nsMathMLContainerFrame::GetPreferredStretchSize( DrawTarget* aDrawTarget, uint32_t aOptions, nsStretchDirection aStretchDirection, nsBoundingMetrics& aPreferredStretchSize) { if (aOptions & STRETCH_CONSIDER_ACTUAL_SIZE) { // when our actual size is ok, just use it aPreferredStretchSize = mBoundingMetrics; } else if (aOptions & STRETCH_CONSIDER_EMBELLISHMENTS) { // compute our up-to-date size using Place() ReflowOutput reflowOutput(GetWritingMode()); Place(aDrawTarget, false, reflowOutput); aPreferredStretchSize = reflowOutput.mBoundingMetrics; } else { // compute a size that includes embellishments iff the container stretches // in the same direction as the embellished operator. bool stretchAll = aStretchDirection == NS_STRETCH_DIRECTION_VERTICAL ? NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY( mPresentationData.flags) : NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY( mPresentationData.flags); NS_ASSERTION(aStretchDirection == NS_STRETCH_DIRECTION_HORIZONTAL || aStretchDirection == NS_STRETCH_DIRECTION_VERTICAL, "You must specify a direction in which to stretch"); NS_ASSERTION( NS_MATHML_IS_EMBELLISH_OPERATOR(mEmbellishData.flags) || stretchAll, "invalid call to GetPreferredStretchSize"); bool firstTime = true; nsBoundingMetrics bm, bmChild; nsIFrame* childFrame = stretchAll ? PrincipalChildList().FirstChild() : mPresentationData.baseFrame; while (childFrame) { // initializations in case this child happens not to be a MathML frame nsIMathMLFrame* mathMLFrame = do_QueryFrame(childFrame); if (mathMLFrame) { nsEmbellishData embellishData; nsPresentationData presentationData; mathMLFrame->GetEmbellishData(embellishData); mathMLFrame->GetPresentationData(presentationData); if (NS_MATHML_IS_EMBELLISH_OPERATOR(embellishData.flags) && embellishData.direction == aStretchDirection && presentationData.baseFrame) { // embellishements are not included, only consider the inner first // child itself // XXXkt Does that mean the core descendent frame should be used // instead of the base child? nsIMathMLFrame* mathMLchildFrame = do_QueryFrame(presentationData.baseFrame); if (mathMLchildFrame) { mathMLFrame = mathMLchildFrame; } } mathMLFrame->GetBoundingMetrics(bmChild); } else { ReflowOutput unused(GetWritingMode()); GetReflowAndBoundingMetricsFor(childFrame, unused, bmChild); } if (firstTime) { firstTime = false; bm = bmChild; if (!stretchAll) { // we may get here for cases such as <msup><mo>...</mo> ... </msup>, // or <maction>...<mo>...</mo></maction>. break; } } else { if (aStretchDirection == NS_STRETCH_DIRECTION_HORIZONTAL) { // if we get here, it means this is container that will stack its // children vertically and fire an horizontal stretch on each them. // This is the case for \munder, \mover, \munderover. We just sum-up // the size vertically. bm.descent += bmChild.ascent + bmChild.descent; // Sometimes non-spacing marks (when width is zero) are positioned // to the left of the origin, but it is the distance between left // and right bearing that is important rather than the offsets from // the origin. if (bmChild.width == 0) { bmChild.rightBearing -= bmChild.leftBearing; bmChild.leftBearing = 0; } if (bm.leftBearing > bmChild.leftBearing) bm.leftBearing = bmChild.leftBearing; if (bm.rightBearing < bmChild.rightBearing) bm.rightBearing = bmChild.rightBearing; } else if (aStretchDirection == NS_STRETCH_DIRECTION_VERTICAL) { // just sum-up the sizes horizontally. bm += bmChild; } else { NS_ERROR("unexpected case in GetPreferredStretchSize"); break; } } childFrame = childFrame->GetNextSibling(); } aPreferredStretchSize = bm; } } NS_IMETHODIMP nsMathMLContainerFrame::Stretch(DrawTarget* aDrawTarget, nsStretchDirection aStretchDirection, nsBoundingMetrics& aContainerSize, ReflowOutput& aDesiredStretchSize) { if (NS_MATHML_IS_EMBELLISH_OPERATOR(mEmbellishData.flags)) { if (NS_MATHML_STRETCH_WAS_DONE(mPresentationData.flags)) { NS_WARNING("it is wrong to fire stretch more than once on a frame"); return NS_OK; } mPresentationData.flags |= NS_MATHML_STRETCH_DONE; if (NS_MATHML_HAS_ERROR(mPresentationData.flags)) { NS_WARNING("it is wrong to fire stretch on a erroneous frame"); return NS_OK; } // Pass the stretch to the base child ... nsIFrame* baseFrame = mPresentationData.baseFrame; if (baseFrame) { nsIMathMLFrame* mathMLFrame = do_QueryFrame(baseFrame); NS_ASSERTION(mathMLFrame, "Something is wrong somewhere"); if (mathMLFrame) { // And the trick is that the child's rect.x is still holding the // descent, and rect.y is still holding the ascent ... ReflowOutput childSize(aDesiredStretchSize); GetReflowAndBoundingMetricsFor(baseFrame, childSize, childSize.mBoundingMetrics); // See if we should downsize and confine the stretch to us... // XXX there may be other cases where we can downsize the stretch, // e.g., the first &Sum; might appear big in the following situation // <math xmlns='http://www.w3.org/1998/Math/MathML'> // <mstyle> // <msub> // <msub><mo>&Sum;</mo><mfrac><mi>a</mi><mi>b</mi></mfrac></msub> // <msub><mo>&Sum;</mo><mfrac><mi>a</mi><mi>b</mi></mfrac></msub> // </msub> // </mstyle> // </math> nsBoundingMetrics containerSize = aContainerSize; if (aStretchDirection != mEmbellishData.direction && mEmbellishData.direction != NS_STRETCH_DIRECTION_UNSUPPORTED) { NS_ASSERTION( mEmbellishData.direction != NS_STRETCH_DIRECTION_DEFAULT, "Stretches may have a default direction, operators can not."); if (mEmbellishData.direction == NS_STRETCH_DIRECTION_VERTICAL ? NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY( mPresentationData.flags) : NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY( mPresentationData.flags)) { GetPreferredStretchSize(aDrawTarget, 0, mEmbellishData.direction, containerSize); // Stop further recalculations aStretchDirection = mEmbellishData.direction; } else { // We aren't going to stretch the child, so just use the child // metrics. containerSize = childSize.mBoundingMetrics; } } // do the stretching... mathMLFrame->Stretch(aDrawTarget, aStretchDirection, containerSize, childSize); // store the updated metrics SaveReflowAndBoundingMetricsFor(baseFrame, childSize, childSize.mBoundingMetrics); // Remember the siblings which were _deferred_. // Now that this embellished child may have changed, we need to // fire the stretch on its siblings using our updated size if (NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY( mPresentationData.flags) || NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY( mPresentationData.flags)) { nsStretchDirection stretchDir = NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY( mPresentationData.flags) ? NS_STRETCH_DIRECTION_VERTICAL : NS_STRETCH_DIRECTION_HORIZONTAL; GetPreferredStretchSize(aDrawTarget, STRETCH_CONSIDER_EMBELLISHMENTS, stretchDir, containerSize); nsIFrame* childFrame = mFrames.FirstChild(); while (childFrame) { if (childFrame != mPresentationData.baseFrame) { mathMLFrame = do_QueryFrame(childFrame); if (mathMLFrame) { // retrieve the metrics that was stored at the previous pass GetReflowAndBoundingMetricsFor(childFrame, childSize, childSize.mBoundingMetrics); // do the stretching... mathMLFrame->Stretch(aDrawTarget, stretchDir, containerSize, childSize); // store the updated metrics SaveReflowAndBoundingMetricsFor(childFrame, childSize, childSize.mBoundingMetrics); } } childFrame = childFrame->GetNextSibling(); } } // re-position all our children nsresult rv = Place(aDrawTarget, true, aDesiredStretchSize); if (NS_MATHML_HAS_ERROR(mPresentationData.flags) || NS_FAILED(rv)) { // Make sure the child frames get their DidReflow() calls. DidReflowChildren(mFrames.FirstChild()); } // If our parent is not embellished, it means we are the outermost // embellished container and so we put the spacing, otherwise we don't // include the spacing, the outermost embellished container will take // care of it. nsEmbellishData parentData; GetEmbellishDataFrom(GetParent(), parentData); // ensure that we are the embellished child, not just a sibling // (need to test coreFrame since <mfrac> resets other things) if (parentData.coreFrame != mEmbellishData.coreFrame) { // (we fetch values from the core since they may use units that depend // on style data, and style changes could have occurred in the core // since our last visit there) nsEmbellishData coreData; GetEmbellishDataFrom(mEmbellishData.coreFrame, coreData); mBoundingMetrics.width += coreData.leadingSpace + coreData.trailingSpace; aDesiredStretchSize.Width() = mBoundingMetrics.width; aDesiredStretchSize.mBoundingMetrics.width = mBoundingMetrics.width; nscoord dx = StyleVisibility()->mDirection == StyleDirection::Rtl ? coreData.trailingSpace : coreData.leadingSpace; if (dx != 0) { mBoundingMetrics.leftBearing += dx; mBoundingMetrics.rightBearing += dx; aDesiredStretchSize.mBoundingMetrics.leftBearing += dx; aDesiredStretchSize.mBoundingMetrics.rightBearing += dx; nsIFrame* childFrame = mFrames.FirstChild(); while (childFrame) { childFrame->SetPosition(childFrame->GetPosition() + nsPoint(dx, 0)); childFrame = childFrame->GetNextSibling(); } } } // Finished with these: ClearSavedChildMetrics(); // Set our overflow area GatherAndStoreOverflow(&aDesiredStretchSize); } } } return NS_OK; } nsresult nsMathMLContainerFrame::FinalizeReflow(DrawTarget* aDrawTarget, ReflowOutput& aDesiredSize) { // During reflow, we use rect.x and rect.y as placeholders for the child's // ascent and descent in expectation of a stretch command. Hence we need to // ensure that a stretch command will actually be fired later on, after // exiting from our reflow. If the stretch is not fired, the rect.x, and // rect.y will remain with inappropriate data causing children to be // improperly positioned. This helper method checks to see if our parent will // fire a stretch command targeted at us. If not, we go ahead and fire an // involutive stretch on ourselves. This will clear all the rect.x and rect.y, // and return our desired size. // First, complete the post-reflow hook. // We use the information in our children rectangles to position them. // If placeOrigin==false, then Place() will not touch rect.x, and rect.y. // They will still be holding the ascent and descent for each child. // The first clause caters for any non-embellished container. // The second clause is for a container which won't fire stretch even though // it is embellished, e.g., as in <mfrac><mo>...</mo> ... </mfrac>, the test // is convoluted because it excludes the particular case of the core // <mo>...</mo> itself. // (<mo> needs to fire stretch on its MathMLChar in any case to initialize it) bool placeOrigin = !NS_MATHML_IS_EMBELLISH_OPERATOR(mEmbellishData.flags) || (mEmbellishData.coreFrame != this && !mPresentationData.baseFrame && mEmbellishData.direction == NS_STRETCH_DIRECTION_UNSUPPORTED); nsresult rv = Place(aDrawTarget, placeOrigin, aDesiredSize); // Place() will call FinishReflowChild() when placeOrigin is true but if // it returns before reaching FinishReflowChild() due to errors we need // to fulfill the reflow protocol by calling DidReflow for the child frames // that still needs it here (or we may crash - bug 366012). // If placeOrigin is false we should reach Place() with aPlaceOrigin == true // through Stretch() eventually. if (NS_MATHML_HAS_ERROR(mPresentationData.flags) || NS_FAILED(rv)) { GatherAndStoreOverflow(&aDesiredSize); DidReflowChildren(PrincipalChildList().FirstChild()); return rv; } bool parentWillFireStretch = false; if (!placeOrigin) { // This means the rect.x and rect.y of our children were not set!! // Don't go without checking to see if our parent will later fire a // Stretch() command targeted at us. The Stretch() will cause the rect.x and // rect.y to clear... nsIMathMLFrame* mathMLFrame = do_QueryFrame(GetParent()); if (mathMLFrame) { nsEmbellishData embellishData; nsPresentationData presentationData; mathMLFrame->GetEmbellishData(embellishData); mathMLFrame->GetPresentationData(presentationData); if (NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY( presentationData.flags) || NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY( presentationData.flags) || (NS_MATHML_IS_EMBELLISH_OPERATOR(embellishData.flags) && presentationData.baseFrame == this)) { parentWillFireStretch = true; } } if (!parentWillFireStretch) { // There is nobody who will fire the stretch for us, we do it ourselves! bool stretchAll = /* NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY(mPresentationData.flags) || */ NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY( mPresentationData.flags); nsStretchDirection stretchDir; if (mEmbellishData.coreFrame == this || /* case of a bare <mo>...</mo> itself */ (mEmbellishData.direction == NS_STRETCH_DIRECTION_HORIZONTAL && stretchAll) || /* or <mover><mo>...</mo>...</mover>, or friends */ mEmbellishData.direction == NS_STRETCH_DIRECTION_UNSUPPORTED) { /* Doesn't stretch */ stretchDir = mEmbellishData.direction; } else { // Let the Stretch() call decide the direction. stretchDir = NS_STRETCH_DIRECTION_DEFAULT; } // Use our current size as computed earlier by Place() // The stretch call will detect if this is incorrect and recalculate the // size. nsBoundingMetrics defaultSize = aDesiredSize.mBoundingMetrics; Stretch(aDrawTarget, stretchDir, defaultSize, aDesiredSize); #ifdef DEBUG { // The Place() call above didn't request FinishReflowChild(), // so let's check that we eventually did through Stretch(). for (nsIFrame* childFrame : PrincipalChildList()) { NS_ASSERTION(!childFrame->HasAnyStateBits(NS_FRAME_IN_REFLOW), "DidReflow() was never called"); } } #endif } } // Also return our bounding metrics aDesiredSize.mBoundingMetrics = mBoundingMetrics; // see if we should fix the spacing FixInterFrameSpacing(aDesiredSize); if (!parentWillFireStretch) { // Not expecting a stretch. // Finished with these: ClearSavedChildMetrics(); // Set our overflow area. GatherAndStoreOverflow(&aDesiredSize); } return NS_OK; } /* ///////////// * nsIMathMLFrame - support methods for scripting elements (nested frames * within msub, msup, msubsup, munder, mover, munderover, mmultiscripts, * mfrac, mroot, mtable). * ============================================================================= */ // helper to let the update of presentation data pass through // a subtree that may contain non-mathml container frames /* static */ void nsMathMLContainerFrame::PropagatePresentationDataFor( nsIFrame* aFrame, uint32_t aFlagsValues, uint32_t aFlagsToUpdate) { if (!aFrame || !aFlagsToUpdate) return; nsIMathMLFrame* mathMLFrame = do_QueryFrame(aFrame); if (mathMLFrame) { // update mathMLFrame->UpdatePresentationData(aFlagsValues, aFlagsToUpdate); // propagate using the base method to make sure that the control // is passed on to MathML frames that may be overloading the method mathMLFrame->UpdatePresentationDataFromChildAt(0, -1, aFlagsValues, aFlagsToUpdate); } else { // propagate down the subtrees for (nsIFrame* childFrame : aFrame->PrincipalChildList()) { PropagatePresentationDataFor(childFrame, aFlagsValues, aFlagsToUpdate); } } } /* static */ void nsMathMLContainerFrame::PropagatePresentationDataFromChildAt( nsIFrame* aParentFrame, int32_t aFirstChildIndex, int32_t aLastChildIndex, uint32_t aFlagsValues, uint32_t aFlagsToUpdate) { if (!aParentFrame || !aFlagsToUpdate) return; int32_t index = 0; for (nsIFrame* childFrame : aParentFrame->PrincipalChildList()) { if ((index >= aFirstChildIndex) && ((aLastChildIndex <= 0) || ((aLastChildIndex > 0) && (index <= aLastChildIndex)))) { PropagatePresentationDataFor(childFrame, aFlagsValues, aFlagsToUpdate); } index++; } } /* ////////////////// * Frame construction * ============================================================================= */ void nsMathMLContainerFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists) { // report an error if something wrong was found in this frame if (NS_MATHML_HAS_ERROR(mPresentationData.flags)) { if (!IsVisibleForPainting()) return; aLists.Content()->AppendNewToTop<nsDisplayMathMLError>(aBuilder, this); return; } BuildDisplayListForInline(aBuilder, aLists); #if defined(DEBUG) && defined(SHOW_BOUNDING_BOX) // for visual debug // ---------------- // if you want to see your bounding box, make sure to properly fill // your mBoundingMetrics and mReference point, and set // mPresentationData.flags |= NS_MATHML_SHOW_BOUNDING_METRICS // in the Init() of your sub-class DisplayBoundingMetrics(aBuilder, this, mReference, mBoundingMetrics, aLists); #endif } // Note that this method re-builds the automatic data in the children -- not // in aParentFrame itself (except for those particular operations that the // parent frame may do in its TransmitAutomaticData()). /* static */ void nsMathMLContainerFrame::RebuildAutomaticDataForChildren( nsIFrame* aParentFrame) { // 1. As we descend the tree, make each child frame inherit data from // the parent // 2. As we ascend the tree, transmit any specific change that we want // down the subtrees for (nsIFrame* childFrame : aParentFrame->PrincipalChildList()) { nsIMathMLFrame* childMathMLFrame = do_QueryFrame(childFrame); if (childMathMLFrame) { childMathMLFrame->InheritAutomaticData(aParentFrame); } RebuildAutomaticDataForChildren(childFrame); } nsIMathMLFrame* mathMLFrame = do_QueryFrame(aParentFrame); if (mathMLFrame) { mathMLFrame->TransmitAutomaticData(); } } /* static */ nsresult nsMathMLContainerFrame::ReLayoutChildren(nsIFrame* aParentFrame) { if (!aParentFrame) return NS_OK; // walk-up to the first frame that is a MathML frame, stop if we reach <math> nsIFrame* frame = aParentFrame; while (1) { nsIFrame* parent = frame->GetParent(); if (!parent || !parent->GetContent()) break; // stop if it is a MathML frame nsIMathMLFrame* mathMLFrame = do_QueryFrame(frame); if (mathMLFrame) break; // stop if we reach the root <math> tag nsIContent* content = frame->GetContent(); NS_ASSERTION(content, "dangling frame without a content node"); if (!content) break; if (content->IsMathMLElement(nsGkAtoms::math)) break; frame = parent; } // re-sync the presentation data and embellishment data of our children RebuildAutomaticDataForChildren(frame); // Ask our parent frame to reflow us nsIFrame* parent = frame->GetParent(); NS_ASSERTION(parent, "No parent to pass the reflow request up to"); if (!parent) return NS_OK; frame->PresShell()->FrameNeedsReflow(frame, IntrinsicDirty::StyleChange, NS_FRAME_IS_DIRTY); return NS_OK; } // There are precise rules governing children of a MathML frame, // and properties such as the scriptlevel depends on those rules. // Hence for things to work, callers must use Append/Insert/etc wisely. nsresult nsMathMLContainerFrame::ChildListChanged(int32_t aModType) { // If this is an embellished frame we need to rebuild the // embellished hierarchy by walking-up to the parent of the // outermost embellished container. nsIFrame* frame = this; if (mEmbellishData.coreFrame) { nsIFrame* parent = GetParent(); nsEmbellishData embellishData; for (; parent; frame = parent, parent = parent->GetParent()) { GetEmbellishDataFrom(parent, embellishData); if (embellishData.coreFrame != mEmbellishData.coreFrame) break; } } return ReLayoutChildren(frame); } void nsMathMLContainerFrame::AppendFrames(ChildListID aListID, nsFrameList& aFrameList) { MOZ_ASSERT(aListID == kPrincipalList); mFrames.AppendFrames(this, aFrameList); ChildListChanged(dom::MutationEvent_Binding::ADDITION); } void nsMathMLContainerFrame::InsertFrames( ChildListID aListID, nsIFrame* aPrevFrame, const nsLineList::iterator* aPrevFrameLine, nsFrameList& aFrameList) { MOZ_ASSERT(aListID == kPrincipalList); mFrames.InsertFrames(this, aPrevFrame, aFrameList); ChildListChanged(dom::MutationEvent_Binding::ADDITION); } void nsMathMLContainerFrame::RemoveFrame(ChildListID aListID, nsIFrame* aOldFrame) { MOZ_ASSERT(aListID == kPrincipalList); mFrames.DestroyFrame(aOldFrame); ChildListChanged(dom::MutationEvent_Binding::REMOVAL); } nsresult nsMathMLContainerFrame::AttributeChanged(int32_t aNameSpaceID, nsAtom* aAttribute, int32_t aModType) { // XXX Since they are numerous MathML attributes that affect layout, and // we can't check all of them here, play safe by requesting a reflow. // XXXldb This should only do work for attributes that cause changes! PresShell()->FrameNeedsReflow(this, IntrinsicDirty::StyleChange, NS_FRAME_IS_DIRTY); return NS_OK; } void nsMathMLContainerFrame::GatherAndStoreOverflow(ReflowOutput* aMetrics) { mBlockStartAscent = aMetrics->BlockStartAscent(); // nsIFrame::FinishAndStoreOverflow likes the overflow area to include the // frame rectangle. aMetrics->SetOverflowAreasToDesiredBounds(); ComputeCustomOverflow(aMetrics->mOverflowAreas); // mBoundingMetrics does not necessarily include content of <mpadded> // elements whose mBoundingMetrics may not be representative of the true // bounds, and doesn't include the CSS2 outline rectangles of children, so // make such to include child overflow areas. UnionChildOverflow(aMetrics->mOverflowAreas); FinishAndStoreOverflow(aMetrics); } bool nsMathMLContainerFrame::ComputeCustomOverflow( OverflowAreas& aOverflowAreas) { // All non-child-frame content such as nsMathMLChars (and most child-frame // content) is included in mBoundingMetrics. nsRect boundingBox( mBoundingMetrics.leftBearing, mBlockStartAscent - mBoundingMetrics.ascent, mBoundingMetrics.rightBearing - mBoundingMetrics.leftBearing, mBoundingMetrics.ascent + mBoundingMetrics.descent); // REVIEW: Maybe this should contribute only to ink overflow // and not scrollable? aOverflowAreas.UnionAllWith(boundingBox); return nsContainerFrame::ComputeCustomOverflow(aOverflowAreas); } void nsMathMLContainerFrame::ReflowChild(nsIFrame* aChildFrame, nsPresContext* aPresContext, ReflowOutput& aDesiredSize, const ReflowInput& aReflowInput, nsReflowStatus& aStatus) { // Having foreign/hybrid children, e.g., from html markups, is not defined by // the MathML spec. But it can happen in practice, e.g., <html:img> allows us // to do some cool demos... or we may have a child that is an nsInlineFrame // from a generated content such as :before { content: open-quote } or // :after { content: close-quote }. Unfortunately, the other frames out-there // may expect their own invariants that are not met when we mix things. // Hence we do not claim their support, but we will nevertheless attempt to // keep them in the flow, if we can get their desired size. We observed that // most frames may be reflowed generically, but nsInlineFrames need extra // care. #ifdef DEBUG nsInlineFrame* inlineFrame = do_QueryFrame(aChildFrame); NS_ASSERTION(!inlineFrame, "Inline frames should be wrapped in blocks"); #endif nsContainerFrame::ReflowChild(aChildFrame, aPresContext, aDesiredSize, aReflowInput, 0, 0, ReflowChildFlags::NoMoveFrame, aStatus); if (aDesiredSize.BlockStartAscent() == ReflowOutput::ASK_FOR_BASELINE) { // This will be suitable for inline frames, which are wrapped in a block. nscoord ascent; WritingMode wm = aDesiredSize.GetWritingMode(); if (!nsLayoutUtils::GetLastLineBaseline(wm, aChildFrame, &ascent)) { // We don't expect any other block children so just place the frame on // the baseline instead of going through DidReflow() and // GetBaseline(). This is what nsIFrame::GetBaseline() will do anyway. aDesiredSize.SetBlockStartAscent(aDesiredSize.BSize(wm)); } else { aDesiredSize.SetBlockStartAscent(ascent); } } if (IsForeignChild(aChildFrame)) { // use ComputeTightBounds API as aDesiredSize.mBoundingMetrics is not set. nsRect r = aChildFrame->ComputeTightBounds( aReflowInput.mRenderingContext->GetDrawTarget()); aDesiredSize.mBoundingMetrics.leftBearing = r.x; aDesiredSize.mBoundingMetrics.rightBearing = r.XMost(); aDesiredSize.mBoundingMetrics.ascent = aDesiredSize.BlockStartAscent() - r.y; aDesiredSize.mBoundingMetrics.descent = r.YMost() - aDesiredSize.BlockStartAscent(); aDesiredSize.mBoundingMetrics.width = aDesiredSize.Width(); } } void nsMathMLContainerFrame::Reflow(nsPresContext* aPresContext, ReflowOutput& aDesiredSize, const ReflowInput& aReflowInput, nsReflowStatus& aStatus) { MarkInReflow(); MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!"); mPresentationData.flags &= ~NS_MATHML_ERROR; aDesiredSize.Width() = aDesiredSize.Height() = 0; aDesiredSize.SetBlockStartAscent(0); aDesiredSize.mBoundingMetrics = nsBoundingMetrics(); ///////////// // Reflow children // Asking each child to cache its bounding metrics nsReflowStatus childStatus; nsIFrame* childFrame = mFrames.FirstChild(); while (childFrame) { ReflowOutput childDesiredSize(aReflowInput); WritingMode wm = childFrame->GetWritingMode(); LogicalSize availSize = aReflowInput.ComputedSize(wm); availSize.BSize(wm) = NS_UNCONSTRAINEDSIZE; ReflowInput childReflowInput(aPresContext, aReflowInput, childFrame, availSize); ReflowChild(childFrame, aPresContext, childDesiredSize, childReflowInput, childStatus); // NS_ASSERTION(childStatus.IsComplete(), "bad status"); SaveReflowAndBoundingMetricsFor(childFrame, childDesiredSize, childDesiredSize.mBoundingMetrics); childFrame = childFrame->GetNextSibling(); } ///////////// // If we are a container which is entitled to stretch its children, then we // ask our stretchy children to stretch themselves // The stretching of siblings of an embellished child is _deferred_ until // after finishing the stretching of the embellished child - bug 117652 DrawTarget* drawTarget = aReflowInput.mRenderingContext->GetDrawTarget(); if (!NS_MATHML_IS_EMBELLISH_OPERATOR(mEmbellishData.flags) && (NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY( mPresentationData.flags) || NS_MATHML_WILL_STRETCH_ALL_CHILDREN_HORIZONTALLY( mPresentationData.flags))) { // get the stretchy direction nsStretchDirection stretchDir = NS_MATHML_WILL_STRETCH_ALL_CHILDREN_VERTICALLY(mPresentationData.flags) ? NS_STRETCH_DIRECTION_VERTICAL : NS_STRETCH_DIRECTION_HORIZONTAL; // what size should we use to stretch our stretchy children // We don't use STRETCH_CONSIDER_ACTUAL_SIZE -- because our size is not // known yet We don't use STRETCH_CONSIDER_EMBELLISHMENTS -- because we // don't want to include them in the caculations of the size of stretchy // elements nsBoundingMetrics containerSize; GetPreferredStretchSize(drawTarget, 0, stretchDir, containerSize); // fire the stretch on each child childFrame = mFrames.FirstChild(); while (childFrame) { nsIMathMLFrame* mathMLFrame = do_QueryFrame(childFrame); if (mathMLFrame) { // retrieve the metrics that was stored at the previous pass ReflowOutput childDesiredSize(aReflowInput); GetReflowAndBoundingMetricsFor(childFrame, childDesiredSize, childDesiredSize.mBoundingMetrics); mathMLFrame->Stretch(drawTarget, stretchDir, containerSize, childDesiredSize); // store the updated metrics SaveReflowAndBoundingMetricsFor(childFrame, childDesiredSize, childDesiredSize.mBoundingMetrics); } childFrame = childFrame->GetNextSibling(); } } ///////////// // Place children now by re-adjusting the origins to align the baselines FinalizeReflow(drawTarget, aDesiredSize); NS_FRAME_SET_TRUNCATION(aStatus, aReflowInput, aDesiredSize); } static nscoord AddInterFrameSpacingToSize(ReflowOutput& aDesiredSize, nsMathMLContainerFrame* aFrame); /* virtual */ void nsMathMLContainerFrame::MarkIntrinsicISizesDirty() { mIntrinsicWidth = NS_INTRINSIC_ISIZE_UNKNOWN; nsContainerFrame::MarkIntrinsicISizesDirty(); } void nsMathMLContainerFrame::UpdateIntrinsicWidth( gfxContext* aRenderingContext) { if (mIntrinsicWidth == NS_INTRINSIC_ISIZE_UNKNOWN) { ReflowOutput desiredSize(GetWritingMode()); GetIntrinsicISizeMetrics(aRenderingContext, desiredSize); // Include the additional width added by FixInterFrameSpacing to ensure // consistent width calculations. AddInterFrameSpacingToSize(desiredSize, this); mIntrinsicWidth = desiredSize.ISize(GetWritingMode()); } } /* virtual */ nscoord nsMathMLContainerFrame::GetMinISize(gfxContext* aRenderingContext) { nscoord result; DISPLAY_MIN_INLINE_SIZE(this, result); UpdateIntrinsicWidth(aRenderingContext); result = mIntrinsicWidth; return result; } /* virtual */ nscoord nsMathMLContainerFrame::GetPrefISize(gfxContext* aRenderingContext) { nscoord result; DISPLAY_PREF_INLINE_SIZE(this, result); UpdateIntrinsicWidth(aRenderingContext); result = mIntrinsicWidth; return result; } /* virtual */ void nsMathMLContainerFrame::GetIntrinsicISizeMetrics( gfxContext* aRenderingContext, ReflowOutput& aDesiredSize) { // Get child widths nsIFrame* childFrame = mFrames.FirstChild(); while (childFrame) { ReflowOutput childDesiredSize(GetWritingMode()); // ??? nsMathMLContainerFrame* containerFrame = do_QueryFrame(childFrame); if (containerFrame) { containerFrame->GetIntrinsicISizeMetrics(aRenderingContext, childDesiredSize); } else { // XXX This includes margin while Reflow currently doesn't consider // margin, so we may end up with too much space, but, with stretchy // characters, this is an approximation anyway. nscoord width = nsLayoutUtils::IntrinsicForContainer( aRenderingContext, childFrame, IntrinsicISizeType::PrefISize); childDesiredSize.Width() = width; childDesiredSize.mBoundingMetrics.width = width; childDesiredSize.mBoundingMetrics.leftBearing = 0; childDesiredSize.mBoundingMetrics.rightBearing = width; nscoord x, xMost; if (NS_SUCCEEDED(childFrame->GetPrefWidthTightBounds(aRenderingContext, &x, &xMost))) { childDesiredSize.mBoundingMetrics.leftBearing = x; childDesiredSize.mBoundingMetrics.rightBearing = xMost; } } SaveReflowAndBoundingMetricsFor(childFrame, childDesiredSize, childDesiredSize.mBoundingMetrics); childFrame = childFrame->GetNextSibling(); } // Measure nsresult rv = MeasureForWidth(aRenderingContext->GetDrawTarget(), aDesiredSize); if (NS_FAILED(rv)) { ReflowError(aRenderingContext->GetDrawTarget(), aDesiredSize); } ClearSavedChildMetrics(); } /* virtual */ nsresult nsMathMLContainerFrame::MeasureForWidth(DrawTarget* aDrawTarget, ReflowOutput& aDesiredSize) { return Place(aDrawTarget, false, aDesiredSize); } // see spacing table in Chapter 18, TeXBook (p.170) // Our table isn't quite identical to TeX because operators have // built-in values for lspace & rspace in the Operator Dictionary. static int32_t kInterFrameSpacingTable[eMathMLFrameType_COUNT][eMathMLFrameType_COUNT] = { // in units of muspace. // upper half of the byte is set if the // spacing is not to be used for scriptlevel > 0 /* Ord OpOrd OpInv OpUsr Inner Italic Upright */ /*Ord */ {0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00}, /*OpOrd */ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /*OpInv */ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /*OpUsr */ {0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01}, /*Inner */ {0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01}, /*Italic */ {0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x01}, /*Upright*/ {0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00}}; #define GET_INTERSPACE(scriptlevel_, frametype1_, frametype2_, space_) \ /* no space if there is a frame that we know nothing about */ \ if (frametype1_ == eMathMLFrameType_UNKNOWN || \ frametype2_ == eMathMLFrameType_UNKNOWN) \ space_ = 0; \ else { \ space_ = kInterFrameSpacingTable[frametype1_][frametype2_]; \ space_ = (scriptlevel_ > 0 && (space_ & 0xF0)) \ ? 0 /* spacing is disabled */ \ : space_ & 0x0F; \ } // This function computes the inter-space between two frames. However, // since invisible operators need special treatment, the inter-space may // be delayed when an invisible operator is encountered. In this case, // the function will carry the inter-space forward until it is determined // that it can be applied properly (i.e., until we encounter a visible // frame where to decide whether to accept or reject the inter-space). // aFromFrameType: remembers the frame when the carry-forward initiated. // aCarrySpace: keeps track of the inter-space that is delayed. // @returns: current inter-space (which is 0 when the true inter-space is // delayed -- and thus has no effect since the frame is invisible anyway). static nscoord GetInterFrameSpacing(int32_t aScriptLevel, eMathMLFrameType aFirstFrameType, eMathMLFrameType aSecondFrameType, eMathMLFrameType* aFromFrameType, // IN/OUT int32_t* aCarrySpace) // IN/OUT { eMathMLFrameType firstType = aFirstFrameType; eMathMLFrameType secondType = aSecondFrameType; int32_t space; GET_INTERSPACE(aScriptLevel, firstType, secondType, space); // feedback control to avoid the inter-space to be added when not necessary if (secondType == eMathMLFrameType_OperatorInvisible) { // see if we should start to carry the space forward until we // encounter a visible frame if (*aFromFrameType == eMathMLFrameType_UNKNOWN) { *aFromFrameType = firstType; *aCarrySpace = space; } // keep carrying *aCarrySpace forward, while returning 0 for this stage space = 0; } else if (*aFromFrameType != eMathMLFrameType_UNKNOWN) { // no carry-forward anymore, get the real inter-space between // the two frames of interest firstType = *aFromFrameType; // But... the invisible operator that we encountered earlier could // be sitting between italic and upright identifiers, e.g., // // 1. <mi>sin</mi> <mo>&ApplyFunction;</mo> <mi>x</mi> // 2. <mi>x</mi> <mo>&InvisibileTime;</mo> <mi>sin</mi> // // the trick to get the inter-space in either situation // is to promote "<mi>sin</mi><mo>&ApplyFunction;</mo>" and // "<mo>&InvisibileTime;</mo><mi>sin</mi>" to user-defined operators... if (firstType == eMathMLFrameType_UprightIdentifier) { firstType = eMathMLFrameType_OperatorUserDefined; } else if (secondType == eMathMLFrameType_UprightIdentifier) { secondType = eMathMLFrameType_OperatorUserDefined; } GET_INTERSPACE(aScriptLevel, firstType, secondType, space); // Now, we have two values: the computed space and the space that // has been carried forward until now. Which value do we pick? // If the second type is an operator (e.g., fence), it already has // built-in lspace & rspace, so we let them win. Otherwise we pick // the max between the two values that we have. if (secondType != eMathMLFrameType_OperatorOrdinary && space < *aCarrySpace) space = *aCarrySpace; // reset everything now that the carry-forward is done *aFromFrameType = eMathMLFrameType_UNKNOWN; *aCarrySpace = 0; } return space; } static nscoord GetThinSpace(const nsStyleFont* aStyleFont) { return aStyleFont->mFont.size.ScaledBy(3.0f / 18.0f).ToAppUnits(); } class nsMathMLContainerFrame::RowChildFrameIterator { public: explicit RowChildFrameIterator(nsMathMLContainerFrame* aParentFrame) : mParentFrame(aParentFrame), mReflowOutput(aParentFrame->GetWritingMode()), mX(0), mChildFrameType(eMathMLFrameType_UNKNOWN), mCarrySpace(0), mFromFrameType(eMathMLFrameType_UNKNOWN), mRTL(aParentFrame->StyleVisibility()->mDirection == StyleDirection::Rtl) { if (!mRTL) { mChildFrame = aParentFrame->mFrames.FirstChild(); } else { mChildFrame = aParentFrame->mFrames.LastChild(); } if (!mChildFrame) return; InitMetricsForChild(); } RowChildFrameIterator& operator++() { // add child size + italic correction mX += mReflowOutput.mBoundingMetrics.width + mItalicCorrection; if (!mRTL) { mChildFrame = mChildFrame->GetNextSibling(); } else { mChildFrame = mChildFrame->GetPrevSibling(); } if (!mChildFrame) return *this; eMathMLFrameType prevFrameType = mChildFrameType; InitMetricsForChild(); // add inter frame spacing const nsStyleFont* font = mParentFrame->StyleFont(); nscoord space = GetInterFrameSpacing(font->mMathDepth, prevFrameType, mChildFrameType, &mFromFrameType, &mCarrySpace); mX += space * GetThinSpace(font); return *this; } nsIFrame* Frame() const { return mChildFrame; } nscoord X() const { return mX; } const ReflowOutput& GetReflowOutput() const { return mReflowOutput; } nscoord Ascent() const { return mReflowOutput.BlockStartAscent(); } nscoord Descent() const { return mReflowOutput.Height() - mReflowOutput.BlockStartAscent(); } const nsBoundingMetrics& BoundingMetrics() const { return mReflowOutput.mBoundingMetrics; } private: const nsMathMLContainerFrame* mParentFrame; nsIFrame* mChildFrame; ReflowOutput mReflowOutput; nscoord mX; nscoord mItalicCorrection; eMathMLFrameType mChildFrameType; int32_t mCarrySpace; eMathMLFrameType mFromFrameType; bool mRTL; void InitMetricsForChild() { GetReflowAndBoundingMetricsFor(mChildFrame, mReflowOutput, mReflowOutput.mBoundingMetrics, &mChildFrameType); nscoord leftCorrection, rightCorrection; GetItalicCorrection(mReflowOutput.mBoundingMetrics, leftCorrection, rightCorrection); if (!mChildFrame->GetPrevSibling() && mParentFrame->GetContent()->IsMathMLElement(nsGkAtoms::msqrt_)) { // Remove leading correction in <msqrt> because the sqrt glyph itself is // there first. if (!mRTL) { leftCorrection = 0; } else { rightCorrection = 0; } } // add left correction -- this fixes the problem of the italic 'f' // e.g., <mo>q</mo> <mi>f</mi> <mo>I</mo> mX += leftCorrection; mItalicCorrection = rightCorrection; } }; /* virtual */ nsresult nsMathMLContainerFrame::Place(DrawTarget* aDrawTarget, bool aPlaceOrigin, ReflowOutput& aDesiredSize) { // This is needed in case this frame is empty (i.e., no child frames) mBoundingMetrics = nsBoundingMetrics(); RowChildFrameIterator child(this); nscoord ascent = 0, descent = 0; while (child.Frame()) { if (descent < child.Descent()) descent = child.Descent(); if (ascent < child.Ascent()) ascent = child.Ascent(); // add the child size mBoundingMetrics.width = child.X(); mBoundingMetrics += child.BoundingMetrics(); ++child; } // Add the italic correction at the end (including the last child). // This gives a nice gap between math and non-math frames, and still // gives the same math inter-spacing in case this frame connects to // another math frame mBoundingMetrics.width = child.X(); aDesiredSize.Width() = std::max(0, mBoundingMetrics.width); aDesiredSize.Height() = ascent + descent; aDesiredSize.SetBlockStartAscent(ascent); aDesiredSize.mBoundingMetrics = mBoundingMetrics; mReference.x = 0; mReference.y = aDesiredSize.BlockStartAscent(); ////////////////// // Place Children if (aPlaceOrigin) { PositionRowChildFrames(0, aDesiredSize.BlockStartAscent()); } return NS_OK; } void nsMathMLContainerFrame::PositionRowChildFrames(nscoord aOffsetX, nscoord aBaseline) { RowChildFrameIterator child(this); while (child.Frame()) { nscoord dx = aOffsetX + child.X(); nscoord dy = aBaseline - child.Ascent(); FinishReflowChild(child.Frame(), PresContext(), child.GetReflowOutput(), nullptr, dx, dy, ReflowChildFlags::Default); ++child; } } // helpers to fix the inter-spacing when <math> is the only parent // e.g., it fixes <math> <mi>f</mi> <mo>q</mo> <mi>f</mi> <mo>I</mo> </math> static nscoord GetInterFrameSpacingFor(int32_t aScriptLevel, nsIFrame* aParentFrame, nsIFrame* aChildFrame) { nsIFrame* childFrame = aParentFrame->PrincipalChildList().FirstChild(); if (!childFrame || aChildFrame == childFrame) return 0; int32_t carrySpace = 0; eMathMLFrameType fromFrameType = eMathMLFrameType_UNKNOWN; eMathMLFrameType prevFrameType = eMathMLFrameType_UNKNOWN; eMathMLFrameType childFrameType = nsMathMLFrame::GetMathMLFrameTypeFor(childFrame); childFrame = childFrame->GetNextSibling(); while (childFrame) { prevFrameType = childFrameType; childFrameType = nsMathMLFrame::GetMathMLFrameTypeFor(childFrame); nscoord space = GetInterFrameSpacing(aScriptLevel, prevFrameType, childFrameType, &fromFrameType, &carrySpace); if (aChildFrame == childFrame) { // get thinspace ComputedStyle* parentContext = aParentFrame->Style(); nscoord thinSpace = GetThinSpace(parentContext->StyleFont()); // we are done return space * thinSpace; } childFrame = childFrame->GetNextSibling(); } MOZ_ASSERT_UNREACHABLE("child not in the childlist of its parent"); return 0; } static nscoord AddInterFrameSpacingToSize(ReflowOutput& aDesiredSize, nsMathMLContainerFrame* aFrame) { nscoord gap = 0; nsIFrame* parent = aFrame->GetParent(); nsIContent* parentContent = parent->GetContent(); if (MOZ_UNLIKELY(!parentContent)) { return 0; } if (parentContent->IsAnyOfMathMLElements(nsGkAtoms::math, nsGkAtoms::mtd_)) { gap = GetInterFrameSpacingFor(aFrame->StyleFont()->mMathDepth, parent, aFrame); // add our own italic correction nscoord leftCorrection = 0, italicCorrection = 0; nsMathMLContainerFrame::GetItalicCorrection( aDesiredSize.mBoundingMetrics, leftCorrection, italicCorrection); gap += leftCorrection; if (gap) { aDesiredSize.mBoundingMetrics.leftBearing += gap; aDesiredSize.mBoundingMetrics.rightBearing += gap; aDesiredSize.mBoundingMetrics.width += gap; aDesiredSize.Width() += gap; } aDesiredSize.mBoundingMetrics.width += italicCorrection; aDesiredSize.Width() += italicCorrection; } return gap; } nscoord nsMathMLContainerFrame::FixInterFrameSpacing( ReflowOutput& aDesiredSize) { nscoord gap = 0; gap = AddInterFrameSpacingToSize(aDesiredSize, this); if (gap) { // Shift our children to account for the correction nsIFrame* childFrame = mFrames.FirstChild(); while (childFrame) { childFrame->SetPosition(childFrame->GetPosition() + nsPoint(gap, 0)); childFrame = childFrame->GetNextSibling(); } } return gap; } /* static */ void nsMathMLContainerFrame::DidReflowChildren(nsIFrame* aFirst, nsIFrame* aStop) { if (MOZ_UNLIKELY(!aFirst)) return; for (nsIFrame* frame = aFirst; frame != aStop; frame = frame->GetNextSibling()) { NS_ASSERTION(frame, "aStop isn't a sibling"); if (frame->HasAnyStateBits(NS_FRAME_IN_REFLOW)) { // finish off principal descendants, too nsIFrame* grandchild = frame->PrincipalChildList().FirstChild(); if (grandchild) DidReflowChildren(grandchild, nullptr); frame->DidReflow(frame->PresContext(), nullptr); } } } // helper used by mstyle, mphantom, mpadded and mrow in their implementations // of TransmitAutomaticData(). nsresult nsMathMLContainerFrame::TransmitAutomaticDataForMrowLikeElement() { // // One loop to check both conditions below: // // 1) whether all the children of the mrow-like element are space-like. // // The REC defines the following elements to be "space-like": // * an mstyle, mphantom, or mpadded element, all of whose direct // sub-expressions are space-like; // * an mrow all of whose direct sub-expressions are space-like. // // 2) whether all but one child of the mrow-like element are space-like and // this non-space-like child is an embellished operator. // // The REC defines the following elements to be embellished operators: // * one of the elements mstyle, mphantom, or mpadded, such that an mrow // containing the same arguments would be an embellished operator; // * an mrow whose arguments consist (in any order) of one embellished // operator and zero or more space-like elements. // nsIFrame *childFrame, *baseFrame; bool embellishedOpFound = false; nsEmbellishData embellishData; for (childFrame = PrincipalChildList().FirstChild(); childFrame; childFrame = childFrame->GetNextSibling()) { nsIMathMLFrame* mathMLFrame = do_QueryFrame(childFrame); if (!mathMLFrame) break; if (!mathMLFrame->IsSpaceLike()) { if (embellishedOpFound) break; baseFrame = childFrame; GetEmbellishDataFrom(baseFrame, embellishData); if (!NS_MATHML_IS_EMBELLISH_OPERATOR(embellishData.flags)) break; embellishedOpFound = true; } } if (!childFrame) { // we successfully went to the end of the loop. This means that one of // condition 1) or 2) holds. if (!embellishedOpFound) { // the mrow-like element is space-like. mPresentationData.flags |= NS_MATHML_SPACE_LIKE; } else { // the mrow-like element is an embellished operator. // let the state of the embellished operator found bubble to us. mPresentationData.baseFrame = baseFrame; mEmbellishData = embellishData; } } if (childFrame || !embellishedOpFound) { // The element is not embellished operator mPresentationData.baseFrame = nullptr; mEmbellishData.flags = 0; mEmbellishData.coreFrame = nullptr; mEmbellishData.direction = NS_STRETCH_DIRECTION_UNSUPPORTED; mEmbellishData.leadingSpace = 0; mEmbellishData.trailingSpace = 0; } if (childFrame || embellishedOpFound) { // The element is not space-like mPresentationData.flags &= ~NS_MATHML_SPACE_LIKE; } return NS_OK; } /*static*/ void nsMathMLContainerFrame::PropagateFrameFlagFor(nsIFrame* aFrame, nsFrameState aFlags) { if (!aFrame || !aFlags) return; aFrame->AddStateBits(aFlags); for (nsIFrame* childFrame : aFrame->PrincipalChildList()) { PropagateFrameFlagFor(childFrame, aFlags); } } nsresult nsMathMLContainerFrame::ReportErrorToConsole( const char* errorMsgId, const nsTArray<nsString>& aParams) { return nsContentUtils::ReportToConsole( nsIScriptError::errorFlag, "Layout: MathML"_ns, mContent->OwnerDoc(), nsContentUtils::eMATHML_PROPERTIES, errorMsgId, aParams); } nsresult nsMathMLContainerFrame::ReportParseError(const char16_t* aAttribute, const char16_t* aValue) { AutoTArray<nsString, 3> argv; argv.AppendElement(aValue); argv.AppendElement(aAttribute); argv.AppendElement(nsDependentAtomString(mContent->NodeInfo()->NameAtom())); return ReportErrorToConsole("AttributeParsingError", argv); } nsresult nsMathMLContainerFrame::ReportChildCountError() { AutoTArray<nsString, 1> arg = { nsDependentAtomString(mContent->NodeInfo()->NameAtom())}; return ReportErrorToConsole("ChildCountIncorrect", arg); } nsresult nsMathMLContainerFrame::ReportInvalidChildError(nsAtom* aChildTag) { AutoTArray<nsString, 2> argv = { nsDependentAtomString(aChildTag), nsDependentAtomString(mContent->NodeInfo()->NameAtom())}; return ReportErrorToConsole("InvalidChild", argv); } //========================== nsContainerFrame* NS_NewMathMLmathBlockFrame(PresShell* aPresShell, ComputedStyle* aStyle) { auto newFrame = new (aPresShell) nsMathMLmathBlockFrame(aStyle, aPresShell->GetPresContext()); newFrame->AddStateBits(NS_BLOCK_FORMATTING_CONTEXT_STATE_BITS); return newFrame; } NS_IMPL_FRAMEARENA_HELPERS(nsMathMLmathBlockFrame) NS_QUERYFRAME_HEAD(nsMathMLmathBlockFrame) NS_QUERYFRAME_ENTRY(nsMathMLmathBlockFrame) NS_QUERYFRAME_TAIL_INHERITING(nsBlockFrame) nsContainerFrame* NS_NewMathMLmathInlineFrame(PresShell* aPresShell, ComputedStyle* aStyle) { return new (aPresShell) nsMathMLmathInlineFrame(aStyle, aPresShell->GetPresContext()); } NS_IMPL_FRAMEARENA_HELPERS(nsMathMLmathInlineFrame) NS_QUERYFRAME_HEAD(nsMathMLmathInlineFrame) NS_QUERYFRAME_ENTRY(nsIMathMLFrame) NS_QUERYFRAME_TAIL_INHERITING(nsInlineFrame)
utf-8
1
MPL-2.0 or GPL-2 or LGPL-2.1
1998-2016, Mozilla Project
libtk-img-1.4.13+dfsg/.pc/libz.diff/zlib/zlibtclDecls.h
/* * zlibtclDecls.h -- * * Declarations of functions in the platform independent public ZLIBTCL API. * */ #ifndef _ZLIBTCLDECLS #define _ZLIBTCLDECLS /* * WARNING: The contents of this file is automatically generated by the * genStubs.tcl script. Any modifications to the function declarations * below should be made in the zlibtcl.decls script. */ #include <tcl.h> #ifdef ZEXTERN # undef TCL_STORAGE_CLASS # define TCL_STORAGE_CLASS DLLEXPORT #else # define ZEXTERN extern # undef USE_ZLIBTCL_STUBS # define USE_ZLIBTCL_STUBS 1 #endif EXTERN int Zlibtcl_Init(Tcl_Interp *interp); EXTERN int Zlibtcl_SafeInit(Tcl_Interp *interp); #include "../compat/zlib/zlib.h" #undef gzgetc /* Became a macro in zlib 1.2.7 */ /* !BEGIN!: Do not edit below this line. */ /* * Exported function declarations: */ /* 0 */ ZEXTERN const char * zlibVersion(void); /* 1 */ ZEXTERN const char * zError(int err); /* 2 */ ZEXTERN uLong crc32(uLong crc, const Bytef *buf, uInt len); /* 3 */ ZEXTERN uLong adler32(uLong adler, const Bytef *buf, uInt len); /* Slot 4 is reserved */ /* Slot 5 is reserved */ /* Slot 6 is reserved */ /* Slot 7 is reserved */ /* Slot 8 is reserved */ /* Slot 9 is reserved */ /* 10 */ ZEXTERN int deflateInit_(z_streamp stream, int level, const char *version, int stream_size); /* 11 */ ZEXTERN int deflateInit2_(z_streamp stream, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size); /* 12 */ ZEXTERN int deflate(z_streamp stream, int flush); /* 13 */ ZEXTERN int deflateEnd(z_streamp stream); /* 14 */ ZEXTERN int deflateSetDictionary(z_streamp stream, const Bytef *dict, uInt dictLength); /* 15 */ ZEXTERN int deflateCopy(z_streamp dst, z_streamp src); /* 16 */ ZEXTERN int deflateReset(z_streamp stream); /* 17 */ ZEXTERN int deflateParams(z_streamp stream, int level, int strategy); /* 18 */ ZEXTERN int compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); /* 19 */ ZEXTERN int compress2(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level); /* 20 */ ZEXTERN int inflateInit_(z_streamp stream, const char *version, int stream_size); /* 21 */ ZEXTERN int inflateInit2_(z_streamp stream, int windowBits, const char *version, int stream_size); /* 22 */ ZEXTERN int inflate(z_streamp stream, int flush); /* 23 */ ZEXTERN int inflateEnd(z_streamp stream); /* 24 */ ZEXTERN int inflateSetDictionary(z_streamp stream, const Bytef *dict, uInt dictLength); /* 25 */ ZEXTERN int inflateSync(z_streamp stream); /* 26 */ ZEXTERN int inflateReset(z_streamp stream); /* 27 */ ZEXTERN int uncompress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); /* 28 */ ZEXTERN int inflateReset2(z_streamp strm, int windowBits); /* 29 */ ZEXTERN int inflateValidate(z_streamp strm, int check); /* 30 */ ZEXTERN gzFile gzopen(const char *path, const char *mode); /* 31 */ ZEXTERN gzFile gzdopen(int fd, const char *mode); /* 32 */ ZEXTERN int gzsetparams(gzFile file, int level, int strategy); /* 33 */ ZEXTERN int gzread(gzFile file, voidp buf, unsigned len); /* 34 */ ZEXTERN int gzwrite(gzFile file, voidpc buf, unsigned len); /* 35 */ ZEXTERN int gzprintf(gzFile file, const char *format, ...); /* 36 */ ZEXTERN int gzputs(gzFile file, const char *s); /* 37 */ ZEXTERN char * gzgets(gzFile file, char *buf, int len); /* 38 */ ZEXTERN int gzputc(gzFile file, int c); /* 39 */ ZEXTERN int gzgetc(gzFile file); /* 40 */ ZEXTERN int gzflush(gzFile file, int flush); /* 41 */ ZEXTERN z_off_t gzseek(gzFile file, z_off_t offset, int whence); /* 42 */ ZEXTERN int gzrewind(gzFile file); /* 43 */ ZEXTERN z_off_t gztell(gzFile file); /* 44 */ ZEXTERN int gzeof(gzFile file); /* 45 */ ZEXTERN int gzclose(gzFile file); /* 46 */ ZEXTERN const char * gzerror(gzFile file, int *errnum); typedef struct ZlibtclStubs { int magic; const struct ZlibtclStubHooks *hooks; const char * (*zlibVersionPtr) (void); /* 0 */ const char * (*zErrorPtr) (int err); /* 1 */ uLong (*crc32Ptr) (uLong crc, const Bytef *buf, uInt len); /* 2 */ uLong (*adler32Ptr) (uLong adler, const Bytef *buf, uInt len); /* 3 */ void (*reserved4)(void); void (*reserved5)(void); void (*reserved6)(void); void (*reserved7)(void); void (*reserved8)(void); void (*reserved9)(void); int (*deflateInit_Ptr) (z_streamp stream, int level, const char *version, int stream_size); /* 10 */ int (*deflateInit2_Ptr) (z_streamp stream, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size); /* 11 */ int (*deflatePtr) (z_streamp stream, int flush); /* 12 */ int (*deflateEndPtr) (z_streamp stream); /* 13 */ int (*deflateSetDictionaryPtr) (z_streamp stream, const Bytef *dict, uInt dictLength); /* 14 */ int (*deflateCopyPtr) (z_streamp dst, z_streamp src); /* 15 */ int (*deflateResetPtr) (z_streamp stream); /* 16 */ int (*deflateParamsPtr) (z_streamp stream, int level, int strategy); /* 17 */ int (*compressPtr) (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); /* 18 */ int (*compress2Ptr) (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level); /* 19 */ int (*inflateInit_Ptr) (z_streamp stream, const char *version, int stream_size); /* 20 */ int (*inflateInit2_Ptr) (z_streamp stream, int windowBits, const char *version, int stream_size); /* 21 */ int (*inflatePtr) (z_streamp stream, int flush); /* 22 */ int (*inflateEndPtr) (z_streamp stream); /* 23 */ int (*inflateSetDictionaryPtr) (z_streamp stream, const Bytef *dict, uInt dictLength); /* 24 */ int (*inflateSyncPtr) (z_streamp stream); /* 25 */ int (*inflateResetPtr) (z_streamp stream); /* 26 */ int (*uncompressPtr) (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); /* 27 */ int (*inflateReset2Ptr) (z_streamp strm, int windowBits); /* 28 */ int (*inflateValidatePtr) (z_streamp strm, int check); /* 29 */ gzFile (*gzopenPtr) (const char *path, const char *mode); /* 30 */ gzFile (*gzdopenPtr) (int fd, const char *mode); /* 31 */ int (*gzsetparamsPtr) (gzFile file, int level, int strategy); /* 32 */ int (*gzreadPtr) (gzFile file, voidp buf, unsigned len); /* 33 */ int (*gzwritePtr) (gzFile file, voidpc buf, unsigned len); /* 34 */ int (*gzprintfPtr) (gzFile file, const char *format, ...); /* 35 */ int (*gzputsPtr) (gzFile file, const char *s); /* 36 */ char * (*gzgetsPtr) (gzFile file, char *buf, int len); /* 37 */ int (*gzputcPtr) (gzFile file, int c); /* 38 */ int (*gzgetcPtr) (gzFile file); /* 39 */ int (*gzflushPtr) (gzFile file, int flush); /* 40 */ z_off_t (*gzseekPtr) (gzFile file, z_off_t offset, int whence); /* 41 */ int (*gzrewindPtr) (gzFile file); /* 42 */ z_off_t (*gztellPtr) (gzFile file); /* 43 */ int (*gzeofPtr) (gzFile file); /* 44 */ int (*gzclosePtr) (gzFile file); /* 45 */ const char * (*gzerrorPtr) (gzFile file, int *errnum); /* 46 */ } ZlibtclStubs; #ifdef __cplusplus extern "C" { #endif ZEXTERN const ZlibtclStubs *zlibtclStubsPtr; #ifdef __cplusplus } #endif #if defined(USE_ZLIBTCL_STUBS) /* * Inline function declarations: */ #define zlibVersion \ (zlibtclStubsPtr->zlibVersionPtr) /* 0 */ #define zError \ (zlibtclStubsPtr->zErrorPtr) /* 1 */ #define crc32 \ (zlibtclStubsPtr->crc32Ptr) /* 2 */ #define adler32 \ (zlibtclStubsPtr->adler32Ptr) /* 3 */ /* Slot 4 is reserved */ /* Slot 5 is reserved */ /* Slot 6 is reserved */ /* Slot 7 is reserved */ /* Slot 8 is reserved */ /* Slot 9 is reserved */ #define deflateInit_ \ (zlibtclStubsPtr->deflateInit_Ptr) /* 10 */ #define deflateInit2_ \ (zlibtclStubsPtr->deflateInit2_Ptr) /* 11 */ #define deflate \ (zlibtclStubsPtr->deflatePtr) /* 12 */ #define deflateEnd \ (zlibtclStubsPtr->deflateEndPtr) /* 13 */ #define deflateSetDictionary \ (zlibtclStubsPtr->deflateSetDictionaryPtr) /* 14 */ #define deflateCopy \ (zlibtclStubsPtr->deflateCopyPtr) /* 15 */ #define deflateReset \ (zlibtclStubsPtr->deflateResetPtr) /* 16 */ #define deflateParams \ (zlibtclStubsPtr->deflateParamsPtr) /* 17 */ #define compress \ (zlibtclStubsPtr->compressPtr) /* 18 */ #define compress2 \ (zlibtclStubsPtr->compress2Ptr) /* 19 */ #define inflateInit_ \ (zlibtclStubsPtr->inflateInit_Ptr) /* 20 */ #define inflateInit2_ \ (zlibtclStubsPtr->inflateInit2_Ptr) /* 21 */ #define inflate \ (zlibtclStubsPtr->inflatePtr) /* 22 */ #define inflateEnd \ (zlibtclStubsPtr->inflateEndPtr) /* 23 */ #define inflateSetDictionary \ (zlibtclStubsPtr->inflateSetDictionaryPtr) /* 24 */ #define inflateSync \ (zlibtclStubsPtr->inflateSyncPtr) /* 25 */ #define inflateReset \ (zlibtclStubsPtr->inflateResetPtr) /* 26 */ #define uncompress \ (zlibtclStubsPtr->uncompressPtr) /* 27 */ #define inflateReset2 \ (zlibtclStubsPtr->inflateReset2Ptr) /* 28 */ #define inflateValidate \ (zlibtclStubsPtr->inflateValidatePtr) /* 29 */ #define gzopen \ (zlibtclStubsPtr->gzopenPtr) /* 30 */ #define gzdopen \ (zlibtclStubsPtr->gzdopenPtr) /* 31 */ #define gzsetparams \ (zlibtclStubsPtr->gzsetparamsPtr) /* 32 */ #define gzread \ (zlibtclStubsPtr->gzreadPtr) /* 33 */ #define gzwrite \ (zlibtclStubsPtr->gzwritePtr) /* 34 */ #define gzprintf \ (zlibtclStubsPtr->gzprintfPtr) /* 35 */ #define gzputs \ (zlibtclStubsPtr->gzputsPtr) /* 36 */ #define gzgets \ (zlibtclStubsPtr->gzgetsPtr) /* 37 */ #define gzputc \ (zlibtclStubsPtr->gzputcPtr) /* 38 */ #define gzgetc \ (zlibtclStubsPtr->gzgetcPtr) /* 39 */ #define gzflush \ (zlibtclStubsPtr->gzflushPtr) /* 40 */ #define gzseek \ (zlibtclStubsPtr->gzseekPtr) /* 41 */ #define gzrewind \ (zlibtclStubsPtr->gzrewindPtr) /* 42 */ #define gztell \ (zlibtclStubsPtr->gztellPtr) /* 43 */ #define gzeof \ (zlibtclStubsPtr->gzeofPtr) /* 44 */ #define gzclose \ (zlibtclStubsPtr->gzclosePtr) /* 45 */ #define gzerror \ (zlibtclStubsPtr->gzerrorPtr) /* 46 */ #endif /* defined(USE_ZLIBTCL_STUBS) */ /* !END!: Do not edit above this line. */ #undef TCL_STORAGE_CLASS #define TCL_STORAGE_CLASS DLLIMPORT #endif /* _ZLIBTCLDECLS */
utf-8
1
Tcl
1997-2004 Jan Nijtmans
libreoffice-7.3.1~rc1/sc/source/filter/inc/richstring.hxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #pragma once #include <oox/helper/refvector.hxx> #include "stylesbuffer.hxx" class EditTextObject; struct ESelection; class ScEditEngineDefaulter; namespace com::sun::star { namespace text { class XText; } } namespace oox { class SequenceInputStream; } namespace oox::xls { /** Contains text data and font attributes for a part of a rich formatted string. */ class RichStringPortion : public WorkbookHelper { public: explicit RichStringPortion( const WorkbookHelper& rHelper ); /** Sets text data for this portion. */ void setText( const OUString& rText ); /** Creates and returns a new font formatting object. */ FontRef const & createFont(); /** Links this portion to a font object from the global font list. */ void setFontId( sal_Int32 nFontId ); /** Final processing after import of all strings. */ void finalizeImport(); /** Returns the text data of this portion. */ const OUString& getText() const { return maText; } /** Returns true, if the portion contains font formatting. */ bool hasFont() const { return bool(mxFont); } /** Converts the portion and replaces or appends to the passed XText. */ void convert( const css::uno::Reference< css::text::XText >& rxText, bool bReplace ); void convert( ScEditEngineDefaulter& rEE, ESelection& rSelection, const oox::xls::Font* pFont ); void writeFontProperties( const css::uno::Reference< css::text::XText >& rxText ) const; private: OUString maText; /// Portion text. FontRef mxFont; /// Embedded portion font, may be empty. sal_Int32 mnFontId; /// Link to global font list. bool mbConverted; /// Without repeatedly convert }; typedef std::shared_ptr< RichStringPortion > RichStringPortionRef; /** Represents a position in a rich-string containing current font identifier. This object stores the position of a formatted character in a rich-string and the identifier of a font from the global font list used to format this and the following characters. Used in binary filters only. */ struct FontPortionModel { sal_Int32 mnPos; /// First character in the string. sal_Int32 mnFontId; /// Font identifier for the next characters. explicit FontPortionModel() : mnPos( 0 ), mnFontId( -1 ) {} explicit FontPortionModel( sal_Int32 nPos ) : mnPos( nPos ), mnFontId( -1 ) {} void read( SequenceInputStream& rStrm ); }; /** A vector with all font portions in a rich-string. */ class FontPortionModelList { ::std::vector< FontPortionModel > mvModels; public: explicit FontPortionModelList() : mvModels() {} bool empty() const { return mvModels.empty(); } const FontPortionModel& back() const { return mvModels.back(); } const FontPortionModel& front() const { return mvModels.front(); } void push_back(const FontPortionModel& rModel) { mvModels.push_back(rModel); } void insert(::std::vector< FontPortionModel >::iterator it, const FontPortionModel& rModel) { mvModels.insert(it, rModel); } ::std::vector< FontPortionModel >::iterator begin() { return mvModels.begin(); } /** Appends a rich-string font identifier. */ void appendPortion( const FontPortionModel& rPortion ); /** Reads count and font identifiers from the passed stream. */ void importPortions( SequenceInputStream& rStrm ); }; struct PhoneticDataModel { sal_Int32 mnFontId; /// Font identifier for text formatting. sal_Int32 mnType; /// Phonetic text type. sal_Int32 mnAlignment; /// Phonetic portion alignment. explicit PhoneticDataModel(); /** Sets the passed data from binary import. */ void setBiffData( sal_Int32 nType, sal_Int32 nAlignment ); }; class PhoneticSettings : public WorkbookHelper { public: explicit PhoneticSettings( const WorkbookHelper& rHelper ); /** Imports phonetic settings from the phoneticPr element. */ void importPhoneticPr( const AttributeList& rAttribs ); /** Imports phonetic settings from the PHONETICPR record. */ void importPhoneticPr( SequenceInputStream& rStrm ); /** Imports phonetic settings from a rich string. */ void importStringData( SequenceInputStream& rStrm ); private: PhoneticDataModel maModel; }; /** Contains text data and positioning information for a phonetic text portion. */ class RichStringPhonetic : public WorkbookHelper { public: explicit RichStringPhonetic( const WorkbookHelper& rHelper ); /** Sets text data for this phonetic portion. */ void setText( const OUString& rText ); /** Imports attributes of a phonetic run (rPh element). */ void importPhoneticRun( const AttributeList& rAttribs ); /** Sets the associated range in base text for this phonetic portion. */ void setBaseRange( sal_Int32 nBasePos, sal_Int32 nBaseEnd ); private: OUString maText; /// Portion text. sal_Int32 mnBasePos; /// Start position in base text. sal_Int32 mnBaseEnd; /// One-past-end position in base text. }; typedef std::shared_ptr< RichStringPhonetic > RichStringPhoneticRef; /** Represents a phonetic text portion in a rich-string with phonetic text. Used in binary filters only. */ struct PhoneticPortionModel { sal_Int32 mnPos; /// First character in phonetic text. sal_Int32 mnBasePos; /// First character in base text. sal_Int32 mnBaseLen; /// Number of characters in base text. explicit PhoneticPortionModel() : mnPos( -1 ), mnBasePos( -1 ), mnBaseLen( 0 ) {} explicit PhoneticPortionModel( sal_Int32 nPos, sal_Int32 nBasePos, sal_Int32 nBaseLen ) : mnPos( nPos ), mnBasePos( nBasePos ), mnBaseLen( nBaseLen ) {} void read( SequenceInputStream& rStrm ); }; /** A vector with all phonetic portions in a rich-string. */ class PhoneticPortionModelList { public: explicit PhoneticPortionModelList() : mvModels() {} bool empty() const { return mvModels.empty(); } const PhoneticPortionModel& back() const { return mvModels.back(); } void push_back(const PhoneticPortionModel& rModel) { mvModels.push_back(rModel); } ::std::vector< PhoneticPortionModel >::const_iterator begin() const { return mvModels.begin(); } /** Appends a rich-string phonetic portion. */ void appendPortion( const PhoneticPortionModel& rPortion ); /** Reads all phonetic portions from the passed stream. */ void importPortions( SequenceInputStream& rStrm ); private: ::std::vector< PhoneticPortionModel > mvModels; }; /** Contains string data and a list of formatting runs for a rich formatted string. */ class RichString : public WorkbookHelper { public: explicit RichString( const WorkbookHelper& rHelper ); /** Appends and returns a portion object for a plain string (t element). */ RichStringPortionRef importText(); /** Appends and returns a portion object for a new formatting run (r element). */ RichStringPortionRef importRun(); /** Appends and returns a phonetic text object for a new phonetic run (rPh element). */ RichStringPhoneticRef importPhoneticRun( const AttributeList& rAttribs ); /** Imports phonetic settings from the rPhoneticPr element. */ void importPhoneticPr( const AttributeList& rAttribs ); /** Imports a Unicode rich-string from the passed record stream. */ void importString( SequenceInputStream& rStrm, bool bRich ); /** Final processing after import of all strings. */ void finalizeImport(); /** Tries to extract a plain string from this object. Returns the string, if there is only one unformatted portion. */ bool extractPlainString( OUString& orString, const oox::xls::Font* pFirstPortionFont ) const; /** Converts the string and writes it into the passed XText, replace old contents of the text object,. @param rxText The XText interface of the target object. */ void convert( const css::uno::Reference< css::text::XText >& rxText ) const; std::unique_ptr<EditTextObject> convert( ScEditEngineDefaulter& rEE, const oox::xls::Font* pFont ) const; private: /** Creates, appends, and returns a new empty string portion. */ RichStringPortionRef createPortion(); /** Creates, appends, and returns a new empty phonetic text portion. */ RichStringPhoneticRef createPhonetic(); /** Create base text portions from the passed string and character formatting. */ void createTextPortions( const OUString& rText, FontPortionModelList& rPortions ); /** Create phonetic text portions from the passed string and portion data. */ void createPhoneticPortions( const OUString& rText, PhoneticPortionModelList& rPortions, sal_Int32 nBaseLen ); private: typedef RefVector< RichStringPortion > PortionVector; typedef RefVector< RichStringPhonetic > PhoneticVector; PortionVector maTextPortions; /// String portions with font data. PhoneticSettings maPhonSettings; /// Phonetic settings for this string. PhoneticVector maPhonPortions; /// Phonetic text portions. }; typedef std::shared_ptr< RichString > RichStringRef; } // namespace oox::xls /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
utf-8
1
MPL-2.0
Copyright 2000, 2010 Oracle and/or its affiliates. Copyright (c) 2000, 2010 LibreOffice contributors and/or their affiliates.
chromium-98.0.4758.102/components/data_reduction_proxy/core/browser/db_data_owner.cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/data_reduction_proxy/core/browser/db_data_owner.h" #include <utility> #include "base/check.h" #include "components/data_reduction_proxy/core/browser/data_store.h" #include "components/data_reduction_proxy/core/browser/data_usage_store.h" #include "components/data_reduction_proxy/proto/data_store.pb.h" namespace data_reduction_proxy { DBDataOwner::DBDataOwner(std::unique_ptr<DataStore> store) : store_(std::move(store)), data_usage_(new DataUsageStore(store_.get())) { sequence_checker_.DetachFromSequence(); } DBDataOwner::~DBDataOwner() { DCHECK(sequence_checker_.CalledOnValidSequence()); } void DBDataOwner::InitializeOnDBThread() { DCHECK(sequence_checker_.CalledOnValidSequence()); store_->InitializeOnDBThread(); } void DBDataOwner::LoadHistoricalDataUsage( std::vector<DataUsageBucket>* data_usage) { DCHECK(sequence_checker_.CalledOnValidSequence()); data_usage_->LoadDataUsage(data_usage); } void DBDataOwner::LoadCurrentDataUsageBucket(DataUsageBucket* bucket) { DCHECK(sequence_checker_.CalledOnValidSequence()); data_usage_->LoadCurrentDataUsageBucket(bucket); } void DBDataOwner::StoreCurrentDataUsageBucket( std::unique_ptr<DataUsageBucket> current) { DCHECK(sequence_checker_.CalledOnValidSequence()); data_usage_->StoreCurrentDataUsageBucket(*current); } void DBDataOwner::DeleteHistoricalDataUsage() { DCHECK(sequence_checker_.CalledOnValidSequence()); data_usage_->DeleteHistoricalDataUsage(); } void DBDataOwner::DeleteBrowsingHistory(const base::Time& start, const base::Time& end) { DCHECK(sequence_checker_.CalledOnValidSequence()); data_usage_->DeleteBrowsingHistory(start, end); } base::WeakPtr<DBDataOwner> DBDataOwner::GetWeakPtr() { return weak_factory_.GetWeakPtr(); } } // namespace data_reduction_proxy
utf-8
1
BSD-3-clause
The Chromium Authors. All rights reserved.
netpbm-free-10.0/pgm/psidtopgm.c
/* psidtopgm.c - convert PostScript "image" data into a portable graymap ** ** Copyright (C) 1989 by Jef Poskanzer. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. */ #include "pgm.h" static int gethexit ARGS(( FILE* ifp )); int main( argc, argv ) int argc; char* argv[]; { FILE* ifp; gray* grayrow; register gray* gP; int argn, row; register int col, val; int maxval; int rows, cols, bitspersample; char* usage = "<width> <height> <bits/sample> [imagedata]"; pgm_init( &argc, argv ); argn = 1; if ( argn + 3 > argc ) pm_usage( usage ); cols = atoi( argv[argn++] ); rows = atoi( argv[argn++] ); bitspersample = atoi( argv[argn++] ); if ( cols <= 0 || rows <= 0 || bitspersample <= 0 ) pm_usage( usage ); if ( argn < argc ) { ifp = pm_openr( argv[argn] ); ++argn; } else ifp = stdin; if ( argn != argc ) pm_usage( usage ); maxval = pm_bitstomaxval( bitspersample ); if ( maxval > PGM_OVERALLMAXVAL ) pm_error( "bits/sample (%d) is too large.", bitspersample ); pgm_writepgminit( stdout, cols, rows, (gray) maxval, 0 ); overflow_add(cols, 7); grayrow = pgm_allocrow( ( cols + 7 ) / 8 * 8 ); for ( row = 0; row < rows; ++row) { for ( col = 0, gP = grayrow; col < cols; ) { val = gethexit( ifp ) << 4; val += gethexit( ifp ); switch ( bitspersample ) { case 1: *gP++ = val >> 7; *gP++ = ( val >> 6 ) & 0x1; *gP++ = ( val >> 5 ) & 0x1; *gP++ = ( val >> 4 ) & 0x1; *gP++ = ( val >> 3 ) & 0x1; *gP++ = ( val >> 2 ) & 0x1; *gP++ = ( val >> 1 ) & 0x1; *gP++ = val & 0x1; col += 8; break; case 2: *gP++ = val >> 6; *gP++ = ( val >> 4 ) & 0x3; *gP++ = ( val >> 2 ) & 0x3; *gP++ = val & 0x3; col += 4; break; case 4: *gP++ = val >> 4; *gP++ = val & 0xf; col += 2; break; case 8: *gP++ = val; ++col; break; default: pm_error( "bitspersample of %d not supported", bitspersample ); } } pgm_writepgmrow( stdout, grayrow, cols, (gray) maxval, 0 ); } pm_close( ifp ); pm_close( stdout ); exit( 0 ); } static int gethexit( ifp ) FILE* ifp; { register int i; register char c; for ( ; ; ) { i = getc( ifp ); if ( i == EOF ) pm_error( "EOF / read error" ); c = (char) i; if ( c >= '0' && c <= '9' ) return c - '0'; else if ( c >= 'A' && c <= 'F' ) return c - 'A' + 10; else if ( c >= 'a' && c <= 'f' ) return c - 'a' + 10; /* Else ignore - whitespace. */ } }
utf-8
1
unknown
unknown
open-iscsi-2.1.5/usr/session_info.c
#include <stdlib.h> #include <stdio.h> #include <errno.h> #include <stdint.h> #include <inttypes.h> #include <libopeniscsiusr/libopeniscsiusr.h> #include "list.h" #include "log.h" #include "iscsi_sysfs.h" #include "version.h" #include "iscsi_settings.h" #include "mgmt_ipc.h" #include "session_info.h" #include "transport.h" #include "initiator.h" #include "iface.h" #include "iscsid_req.h" #include "iscsi_err.h" static int session_info_print_flat(struct iscsi_session *se); int session_info_create_list(void *data, struct session_info *info) { struct session_link_info *link_info = data; struct list_head *list = link_info->list; struct session_info *new, *curr, *match = NULL; if (link_info->match_fn && !link_info->match_fn(link_info->data, info)) return -1; new = calloc(1, sizeof(*new)); if (!new) return ISCSI_ERR_NOMEM; memcpy(new, info, sizeof(*new)); INIT_LIST_HEAD(&new->list); if (list_empty(list)) { list_add_tail(&new->list, list); return 0; } list_for_each_entry(curr, list, list) { if (!strcmp(curr->targetname, info->targetname)) { match = curr; if (!strcmp(curr->address, info->address)) { match = curr; if (curr->port == info->port) { match = curr; break; } } } } list_add_tail(&new->list, match ? match->list.next : list); return 0; } void session_info_free_list(struct list_head *list) { struct session_info *curr, *tmp; list_for_each_entry_safe(curr, tmp, list, list) { list_del(&curr->list); free(curr); } } static char *get_iscsi_node_type(uint32_t sid) { int pid = iscsi_sysfs_session_user_created((int) sid); if (!pid) return "flash"; else return "non-flash"; } static int session_info_print_flat(struct iscsi_session *se) { uint32_t sid = 0; struct iscsi_transport *t = NULL; sid = iscsi_session_sid_get(se); t = iscsi_sysfs_get_transport_by_sid((int) sid); if (strchr(iscsi_session_persistent_address_get(se), '.')) printf("%s: [%" PRIu32 "] %s:%" PRIi32 ",%"PRIi32 " %s (%s)\n", t ? t->name : UNKNOWN_VALUE, sid, iscsi_session_persistent_address_get(se), iscsi_session_persistent_port_get(se), iscsi_session_tpgt_get(se), iscsi_session_target_name_get(se), get_iscsi_node_type(sid)); else printf("%s: [%" PRIu32 "] [%s]:%" PRIi32 ",%" PRIi32 " %s (%s)\n", t ? t->name : UNKNOWN_VALUE, sid, iscsi_session_persistent_address_get(se), iscsi_session_persistent_port_get(se), iscsi_session_tpgt_get(se), iscsi_session_target_name_get(se), get_iscsi_node_type(sid)); return 0; } static int print_iscsi_state(int sid, char *prefix, int tmo) { iscsiadm_req_t req; iscsiadm_rsp_t rsp; int err; char *state = NULL; char state_buff[SCSI_MAX_STATE_VALUE]; static char *conn_state[] = { "FREE", "TRANSPORT WAIT", "IN LOGIN", "LOGGED IN", "IN LOGOUT", "LOGOUT REQUESTED", "CLEANUP WAIT", }; static char *session_state[] = { "NO CHANGE", "CLEANUP", "REOPEN", "REDIRECT", }; memset(&req, 0, sizeof(iscsiadm_req_t)); req.command = MGMT_IPC_SESSION_INFO; req.u.session.sid = sid; err = iscsid_exec_req(&req, &rsp, 1, tmo); /* * for drivers like qla4xxx, iscsid does not display * anything here since it does not know about it. */ if (!err && rsp.u.session_state.conn_state >= 0 && rsp.u.session_state.conn_state <= ISCSI_CONN_STATE_CLEANUP_WAIT) state = conn_state[rsp.u.session_state.conn_state]; printf("%s\t\tiSCSI Connection State: %s\n", prefix, state ? state : "Unknown"); state = NULL; memset(state_buff, 0, SCSI_MAX_STATE_VALUE); if (!iscsi_sysfs_get_session_state(state_buff, sid)) printf("%s\t\tiSCSI Session State: %s\n", prefix, state_buff); else printf("%s\t\tiSCSI Session State: Unknown\n", prefix); if (!err && rsp.u.session_state.session_state >= 0 && rsp.u.session_state.session_state <= R_STAGE_SESSION_REDIRECT) state = session_state[rsp.u.session_state.session_state]; printf("%s\t\tInternal iscsid Session State: %s\n", prefix, state ? state : "Unknown"); return 0; } static void print_iscsi_params(int sid, char *prefix) { struct iscsi_session_operational_config session_conf; struct iscsi_conn_operational_config conn_conf; iscsi_sysfs_get_negotiated_session_conf(sid, &session_conf); iscsi_sysfs_get_negotiated_conn_conf(sid, &conn_conf); printf("%s\t\t************************\n", prefix); printf("%s\t\tNegotiated iSCSI params:\n", prefix); printf("%s\t\t************************\n", prefix); if (is_valid_operational_value(conn_conf.HeaderDigest)) printf("%s\t\tHeaderDigest: %s\n", prefix, conn_conf.HeaderDigest ? "CRC32C" : "None"); if (is_valid_operational_value(conn_conf.DataDigest)) printf("%s\t\tDataDigest: %s\n", prefix, conn_conf.DataDigest ? "CRC32C" : "None"); if (is_valid_operational_value(conn_conf.MaxRecvDataSegmentLength)) printf("%s\t\tMaxRecvDataSegmentLength: %d\n", prefix, conn_conf.MaxRecvDataSegmentLength); if (is_valid_operational_value(conn_conf.MaxXmitDataSegmentLength)) printf("%s\t\tMaxXmitDataSegmentLength: %d\n", prefix, conn_conf.MaxXmitDataSegmentLength); if (is_valid_operational_value(session_conf.FirstBurstLength)) printf("%s\t\tFirstBurstLength: %d\n", prefix, session_conf.FirstBurstLength); if (is_valid_operational_value(session_conf.MaxBurstLength)) printf("%s\t\tMaxBurstLength: %d\n", prefix, session_conf.MaxBurstLength); if (is_valid_operational_value(session_conf.ImmediateData)) printf("%s\t\tImmediateData: %s\n", prefix, session_conf.ImmediateData ? "Yes" : "No"); if (is_valid_operational_value(session_conf.InitialR2T)) printf("%s\t\tInitialR2T: %s\n", prefix, session_conf.InitialR2T ? "Yes" : "No"); if (is_valid_operational_value(session_conf.MaxOutstandingR2T)) printf("%s\t\tMaxOutstandingR2T: %d\n", prefix, session_conf.MaxOutstandingR2T); } static void print_scsi_device_info(void *data, int host_no, int target, int lun) { char *prefix = data; char *blockdev, state[SCSI_MAX_STATE_VALUE]; printf("%s\t\tscsi%d Channel 00 Id %d Lun: %d\n", prefix, host_no, target, lun); blockdev = iscsi_sysfs_get_blockdev_from_lun(host_no, target, lun); if (blockdev) { printf("%s\t\t\tAttached scsi disk %s\t\t", prefix, blockdev); free(blockdev); if (!iscsi_sysfs_get_device_state(state, host_no, target, lun)) printf("State: %s\n", state); else printf("State: Unknown\n"); } } static int print_scsi_state(int sid, char *prefix, unsigned int flags) { int host_no = -1, err = 0; char state[SCSI_MAX_STATE_VALUE]; printf("%s\t\t************************\n", prefix); printf("%s\t\tAttached SCSI devices:\n", prefix); printf("%s\t\t************************\n", prefix); host_no = iscsi_sysfs_get_host_no_from_sid(sid, &err); if (err) { printf("%s\t\tUnavailable\n", prefix); return err; } if (flags & SESSION_INFO_HOST_DEVS) { printf("%s\t\tHost Number: %d\t", prefix, host_no); if (!iscsi_sysfs_get_host_state(state, host_no)) printf("State: %s\n", state); else printf("State: Unknown\n"); } if (flags & SESSION_INFO_SCSI_DEVS) iscsi_sysfs_for_each_device(prefix, host_no, sid, print_scsi_device_info); return 0; } void session_info_print_tree(struct iscsi_session **ses, uint32_t se_count, char *prefix, unsigned int flags, int do_show) { struct iscsi_session *curr = NULL; struct iscsi_session *prev = NULL; const char *curr_targetname = NULL; const char *curr_address = NULL; const char *persistent_address = NULL; const char *prev_targetname = NULL; const char *prev_address = NULL; int32_t curr_port = 0; int32_t prev_port = 0; uint32_t i = 0; uint32_t sid = 0; char *new_prefix = NULL; int32_t tgt_reset_tmo = -1; int32_t lu_reset_tmo = -1; int32_t abort_tmo = -1; const char *pass = NULL; for (i = 0; i < se_count; ++i) { curr = ses[i]; curr_targetname = iscsi_session_target_name_get(curr); sid = iscsi_session_sid_get(curr); if (prev != NULL) prev_targetname = iscsi_session_target_name_get(prev); else prev_targetname = NULL; if (! ((prev_targetname != NULL) && (curr_targetname != NULL) && (strcmp(prev_targetname, curr_targetname) == 0))) { printf("%sTarget: %s (%s)\n", prefix, curr_targetname, get_iscsi_node_type(sid)); prev = NULL; } curr_address = iscsi_session_address_get(curr); curr_port = iscsi_session_port_get(curr); if (prev != NULL) { prev_address = iscsi_session_address_get(prev); prev_port = iscsi_session_port_get(prev); } else { prev_address = NULL; prev_port = 0; } if (! ((prev_address != NULL) && (curr_address != NULL) && (prev_port != 0) && (curr_port != 0) && (strcmp(prev_address, curr_address) == 0) && (curr_port == prev_port))) { if (strchr(curr_address, '.')) printf("%s\tCurrent Portal: %s:%" PRIi32 ",%" PRIi32 "\n", prefix, curr_address, curr_port, iscsi_session_tpgt_get(curr)); else printf("%s\tCurrent Portal: [%s]:%" PRIi32 ",%" PRIi32 "\n", prefix, curr_address, curr_port, iscsi_session_tpgt_get(curr)); persistent_address = iscsi_session_persistent_address_get(curr); if (strchr(persistent_address, '.')) printf("%s\tPersistent Portal: %s:%" PRIi32 ",%" PRIi32 "\n", prefix, persistent_address, iscsi_session_persistent_port_get(curr), iscsi_session_tpgt_get(curr)); else printf("%s\tPersistent Portal: [%s]:%" PRIi32 ",%" PRIi32 "\n", prefix, persistent_address, iscsi_session_persistent_port_get(curr), iscsi_session_tpgt_get(curr)); } else printf("\n"); if (flags & SESSION_INFO_IFACE) { printf("%s\t\t**********\n", prefix); printf("%s\t\tInterface:\n", prefix); printf("%s\t\t**********\n", prefix); new_prefix = calloc(1, 1 + strlen(prefix) + strlen("\t\t")); if (new_prefix == NULL) { printf("Could not print interface info. " "Out of Memory.\n"); return; } else { sprintf(new_prefix, "%s%s", prefix, "\t\t"); iface_print(iscsi_session_iface_get(curr), new_prefix); } free(new_prefix); } if (flags & SESSION_INFO_ISCSI_STATE) { printf("%s\t\tSID: %" PRIu32 "\n", prefix, sid); print_iscsi_state((int) sid, prefix, -1 /* tmo */); /* TODO(Gris Ge): It seems in the whole project, * tmo is always -1, correct? */ } if (flags & SESSION_INFO_ISCSI_TIM) { printf("%s\t\t*********\n", prefix); printf("%s\t\tTimeouts:\n", prefix); printf("%s\t\t*********\n", prefix); printf("%s\t\tRecovery Timeout: %" PRIi32 "\n", prefix, iscsi_session_recovery_tmo_get(curr)); tgt_reset_tmo = iscsi_session_tgt_reset_tmo_get(curr); lu_reset_tmo = iscsi_session_lu_reset_tmo_get(curr); abort_tmo = iscsi_session_abort_tmo_get(curr); if (tgt_reset_tmo >= 0) printf("%s\t\tTarget Reset Timeout: %" PRIi32 "\n", prefix, tgt_reset_tmo); else printf("%s\t\tTarget Reset Timeout: %s\n", prefix, UNKNOWN_VALUE); if (lu_reset_tmo >= 0) printf("%s\t\tLUN Reset Timeout: %" PRIi32 "\n", prefix, lu_reset_tmo); else printf("%s\t\tLUN Reset Timeout: %s\n", prefix, UNKNOWN_VALUE); if (abort_tmo >= 0) printf("%s\t\tAbort Timeout: %" PRIi32 "\n", prefix, abort_tmo); else printf("%s\t\tAbort Timeout: %s\n", prefix, UNKNOWN_VALUE); } if (flags & SESSION_INFO_ISCSI_AUTH) { printf("%s\t\t*****\n", prefix); printf("%s\t\tCHAP:\n", prefix); printf("%s\t\t*****\n", prefix); printf("%s\t\tusername: %s\n", prefix, strlen(iscsi_session_username_get(curr)) ? iscsi_session_username_get(curr) : UNKNOWN_VALUE); if (!do_show) printf("%s\t\tpassword: %s\n", prefix, "********"); else { pass = iscsi_session_password_get(curr); printf("%s\t\tpassword: %s\n", prefix, strlen(pass) ? pass : UNKNOWN_VALUE); } printf("%s\t\tusername_in: %s\n", prefix, strlen(iscsi_session_username_in_get(curr)) ? iscsi_session_username_in_get(curr) : UNKNOWN_VALUE); if (!do_show) printf("%s\t\tpassword_in: %s\n", prefix, "********"); else { pass = iscsi_session_password_in_get(curr); printf("%s\t\tpassword: %s\n", prefix, strlen(pass) ? pass : UNKNOWN_VALUE); } } if (flags & SESSION_INFO_ISCSI_PARAMS) print_iscsi_params((int) sid, prefix); if (flags & (SESSION_INFO_SCSI_DEVS | SESSION_INFO_HOST_DEVS)) print_scsi_state((int) sid, prefix, flags); prev = curr; } } int session_info_print(int info_level, struct iscsi_session **ses, uint32_t se_count, int do_show) { int err = 0; char *version; unsigned int flags = 0; uint32_t i = 0; switch (info_level) { case 0: case -1: for (i = 0; i < se_count; ++i) { err = session_info_print_flat(ses[i]); if (err != 0) break; } break; case 3: version = iscsi_sysfs_get_iscsi_kernel_version(); if (version) { printf("iSCSI Transport Class version %s\n", version); printf("version %s\n", ISCSI_VERSION_STR); free(version); } flags |= (SESSION_INFO_SCSI_DEVS | SESSION_INFO_HOST_DEVS); /* fall through */ case 2: flags |= (SESSION_INFO_ISCSI_PARAMS | SESSION_INFO_ISCSI_TIM | SESSION_INFO_ISCSI_AUTH); /* fall through */ case 1: flags |= (SESSION_INFO_ISCSI_STATE | SESSION_INFO_IFACE); session_info_print_tree(ses, se_count, "", flags, do_show); break; default: log_error("Invalid info level %d. Try 0 - 3.", info_level); return ISCSI_ERR_INVAL; } if (err) { log_error("Can not get list of active sessions (%d)", err); return err; } return 0; }
utf-8
1
GPL-2+
2011, Aastha Mehta 2005, Alex Aizman 2002-2003, Ardis Technolgies <roman@ardistech.com> 2014-2015, Chris Leech 2001-2002, Cisco Systems, Inc 2011, Dell Inc 2004-2005, Dmitry Yusupov 2004-2005, Dmitry Yusupov, Alex Aizman 2004, FUJITA Tomonori <tomof@acm.org> 1989-1991, Free Software Foundation, Inc 2006-2007, IBM Corporation 2006-2011, Mike Christie 2013, QLogic Corporation 2014, Red Hat Inc 2006-2015, Red Hat, Inc 2006, Voltaire Ltd
qtcreator-6.0.2/tests/auto/algorithm/tst_algorithm.cpp
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include <QtTest> #include <array> #include <deque> #include <list> #include <memory> #include <unordered_map> #include <unordered_set> #include <valarray> // must get included after the containers above or gcc4.9 will have a problem using // initializer_list related code on the templates inside algorithm.h #include <utils/algorithm.h> #include <utils/porting.h> class tst_Algorithm : public QObject { Q_OBJECT private slots: void anyOf(); void transform(); void sort(); void contains(); void findOr(); void findOrDefault(); void toReferences(); void take(); }; int stringToInt(const QString &s) { return s.toInt(); } namespace { struct BaseStruct { BaseStruct(int m) : member(m) {} bool operator==(const BaseStruct &other) const { return member == other.member; } int member; }; struct Struct : public BaseStruct { Struct(int m) : BaseStruct(m) {} bool isOdd() const { return member % 2 == 1; } bool isEven() const { return !isOdd(); } int getMember() const { return member; } }; } void tst_Algorithm::anyOf() { { const QList<QString> strings({"1", "3", "132"}); QVERIFY(Utils::anyOf(strings, [](const QString &s) { return s == "132"; })); QVERIFY(!Utils::anyOf(strings, [](const QString &s) { return s == "1324"; })); } { const QList<Struct> list({2, 4, 6, 8}); QVERIFY(Utils::anyOf(list, &Struct::isEven)); QVERIFY(!Utils::anyOf(list, &Struct::isOdd)); } { const QList<Struct> list({0, 0, 0, 0, 1, 0, 0}); QVERIFY(Utils::anyOf(list, &Struct::member)); } { const QList<Struct> list({0, 0, 0, 0, 0, 0, 0}); QVERIFY(!Utils::anyOf(list, &Struct::member)); } } void tst_Algorithm::transform() { // same container type { // QList has standard inserter const QList<QString> strings({"1", "3", "132"}); const QList<int> i1 = Utils::transform(strings, [](const QString &s) { return s.toInt(); }); QCOMPARE(i1, QList<int>({1, 3, 132})); const QList<int> i2 = Utils::transform(strings, stringToInt); QCOMPARE(i2, QList<int>({1, 3, 132})); const QList<Utils::QtSizeType> i3 = Utils::transform(strings, &QString::size); QCOMPARE(i3, QList<Utils::QtSizeType>({1, 1, 3})); } { // QStringList const QStringList strings({"1", "3", "132"}); const QList<int> i1 = Utils::transform(strings, [](const QString &s) { return s.toInt(); }); QCOMPARE(i1, QList<int>({1, 3, 132})); const QList<int> i2 = Utils::transform(strings, stringToInt); QCOMPARE(i2, QList<int>({1, 3, 132})); const QList<Utils::QtSizeType> i3 = Utils::transform(strings, &QString::size); QCOMPARE(i3, QList<Utils::QtSizeType>({1, 1, 3})); } { // QSet internally needs special inserter const QSet<QString> strings({QString("1"), QString("3"), QString("132")}); const QSet<int> i1 = Utils::transform(strings, [](const QString &s) { return s.toInt(); }); QCOMPARE(i1, QSet<int>({1, 3, 132})); const QSet<int> i2 = Utils::transform(strings, stringToInt); QCOMPARE(i2, QSet<int>({1, 3, 132})); const QSet<Utils::QtSizeType> i3 = Utils::transform(strings, &QString::size); QCOMPARE(i3, QSet<Utils::QtSizeType>({1, 3})); } // different container types { // QList to QSet const QList<QString> strings({"1", "3", "132"}); const QSet<int> i1 = Utils::transform<QSet>(strings, [](const QString &s) { return s.toInt(); }); QCOMPARE(i1, QSet<int>({1, 3, 132})); const QSet<int> i2 = Utils::transform<QSet>(strings, stringToInt); QCOMPARE(i2, QSet<int>({1, 3, 132})); const QSet<Utils::QtSizeType> i3 = Utils::transform<QSet>(strings, &QString::size); QCOMPARE(i3, QSet<Utils::QtSizeType>({1, 3})); } { // QStringList to QSet const QStringList strings({"1", "3", "132"}); const QSet<int> i1 = Utils::transform<QSet>(strings, [](const QString &s) { return s.toInt(); }); QCOMPARE(i1, QSet<int>({1, 3, 132})); const QSet<int> i2 = Utils::transform<QSet>(strings, stringToInt); QCOMPARE(i2, QSet<int>({1, 3, 132})); const QSet<Utils::QtSizeType> i3 = Utils::transform<QSet>(strings, &QString::size); QCOMPARE(i3, QSet<Utils::QtSizeType>({1, 3})); } { // QSet to QList const QSet<QString> strings({QString("1"), QString("3"), QString("132")}); QList<int> i1 = Utils::transform<QList>(strings, [](const QString &s) { return s.toInt(); }); Utils::sort(i1); QCOMPARE(i1, QList<int>({1, 3, 132})); QList<int> i2 = Utils::transform<QList>(strings, stringToInt); Utils::sort(i2); QCOMPARE(i2, QList<int>({1, 3, 132})); QList<Utils::QtSizeType> i3 = Utils::transform<QList>(strings, &QString::size); Utils::sort(i3); QCOMPARE(i3, QList<Utils::QtSizeType>({1, 1, 3})); } { const QList<Struct> list({4, 3, 2, 1, 2}); const QList<int> trans = Utils::transform(list, &Struct::member); QCOMPARE(trans, QList<int>({4, 3, 2, 1, 2})); } { // QList -> std::vector const QList<int> v({1, 2, 3, 4}); const std::vector<int> trans = Utils::transform<std::vector>(v, [](int i) { return i + 1; }); QCOMPARE(trans, std::vector<int>({2, 3, 4, 5})); } { // QList -> std::vector const QList<Struct> v({1, 2, 3, 4}); const std::vector<int> trans = Utils::transform<std::vector>(v, &Struct::getMember); QCOMPARE(trans, std::vector<int>({1, 2, 3, 4})); } { // QList -> std::vector const QList<Struct> v({1, 2, 3, 4}); const std::vector<int> trans = Utils::transform<std::vector>(v, &Struct::member); QCOMPARE(trans, std::vector<int>({1, 2, 3, 4})); } { // std::vector -> QList const std::vector<int> v({1, 2, 3, 4}); const QList<int> trans = Utils::transform<QList>(v, [](int i) { return i + 1; }); QCOMPARE(trans, QList<int>({2, 3, 4, 5})); } { // std::vector -> QList const std::vector<Struct> v({1, 2, 3, 4}); const QList<int> trans = Utils::transform<QList>(v, &Struct::getMember); QCOMPARE(trans, QList<int>({1, 2, 3, 4})); } { // std::vector -> QList const std::vector<Struct> v({1, 2, 3, 4}); const QList<int> trans = Utils::transform<QList>(v, &Struct::member); QCOMPARE(trans, QList<int>({1, 2, 3, 4})); } { // std::deque -> std::vector const std::deque<int> v({1, 2, 3, 4}); const std::vector<int> trans = Utils::transform<std::vector>(v, [](int i) { return i + 1; }); QCOMPARE(trans, std::vector<int>({2, 3, 4, 5})); } { // std::deque -> std::vector const std::deque<Struct> v({1, 2, 3, 4}); const std::vector<int> trans = Utils::transform<std::vector>(v, &Struct::getMember); QCOMPARE(trans, std::vector<int>({1, 2, 3, 4})); } { // std::deque -> std::vector const std::deque<Struct> v({1, 2, 3, 4}); const std::vector<int> trans = Utils::transform<std::vector>(v, &Struct::member); QCOMPARE(trans, std::vector<int>({1, 2, 3, 4})); } { // std::vector -> std::vector const std::vector<int> v({1, 2, 3, 4}); const std::vector<int> trans = Utils::transform(v, [](int i) { return i + 1; }); QCOMPARE(trans, std::vector<int>({2, 3, 4, 5})); } { // std::vector -> std::vector const std::vector<Struct> v({1, 2, 3, 4}); const std::vector<int> trans = Utils::transform(v, &Struct::getMember); QCOMPARE(trans, std::vector<int>({1, 2, 3, 4})); } { // std::vector -> std::vector const std::vector<Struct> v({1, 2, 3, 4}); const std::vector<int> trans = Utils::transform(v, &Struct::member); QCOMPARE(trans, std::vector<int>({1, 2, 3, 4})); } { // std::unordered_map -> QList std::unordered_map<int, double> m; m.emplace(1, 1.5); m.emplace(3, 2.5); m.emplace(5, 3.5); QList<double> trans = Utils::transform<QList>(m, [](const std::pair<int, double> &in) { return in.first * in.second; }); Utils::sort(trans); QCOMPARE(trans, QList<double>({1.5, 7.5, 17.5})); } { // specific result container with one template parameter (QVector) std::vector<int> v({1, 2, 3, 4}); const QVector<BaseStruct *> trans = Utils::transform<QVector<BaseStruct *>>(v, [](int i) { return new Struct(i); }); QCOMPARE(trans.size(), 4); QCOMPARE(trans.at(0)->member, 1); QCOMPARE(trans.at(1)->member, 2); QCOMPARE(trans.at(2)->member, 3); QCOMPARE(trans.at(3)->member, 4); qDeleteAll(trans); } { // specific result container with one of two template parameters (std::vector) std::vector<int> v({1, 2, 3, 4}); const std::vector<BaseStruct *> trans = Utils::transform<std::vector<BaseStruct *>>(v, [](int i) { return new Struct(i); }); QCOMPARE(trans.size(), static_cast<std::vector<int>::size_type>(4ul)); QCOMPARE(trans.at(0)->member, 1); QCOMPARE(trans.at(1)->member, 2); QCOMPARE(trans.at(2)->member, 3); QCOMPARE(trans.at(3)->member, 4); qDeleteAll(trans); } { // specific result container with two template parameters (std::vector) std::vector<int> v({1, 2, 3, 4}); const std::vector<BaseStruct *, std::allocator<BaseStruct *>> trans = Utils::transform<std::vector<BaseStruct *, std::allocator<BaseStruct *>>>(v, [](int i) { return new Struct(i); }); QCOMPARE(trans.size(), static_cast<std::vector<int>::size_type>(4ul)); QCOMPARE(trans.at(0)->member, 1); QCOMPARE(trans.at(1)->member, 2); QCOMPARE(trans.at(2)->member, 3); QCOMPARE(trans.at(3)->member, 4); qDeleteAll(trans); } { // specific result container with member function QList<Struct> v({1, 2, 3, 4}); const QVector<double> trans = Utils::transform<QVector<double>>(v, &Struct::getMember); QCOMPARE(trans, QVector<double>({1.0, 2.0, 3.0, 4.0})); } { // specific result container with member QList<Struct> v({1, 2, 3, 4}); const QVector<double> trans = Utils::transform<QVector<double>>(v, &Struct::member); QCOMPARE(trans, QVector<double>({1.0, 2.0, 3.0, 4.0})); } { // non-const container and function parameter // same container type std::vector<Struct> v({1, 2, 3, 4}); const std::vector<std::reference_wrapper<Struct>> trans = Utils::transform(v, [](Struct &s) { return std::ref(s); }); // different container type QVector<Struct> v2({1, 2, 3, 4}); const std::vector<std::reference_wrapper<Struct>> trans2 = Utils::transform<std::vector>(v, [](Struct &s) { return std::ref(s); }); // temporaries const auto tempv = [] { return QList<Struct>({1, 2, 3, 4}); }; // temporary with member function const QList<int> trans3 = Utils::transform(tempv(), &Struct::getMember); const std::vector<int> trans4 = Utils::transform<std::vector>(tempv(), &Struct::getMember); const std::vector<int> trans5 = Utils::transform<std::vector<int>>(tempv(), &Struct::getMember); // temporary with member const QList<int> trans6 = Utils::transform(tempv(), &Struct::member); const std::vector<int> trans7 = Utils::transform<std::vector>(tempv(), &Struct::member); const std::vector<int> trans8 = Utils::transform<std::vector<int>>(tempv(), &Struct::member); // temporary with function const QList<int> trans9 = Utils::transform(tempv(), [](const Struct &s) { return s.getMember(); }); const std::vector<int> trans10 = Utils::transform<std::vector>(tempv(), [](const Struct &s) { return s.getMember(); }); const std::vector<int> trans11 = Utils::transform<std::vector<int>>(tempv(), [](const Struct &s) { return s.getMember(); }); } // target containers without reserve(...) { // std::vector -> std::deque const std::vector<int> v({1, 2, 3, 4}); const std::deque<int> trans = Utils::transform<std::deque>(v, [](int i) { return i + 1; }); QCOMPARE(trans, std::deque<int>({2, 3, 4, 5})); } { // std::vector -> std::list const std::vector<int> v({1, 2, 3, 4}); const std::list<int> trans = Utils::transform<std::list>(v, [](int i) { return i + 1; }); QCOMPARE(trans, std::list<int>({2, 3, 4, 5})); } { // std::vector -> std::set const std::vector<int> v({1, 2, 3, 4}); const std::set<int> trans = Utils::transform<std::set<int>>(v, [](int i) { return i + 1; }); QCOMPARE(trans, std::set<int>({2, 3, 4, 5})); } // various map/set/hash without push_back { // std::vector -> std::map const std::vector<int> v({1, 2, 3, 4}); const std::map<int, int> trans = Utils::transform<std::map<int, int>>(v, [](int i) { return std::make_pair(i, i + 1); }); const std::map<int, int> expected({{1, 2}, {2, 3}, {3, 4}, {4, 5}}); QCOMPARE(trans, expected); } { // std::vector -> std::unordered_set const std::vector<int> v({1, 2, 3, 4}); const std::unordered_set<int> trans = Utils::transform<std::unordered_set<int>>(v, [](int i) { return i + 1; }); QCOMPARE(trans, std::unordered_set<int>({2, 3, 4, 5})); } { // std::vector -> std::unordered_map const std::vector<int> v({1, 2, 3, 4}); const std::unordered_map<int, int> trans = Utils::transform<std::unordered_map<int, int>>(v, [](int i) { return std::make_pair(i, i + 1); }); const std::unordered_map<int, int> expected({{1, 2}, {2, 3}, {3, 4}, {4, 5}}); QCOMPARE(trans, expected); } { // std::vector -> QMap using std::pair const std::vector<int> v({1, 2, 3, 4}); const QMap<int, int> trans = Utils::transform<QMap<int, int>>(v, [](int i) { return std::make_pair(i, i + 1); }); const QMap<int, int> expected({{1, 2}, {2, 3}, {3, 4}, {4, 5}}); QCOMPARE(trans, expected); } { // std::vector -> QMap using QPair const std::vector<int> v({1, 2, 3, 4}); const QMap<int, int> trans = Utils::transform<QMap<int, int>>(v, [](int i) { return qMakePair(i, i + 1); }); const QMap<int, int> expected({{1, 2}, {2, 3}, {3, 4}, {4, 5}}); QCOMPARE(trans, expected); } { // std::vector -> QHash using std::pair const std::vector<int> v({1, 2, 3, 4}); const QHash<int, int> trans = Utils::transform<QHash<int, int>>(v, [](int i) { return std::make_pair(i, i + 1); }); const QHash<int, int> expected({{1, 2}, {2, 3}, {3, 4}, {4, 5}}); QCOMPARE(trans, expected); } { // std::vector -> QHash using QPair const std::vector<int> v({1, 2, 3, 4}); const QHash<int, int> trans = Utils::transform<QHash<int, int>>(v, [](int i) { return qMakePair(i, i + 1); }); const QHash<int, int> expected({{1, 2}, {2, 3}, {3, 4}, {4, 5}}); QCOMPARE(trans, expected); } } void tst_Algorithm::sort() { QStringList s1({"3", "2", "1"}); Utils::sort(s1); QCOMPARE(s1, QStringList({"1", "2", "3"})); QStringList s2({"13", "31", "22"}); Utils::sort(s2, [](const QString &a, const QString &b) { return a[1] < b[1]; }); QCOMPARE(s2, QStringList({"31", "22", "13"})); QList<QString> s3({"12345", "3333", "22"}); Utils::sort(s3, &QString::size); QCOMPARE(s3, QList<QString>({"22", "3333", "12345"})); QList<Struct> s4({4, 3, 2, 1}); Utils::sort(s4, &Struct::member); QCOMPARE(s4, QList<Struct>({1, 2, 3, 4})); // member function with pointers QList<QString> arr1({"12345", "3333", "22"}); QList<QString *> s5({&arr1[0], &arr1[1], &arr1[2]}); Utils::sort(s5, &QString::size); QCOMPARE(s5, QList<QString *>({&arr1[2], &arr1[1], &arr1[0]})); // member with pointers QList<Struct> arr2({4, 1, 3}); QList<Struct *> s6({&arr2[0], &arr2[1], &arr2[2]}); Utils::sort(s6, &Struct::member); QCOMPARE(s6, QList<Struct *>({&arr2[1], &arr2[2], &arr2[0]})); // std::array: std::array<int, 4> array = {{4, 10, 8, 1}}; Utils::sort(array); std::array<int, 4> arrayResult = {{1, 4, 8, 10}}; QCOMPARE(array, arrayResult); // valarray (no begin/end member functions): std::valarray<int> valarray(array.data(), array.size()); std::valarray<int> valarrayResult(arrayResult.data(), arrayResult.size()); Utils::sort(valarray); QCOMPARE(valarray.size(), valarrayResult.size()); for (size_t i = 0; i < valarray.size(); ++i) QCOMPARE(valarray[i], valarrayResult[i]); } void tst_Algorithm::contains() { std::vector<int> v1{1, 2, 3, 4}; QVERIFY(Utils::contains(v1, [](int i) { return i == 2; })); QVERIFY(!Utils::contains(v1, [](int i) { return i == 5; })); std::vector<Struct> structs = {2, 4, 6, 8}; QVERIFY(Utils::contains(structs, &Struct::isEven)); QVERIFY(!Utils::contains(structs, &Struct::isOdd)); QList<Struct> structQlist = {2, 4, 6, 8}; QVERIFY(Utils::contains(structQlist, &Struct::isEven)); QVERIFY(!Utils::contains(structQlist, &Struct::isOdd)); } void tst_Algorithm::findOr() { std::vector<int> v1{1, 2, 3, 4}; QCOMPARE(Utils::findOr(v1, 10, [](int i) { return i == 2; }), 2); QCOMPARE(Utils::findOr(v1, 10, [](int i) { return i == 5; }), 10); } void tst_Algorithm::findOrDefault() { { std::vector<int> v1{1, 2, 3, 4}; QCOMPARE(Utils::findOrDefault(v1, [](int i) { return i == 2; }), 2); QCOMPARE(Utils::findOrDefault(v1, [](int i) { return i == 5; }), 0); } { std::vector<std::shared_ptr<Struct>> v4; v4.emplace_back(std::make_shared<Struct>(1)); v4.emplace_back(std::make_shared<Struct>(3)); v4.emplace_back(std::make_shared<Struct>(5)); v4.emplace_back(std::make_shared<Struct>(7)); QCOMPARE(Utils::findOrDefault(v4, &Struct::isOdd), v4.at(0)); QCOMPARE(Utils::findOrDefault(v4, &Struct::isEven), std::shared_ptr<Struct>()); } } void tst_Algorithm::toReferences() { // toReference { // std::vector -> std::vector std::vector<Struct> v; const std::vector<std::reference_wrapper<Struct>> x = Utils::toReferences(v); } { // QList -> std::vector QList<Struct> v; const std::vector<std::reference_wrapper<Struct>> x = Utils::toReferences<std::vector>(v); } { // std::vector -> QList std::vector<Struct> v; const QList<std::reference_wrapper<Struct>> x = Utils::toReferences<QList>(v); } { // std::vector -> std::list std::vector<Struct> v; const std::list<std::reference_wrapper<Struct>> x = Utils::toReferences<std::list>(v); } // toConstReference { // std::vector -> std::vector const std::vector<Struct> v; const std::vector<std::reference_wrapper<const Struct>> x = Utils::toConstReferences(v); } { // QList -> std::vector const QList<Struct> v; const std::vector<std::reference_wrapper<const Struct>> x = Utils::toConstReferences<std::vector>(v); } { // std::vector -> QList const std::vector<Struct> v; const QList<std::reference_wrapper<const Struct>> x = Utils::toConstReferences<QList>(v); } { // std::vector -> std::list const std::vector<Struct> v; const std::list<std::reference_wrapper<const Struct>> x = Utils::toConstReferences<std::list>(v); } } void tst_Algorithm::take() { { QList<Struct> v {1, 3, 5, 6, 7, 8, 9, 11, 13, 15, 13, 16, 17}; Utils::optional<Struct> r1 = Utils::take(v, [](const Struct &s) { return s.member == 13; }); QVERIFY(static_cast<bool>(r1)); QCOMPARE(r1.value().member, 13); Utils::optional<Struct> r2 = Utils::take(v, [](const Struct &s) { return s.member == 13; }); QVERIFY(static_cast<bool>(r2)); QCOMPARE(r2.value().member, 13); Utils::optional<Struct> r3 = Utils::take(v, [](const Struct &s) { return s.member == 13; }); QVERIFY(!static_cast<bool>(r3)); Utils::optional<Struct> r4 = Utils::take(v, &Struct::isEven); QVERIFY(static_cast<bool>(r4)); QCOMPARE(r4.value().member, 6); } { QList<Struct> v {0, 0, 0, 0, 0, 0, 1, 2, 3}; Utils::optional<Struct> r1 = Utils::take(v, &Struct::member); QVERIFY(static_cast<bool>(r1)); QCOMPARE(r1.value().member, 1); } } QTEST_MAIN(tst_Algorithm) #include "tst_algorithm.moc"
utf-8
1
GPL-3 with Qt-1.0 exception
2008-2020 The Qt Company
network-manager-1.35.91/src/core/nm-dispatcher.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2004 - 2012 Red Hat, Inc. * Copyright (C) 2005 - 2008 Novell, Inc. */ #ifndef __NM_DISPATCHER_H__ #define __NM_DISPATCHER_H__ #include "nm-connection.h" typedef enum { NM_DISPATCHER_ACTION_HOSTNAME, NM_DISPATCHER_ACTION_PRE_UP, NM_DISPATCHER_ACTION_UP, NM_DISPATCHER_ACTION_PRE_DOWN, NM_DISPATCHER_ACTION_DOWN, NM_DISPATCHER_ACTION_VPN_PRE_UP, NM_DISPATCHER_ACTION_VPN_UP, NM_DISPATCHER_ACTION_VPN_PRE_DOWN, NM_DISPATCHER_ACTION_VPN_DOWN, NM_DISPATCHER_ACTION_DHCP_CHANGE_4, NM_DISPATCHER_ACTION_DHCP_CHANGE_6, NM_DISPATCHER_ACTION_CONNECTIVITY_CHANGE } NMDispatcherAction; #define NM_DISPATCHER_ACTION_DHCP_CHANGE_X(IS_IPv4) \ ((IS_IPv4) ? NM_DISPATCHER_ACTION_DHCP_CHANGE_4 : NM_DISPATCHER_ACTION_DHCP_CHANGE_6) typedef struct NMDispatcherCallId NMDispatcherCallId; typedef void (*NMDispatcherFunc)(NMDispatcherCallId *call_id, gpointer user_data); gboolean nm_dispatcher_call_hostname(NMDispatcherFunc callback, gpointer user_data, NMDispatcherCallId **out_call_id); gboolean nm_dispatcher_call_device(NMDispatcherAction action, NMDevice *device, NMActRequest *act_request, NMDispatcherFunc callback, gpointer user_data, NMDispatcherCallId **out_call_id); gboolean nm_dispatcher_call_device_sync(NMDispatcherAction action, NMDevice *device, NMActRequest *act_request); gboolean nm_dispatcher_call_vpn(NMDispatcherAction action, NMSettingsConnection *settings_connection, NMConnection *applied_connection, NMDevice *parent_device, const char *vpn_iface, const NML3ConfigData *l3cd, NMDispatcherFunc callback, gpointer user_data, NMDispatcherCallId **out_call_id); gboolean nm_dispatcher_call_vpn_sync(NMDispatcherAction action, NMSettingsConnection *settings_connection, NMConnection *applied_connection, NMDevice *parent_device, const char *vpn_iface, const NML3ConfigData *l3cd); gboolean nm_dispatcher_call_connectivity(NMConnectivityState state, NMDispatcherFunc callback, gpointer user_data, NMDispatcherCallId **out_call_id); void nm_dispatcher_call_cancel(NMDispatcherCallId *call_id); #endif /* __NM_DISPATCHER_H__ */
utf-8
1
GPL-2+
2004 - 2019 Red Hat, Inc. 2005 - 2009 Novell, Inc.
ucx-1.12.1~rc2/src/ucs/sys/module.h
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2019. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifndef UCS_MODULE_H_ #define UCS_MODULE_H_ #include <ucs/type/init_once.h> #include <ucs/sys/compiler_def.h> /** * Flags for @ref UCS_MODULE_FRAMEWORK_LOAD */ typedef enum { UCS_MODULE_LOAD_FLAG_NODELETE = UCS_BIT(0), /**< Never unload */ UCS_MODULE_LOAD_FLAG_GLOBAL = UCS_BIT(1) /**< Load to global scope */ } ucs_module_load_flags_t; /** * Declare a "framework", which is a context for a specific collection of * loadable modules. Usually the modules in a particular framework provide * alternative implementations of the same internal interface. * * @param [in] _name Framework name (as a token) */ #define UCS_MODULE_FRAMEWORK_DECLARE(_name) \ static ucs_init_once_t ucs_framework_init_once_##_name = \ UCS_INIT_ONCE_INITIALIZER /** * Load all modules in a particular framework. * * @param [in] _name Framework name, same as passed to * @ref UCS_MODULE_FRAMEWORK_DECLARE * @param [in] _flags Modules load flags, see @ref ucs_module_load_flags_t * * The modules in the framework are loaded by dlopen(). The shared library name * of a module is: "lib<framework>_<module>.so.<version>", where: * - <framework> is the framework name * - <module> is the module name. The list of all modules in a framework is * defined by the preprocessor macro <framework>_MODULES in the auto-generated * config.h file, for example: #define foo_MODULES ":bar1:bar2". * - <version> is the shared library version of the module, as generated by * libtool. It's extracted from the full path of the current library (libucs). * * Module shared libraries are searched in the following locations (in order of * priority): * 1. 'ucx' sub-directory inside the directory of the current shared library (libucs) * 2. ${libdir}/ucx, where ${libdir} is the directory where libraries are installed * Note that if libucs is loaded from its installation path, (1) and (2) are the * same location. Only if libucs is moved or ran from build directory, the paths * will be different, in which case we prefer the 'local' library rather than the * 'installed' one. * * @param [in] _name Framework name (as a token) */ #define UCS_MODULE_FRAMEWORK_LOAD(_name, _flags) \ ucs_load_modules(#_name, _name##_MODULES, &ucs_framework_init_once_##_name, \ _flags) /** * Define a function to be called when a module is loaded. * Some things can't be done in shared library constructor, and need to be done * only after dlopen() completes. For example, loading another shared library * which uses symbols from the current module. * * Usage: * UCS_MODULE_INIT() { ... code ... } */ #define UCS_MODULE_INIT() \ ucs_status_t __attribute__((visibility("protected"))) \ UCS_MODULE_CONSTRUCTOR_NAME(void) /** * Define the name of a loadable module global constructor */ #define UCS_MODULE_CONSTRUCTOR_NAME \ ucs_module_global_init /** * Internal function. Please use @ref UCS_MODULE_FRAMEWORK_LOAD macro instead. */ void ucs_load_modules(const char *framework, const char *modules, ucs_init_once_t *init_once, unsigned flags); #endif
utf-8
1
BSD-3-Clause
(c) 2014-2015 UT-Battelle, LLC. All rights reserved. (C) 2014-2015 Mellanox Technologies Ltd. All rights reserved. (C) 2019- Mellanox Technologies Ltd. All rights reserved.
linux-5.16.7/drivers/usb/c67x00/c67x00.h
/* SPDX-License-Identifier: GPL-2.0+ */ /* * c67x00.h: Cypress C67X00 USB register and field definitions * * Copyright (C) 2006-2008 Barco N.V. * Derived from the Cypress cy7c67200/300 ezusb linux driver and * based on multiple host controller drivers inside the linux kernel. */ #ifndef _USB_C67X00_H #define _USB_C67X00_H #include <linux/spinlock.h> #include <linux/platform_device.h> #include <linux/completion.h> #include <linux/mutex.h> /* --------------------------------------------------------------------- * Cypress C67x00 register definitions */ /* Hardware Revision Register */ #define HW_REV_REG 0xC004 /* General USB registers */ /* ===================== */ /* USB Control Register */ #define USB_CTL_REG(x) ((x) ? 0xC0AA : 0xC08A) #define LOW_SPEED_PORT(x) ((x) ? 0x0800 : 0x0400) #define HOST_MODE 0x0200 #define PORT_RES_EN(x) ((x) ? 0x0100 : 0x0080) #define SOF_EOP_EN(x) ((x) ? 0x0002 : 0x0001) /* USB status register - Notice it has different content in hcd/udc mode */ #define USB_STAT_REG(x) ((x) ? 0xC0B0 : 0xC090) #define EP0_IRQ_FLG 0x0001 #define EP1_IRQ_FLG 0x0002 #define EP2_IRQ_FLG 0x0004 #define EP3_IRQ_FLG 0x0008 #define EP4_IRQ_FLG 0x0010 #define EP5_IRQ_FLG 0x0020 #define EP6_IRQ_FLG 0x0040 #define EP7_IRQ_FLG 0x0080 #define RESET_IRQ_FLG 0x0100 #define SOF_EOP_IRQ_FLG 0x0200 #define ID_IRQ_FLG 0x4000 #define VBUS_IRQ_FLG 0x8000 /* USB Host only registers */ /* ======================= */ /* Host n Control Register */ #define HOST_CTL_REG(x) ((x) ? 0xC0A0 : 0xC080) #define PREAMBLE_EN 0x0080 /* Preamble enable */ #define SEQ_SEL 0x0040 /* Data Toggle Sequence Bit Select */ #define ISO_EN 0x0010 /* Isochronous enable */ #define ARM_EN 0x0001 /* Arm operation */ /* Host n Interrupt Enable Register */ #define HOST_IRQ_EN_REG(x) ((x) ? 0xC0AC : 0xC08C) #define SOF_EOP_IRQ_EN 0x0200 /* SOF/EOP Interrupt Enable */ #define SOF_EOP_TMOUT_IRQ_EN 0x0800 /* SOF/EOP Timeout Interrupt Enable */ #define ID_IRQ_EN 0x4000 /* ID interrupt enable */ #define VBUS_IRQ_EN 0x8000 /* VBUS interrupt enable */ #define DONE_IRQ_EN 0x0001 /* Done Interrupt Enable */ /* USB status register */ #define HOST_STAT_MASK 0x02FD #define PORT_CONNECT_CHANGE(x) ((x) ? 0x0020 : 0x0010) #define PORT_SE0_STATUS(x) ((x) ? 0x0008 : 0x0004) /* Host Frame Register */ #define HOST_FRAME_REG(x) ((x) ? 0xC0B6 : 0xC096) #define HOST_FRAME_MASK 0x07FF /* USB Peripheral only registers */ /* ============================= */ /* Device n Port Sel reg */ #define DEVICE_N_PORT_SEL(x) ((x) ? 0xC0A4 : 0xC084) /* Device n Interrupt Enable Register */ #define DEVICE_N_IRQ_EN_REG(x) ((x) ? 0xC0AC : 0xC08C) #define DEVICE_N_ENDPOINT_N_CTL_REG(dev, ep) ((dev) \ ? (0x0280 + (ep << 4)) \ : (0x0200 + (ep << 4))) #define DEVICE_N_ENDPOINT_N_STAT_REG(dev, ep) ((dev) \ ? (0x0286 + (ep << 4)) \ : (0x0206 + (ep << 4))) #define DEVICE_N_ADDRESS(dev) ((dev) ? (0xC0AE) : (0xC08E)) /* HPI registers */ /* ============= */ /* HPI Status register */ #define SOFEOP_FLG(x) (1 << ((x) ? 12 : 10)) #define SIEMSG_FLG(x) (1 << (4 + (x))) #define RESET_FLG(x) ((x) ? 0x0200 : 0x0002) #define DONE_FLG(x) (1 << (2 + (x))) #define RESUME_FLG(x) (1 << (6 + (x))) #define MBX_OUT_FLG 0x0001 /* Message out available */ #define MBX_IN_FLG 0x0100 #define ID_FLG 0x4000 #define VBUS_FLG 0x8000 /* Interrupt routing register */ #define HPI_IRQ_ROUTING_REG 0x0142 #define HPI_SWAP_ENABLE(x) ((x) ? 0x0100 : 0x0001) #define RESET_TO_HPI_ENABLE(x) ((x) ? 0x0200 : 0x0002) #define DONE_TO_HPI_ENABLE(x) ((x) ? 0x0008 : 0x0004) #define RESUME_TO_HPI_ENABLE(x) ((x) ? 0x0080 : 0x0040) #define SOFEOP_TO_HPI_EN(x) ((x) ? 0x2000 : 0x0800) #define SOFEOP_TO_CPU_EN(x) ((x) ? 0x1000 : 0x0400) #define ID_TO_HPI_ENABLE 0x4000 #define VBUS_TO_HPI_ENABLE 0x8000 /* SIE msg registers */ #define SIEMSG_REG(x) ((x) ? 0x0148 : 0x0144) #define HUSB_TDListDone 0x1000 #define SUSB_EP0_MSG 0x0001 #define SUSB_EP1_MSG 0x0002 #define SUSB_EP2_MSG 0x0004 #define SUSB_EP3_MSG 0x0008 #define SUSB_EP4_MSG 0x0010 #define SUSB_EP5_MSG 0x0020 #define SUSB_EP6_MSG 0x0040 #define SUSB_EP7_MSG 0x0080 #define SUSB_RST_MSG 0x0100 #define SUSB_SOF_MSG 0x0200 #define SUSB_CFG_MSG 0x0400 #define SUSB_SUS_MSG 0x0800 #define SUSB_ID_MSG 0x4000 #define SUSB_VBUS_MSG 0x8000 /* BIOS interrupt routines */ #define SUSBx_RECEIVE_INT(x) ((x) ? 97 : 81) #define SUSBx_SEND_INT(x) ((x) ? 96 : 80) #define SUSBx_DEV_DESC_VEC(x) ((x) ? 0x00D4 : 0x00B4) #define SUSBx_CONF_DESC_VEC(x) ((x) ? 0x00D6 : 0x00B6) #define SUSBx_STRING_DESC_VEC(x) ((x) ? 0x00D8 : 0x00B8) #define CY_HCD_BUF_ADDR 0x500 /* Base address for host */ #define SIE_TD_SIZE 0x200 /* size of the td list */ #define SIE_TD_BUF_SIZE 0x400 /* size of the data buffer */ #define SIE_TD_OFFSET(host) ((host) ? (SIE_TD_SIZE+SIE_TD_BUF_SIZE) : 0) #define SIE_BUF_OFFSET(host) (SIE_TD_OFFSET(host) + SIE_TD_SIZE) /* Base address of HCD + 2 x TD_SIZE + 2 x TD_BUF_SIZE */ #define CY_UDC_REQ_HEADER_BASE 0x1100 /* 8- byte request headers for IN/OUT transfers */ #define CY_UDC_REQ_HEADER_SIZE 8 #define CY_UDC_REQ_HEADER_ADDR(ep_num) (CY_UDC_REQ_HEADER_BASE + \ ((ep_num) * CY_UDC_REQ_HEADER_SIZE)) #define CY_UDC_DESC_BASE_ADDRESS (CY_UDC_REQ_HEADER_ADDR(8)) #define CY_UDC_BIOS_REPLACE_BASE 0x1800 #define CY_UDC_REQ_BUFFER_BASE 0x2000 #define CY_UDC_REQ_BUFFER_SIZE 0x0400 #define CY_UDC_REQ_BUFFER_ADDR(ep_num) (CY_UDC_REQ_BUFFER_BASE + \ ((ep_num) * CY_UDC_REQ_BUFFER_SIZE)) /* --------------------------------------------------------------------- * Driver data structures */ struct c67x00_device; /** * struct c67x00_sie - Common data associated with a SIE * @lock: lock to protect this struct and the associated chip registers * @private_data: subdriver dependent data * @irq: subdriver dependent irq handler, set NULL when not used * @dev: link to common driver structure * @sie_num: SIE number on chip, starting from 0 * @mode: SIE mode (host/peripheral/otg/not used) */ struct c67x00_sie { /* Entries to be used by the subdrivers */ spinlock_t lock; /* protect this structure */ void *private_data; void (*irq) (struct c67x00_sie *sie, u16 int_status, u16 msg); /* Read only: */ struct c67x00_device *dev; int sie_num; int mode; }; #define sie_dev(s) (&(s)->dev->pdev->dev) /** * struct c67x00_lcp */ struct c67x00_lcp { /* Internal use only */ struct mutex mutex; struct completion msg_received; u16 last_msg; }; /* * struct c67x00_hpi */ struct c67x00_hpi { void __iomem *base; int regstep; spinlock_t lock; struct c67x00_lcp lcp; }; #define C67X00_SIES 2 #define C67X00_PORTS 2 /** * struct c67x00_device - Common data associated with a c67x00 instance * @hpi: hpi addresses * @sie: array of sie's on this chip * @pdev: platform device of instance * @pdata: configuration provided by the platform */ struct c67x00_device { struct c67x00_hpi hpi; struct c67x00_sie sie[C67X00_SIES]; struct platform_device *pdev; struct c67x00_platform_data *pdata; }; /* --------------------------------------------------------------------- * Low level interface functions */ /* Host Port Interface (HPI) functions */ u16 c67x00_ll_hpi_status(struct c67x00_device *dev); void c67x00_ll_hpi_reg_init(struct c67x00_device *dev); void c67x00_ll_hpi_enable_sofeop(struct c67x00_sie *sie); void c67x00_ll_hpi_disable_sofeop(struct c67x00_sie *sie); /* General functions */ u16 c67x00_ll_fetch_siemsg(struct c67x00_device *dev, int sie_num); u16 c67x00_ll_get_usb_ctl(struct c67x00_sie *sie); void c67x00_ll_usb_clear_status(struct c67x00_sie *sie, u16 bits); u16 c67x00_ll_usb_get_status(struct c67x00_sie *sie); void c67x00_ll_write_mem_le16(struct c67x00_device *dev, u16 addr, void *data, int len); void c67x00_ll_read_mem_le16(struct c67x00_device *dev, u16 addr, void *data, int len); /* Host specific functions */ void c67x00_ll_set_husb_eot(struct c67x00_device *dev, u16 value); void c67x00_ll_husb_reset(struct c67x00_sie *sie, int port); void c67x00_ll_husb_set_current_td(struct c67x00_sie *sie, u16 addr); u16 c67x00_ll_husb_get_current_td(struct c67x00_sie *sie); u16 c67x00_ll_husb_get_frame(struct c67x00_sie *sie); void c67x00_ll_husb_init_host_port(struct c67x00_sie *sie); void c67x00_ll_husb_reset_port(struct c67x00_sie *sie, int port); /* Called by c67x00_irq to handle lcp interrupts */ void c67x00_ll_irq(struct c67x00_device *dev, u16 int_status); /* Setup and teardown */ void c67x00_ll_init(struct c67x00_device *dev); void c67x00_ll_release(struct c67x00_device *dev); int c67x00_ll_reset(struct c67x00_device *dev); #endif /* _USB_C67X00_H */
utf-8
1
GPL-2
1991-2012 Linus Torvalds and many others
dolfin-2019.2.0~git20210928.3eacdb4/dolfin/fem/NonlinearVariationalSolver.h
// Copyright (C) 2008-2011 Anders Logg and Garth N. Wells // // This file is part of DOLFIN. // // DOLFIN 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 3 of the License, or // (at your option) any later version. // // DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>. // // Modified by Marie E. Rognes, 2011. // Modified by Corrado Maurini, 2013. // // First added: 2011-01-14 (2008-12-26 as VariationalProblem.h) // Last changed: 2013-11-20 #ifndef __NONLINEAR_VARIATIONAL_SOLVER_H #define __NONLINEAR_VARIATIONAL_SOLVER_H #include <dolfin/nls/NonlinearProblem.h> #include <dolfin/nls/NewtonSolver.h> #include <dolfin/nls/PETScSNESSolver.h> #include "NonlinearVariationalProblem.h" #include "SystemAssembler.h" namespace dolfin { /// This class implements a solver for nonlinear variational /// problems. class NonlinearVariationalSolver : public Variable { public: /// Create nonlinear variational solver for given problem explicit NonlinearVariationalSolver(std::shared_ptr<NonlinearVariationalProblem> problem); /// Solve variational problem /// /// *Returns* /// std::pair<std::size_t, bool> /// Pair of number of Newton iterations, and whether /// iteration converged) std::pair<std::size_t, bool> solve(); /// Default parameter values static Parameters default_parameters() { Parameters p("nonlinear_variational_solver"); p.add("symmetric", false); p.add("print_rhs", false); p.add("print_matrix", false); std::set<std::string> nonlinear_solvers = {"newton"}; std::string default_nonlinear_solver = "newton"; p.add(NewtonSolver::default_parameters()); #ifdef HAS_PETSC p.add(PETScSNESSolver::default_parameters()); nonlinear_solvers.insert("snes"); #endif p.add("nonlinear_solver", default_nonlinear_solver, nonlinear_solvers); return p; } private: // Nonlinear (algebraic) problem class NonlinearDiscreteProblem : public NonlinearProblem { public: // Constructor NonlinearDiscreteProblem( std::shared_ptr<const NonlinearVariationalProblem> problem, std::shared_ptr<const NonlinearVariationalSolver> solver); // Destructor ~NonlinearDiscreteProblem(); // Compute F at current point x virtual void F(GenericVector& b, const GenericVector& x); // Compute J = F' at current point x virtual void J(GenericMatrix& A, const GenericVector& x); private: // Problem and solver objects std::shared_ptr<const NonlinearVariationalProblem> _problem; std::shared_ptr<const NonlinearVariationalSolver> _solver; }; // The nonlinear problem std::shared_ptr<NonlinearVariationalProblem> _problem; // The nonlinear discrete problem std::shared_ptr<NonlinearDiscreteProblem> nonlinear_problem; // The Newton solver std::shared_ptr<NewtonSolver> newton_solver; #ifdef HAS_PETSC // Or, alternatively, the SNES solver std::shared_ptr<PETScSNESSolver> snes_solver; #endif }; } #endif
utf-8
1
LGPL-3+
2001-2019, Authors/contributors in alphabetical order: Ido Akkerman <I.Akkerman@tudelft.nl> Martin Sandve Alnæs <martinal@simula.no> Fredrik Bengzon <bengzon@math.chalmers.se> Aslak Bergersen <aslak.bergersen@gmail.com> Jan Blechta <blechta@karlin.mff.cuni.cz> Rolv Erlend Bredesen <rolv@simula.no> Jed Brown <fenics@59A2.org> Solveig Bruvoll <solveio@ifi.uio.no> Jørgen S. Dokken <dokken92@gmail.com> Niklas Ericsson <nen@math.chalmers.se> Patrick Farrell <patrick.farrell06@imperial.ac.uk> Georgios Foufas <foufas@math.chalmers.se> Tom Gustafsson <tom.gustafsson@aalto.fi> Joachim B Haga <jobh@broadpark.no> Johan Hake <hake@simula.no> Jack S. Hale <j.hale09@imperial.ac.uk> Rasmus Hemph <PDE project course 2001/2002> David Heintz <david.heintz@comhem.se> Johan Hoffman <hoffman@csc.kth.se> Par Ingelstrom <pi@elmagn.chalmers.se> Anders E. Johansen <andersej@math.uio.no> Johan Jansson <johanjan@math.chalmers.se> Niclas Jansson <njansson@kth.se> Alexander Jarosch <alexanj@hi.is> Kristen Kaasbjerg <cosby@fys.ku.dk> Benjamin Kehlet <benjamik@simula.no> Arve Knudsen <arvenk@simula.no> Karin Kraft <kakr@math.chalmers.se> Aleksandra Krusper <PDE project course 2001/2002> Evan Lezar <mail@evanlezar.com> Tianyi Li <tianyi.li@polytechnique.edu> Matthias Liertzer <matthias.liertzer@tuwien.ac.at> Dag Lindbo <dag@csc.kth.se> Glenn Terje Lines <glennli@simula.no> Anders Logg <logg@simula.no> Nuno Lopes <ndl@ptmat.fc.ul.pt> Kent-Andre Mardal <kent-and@simula.no> Sigvald Marholm <sigvald@marebakken.com> Andreas Mark <f00anma@dd.chalmers.se> Andre Massing <massing@simula.no> Lawrence Mitchell <lawrence.mitchell@imperial.ac.uk> Marco Morandini <morandini@aero.polimi.it> Mikael Mortensen <mikael.mortensen@gmail.com> Corrado Maurini <cmaurini@gmail.com> Pablo De Napoli <pdenapo@gmail.com> Harish Narayanan <hnarayanan@gmail.com> Andreas Nilsson <f99anni@dd.chalmers.se> Minh Do-Quang <minh@mech.kth.se> Chris Richardson <chris@bpi.cam.ac.uk> Johannes Ring <johannr@simula.no> Marie E. Rognes <meg@simula.no> John Rudge <jfr23@cam.ac.uk> Bartosz Sawicki <sawickib@iem.pw.edu.pl> Nico Schlömer <nico.schloemer@gmail.com> Kristoffer Selim <selim@simula.no> Angelo Simone <a.simone@tudelft.nl> Ola Skavhaug <skavhaug@simula.no> Thomas Svedberg <thsv@am.chalmers.se> Erik Svensson <eriksv@math.chalmers.se> Harald Svensson <harald.s@home.se> Andy Terrel <aterrel@uchicago.edu> Jim Tilander <jt@dd.chalmers.se> Fredrik Valdmanis <fredrik@valdmanis.com> Magnus Vikstrøm <gustavv@ifi.uio.no> Walter Villanueva <PDE project course 2001/2002> Shawn Walker <walker@cims.nyu.edu> Garth N. Wells <gnw20@cam.ac.uk> Ilmar Wilbers <ilmarw@simula.dot.no> Cian Wilson <cwilson@ldeo.columbia.edu> Ivan Yashchuk <ivan.yashchuk@aalto.fi> Michele Zaffalon <michele.zaffalon@gmail.com> Åsmund Ødegård <aasmund@simula.no> Kristian Ølgaard <kbo@civil.aau.dk>
cdebootstrap-0.7.8/src/target.c
/* * target.c * * Copyright (C) 2003-2016 Bastian Blank <waldi@debian.org> * * 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; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <config.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "log.h" #include "target.h" void target_create(const char *name_in, bool create_dir) { char *name, *name_tmp; if (name_in[0] == '/') name = name_tmp = strdup(name_in + 1); else name = name_tmp = strdup(name_in); int fd_root = open(target_root, O_DIRECTORY | O_RDONLY); if (fd_root < 0) abort(); while (true) { // Overwrites the next seperator with \0 strsep(&name_tmp, "/"); if (name_tmp || create_dir) { if (mkdirat(fd_root, name, 0755) < 0) { if (errno != EEXIST) log_text(DI_LOG_LEVEL_ERROR, "Directory creation failed for %s: %s", name, strerror(errno)); } } else { int fd = openat(fd_root, name, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd < 0) { if (errno != EEXIST) log_text(DI_LOG_LEVEL_ERROR, "File creation failed for %s: %s", name, strerror(errno)); } close(fd); } if (!name_tmp) break; // Reset overwritten seperator *(name_tmp - 1) = '/'; } close(fd_root); free(name); }
utf-8
1
unknown
unknown
coda-2.23/libcoda/coda-mem-internal.h
/* * Copyright (C) 2007-2021 S[&]T, The Netherlands. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 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 COPYRIGHT HOLDER 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. */ #ifndef CODA_MEM_INTERNAL_H #define CODA_MEM_INTERNAL_H #include "coda-mem.h" #include "coda-type.h" /* When auto-growing coda_product.mem_ptr (using realloc) this will be a multiple of DATA_BLOCK_SIZE */ #define DATA_BLOCK_SIZE 4096 typedef enum mem_type_tag_enum { tag_mem_record, tag_mem_array, tag_mem_data, tag_mem_special } mem_type_tag; typedef struct coda_mem_type_struct { coda_backend backend; coda_type *definition; mem_type_tag tag; coda_dynamic_type *attributes; } coda_mem_type; typedef struct coda_mem_record_struct { coda_backend backend; coda_type_record *definition; mem_type_tag tag; coda_dynamic_type *attributes; long num_fields; coda_dynamic_type **field_type; /* if field_type[i] == NULL then field #i is not available */ } coda_mem_record; typedef struct coda_mem_array_struct { coda_backend backend; coda_type_array *definition; mem_type_tag tag; coda_dynamic_type *attributes; long num_elements; coda_dynamic_type **element; } coda_mem_array; typedef struct coda_mem_data_struct { coda_backend backend; coda_type *definition; mem_type_tag tag; coda_dynamic_type *attributes; long length; /* byte length of data block in coda_product.mem_ptr */ int64_t offset; /* byte offset within coda_product.mem_ptr */ } coda_mem_data; typedef struct coda_mem_special_struct { coda_backend backend; coda_type_special *definition; mem_type_tag tag; coda_dynamic_type *attributes; coda_dynamic_type *base_type; } coda_mem_special; int coda_mem_type_update(coda_dynamic_type **type, coda_type *definition); int coda_mem_type_add_attribute(coda_mem_type *type, const char *real_name, coda_dynamic_type *attribute_type, int update_definition); int coda_mem_type_set_attributes(coda_mem_type *type, coda_dynamic_type *attributes, int update_definition); coda_mem_record *coda_mem_record_new(coda_type_record *definition, coda_dynamic_type *attributes); int coda_mem_record_add_field(coda_mem_record *type, const char *real_name, coda_dynamic_type *field_type, int update_definition); int coda_mem_record_validate(coda_mem_record *type); coda_mem_array *coda_mem_array_new(coda_type_array *definition, coda_dynamic_type *attributes); /* use coda_mem_array_add_element() if array definition has dynamic length */ int coda_mem_array_add_element(coda_mem_array *type, coda_dynamic_type *element); /* use coda_mem_array_set_element() if array definition has static length */ int coda_mem_array_set_element(coda_mem_array *type, long index, coda_dynamic_type *element); int coda_mem_array_validate(coda_mem_array *type); coda_mem_data *coda_mem_data_new(coda_type *definition, coda_dynamic_type *attributes, coda_product *product, long length, const uint8_t *data); coda_mem_data *coda_mem_int8_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, int8_t value); coda_mem_data *coda_mem_uint8_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, uint8_t value); coda_mem_data *coda_mem_int16_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, int16_t value); coda_mem_data *coda_mem_uint16_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, uint16_t value); coda_mem_data *coda_mem_int32_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, int32_t value); coda_mem_data *coda_mem_uint32_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, uint32_t value); coda_mem_data *coda_mem_int64_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, int64_t value); coda_mem_data *coda_mem_uint64_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, uint64_t value); coda_mem_data *coda_mem_float_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, float value); coda_mem_data *coda_mem_double_new(coda_type_number *definition, coda_dynamic_type *attributes, coda_product *product, double value); coda_mem_data *coda_mem_char_new(coda_type_text *definition, coda_dynamic_type *attributes, coda_product *product, char value); coda_mem_data *coda_mem_string_new(coda_type_text *definition, coda_dynamic_type *attributes, coda_product *product, const char *str); coda_mem_data *coda_mem_raw_new(coda_type_raw *definition, coda_dynamic_type *attributes, coda_product *product, long length, const uint8_t *data); coda_mem_special *coda_mem_time_new(coda_type_special *definition, coda_dynamic_type *attributes, coda_dynamic_type *base_type); coda_mem_special *coda_mem_no_data_new(coda_format format); #endif
utf-8
1
BSD
Copyright (C) 2007-2017 S[&]T, The Netherlands.
nodejs-12.22.9~dfsg/src/inspector/runtime_agent.h
#ifndef SRC_INSPECTOR_RUNTIME_AGENT_H_ #define SRC_INSPECTOR_RUNTIME_AGENT_H_ #include "node/inspector/protocol/NodeRuntime.h" #include "v8.h" namespace node { class Environment; namespace inspector { namespace protocol { class RuntimeAgent : public NodeRuntime::Backend { public: RuntimeAgent(); void Wire(UberDispatcher* dispatcher); DispatchResponse notifyWhenWaitingForDisconnect(bool enabled) override; bool notifyWaitingForDisconnect(); private: std::shared_ptr<NodeRuntime::Frontend> frontend_; bool notify_when_waiting_for_disconnect_; }; } // namespace protocol } // namespace inspector } // namespace node #endif // SRC_INSPECTOR_RUNTIME_AGENT_H_
utf-8
1
Expat
Node.js contributors, Joyent, Inc. and other Node contributors.
grass-7.8.6/lib/gpde/test/test_gwflow.c
/***************************************************************************** * * MODULE: Grass PDE Numerical Library * AUTHOR(S): Soeren Gebbert, Berlin (GER) Dec 2006 * soerengebbert <at> gmx <dot> de * * PURPOSE: gwflow integration tests * * COPYRIGHT: (C) 2000 by the GRASS Development Team * * This program is free software under the GNU General Public * License (>=v2). Read the file COPYING that comes with GRASS * for details. * *****************************************************************************/ #include <grass/gmath.h> #include <grass/gis.h> #include <grass/N_pde.h> #include <grass/gmath.h> #include <grass/N_gwflow.h> #include "test_gpde_lib.h" /*redefine */ #define TEST_N_NUM_DEPTHS_LOCAL 2 #define TEST_N_NUM_ROWS_LOCAL 3 #define TEST_N_NUM_COLS_LOCAL 3 /* prototypes */ static N_gwflow_data2d *create_gwflow_data_2d(void); static N_gwflow_data3d *create_gwflow_data_3d(void); static int test_gwflow_2d(void); static int test_gwflow_3d(void); /* *************************************************************** */ /* Performe the gwflow integration tests ************************* */ /* *************************************************************** */ int integration_test_gwflow(void) { int sum = 0; G_message("\n++ Running gwflow integration tests ++"); G_message("\t 1. testing 2d gwflow"); sum += test_gwflow_2d(); G_message("\t 2. testing 3d gwflow"); sum += test_gwflow_3d(); if (sum > 0) G_warning("\n-- gwflow integration tests failure --"); else G_message("\n-- gwflow integration tests finished successfully --"); return sum; } /* *************************************************************** */ /* Create valid groundwater flow data **************************** */ /* *************************************************************** */ N_gwflow_data3d *create_gwflow_data_3d(void) { N_gwflow_data3d *data; int i, j, k; data = N_alloc_gwflow_data3d(TEST_N_NUM_COLS_LOCAL, TEST_N_NUM_ROWS_LOCAL, TEST_N_NUM_DEPTHS_LOCAL, 1, 1); #pragma omp parallel for private (i, j, k) shared (data) for (k = 0; k < TEST_N_NUM_DEPTHS_LOCAL; k++) for (j = 0; j < TEST_N_NUM_ROWS_LOCAL; j++) { for (i = 0; i < TEST_N_NUM_COLS_LOCAL; i++) { if (j == 0) { N_put_array_3d_d_value(data->phead, i, j, k, 50); N_put_array_3d_d_value(data->phead_start, i, j, k, 50); N_put_array_3d_d_value(data->status, i, j, k, 2); } else { N_put_array_3d_d_value(data->phead, i, j, k, 40); N_put_array_3d_d_value(data->phead_start, i, j, k, 40); N_put_array_3d_d_value(data->status, i, j, k, 1); } N_put_array_3d_d_value(data->hc_x, i, j, k, 0.0001); N_put_array_3d_d_value(data->hc_y, i, j, k, 0.0001); N_put_array_3d_d_value(data->hc_z, i, j, k, 0.0001); N_put_array_3d_d_value(data->q, i, j, k, 0.0); N_put_array_3d_d_value(data->s, i, j, k, 0.001); N_put_array_2d_d_value(data->r, i, j, 0.0); N_put_array_3d_d_value(data->nf, i, j, k, 0.1); } } return data; } /* *************************************************************** */ /* Create valid groundwater flow data **************************** */ /* *************************************************************** */ N_gwflow_data2d *create_gwflow_data_2d(void) { int i, j; N_gwflow_data2d *data; data = N_alloc_gwflow_data2d(TEST_N_NUM_COLS_LOCAL, TEST_N_NUM_ROWS_LOCAL, 1, 1); #pragma omp parallel for private (i, j) shared (data) for (j = 0; j < TEST_N_NUM_ROWS_LOCAL; j++) { for (i = 0; i < TEST_N_NUM_COLS_LOCAL; i++) { if (j == 0) { N_put_array_2d_d_value(data->phead, i, j, 50); N_put_array_2d_d_value(data->phead_start, i, j, 50); N_put_array_2d_d_value(data->status, i, j, 2); } else { N_put_array_2d_d_value(data->phead, i, j, 40); N_put_array_2d_d_value(data->phead_start, i, j, 40); N_put_array_2d_d_value(data->status, i, j, 1); } N_put_array_2d_d_value(data->hc_x, i, j, 30.0001); N_put_array_2d_d_value(data->hc_y, i, j, 30.0001); N_put_array_2d_d_value(data->q, i, j, 0.0); N_put_array_2d_d_value(data->s, i, j, 0.001); N_put_array_2d_d_value(data->r, i, j, 0.0); N_put_array_2d_d_value(data->nf, i, j, 0.1); N_put_array_2d_d_value(data->top, i, j, 20.0); N_put_array_2d_d_value(data->bottom, i, j, 0.0); } } return data; } /* *************************************************************** */ /* Test the groundwater flow in 3d with different solvers ******** */ /* *************************************************************** */ int test_gwflow_3d(void) { N_gwflow_data3d *data; N_geom_data *geom; N_les *les; N_les_callback_3d *call; call = N_alloc_les_callback_3d(); N_set_les_callback_3d_func(call, (*N_callback_gwflow_3d)); /*gwflow 3d */ data = create_gwflow_data_3d(); data->dt = 86400; geom = N_alloc_geom_data(); geom->dx = 10; geom->dy = 15; geom->dz = 3; geom->Az = 150; geom->depths = TEST_N_NUM_DEPTHS_LOCAL; geom->rows = TEST_N_NUM_ROWS_LOCAL; geom->cols = TEST_N_NUM_COLS_LOCAL; /*Assemble the matrix */ /* */ /*CG*/ les = N_assemble_les_3d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_cg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*PCG G_MATH_DIAGONAL_PRECONDITION*/ les = N_assemble_les_3d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_pcg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_DIAGONAL_PRECONDITION); N_print_les(les); N_free_les(les); /*PCG G_MATH_ROWSCALE_EUKLIDNORM_PRECONDITION*/ les = N_assemble_les_3d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_pcg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_ROWSCALE_EUKLIDNORM_PRECONDITION); N_print_les(les); N_free_les(les); /*PCG G_MATH_ROWSCALE_ABSSUMNORM_PRECONDITION*/ les = N_assemble_les_3d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_pcg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_ROWSCALE_ABSSUMNORM_PRECONDITION); N_print_les(les); N_free_les(les); /*CG*/ les = N_assemble_les_3d_dirichlet(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_3d(les, geom, data->status, data->phead_start); G_math_solver_sparse_cg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*CG*/ les = N_assemble_les_3d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_cg(les->A, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*PCG G_MATH_DIAGONAL_PRECONDITION*/ les = N_assemble_les_3d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_pcg(les->A, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_DIAGONAL_PRECONDITION); N_print_les(les); N_free_les(les); /*PCG G_MATH_ROWSCALE_EUKLIDNORM_PRECONDITION*/ les = N_assemble_les_3d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_pcg(les->A, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_ROWSCALE_EUKLIDNORM_PRECONDITION); N_print_les(les); N_free_les(les); /*PCG G_MATH_ROWSCALE_ABSSUMNORM_PRECONDITION*/ les = N_assemble_les_3d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_pcg(les->A, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_ROWSCALE_ABSSUMNORM_PRECONDITION); N_print_les(les); N_free_les(les); /*CG*/ les = N_assemble_les_3d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_3d(les, geom, data->status, data->phead_start); G_math_solver_cg(les->A, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*BICG*/ les = N_assemble_les_3d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_bicgstab(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*BICG*/ les = N_assemble_les_3d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_bicgstab(les->A, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*BICG*/ les = N_assemble_les_3d_dirichlet(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_3d(les, geom, data->status, data->phead_start); G_math_solver_sparse_bicgstab(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*BICG*/ les = N_assemble_les_3d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_3d(les, geom, data->status, data->phead_start); G_math_solver_bicgstab(les->A, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*GUASS*/ les = N_assemble_les_3d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_gauss(les->A, les->x, les->b, les->rows); N_print_les(les); N_free_les(les); /*LU*/ les = N_assemble_les_3d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_lu(les->A, les->x, les->b, les->rows); N_print_les(les); N_free_les(les); /*GUASS*/ les = N_assemble_les_3d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_3d(les, geom, data->status, data->phead_start); G_math_solver_gauss(les->A, les->x, les->b, les->rows); N_print_les(les); N_free_les(les); /*LU*/ les = N_assemble_les_3d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_3d(les, geom, data->status, data->phead_start); G_math_solver_lu(les->A, les->x, les->b, les->rows); N_print_les(les); N_free_les(les); /*Cholesky*/ les = N_assemble_les_3d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_cholesky(les->A, les->x, les->b, les->rows, les->rows); N_print_les(les); N_free_les(les); /*Cholesky*/ les = N_assemble_les_3d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_3d(les, geom, data->status, data->phead_start); G_math_solver_cholesky(les->A, les->x, les->b, les->rows, les->rows); N_print_les(les); N_free_les(les); N_free_gwflow_data3d(data); G_free(geom); G_free(call); return 0; } /* *************************************************************** */ int test_gwflow_2d(void) { N_gwflow_data2d *data; N_geom_data *geom; N_les *les; N_les_callback_2d *call; /*set the callback */ call = N_alloc_les_callback_2d(); N_set_les_callback_2d_func(call, (*N_callback_gwflow_2d)); data = create_gwflow_data_2d(); data->dt = 600; geom = N_alloc_geom_data(); geom->dx = 10; geom->dy = 15; geom->Az = 150; geom->rows = TEST_N_NUM_ROWS_LOCAL; geom->cols = TEST_N_NUM_COLS_LOCAL; /*Assemble the matrix */ /* */ /*CG*/ les = N_assemble_les_2d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_cg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*PCG G_MATH_DIAGONAL_PRECONDITION*/ les = N_assemble_les_2d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_pcg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_DIAGONAL_PRECONDITION); N_print_les(les); N_free_les(les); /*PCG G_MATH_ROWSCALE_EUKLIDNORM_PRECONDITION*/ les = N_assemble_les_2d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_pcg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_ROWSCALE_EUKLIDNORM_PRECONDITION); N_print_les(les); N_free_les(les); /*PCG G_MATH_ROWSCALE_ABSSUMNORM_PRECONDITION*/ les = N_assemble_les_2d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_pcg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_ROWSCALE_ABSSUMNORM_PRECONDITION); N_print_les(les); N_free_les(les); /*CG*/ les = N_assemble_les_2d_dirichlet(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_2d(les, geom, data->status, data->phead_start); G_math_solver_sparse_cg(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*CG*/ les = N_assemble_les_2d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_cg(les->A, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*PCG G_MATH_DIAGONAL_PRECONDITION*/ les = N_assemble_les_2d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_pcg(les->A, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_DIAGONAL_PRECONDITION); N_print_les(les); N_free_les(les); /*PCG G_MATH_ROWSCALE_EUKLIDNORM_PRECONDITION*/ les = N_assemble_les_2d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_pcg(les->A, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_ROWSCALE_EUKLIDNORM_PRECONDITION); N_print_les(les); N_free_les(les); /*PCG G_MATH_ROWSCALE_ABSSUMNORM_PRECONDITION*/ les = N_assemble_les_2d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_pcg(les->A, les->x, les->b, les->rows, 100, 0.1e-8, G_MATH_ROWSCALE_ABSSUMNORM_PRECONDITION); N_print_les(les); N_free_les(les); /*CG*/ les = N_assemble_les_2d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_2d(les, geom, data->status, data->phead_start); G_math_solver_cg(les->A, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*BICG*/ les = N_assemble_les_2d(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_sparse_bicgstab(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*BICG*/ les = N_assemble_les_2d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_bicgstab(les->A, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*BICG*/ les = N_assemble_les_2d_dirichlet(N_SPARSE_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_2d(les, geom, data->status, data->phead_start); G_math_solver_sparse_bicgstab(les->Asp, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*BICG*/ les = N_assemble_les_2d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_2d(les, geom, data->status, data->phead_start); G_math_solver_bicgstab(les->A, les->x, les->b, les->rows, 100, 0.1e-8); N_print_les(les); N_free_les(les); /*GUASS*/ les = N_assemble_les_2d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_gauss(les->A, les->x, les->b, les->rows); N_print_les(les); N_free_les(les); /*LU*/ les = N_assemble_les_2d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_lu(les->A, les->x, les->b, les->rows); N_print_les(les); N_free_les(les); /*GUASS*/ les = N_assemble_les_2d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_2d(les, geom, data->status, data->phead_start); G_math_solver_gauss(les->A, les->x, les->b, les->rows); N_print_les(les); N_free_les(les); /*LU*/ les = N_assemble_les_2d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_2d(les, geom, data->status, data->phead_start); G_math_solver_lu(les->A, les->x, les->b, les->rows); N_print_les(les); N_free_les(les); /*Cholesky*/ les = N_assemble_les_2d(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); G_math_solver_cholesky(les->A, les->x, les->b, les->rows, les->rows); N_print_les(les); N_free_les(les); /*Cholesky*/ les = N_assemble_les_2d_dirichlet(N_NORMAL_LES, geom, data->status, data->phead_start, (void *)data, call); N_les_integrate_dirichlet_2d(les, geom, data->status, data->phead_start); G_math_solver_cholesky(les->A, les->x, les->b, les->rows, les->rows); N_print_les(les); N_free_les(les); N_free_gwflow_data2d(data); G_free(geom); G_free(call); return 0; }
utf-8
1
GPL-2+
1989-2021, GRASS Development Team 2003-2021, Markus Neteler 2003-2021, Glynn Clements 2003-2021, Luca Delucchi 2006-2021, Martin Landa 2011-2021, Vaclav Petras 2012-2021, Stepan Turek 2011-2020, Markus Metz 2017-2018, Supreet Singh 2014-2018, Tereza Fiedlerova 2018, Shubham Sharma 1992-2017, Helena Mitasova 2011-2017, Soeren Gebbert 2017, Maris Nartiss 2017, Sunveer Singh 2012-2016, Anna Petrasova 2016, Adam Laza 2016, Zofie Cimburova 2014-2015, Matej Krejci 2015, Jachym Ceppicky 2015, pietro 2015, Stephanie Wendel 1993-2014, James Darrell McCauley <darrell@mccauley-usa.com> 2003-2014, Per Henrik Johansen 2006-2014, Hamish Bowman 2007-2014, Lars Ahlzen 2011-2013, Anna Kratochvilova 2013, GKX Associates Inc. 2009-2010, 2012, Daniel Bundala 2012, Eric Momsen 2001-2011, Frank Warmerdam 2011, Tom Kralidis 2007-2010, E. Jorge Tizado 2007, 2010, Laura Toma 2006-2009, Cedric Shoc 2009, Gabor Grothendieck 2007-2008, Martin Schroeder 2008, Marcus D. Hanwell <marcus@cryos.org> 2005-2006, Politecnico di Milano 2004-2005, GDF Hannover 2002-2003, University of Sannio (BN) - Italy 2003, Christo Zietsman 1989, 1993-2000, 2002, Lubos Mitas 1995, 2002, J. Hofierka 1998-2002, Free Software Foundation, Inc 2002, Jaro Hofierka 2002, Roberto Micarelli 1996-2000, Brian Gough 2000, David D.Gray <ddgray@armadce.demon.co.uk> 1995, Bill Brown <brown@gis.uiuc.edu> & Michael Shapiro 1995, M. Ruesink 1995, J. Caplan, 1995, M. Zlocha 1993, 1995, D. McCauley 1992-1993, 1995, D. Gerdes 1992-1993, 1995, I. Kosinovsky 1994, Bill Brown, USACERL 1993, RMIT 1992, USA-CERL
php-redis-5.3.5+4.3.0/redis-5.3.5/sentinel_library.h
#ifndef REDIS_SENTINEL_LIBRARY_H #define REDIS_SENTINEL_LIBRARY_H #include "common.h" #include "library.h" typedef redis_object redis_sentinel_object; zend_object *create_sentinel_object(zend_class_entry *ce); PHP_REDIS_API int sentinel_mbulk_reply_zipped_assoc(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx); #endif /* REDIS_SENTINEL_LIBRARY_H */
utf-8
1
PHP-3.01
1997-2009 The PHP Group
syslinux-6.04~git20190206.bf6db5b4+dfsg1/core/writestr.c
/* * ----------------------------------------------------------------------- * * Copyright 1994-2008 H. Peter Anvin - All Rights Reserved * * 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, Inc., 53 Temple Place Ste 330, * Boston MA 02111-1307, USA; either version 2 of the License, or * (at your option) any later version; incorporated herein by reference. * * ----------------------------------------------------------------------- * * * writestr.c * * Code to write a simple string. */ #include <com32.h> #include <core.h> /* * crlf: Print a newline */ void crlf(void) { writechr('\r'); writechr('\n'); } /* * writestr: write a null-terminated string to the console, saving * registers on entry. * * Note: writestr_early and writestr are distinct in * SYSLINUX and EXTLINUX, but not PXELINUX and ISOLINUX */ void writestr(char *str) { while (*str) writechr(*str++); } void pm_writestr(com32sys_t *regs) { writestr(MK_PTR(regs->ds, regs->esi.w[0])); }
utf-8
1
GPL-2+
2009-2014, Intel Corporation; author: H. Peter Anvin 1994-2009, H. Peter Anvin 2008-2012, Gene Cumm
oce-0.18.3/inc/IGESBasic_AssocGroupType.hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _IGESBasic_AssocGroupType_HeaderFile #define _IGESBasic_AssocGroupType_HeaderFile #include <Standard.hxx> #include <Standard_DefineHandle.hxx> #include <Handle_IGESBasic_AssocGroupType.hxx> #include <Standard_Integer.hxx> #include <Handle_TCollection_HAsciiString.hxx> #include <IGESData_IGESEntity.hxx> class TCollection_HAsciiString; //! defines AssocGroupType, Type <406> Form <23> //! in package IGESBasic //! Used to assign an unambiguous identification to a Group //! Associativity. class IGESBasic_AssocGroupType : public IGESData_IGESEntity { public: Standard_EXPORT IGESBasic_AssocGroupType(); //! This method is used to set the fields of the class //! AssocGroupType //! - nbDataFields : number of parameter data fields = 2 //! - aType : type of attached associativity //! - aName : identifier of associativity of type AType Standard_EXPORT void Init (const Standard_Integer nbDataFields, const Standard_Integer aType, const Handle(TCollection_HAsciiString)& aName) ; //! returns the number of parameter data fields, always = 2 Standard_EXPORT Standard_Integer NbData() const; //! returns the type of attached associativity Standard_EXPORT Standard_Integer AssocType() const; //! returns identifier of instance of specified associativity Standard_EXPORT Handle(TCollection_HAsciiString) Name() const; DEFINE_STANDARD_RTTI(IGESBasic_AssocGroupType) protected: private: Standard_Integer theNbData; Standard_Integer theType; Handle(TCollection_HAsciiString) theName; }; #endif // _IGESBasic_AssocGroupType_HeaderFile
utf-8
1
LGPL-2.1 with OpenCASCADE exception
Copyright (C) 1991-2000 by Matra Datavision SA., Copyright (C) 2001-2013 Open CASCADE S.A.S.
atlas-3.10.3/src/blas/pklevel3/gpmm/ATL_pcol2blk.c
/* * Automatically Tuned Linear Algebra Software v3.10.3 * (C) Copyright 2003 R. Clint Whaley * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the ATLAS group or the names of its contributers may * not be used to endorse or promote products derived from this * software without specific 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 ATLAS GROUP OR ITS 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. * */ #include "atlas_pkblas.h" void Mjoin(Mjoin(PATL,pcol2blk),NM) (const int M, const int N, const TYPE alpha, const TYPE *A, int lda, const int ldainc, TYPE *V) /* * Given a packed matrix A, copies N columns starting at A into * block-major column panel * ldainc = 0 : General * ldainc = 1 : Upper * ldainc = -1 : Lower * NOTE: specialize to alpha cases after it works! */ { const int kb = Mmin(M,NB); const int nrb = M / kb, mr = M - nrb*kb; int i, ib, j, J; const int NN = N*kb; TYPE *v = V + nrb*NN; if (ldainc) { if (ldainc == -1) lda--; ATL_assert(N <= NB); for (j=0; j != N; j++) { for (ib=nrb; ib; ib--) { for (i=0; i < kb; i++) V[i] = ATL_MulByALPHA(A[i]); V += NN; A += kb; } if (mr) { for (i=0; i < mr; i++) v[i] = ATL_MulByALPHA(A[i]); v += mr; } V += kb - nrb*NN; A += lda - nrb*kb; lda += ldainc; } } else Mjoin(Mjoin(PATL,col2blk),NM)(M, N, A, lda, V, alpha); } #ifdef ALPHA1 void Mjoin(PATL,pcol2blkF) (const int M, const int N, const SCALAR alpha, const TYPE *A, int lda, const int ldainc, TYPE *V) /* * Copies entire MxN matrix to block major format */ { int j, jb; const int incV = ATL_MulByNB(M); const enum PACK_UPLO UA = (ldainc == 1) ? PackUpper : ( (lda == -1) ? PackLower : PackGen ); void (*col2blk)(const int M, const int N, const SCALAR alpha, const TYPE *A, int lda, const int ldainc, TYPE *V); if (ldainc) { if (alpha == ATL_rone) col2blk = Mjoin(PATL,pcol2blk_a1); else col2blk = Mjoin(PATL,pcol2blk_aX); for (j=0; j < N; j += NB) { jb = N-j; jb = Mmin(jb, NB); col2blk(M, jb, alpha, A+MindexP(UA,0,j,lda), Mpld(UA,j,lda), ldainc,V); V += incV; } } else if (alpha == ATL_rone) Mjoin(PATL,col2blk2_a1)(M, N, A, lda, V, alpha); else Mjoin(PATL,col2blk2_aX)(M, N, A, lda, V, alpha); } #endif
utf-8
1
BSD-3-clause-ATLAS
1997-2016 R. Clint Whaley 1999-2000, 2004 Antoine P. Petitet 2000-2001 Peter Soendergaard 2009, 2012 Siju Samuel 2001 Julian Ruhe 2010 IBM Corporation 1998 Jeff Horner 2011 Md. Rakib Hasan 2010-2011 Vesperix Corporation 2009 Chad Zalkin 2011 Md. Majedul Haque Sujon 1999 The Australian National University
gmerlin-2.0.0~svn6298~dfsg0/apps/visualizer/gmerlin_visualizer.c
/***************************************************************** * gmerlin - a general purpose multimedia framework and applications * * Copyright (c) 2001 - 2012 Members of the Gmerlin project * gmerlin-general@lists.sourceforge.net * http://gmerlin.sourceforge.net * * 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. If not, see <http://www.gnu.org/licenses/>. * *****************************************************************/ #include <string.h> #include <config.h> #include <gmerlin/translation.h> #include <gmerlin/pluginregistry.h> #include <gmerlin/cfg_dialog.h> #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> #include <gui_gtk/aboutwindow.h> #include <gui_gtk/gtkutils.h> #include <gui_gtk/audio.h> #include <gui_gtk/plugin.h> #include <gui_gtk/logwindow.h> #include <gmerlin/utils.h> #include <gmerlin/visualize.h> #include <gdk/gdkx.h> #include <gtk/gtkx.h> #include <gmerlin/log.h> #define LOG_DOMAIN "gmerlin_visualizer" #define TOOLBAR_TRIGGER_KEY (1<<0) #define TOOLBAR_TRIGGER_MOUSE (1<<1) #define TOOLBAR_LOCATION_TOP 0 #define TOOLBAR_LOCATION_BOTTOM 1 typedef struct { GtkWidget * window; GtkWidget * box; GtkWidget * socket; } window_t; typedef struct { GtkWidget * window; bg_gtk_plugin_widget_single_t * ra_plugins; bg_gtk_plugin_widget_single_t * ov_plugins; GtkWidget * close_button; } plugin_window_t; typedef struct { GtkWidget * config_button; GtkWidget * quit_button; GtkWidget * plugin_button; GtkWidget * restart_button; GtkWidget * log_button; GtkWidget * about_button; GtkWidget * help_button; guint log_id; guint about_id; GtkWidget * fullscreen_button; GtkWidget * nofullscreen_button; GtkWidget * toolbar; /* A GtkEventBox actually... */ GtkWidget * fps; bg_gtk_plugin_widget_single_t * vis_plugins; /* Windows are created by gtk and the x11 plugin is embedded inside after */ window_t normal_window; window_t fullscreen_window; window_t *current_window; plugin_window_t plugin_window; bg_gtk_vumeter_t * vumeter; /* Core stuff */ gavl_audio_format_t audio_format; bg_visualizer_t * visualizer; bg_plugin_registry_t * plugin_reg; bg_cfg_registry_t * cfg_reg; bg_plugin_handle_t * ra_handle; bg_recorder_plugin_t * ra_plugin; const bg_plugin_info_t * ov_info; const bg_plugin_info_t * ra_info; /* Config stuff */ // bg_cfg_section_t * vumeter_section; bg_cfg_section_t * visualizer_section; bg_cfg_section_t * general_section; bg_cfg_section_t * log_section; bg_dialog_t * cfg_dialog; int audio_open; int vis_open; int mouse_in_toolbar; int do_hide_toolbar; int toolbar_visible; int toolbar_location; int toolbar_trigger; int x, y, width, height; bg_gtk_log_window_t * log_window; gavl_dictionary_t m; gavl_audio_source_t * src; } visualizer_t; static gboolean configure_callback(GtkWidget * w, GdkEventConfigure *event, gpointer data) { visualizer_t * win; win = (visualizer_t*)data; win->x = event->x; win->y = event->y; win->width = event->width; win->height = event->height; gdk_window_get_root_origin(gtk_widget_get_window(win->current_window->window), &win->x, &win->y); return FALSE; } static char * get_display_string(visualizer_t * v) { char * ret; GdkDisplay * dpy; /* Get the display string */ gtk_widget_realize(v->normal_window.socket); gtk_widget_realize(v->fullscreen_window.socket); dpy = gdk_display_get_default(); // ret = bg_sprintf("%s:%08lx:%08lx", gdk_display_get_name(dpy), // GDK_WINDOW_XID(v->normal_window.window->window), // GDK_WINDOW_XID(v->fullscreen_window.window->window)); ret = bg_sprintf("%s:%08lx:%08lx", gdk_display_get_name(dpy), (long unsigned int)gtk_socket_get_id(GTK_SOCKET(v->normal_window.socket)), (long unsigned int)gtk_socket_get_id(GTK_SOCKET(v->fullscreen_window.socket))); return ret; } static void hide_toolbar(visualizer_t * v) { gtk_widget_hide(v->toolbar); v->toolbar_visible = 0; } static gboolean toolbar_timeout(void * data) { visualizer_t * v; v = (visualizer_t *)data; if(!v->toolbar_visible) return TRUE; /* Maybe the toolbar will be hidden next time */ if(!v->do_hide_toolbar) { v->do_hide_toolbar = 1; return TRUE; } if(!v->mouse_in_toolbar) { hide_toolbar(v); } return TRUE; } static gboolean fps_timeout(void * data) { float fps; char * tmp_string; visualizer_t * v; v = (visualizer_t *)data; if(!v->toolbar_visible || !v->audio_open) return TRUE; fps = bg_visualizer_get_fps(v->visualizer); if(fps >= 0.0) { tmp_string = bg_sprintf("Fps: %.2f", fps); gtk_label_set_text(GTK_LABEL(v->fps), tmp_string); free(tmp_string); } return TRUE; } static void show_toolbar(visualizer_t * v) { if(!v->toolbar_visible) { gtk_widget_show(v->toolbar); v->toolbar_visible = 1; } v->do_hide_toolbar = 0; } static void attach_toolbar(visualizer_t * v, window_t * win) { if(v->toolbar_location == TOOLBAR_LOCATION_TOP) gtk_widget_set_valign(win->box, GTK_ALIGN_START); else gtk_widget_set_valign(win->box, GTK_ALIGN_END); gtk_box_pack_start(GTK_BOX(win->box), v->toolbar, FALSE, FALSE, 0); } static void toggle_fullscreen(visualizer_t * v) { if(v->current_window == &v->normal_window) { /* Reparent toolbar */ gtk_container_remove(GTK_CONTAINER(v->normal_window.box), v->toolbar); attach_toolbar(v, &v->fullscreen_window); /* Hide normal window, show fullscreen window */ gtk_widget_show(v->fullscreen_window.window); gtk_widget_hide(v->normal_window.window); gtk_window_fullscreen(GTK_WINDOW(v->fullscreen_window.window)); /* Update toolbar */ gtk_widget_show(v->nofullscreen_button); gtk_widget_hide(v->fullscreen_button); gtk_widget_hide(v->config_button); gtk_widget_hide(v->plugin_button); bg_gtk_plugin_widget_single_show_buttons(v->vis_plugins, 0); v->current_window = &v->fullscreen_window; } else { /* Reparent toolbar */ gtk_container_remove(GTK_CONTAINER(v->fullscreen_window.box), v->toolbar); attach_toolbar(v, &v->normal_window); /* Hide normal window, show fullscreen window */ gtk_widget_show(v->normal_window.window); gtk_widget_hide(v->fullscreen_window.window); /* Update toolbar */ gtk_widget_show(v->fullscreen_button); gtk_widget_hide(v->nofullscreen_button); gtk_widget_show(v->config_button); gtk_widget_show(v->plugin_button); bg_gtk_plugin_widget_single_show_buttons(v->vis_plugins, 1); v->current_window = &v->normal_window; } hide_toolbar(v); v->mouse_in_toolbar = 0; } static void open_audio(visualizer_t * v) { int i; int was_open; gavl_time_t delay_time = GAVL_TIME_SCALE / 20; /* 50 ms */ memset(&v->audio_format, 0, sizeof(v->audio_format)); v->audio_format.num_channels = 2; v->audio_format.samplerate = 44100; v->audio_format.sample_format = GAVL_SAMPLE_S16; gavl_set_channel_setup(&v->audio_format); if(v->ra_handle) { v->ra_plugin->close(v->ra_handle->priv); bg_plugin_unref(v->ra_handle); was_open = 1; } else was_open = 0; v->audio_open = 0; v->ra_handle = bg_plugin_load(v->plugin_reg, v->ra_info); v->ra_plugin = (bg_recorder_plugin_t*)(v->ra_handle->plugin); /* The soundcard might be busy from last time, give the kernel some time to free the device */ if(!v->ra_plugin->open(v->ra_handle->priv, &v->audio_format, NULL, &v->m)) { if(!was_open) { gavl_log(GAVL_LOG_ERROR, LOG_DOMAIN, "Opening audio device failed, fix settings and click restart"); gtk_label_set_text(GTK_LABEL(v->fps), TR("No audio")); return; } for(i = 0; i < 20; i++) { gavl_time_delay(&delay_time); if(v->ra_plugin->open(v->ra_handle->priv, &v->audio_format, NULL, &v->m)) { v->audio_open = 1; break; } } } else v->audio_open = 1; if(v->audio_open) { v->src = v->ra_plugin->get_audio_source(v->ra_handle->priv); bg_gtk_vumeter_set_format(v->vumeter, &v->audio_format); } else { gavl_log(GAVL_LOG_ERROR, LOG_DOMAIN, "Opening audio device failed, fix settings and click restart"); gtk_label_set_text(GTK_LABEL(v->fps), TR("No audio")); } } static void open_vis(visualizer_t * v) { char * display_string = get_display_string(v); bg_visualizer_open_id(v->visualizer, &v->audio_format, v->ov_info, display_string); free(display_string); v->vis_open = 1; } static void close_vis(visualizer_t * v) { bg_visualizer_close(v->visualizer); v->vis_open = 0; } static void grab_notify_callback(GtkWidget *widget, gboolean was_grabbed, gpointer data) { visualizer_t * win = (visualizer_t*)data; if(!was_grabbed) { bg_gtk_widget_set_can_focus(win->current_window->socket, TRUE); gtk_widget_grab_focus(win->current_window->socket); } } static void about_window_close_callback(bg_gtk_about_window_t* win, void* data) { visualizer_t * v; v = (visualizer_t*)data; gtk_widget_set_sensitive(v->about_button, 1); } static void button_callback(GtkWidget * w, gpointer data) { visualizer_t * win = (visualizer_t*)data; if((w == win->quit_button) || (w == win->normal_window.window)) gtk_main_quit(); else if(w == win->config_button) bg_dialog_show(win->cfg_dialog, win->current_window->window); else if((w == win->fullscreen_button) || (w == win->nofullscreen_button)) toggle_fullscreen(win); else if(w == win->plugin_button) { gtk_widget_show(win->plugin_window.window); gtk_widget_set_sensitive(win->plugin_button, 0); } else if(w == win->restart_button) { if(win->vis_open) { close_vis(win); open_audio(win); open_vis(win); hide_toolbar(win); } } else if(w == win->log_button) { gtk_widget_set_sensitive(win->log_button, 0); bg_gtk_log_window_show(win->log_window); } else if(w == win->about_button) { gtk_widget_set_sensitive(win->about_button, 0); bg_gtk_about_window_create("Gmerlin visualizer", VERSION, "visualizer_icon.png", about_window_close_callback, win); } else if(w == win->help_button) bg_display_html_help("userguide/Visualizer.html"); } static gboolean plug_removed_callback(GtkWidget * w, gpointer data) { /* Reuse socket */ return TRUE; } static void plug_added_callback(GtkWidget * w, gpointer data) { visualizer_t * v; v = (visualizer_t *)data; gtk_widget_hide(v->toolbar); /* Seems that this is switched off, when an earlier client exited */ bg_gtk_widget_set_can_focus(w, TRUE); gtk_widget_grab_focus(w); } static gboolean delete_callback(GtkWidget * w, GdkEventAny * evt, gpointer data) { button_callback(w, data); return TRUE; } static void plugin_window_button_callback(GtkWidget * w, gpointer data) { visualizer_t * v; v = (visualizer_t *)data; gtk_widget_set_sensitive(v->plugin_button, 1); gtk_widget_hide(v->plugin_window.window); } static gboolean plugin_window_delete_callback(GtkWidget * w, GdkEventAny * evt, gpointer data) { plugin_window_button_callback(w, data); return TRUE; } static void set_ra_plugin(const bg_plugin_info_t * plugin, void * data) { visualizer_t * v = (visualizer_t*)data; bg_plugin_registry_set_default(v->plugin_reg, BG_PLUGIN_RECORDER_AUDIO, BG_PLUGIN_RECORDER, plugin->name); v->ra_info = plugin; gavl_log(GAVL_LOG_INFO, LOG_DOMAIN, "Changed recording plugin to %s", v->ra_info->long_name); close_vis(v); open_audio(v); open_vis(v); } static void plugin_window_init(plugin_window_t * win, visualizer_t * v) { int row = 0, num_columns = 4; GtkWidget * table; win->window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_modal(GTK_WINDOW(win->window), TRUE); gtk_window_set_transient_for(GTK_WINDOW(win->window), GTK_WINDOW(v->normal_window.window)); win->ra_plugins = bg_gtk_plugin_widget_single_create(TR("Audio recorder"), v->plugin_reg, BG_PLUGIN_RECORDER_AUDIO, BG_PLUGIN_ALL); bg_gtk_plugin_widget_single_set_change_callback(win->ra_plugins, set_ra_plugin, v); win->ov_plugins = bg_gtk_plugin_widget_single_create(TR("Video output"), v->plugin_reg, BG_PLUGIN_OUTPUT_VIDEO, BG_PLUGIN_ALL); win->close_button = gtk_button_new_with_mnemonic("_Close"); g_signal_connect(win->close_button, "clicked", G_CALLBACK(plugin_window_button_callback), v); g_signal_connect(win->window, "delete-event", G_CALLBACK(plugin_window_delete_callback), v); gtk_widget_show(win->close_button); table = gtk_grid_new(); gtk_grid_set_row_spacing(GTK_GRID(table), 5); gtk_grid_set_column_spacing(GTK_GRID(table), 5); gtk_container_set_border_width(GTK_CONTAINER(table), 5); gtk_window_set_position(GTK_WINDOW(win->window), GTK_WIN_POS_CENTER); bg_gtk_plugin_widget_single_attach(win->ra_plugins, table, &row, &num_columns); bg_gtk_plugin_widget_single_attach(win->ov_plugins, table, &row, &num_columns); bg_gtk_table_attach(table, win->close_button, 0, num_columns, row, row+1, 0, 0); gtk_widget_show(table); gtk_container_add(GTK_CONTAINER(win->window), table); } static int motion_callback(void * data, int x, int y, int mask) { visualizer_t * v = (visualizer_t*)data; if(v->toolbar_trigger & TOOLBAR_TRIGGER_MOUSE) show_toolbar(v); return FALSE; } static gboolean key_callback(GtkWidget * w, GdkEventKey * evt, gpointer data) { visualizer_t * v = (visualizer_t*)data; // gtk_widget_show(v->toolbar); // g_timeout_add(2000, toolbar_timeout, v); switch(evt->keyval) { case GDK_KEY_Tab: case GDK_KEY_f: toggle_fullscreen(v); return TRUE; break; case GDK_KEY_Escape: if(v->current_window == &v->fullscreen_window) toggle_fullscreen(v); return TRUE; break; case GDK_KEY_Menu: if(v->toolbar_trigger & TOOLBAR_TRIGGER_KEY) show_toolbar(v); return TRUE; break; } return FALSE; } static gboolean window_motion_callback(GtkWidget *widget, GdkEventMotion *event, gpointer data) { visualizer_t * v = (visualizer_t*)data; if(v->toolbar_trigger & TOOLBAR_TRIGGER_MOUSE) show_toolbar(v); return FALSE; } static void window_init(visualizer_t * v, window_t * w, int fullscreen) { GtkWidget * table; w->window = bg_gtk_window_new(GTK_WINDOW_TOPLEVEL); if(!fullscreen) g_signal_connect(G_OBJECT(w->window), "configure-event", G_CALLBACK(configure_callback), (gpointer)v); gtk_window_set_title(GTK_WINDOW(w->window), "Gmerlin visualizer"); w->socket = gtk_socket_new(); w->box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); gtk_widget_set_halign(w->box, GTK_ALIGN_FILL); gtk_widget_set_valign(w->box, GTK_ALIGN_START); gtk_widget_show(w->box); gtk_widget_show(w->socket); table = gtk_overlay_new(); gtk_container_add(GTK_CONTAINER(table), w->socket); gtk_overlay_add_overlay(GTK_OVERLAY(table), w->box); gtk_widget_show(table); gtk_widget_set_events(w->window, GDK_POINTER_MOTION_MASK); gtk_widget_set_events(w->socket, GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK ); // gtk_window_set_focus_on_map(w->window, 0); gtk_container_add(GTK_CONTAINER(w->window), table); g_signal_connect(G_OBJECT(w->window), "delete_event", G_CALLBACK(delete_callback), v); g_signal_connect(G_OBJECT(w->socket), "plug-removed", G_CALLBACK(plug_removed_callback), v); g_signal_connect(G_OBJECT(w->socket), "grab-notify", G_CALLBACK(grab_notify_callback), v); g_signal_connect(G_OBJECT(w->socket), "plug-added", G_CALLBACK(plug_added_callback), v); g_signal_connect(G_OBJECT(w->socket), "key-press-event", G_CALLBACK(key_callback), v); g_signal_connect(G_OBJECT(w->window), "motion-notify-event", G_CALLBACK(window_motion_callback), v); gtk_widget_show(w->socket); if(fullscreen) gtk_window_fullscreen(GTK_WINDOW(w->window)); // else // gtk_widget_set_size_request(w->window, 640, 480); } static GtkWidget * create_pixmap_button(visualizer_t * w, const char * filename, const char * tooltip) { GtkWidget * button; GtkWidget * image; char * path; path = bg_search_file_read("icons", filename); if(path) { image = gtk_image_new_from_file(path); free(path); } else image = gtk_image_new(); gtk_widget_show(image); button = gtk_button_new(); gtk_container_add(GTK_CONTAINER(button), image); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(button_callback), w); gtk_widget_show(button); bg_gtk_tooltips_set_tip(button, tooltip, PACKAGE); return button; } #if 0 static GtkWidget * create_pixmap_toggle_button(visualizer_t * w, const char * filename, const char * tooltip, guint * id) { GtkWidget * button; GtkWidget * image; char * path; path = bg_search_file_read("icons", filename); if(path) { image = gtk_image_new_from_file(path); free(path); } else image = gtk_image_new(); gtk_widget_show(image); button = gtk_toggle_button_new(); gtk_container_add(GTK_CONTAINER(button), image); *id = g_signal_connect(G_OBJECT(button), "toggled", G_CALLBACK(button_callback), w); gtk_widget_show(button); bg_gtk_tooltips_set_tip(button, tooltip, PACKAGE); return button; } #endif static void set_vis_param(void * data, const char * name, const gavl_value_t * val) { visualizer_t * v; v = (visualizer_t *)data; bg_visualizer_set_parameter(v->visualizer, name, val); if(bg_visualizer_need_restart(v->visualizer) && v->vis_open && !name) { gtk_widget_hide(v->toolbar); close_vis(v); open_vis(v); } } static void set_general_parameter(void * data, const char * name, const gavl_value_t * val) { visualizer_t * v; int i_tmp; v = (visualizer_t *)data; if(!name) return; if(!strcmp(name, "toolbar_location")) { if(!strcmp(val->v.str, "top")) i_tmp = TOOLBAR_LOCATION_TOP; else i_tmp = TOOLBAR_LOCATION_BOTTOM; if(v->toolbar_location != i_tmp) { v->toolbar_location = i_tmp; /* Reparent toolbar */ gtk_container_remove(GTK_CONTAINER(v->current_window->box), v->toolbar); attach_toolbar(v, v->current_window); } } else if(!strcmp(name, "toolbar_trigger")) { if(!strcmp(val->v.str, "mouse")) { v->toolbar_trigger = TOOLBAR_TRIGGER_MOUSE; } else if(!strcmp(val->v.str, "key")) { v->toolbar_trigger = TOOLBAR_TRIGGER_KEY; } else if(!strcmp(val->v.str, "mousekey")) { v->toolbar_trigger = TOOLBAR_TRIGGER_MOUSE | TOOLBAR_TRIGGER_KEY; } } else if(!strcmp(name, "x")) v->x = val->v.i; else if(!strcmp(name, "y")) v->y = val->v.i; else if(!strcmp(name, "width")) v->width = val->v.i; else if(!strcmp(name, "height")) v->height = val->v.i; } static int get_general_parameter(void * data, const char * name, gavl_value_t * val) { visualizer_t * v; v = (visualizer_t *)data; if(!strcmp(name, "x")) { val->v.i = v->x; return 1; } else if(!strcmp(name, "y")) { val->v.i = v->y; return 1; } else if(!strcmp(name, "width")) { val->v.i = v->width; return 1; } else if(!strcmp(name, "height")) { val->v.i = v->height; return 1; } return 0; } bg_parameter_info_t parameters[] = { { .name = "toolbar_location", .long_name = "Toolbar location", .type = BG_PARAMETER_STRINGLIST, .flags = BG_PARAMETER_SYNC, .val_default = GAVL_VALUE_INIT_STRING("top"), .multi_names = (char const *[]){ "top", "bottom", NULL }, .multi_labels = (char const *[]){ "Top", "Bottom", NULL }, }, { .name = "toolbar_trigger", .long_name = "Toolbar trigger", .type = BG_PARAMETER_STRINGLIST, .val_default = GAVL_VALUE_INIT_STRING("mousekey"), .multi_names = (char const *[]){ "mouse", "key", "mousekey", NULL }, .multi_labels = (char const *[]){ "Mouse motion", "Menu key", "Mouse motion & Menu key", NULL }, }, { .name = "x", .long_name = "X", .type = BG_PARAMETER_INT, .flags = BG_PARAMETER_HIDE_DIALOG, }, { .name = "y", .long_name = "y", .type = BG_PARAMETER_INT, .flags = BG_PARAMETER_HIDE_DIALOG, }, { .name = "width", .long_name = "width", .type = BG_PARAMETER_INT, .flags = BG_PARAMETER_HIDE_DIALOG, }, { .name = "height", .long_name = "height", .type = BG_PARAMETER_INT, .flags = BG_PARAMETER_HIDE_DIALOG, }, { /* End of parameters */ }, }; static bg_dialog_t * create_cfg_dialog(visualizer_t * win) { const bg_parameter_info_t * info; bg_dialog_t * ret; ret = bg_dialog_create_multi(TR("Visualizer configuration")); bg_dialog_add(ret, TR("General"), win->general_section, set_general_parameter, (void*)(win), parameters); info = bg_visualizer_get_parameters(win->visualizer); bg_dialog_add(ret, TR("Visualizer"), win->visualizer_section, set_vis_param, (void*)(win), info); info = bg_gtk_log_window_get_parameters(win->log_window); bg_dialog_add(ret, TR("Log window"), win->log_section, bg_gtk_log_window_set_parameter, (void*)(win->log_window), info); return ret; } static void apply_config(visualizer_t * v) { const bg_parameter_info_t * info; info = bg_visualizer_get_parameters(v->visualizer); bg_cfg_section_apply(v->visualizer_section, info, bg_visualizer_set_parameter, (void*)(v->visualizer)); bg_cfg_section_apply(v->general_section, parameters, set_general_parameter, (void*)(v)); info = bg_gtk_log_window_get_parameters(v->log_window); bg_cfg_section_apply(v->log_section, info, bg_gtk_log_window_set_parameter, (void*)(v->log_window)); } static void get_config(visualizer_t * v) { bg_cfg_section_get(v->general_section, parameters, get_general_parameter, (void*)(v)); } static gboolean idle_func(void * data) { visualizer_t * v = data; gavl_audio_frame_t * frame = NULL; if(v->audio_open) { if(gavl_audio_source_read_frame(v->src, &frame) != GAVL_SOURCE_OK) return FALSE; bg_visualizer_update(v->visualizer, frame); if(v->toolbar_visible) bg_gtk_vumeter_update(v->vumeter, frame); // bg_visualizer_update(v->visualizer, v->audio_frame); } return TRUE; } static gboolean crossing_callback(GtkWidget *widget, GdkEventCrossing *event, gpointer data) { visualizer_t * v = (visualizer_t*)data; if(event->detail == GDK_NOTIFY_INFERIOR) return FALSE; v->mouse_in_toolbar = (event->type == GDK_ENTER_NOTIFY) ? 1 : 0; return FALSE; } static void set_vis_plugin(const bg_plugin_info_t * plugin, void * data) { visualizer_t * v = (visualizer_t*)data; bg_visualizer_set_vis_plugin(v->visualizer, plugin); bg_plugin_registry_set_default(v->plugin_reg, BG_PLUGIN_VISUALIZATION, 0, plugin->name); if(bg_visualizer_need_restart(v->visualizer)) { close_vis(v); open_vis(v); } hide_toolbar(v); } static void set_vis_parameter(void * data, const char * name, const gavl_value_t * val) { visualizer_t * v = (visualizer_t*)data; bg_visualizer_set_vis_parameter(v->visualizer, name, val); } static void log_close_callback(bg_gtk_log_window_t * w, void * data) { visualizer_t * v = (visualizer_t*)data; gtk_widget_set_sensitive(v->log_button, 1); } static visualizer_t * visualizer_create() { const bg_plugin_info_t * info; int row, col; GtkWidget * main_table; GtkWidget * table; GtkWidget * box; visualizer_t * ret; ret = calloc(1, sizeof(*ret)); window_init(ret, &ret->normal_window, 0); window_init(ret, &ret->fullscreen_window, 1); ret->current_window = &ret->normal_window; ret->log_window = bg_gtk_log_window_create(TR("Gmerlin visualizer")); ret->config_button = create_pixmap_button(ret, "config_16.png", TRS("Configure")); ret->plugin_button = create_pixmap_button(ret, "plugin_16.png", TRS("Recording and display plugins")); ret->restart_button = create_pixmap_button(ret, "refresh_16.png", TRS("Restart visualization")); ret->quit_button = create_pixmap_button(ret, "quit_16.png", TRS("Quit")); ret->fullscreen_button = create_pixmap_button(ret, "fullscreen_16.png", TRS("Fullscreen mode")); ret->nofullscreen_button = create_pixmap_button(ret, "windowed_16.png", TRS("Leave fullscreen mode")); ret->log_button = create_pixmap_button(ret, "log_16.png", TRS("Show log window")); ret->about_button = create_pixmap_button(ret, "about_16.png", TRS("About Gmerlin visualizer")); ret->help_button = create_pixmap_button(ret, "help_16.png", TRS("Launch help in a webwroswer")); ret->fps = gtk_label_new("Fps: --:--"); gtk_widget_set_halign(ret->fps, GTK_ALIGN_START); gtk_widget_set_valign(ret->fps, GTK_ALIGN_CENTER); gtk_widget_show(ret->fps); gtk_widget_hide(ret->nofullscreen_button); // bg_gtk_box_pack_start_defaults(GTK_BOX(mainbox), // bg_gtk_vumeter_get_widget(ret->vumeter)); ret->toolbar = gtk_event_box_new(); gtk_widget_set_events(ret->toolbar, GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK); g_signal_connect(G_OBJECT(ret->toolbar), "enter-notify-event", G_CALLBACK(crossing_callback), (gpointer*)ret); g_signal_connect(G_OBJECT(ret->toolbar), "leave-notify-event", G_CALLBACK(crossing_callback), (gpointer*)ret); g_object_ref(ret->toolbar); /* Must be done for widgets, which get reparented after */ ret->vumeter = bg_gtk_vumeter_create(2, 0); /* Create actual objects */ /* Create plugin regsitry */ ret->visualizer = bg_visualizer_create(bg_plugin_reg); /* Create vis plugin widget */ ret->vis_plugins = bg_gtk_plugin_widget_single_create(TR("Visualization"), ret->plugin_reg, BG_PLUGIN_VISUALIZATION, 0); bg_gtk_plugin_widget_single_set_change_callback(ret->vis_plugins, set_vis_plugin, ret); bg_gtk_plugin_widget_single_set_parameter_callback(ret->vis_plugins, set_vis_parameter, ret); /* Create audio and video plugin widgets */ plugin_window_init(&ret->plugin_window, ret); /* Get ov info */ ret->ov_info = bg_gtk_plugin_widget_single_get_plugin(ret->plugin_window.ov_plugins); /* Load recording plugin */ ret->ra_info = bg_gtk_plugin_widget_single_get_plugin(ret->plugin_window.ra_plugins); /* Create config stuff */ ret->visualizer_section = bg_cfg_registry_find_section(ret->cfg_reg, "visualizer"); ret->general_section = bg_cfg_registry_find_section(ret->cfg_reg, "general"); ret->log_section = bg_cfg_registry_find_section(ret->cfg_reg, "log"); ret->cfg_dialog = create_cfg_dialog(ret); /* Pack everything */ main_table = gtk_grid_new(); gtk_grid_set_row_spacing(GTK_GRID(main_table), 5); gtk_grid_set_column_spacing(GTK_GRID(main_table), 5); gtk_container_set_border_width(GTK_CONTAINER(main_table), 5); table = gtk_grid_new(); gtk_grid_set_row_spacing(GTK_GRID(table), 5); gtk_grid_set_column_spacing(GTK_GRID(table), 5); gtk_container_set_border_width(GTK_CONTAINER(table), 5); row = 0; col = 0; bg_gtk_plugin_widget_single_attach(ret->vis_plugins, table, &row, &col); gtk_widget_show(table); bg_gtk_table_attach(main_table, table, 0, 1, 0, 1, 0, 0); box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_pack_start(GTK_BOX(box), ret->plugin_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), ret->config_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), ret->restart_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), ret->fullscreen_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), ret->nofullscreen_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), ret->log_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), ret->about_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), ret->help_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), ret->quit_button, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(box), ret->fps, TRUE, TRUE, 5); gtk_widget_show(box); bg_gtk_table_attach(main_table, box, 0, 1, 1, 2, 0, 0); bg_gtk_table_attach(main_table, bg_gtk_vumeter_get_widget(ret->vumeter), 1, 2, 0, 2, 1, 0); gtk_widget_show(main_table); gtk_container_add(GTK_CONTAINER(ret->toolbar), main_table); // gtk_widget_show(ret->toolbar); /* Start with non-fullscreen mode */ attach_toolbar(ret, &ret->normal_window); apply_config(ret); /* Get visualization plugin */ info = bg_gtk_plugin_widget_single_get_plugin(ret->vis_plugins); bg_visualizer_set_vis_plugin(ret->visualizer, info); /* Initialize stuff */ open_audio(ret); open_vis(ret); gtk_widget_show(ret->current_window->window); if(ret->width && ret->height) gdk_window_move_resize(gtk_widget_get_window(ret->current_window->window), ret->x, ret->y, ret->width, ret->height); else gdk_window_move_resize(gtk_widget_get_window(ret->current_window->window), 100, 100, 640, 480); while(gdk_events_pending() || gtk_events_pending()) gtk_main_iteration(); g_idle_add(idle_func, ret); g_timeout_add(3000, toolbar_timeout, ret); g_timeout_add(1000, fps_timeout, ret); return ret; } static void visualizer_destroy(visualizer_t * v) { char * tmp_path; get_config(v); tmp_path = bg_search_file_write("visualizer", "cfg.xml"); bg_cfg_registry_save(v->cfg_reg, tmp_path); if(tmp_path) free(tmp_path); gavl_dictionary_free(&v->m); free(v); } int main(int argc, char ** argv) { visualizer_t * win; bg_gtk_init(&argc, &argv, "visualizer_icon.png", NULL, NULL); bg_cfg_registry_init("visualizer"); bg_plugins_init(); win = visualizer_create(); gtk_main(); if(win->vis_open) bg_visualizer_close(win->visualizer); visualizer_destroy(win); bg_plugins_cleanup(); bg_cfg_registry_cleanup(); return 0; }
utf-8
1
GPL-3+
2001-2022, Members of the Gmerlin project <gmerlin-general@lists.sourceforge.net> 2006, Burkhard Plaum
sfftobmp-3.1.3/win32/libtiff/libtiff/tif_strip.c
/* $Id: tif_strip.c,v 1.1 2009/08/23 12:38:10 pschaefer Exp $ */ /* * Copyright (c) 1991-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Strip-organized Image Support Routines. */ #include "tiffiop.h" static uint32 summarize(TIFF* tif, size_t summand1, size_t summand2, const char* where) { /* * XXX: We are using casting to uint32 here, bacause sizeof(size_t) * may be larger than sizeof(uint32) on 64-bit architectures. */ uint32 bytes = summand1 + summand2; if (bytes - summand1 != summand2) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Integer overflow in %s", where); bytes = 0; } return (bytes); } static uint32 multiply(TIFF* tif, size_t nmemb, size_t elem_size, const char* where) { uint32 bytes = nmemb * elem_size; if (elem_size && bytes / elem_size != nmemb) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Integer overflow in %s", where); bytes = 0; } return (bytes); } /* * Compute which strip a (row,sample) value is in. */ tstrip_t TIFFComputeStrip(TIFF* tif, uint32 row, tsample_t sample) { TIFFDirectory *td = &tif->tif_dir; tstrip_t strip; strip = row / td->td_rowsperstrip; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { if (sample >= td->td_samplesperpixel) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Sample out of range, max %lu", (unsigned long) sample, (unsigned long) td->td_samplesperpixel); return ((tstrip_t) 0); } strip += sample*td->td_stripsperimage; } return (strip); } /* * Compute how many strips are in an image. */ tstrip_t TIFFNumberOfStrips(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; tstrip_t nstrips; nstrips = (td->td_rowsperstrip == (uint32) -1 ? 1 : TIFFhowmany(td->td_imagelength, td->td_rowsperstrip)); if (td->td_planarconfig == PLANARCONFIG_SEPARATE) nstrips = multiply(tif, nstrips, td->td_samplesperpixel, "TIFFNumberOfStrips"); return (nstrips); } /* * Compute the # bytes in a variable height, row-aligned strip. */ tsize_t TIFFVStripSize(TIFF* tif, uint32 nrows) { TIFFDirectory *td = &tif->tif_dir; if (nrows == (uint32) -1) nrows = td->td_imagelength; if (td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_photometric == PHOTOMETRIC_YCBCR && !isUpSampled(tif)) { /* * Packed YCbCr data contain one Cb+Cr for every * HorizontalSampling*VerticalSampling Y values. * Must also roundup width and height when calculating * since images that are not a multiple of the * horizontal/vertical subsampling area include * YCbCr data for the extended image. */ uint16 ycbcrsubsampling[2]; tsize_t w, scanline, samplingarea; TIFFGetField( tif, TIFFTAG_YCBCRSUBSAMPLING, ycbcrsubsampling + 0, ycbcrsubsampling + 1 ); samplingarea = ycbcrsubsampling[0]*ycbcrsubsampling[1]; if (samplingarea == 0) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Invalid YCbCr subsampling"); return 0; } w = TIFFroundup(td->td_imagewidth, ycbcrsubsampling[0]); scanline = TIFFhowmany8(multiply(tif, w, td->td_bitspersample, "TIFFVStripSize")); nrows = TIFFroundup(nrows, ycbcrsubsampling[1]); /* NB: don't need TIFFhowmany here 'cuz everything is rounded */ scanline = multiply(tif, nrows, scanline, "TIFFVStripSize"); return ((tsize_t) summarize(tif, scanline, multiply(tif, 2, scanline / samplingarea, "TIFFVStripSize"), "TIFFVStripSize")); } else return ((tsize_t) multiply(tif, nrows, TIFFScanlineSize(tif), "TIFFVStripSize")); } /* * Compute the # bytes in a raw strip. */ tsize_t TIFFRawStripSize(TIFF* tif, tstrip_t strip) { TIFFDirectory* td = &tif->tif_dir; tsize_t bytecount = td->td_stripbytecount[strip]; if (bytecount <= 0) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Invalid strip byte count, strip %lu", (unsigned long) bytecount, (unsigned long) strip); bytecount = (tsize_t) -1; } return bytecount; } /* * Compute the # bytes in a (row-aligned) strip. * * Note that if RowsPerStrip is larger than the * recorded ImageLength, then the strip size is * truncated to reflect the actual space required * to hold the strip. */ tsize_t TIFFStripSize(TIFF* tif) { TIFFDirectory* td = &tif->tif_dir; uint32 rps = td->td_rowsperstrip; if (rps > td->td_imagelength) rps = td->td_imagelength; return (TIFFVStripSize(tif, rps)); } /* * Compute a default strip size based on the image * characteristics and a requested value. If the * request is <1 then we choose a strip size according * to certain heuristics. */ uint32 TIFFDefaultStripSize(TIFF* tif, uint32 request) { return (*tif->tif_defstripsize)(tif, request); } uint32 _TIFFDefaultStripSize(TIFF* tif, uint32 s) { if ((int32) s < 1) { /* * If RowsPerStrip is unspecified, try to break the * image up into strips that are approximately * STRIP_SIZE_DEFAULT bytes long. */ tsize_t scanline = TIFFScanlineSize(tif); s = (uint32)STRIP_SIZE_DEFAULT / (scanline == 0 ? 1 : scanline); if (s == 0) /* very wide images */ s = 1; } return (s); } /* * Return the number of bytes to read/write in a call to * one of the scanline-oriented i/o routines. Note that * this number may be 1/samples-per-pixel if data is * stored as separate planes. */ tsize_t TIFFScanlineSize(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; tsize_t scanline; if (td->td_planarconfig == PLANARCONFIG_CONTIG) { if (td->td_photometric == PHOTOMETRIC_YCBCR && !isUpSampled(tif)) { uint16 ycbcrsubsampling[2]; TIFFGetField(tif, TIFFTAG_YCBCRSUBSAMPLING, ycbcrsubsampling + 0, ycbcrsubsampling + 1); if (ycbcrsubsampling[0] == 0) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Invalid YCbCr subsampling"); return 0; } scanline = TIFFroundup(td->td_imagewidth, ycbcrsubsampling[0]); scanline = TIFFhowmany8(multiply(tif, scanline, td->td_bitspersample, "TIFFScanlineSize")); return ((tsize_t) summarize(tif, scanline, multiply(tif, 2, scanline / ycbcrsubsampling[0], "TIFFVStripSize"), "TIFFVStripSize")); } else { scanline = multiply(tif, td->td_imagewidth, td->td_samplesperpixel, "TIFFScanlineSize"); } } else scanline = td->td_imagewidth; return ((tsize_t) TIFFhowmany8(multiply(tif, scanline, td->td_bitspersample, "TIFFScanlineSize"))); } /* * Some stuff depends on this older version of TIFFScanlineSize * TODO: resolve this */ tsize_t TIFFOldScanlineSize(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; tsize_t scanline; scanline = multiply (tif, td->td_bitspersample, td->td_imagewidth, "TIFFScanlineSize"); if (td->td_planarconfig == PLANARCONFIG_CONTIG) scanline = multiply (tif, scanline, td->td_samplesperpixel, "TIFFScanlineSize"); return ((tsize_t) TIFFhowmany8(scanline)); } /* * Return the number of bytes to read/write in a call to * one of the scanline-oriented i/o routines. Note that * this number may be 1/samples-per-pixel if data is * stored as separate planes. * The ScanlineSize in case of YCbCrSubsampling is defined as the * strip size divided by the strip height, i.e. the size of a pack of vertical * subsampling lines divided by vertical subsampling. It should thus make * sense when multiplied by a multiple of vertical subsampling. * Some stuff depends on this newer version of TIFFScanlineSize * TODO: resolve this */ tsize_t TIFFNewScanlineSize(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; tsize_t scanline; if (td->td_planarconfig == PLANARCONFIG_CONTIG) { if (td->td_photometric == PHOTOMETRIC_YCBCR && !isUpSampled(tif)) { uint16 ycbcrsubsampling[2]; TIFFGetField(tif, TIFFTAG_YCBCRSUBSAMPLING, ycbcrsubsampling + 0, ycbcrsubsampling + 1); if (ycbcrsubsampling[0]*ycbcrsubsampling[1] == 0) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "Invalid YCbCr subsampling"); return 0; } return((tsize_t) ((((td->td_imagewidth+ycbcrsubsampling[0]-1) /ycbcrsubsampling[0]) *(ycbcrsubsampling[0]*ycbcrsubsampling[1]+2) *td->td_bitspersample+7) /8)/ycbcrsubsampling[1]); } else { scanline = multiply(tif, td->td_imagewidth, td->td_samplesperpixel, "TIFFScanlineSize"); } } else scanline = td->td_imagewidth; return ((tsize_t) TIFFhowmany8(multiply(tif, scanline, td->td_bitspersample, "TIFFScanlineSize"))); } /* * Return the number of bytes required to store a complete * decoded and packed raster scanline (as opposed to the * I/O size returned by TIFFScanlineSize which may be less * if data is store as separate planes). */ tsize_t TIFFRasterScanlineSize(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; tsize_t scanline; scanline = multiply (tif, td->td_bitspersample, td->td_imagewidth, "TIFFRasterScanlineSize"); if (td->td_planarconfig == PLANARCONFIG_CONTIG) { scanline = multiply (tif, scanline, td->td_samplesperpixel, "TIFFRasterScanlineSize"); return ((tsize_t) TIFFhowmany8(scanline)); } else return ((tsize_t) multiply (tif, TIFFhowmany8(scanline), td->td_samplesperpixel, "TIFFRasterScanlineSize")); } /* vim: set ts=8 sts=8 sw=8 noet: */
utf-8
1
unknown
unknown
gentoo-0.20.7/src/controls.h
/* ** 1999-03-16 - Header for the controls module. The use of opaque object-like data structures ** is spreading rapidly across gentoo, and old proponents of a centralized-data ** architecture are simply being rolled over. Or something. */ #if !defined CONTROLS_H #define CONTROLS_H typedef struct CtrlInfo CtrlInfo; typedef struct CtrlKey CtrlKey; typedef struct CtrlMouse CtrlMouse; /* Functions for creating, copying, and destroying CtrlInfos. */ CtrlInfo * ctrl_new(MainInfo *min); CtrlInfo * ctrl_new_default(MainInfo *min); CtrlInfo * ctrl_copy(CtrlInfo *ctrl); void ctrl_destroy(CtrlInfo *ctrl); /* Functions to allow/disallow numlock's influence on bound commands. ** Does not change the actual binding, only controls if the numlock ** part of an eventual binding is respected or not. */ void ctrl_numlock_ignore_set(CtrlInfo *ctrl, gboolean ignore); gboolean ctrl_numlock_ignore_get(CtrlInfo *ctrl); /* Functions for working with individual keyboard bindings. */ CtrlKey * ctrl_key_add(CtrlInfo *ctrl, const gchar *keyname, const gchar *cmdseq); CtrlKey * ctrl_key_add_unique(CtrlInfo *ctrl); void ctrl_key_remove(CtrlInfo *ctrl, CtrlKey *key); void ctrl_key_remove_by_name(CtrlInfo *ctrl, const gchar *keyname); void ctrl_key_remove_all(CtrlInfo *ctrl); const gchar * ctrl_key_get_keyname(const CtrlKey *key); const gchar * ctrl_key_get_cmdseq(const CtrlKey *key); void ctrl_key_set_keyname(CtrlInfo *ctrl, CtrlKey *key, const gchar *keyname); void ctrl_key_set_cmdseq(CtrlInfo *ctrl, CtrlKey *key, const gchar *cmdseq); gboolean ctrl_key_has_cmdseq(CtrlInfo *ctrl, CtrlKey *key, const gchar *cmdseq); /* These functions work on *all* key bindings. */ void ctrl_keys_install(CtrlInfo *ctrl, KbdContext *ctx); void ctrl_keys_uninstall(CtrlInfo *ctrl, KbdContext *ctx); void ctrl_keys_uninstall_all(CtrlInfo *ctrl); GSList * ctrl_keys_get_list(CtrlInfo *ctrl); /* Functions to add, remove, and manipulate mouse button bindings. */ CtrlMouse * ctrl_mouse_add(CtrlInfo *ctrl, guint button, guint state, const gchar *cmdseq); void ctrl_mouse_set_button(CtrlMouse *mouse, guint state); void ctrl_mouse_set_state(CtrlMouse *mouse, guint state); void ctrl_mouse_set_cmdseq(CtrlMouse *mouse, const gchar *cmdseq); guint ctrl_mouse_get_button(const CtrlMouse *mouse); guint ctrl_mouse_get_state(const CtrlMouse *mouse); const gchar * ctrl_mouse_get_cmdseq(const CtrlMouse *mouse); void ctrl_mouse_remove(CtrlInfo *ctrl, CtrlMouse *mouse); void ctrl_mouse_remove_all(CtrlInfo *ctrl); const gchar * ctrl_mouse_map(CtrlInfo *ctrl, GdkEventButton *evt); GSList * ctrl_mouse_get_list(CtrlInfo *ctrl); gboolean ctrl_mouse_ambiguity_exists(const CtrlInfo *ctrl); /* Functions for assigning a command to Click-M-Click, which is kind of a simple gesture. */ void ctrl_clickmclick_set_cmdseq(CtrlInfo *ctrl, const gchar *cmdseq); const gchar * ctrl_clickmclick_get_cmdseq(const CtrlInfo *ctrl); void ctrl_clickmclick_set_delay(CtrlInfo *ctrl, gfloat delay); gfloat ctrl_clickmclick_get_delay(const CtrlInfo *ctrl); /* Functions for general commands, associated with some context. */ void ctrl_general_clear(CtrlInfo *ctrl); void ctrl_general_set_cmdseq(CtrlInfo *ctrl, const gchar *context, const gchar *cmdseq); const gchar * ctrl_general_get_cmdseq(const CtrlInfo *ctrl, const gchar *context); GSList * ctrl_general_get_contexts(const CtrlInfo *ctrl); #endif /* CONTROLS_H */
utf-8
1
GPL-2+
1998-2015 Emil Brink <emil@obsession.se>
guile-2.2-2.2.7+1/libguile/values.c
/* Copyright (C) 2000, 2001, 2006, 2008, 2009, 2011-2013, 2016, 2018 * Free Software Foundation, 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 3 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 */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "libguile/_scm.h" #include "libguile/eval.h" #include "libguile/feature.h" #include "libguile/gc.h" #include "libguile/numbers.h" #include "libguile/ports.h" #include "libguile/strings.h" #include "libguile/struct.h" #include "libguile/validate.h" #include "libguile/values.h" SCM scm_values_vtable; /* OBJ must be a values object containing exactly two values. scm_i_extract_values_2 puts those two values into *p1 and *p2. */ void scm_i_extract_values_2 (SCM obj, SCM *p1, SCM *p2) { SCM values; SCM_ASSERT_TYPE (SCM_VALUESP (obj), obj, SCM_ARG1, "scm_i_extract_values_2", "values"); values = scm_struct_ref (obj, SCM_INUM0); if (scm_ilength (values) != 2) scm_wrong_type_arg_msg ("scm_i_extract_values_2", SCM_ARG1, obj, "a values object containing exactly two values"); *p1 = SCM_CAR (values); *p2 = SCM_CADR (values); } static SCM print_values (SCM obj, SCM pwps) { SCM values = scm_struct_ref (obj, SCM_INUM0); SCM port = SCM_PORT_WITH_PS_PORT (pwps); scm_print_state *ps = SCM_PRINT_STATE (SCM_PORT_WITH_PS_PS (pwps)); scm_puts ("#<values ", port); scm_iprin1 (values, port, ps); scm_puts (">", port); return SCM_UNSPECIFIED; } size_t scm_c_nvalues (SCM obj) { if (SCM_LIKELY (SCM_VALUESP (obj))) return scm_ilength (scm_struct_ref (obj, SCM_INUM0)); else return 1; } SCM scm_c_value_ref (SCM obj, size_t idx) { if (SCM_LIKELY (SCM_VALUESP (obj))) { SCM values = scm_struct_ref (obj, SCM_INUM0); size_t i = idx; while (SCM_LIKELY (scm_is_pair (values))) { if (i == 0) return SCM_CAR (values); values = SCM_CDR (values); i--; } } else if (idx == 0) return obj; scm_error (scm_out_of_range_key, "scm_c_value_ref", "Too few values in ~S to access index ~S", scm_list_2 (obj, scm_from_size_t (idx)), scm_list_1 (scm_from_size_t (idx))); } SCM_DEFINE (scm_values, "values", 0, 0, 1, (SCM args), "Delivers all of its arguments to its continuation. Except for\n" "continuations created by the @code{call-with-values} procedure,\n" "all continuations take exactly one value. The effect of\n" "passing no value or more than one value to continuations that\n" "were not created by @code{call-with-values} is unspecified.") #define FUNC_NAME s_scm_values { long n; SCM result; SCM_VALIDATE_LIST_COPYLEN (1, args, n); if (n == 1) result = SCM_CAR (args); else result = scm_c_make_struct (scm_values_vtable, 0, 1, SCM_UNPACK (args)); return result; } #undef FUNC_NAME SCM scm_c_values (SCM *base, size_t nvalues) { SCM ret, *walk; if (nvalues == 1) return *base; for (ret = SCM_EOL, walk = base + nvalues - 1; walk >= base; walk--) ret = scm_cons (*walk, ret); return scm_values (ret); } void scm_init_values (void) { SCM print = scm_c_define_gsubr ("%print-values", 2, 0, 0, print_values); scm_values_vtable = scm_make_vtable (scm_from_utf8_string ("pr"), print); scm_add_feature ("values"); #include "libguile/values.x" } /* Local Variables: c-file-style: "gnu" End: */
utf-8
1
unknown
unknown
qtdeclarative-opensource-src-5.15.2+dfsg/src/quick/util/qquickpixmapcache_p.h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QQUICKPIXMAPCACHE_H #define QQUICKPIXMAPCACHE_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtCore/qcoreapplication.h> #include <QtCore/qstring.h> #include <QtGui/qpixmap.h> #include <QtCore/qurl.h> #include <private/qtquickglobal_p.h> #include <QtQuick/qquickimageprovider.h> #include <private/qintrusivelist_p.h> QT_BEGIN_NAMESPACE class QQmlEngine; class QQuickPixmapData; class QQuickTextureFactory; class QQuickImageProviderOptionsPrivate; class QQuickDefaultTextureFactory : public QQuickTextureFactory { Q_OBJECT public: QQuickDefaultTextureFactory(const QImage &i); QSGTexture *createTexture(QQuickWindow *window) const override; QSize textureSize() const override { return size; } int textureByteCount() const override { return size.width() * size.height() * 4; } QImage image() const override { return im; } private: QImage im; QSize size; }; class QQuickImageProviderPrivate { public: QQuickImageProvider::ImageType type; QQuickImageProvider::Flags flags; bool isProviderWithOptions; }; // ### Qt 6: Make public moving to qquickimageprovider.h class Q_QUICK_PRIVATE_EXPORT QQuickImageProviderOptions { public: enum AutoTransform { UsePluginDefaultTransform = -1, ApplyTransform = 0, DoNotApplyTransform = 1 }; QQuickImageProviderOptions(); ~QQuickImageProviderOptions(); QQuickImageProviderOptions(const QQuickImageProviderOptions&); QQuickImageProviderOptions& operator=(const QQuickImageProviderOptions&); bool operator==(const QQuickImageProviderOptions&) const; AutoTransform autoTransform() const; void setAutoTransform(AutoTransform autoTransform); bool preserveAspectRatioCrop() const; void setPreserveAspectRatioCrop(bool preserveAspectRatioCrop); bool preserveAspectRatioFit() const; void setPreserveAspectRatioFit(bool preserveAspectRatioFit); QColorSpace targetColorSpace() const; void setTargetColorSpace(const QColorSpace &colorSpace); private: QSharedDataPointer<QQuickImageProviderOptionsPrivate> d; }; class Q_QUICK_PRIVATE_EXPORT QQuickPixmap { Q_DECLARE_TR_FUNCTIONS(QQuickPixmap) public: QQuickPixmap(); QQuickPixmap(QQmlEngine *, const QUrl &); QQuickPixmap(QQmlEngine *, const QUrl &, const QRect &region, const QSize &); QQuickPixmap(const QUrl &, const QImage &image); ~QQuickPixmap(); enum Status { Null, Ready, Error, Loading }; enum Option { Asynchronous = 0x00000001, Cache = 0x00000002 }; Q_DECLARE_FLAGS(Options, Option) bool isNull() const; bool isReady() const; bool isError() const; bool isLoading() const; Status status() const; QString error() const; const QUrl &url() const; const QSize &implicitSize() const; const QRect &requestRegion() const; const QSize &requestSize() const; QQuickImageProviderOptions::AutoTransform autoTransform() const; int frameCount() const; QImage image() const; void setImage(const QImage &); void setPixmap(const QQuickPixmap &other); QColorSpace colorSpace() const; QQuickTextureFactory *textureFactory() const; QRect rect() const; int width() const; int height() const; void load(QQmlEngine *, const QUrl &); void load(QQmlEngine *, const QUrl &, QQuickPixmap::Options options); void load(QQmlEngine *, const QUrl &, const QRect &requestRegion, const QSize &requestSize); void load(QQmlEngine *, const QUrl &, const QRect &requestRegion, const QSize &requestSize, QQuickPixmap::Options options); void load(QQmlEngine *, const QUrl &, const QRect &requestRegion, const QSize &requestSize, QQuickPixmap::Options options, const QQuickImageProviderOptions &providerOptions, int frame = 0, int frameCount = 1); void clear(); void clear(QObject *); bool connectFinished(QObject *, const char *); bool connectFinished(QObject *, int); bool connectDownloadProgress(QObject *, const char *); bool connectDownloadProgress(QObject *, int); static void purgeCache(); static bool isCached(const QUrl &url, const QRect &requestRegion, const QSize &requestSize, const int frame, const QQuickImageProviderOptions &options); static const QLatin1String itemGrabberScheme; private: Q_DISABLE_COPY(QQuickPixmap) QQuickPixmapData *d; QIntrusiveListNode dataListNode; friend class QQuickPixmapData; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QQuickPixmap::Options) // This class will disappear with Qt6 and will just be the regular QQuickImageProvider // ### Qt 6: Remove this class and fold it with QQuickImageProvider class Q_QUICK_PRIVATE_EXPORT QQuickImageProviderWithOptions : public QQuickAsyncImageProvider { public: QQuickImageProviderWithOptions(ImageType type, Flags flags = Flags()); QImage requestImage(const QString &id, QSize *size, const QSize& requestedSize) override; QPixmap requestPixmap(const QString &id, QSize *size, const QSize& requestedSize) override; QQuickTextureFactory *requestTexture(const QString &id, QSize *size, const QSize &requestedSize) override; QQuickImageResponse *requestImageResponse(const QString &id, const QSize &requestedSize) override; virtual QImage requestImage(const QString &id, QSize *size, const QSize& requestedSize, const QQuickImageProviderOptions &options); virtual QPixmap requestPixmap(const QString &id, QSize *size, const QSize& requestedSize, const QQuickImageProviderOptions &options); virtual QQuickTextureFactory *requestTexture(const QString &id, QSize *size, const QSize &requestedSize, const QQuickImageProviderOptions &options); virtual QQuickImageResponse *requestImageResponse(const QString &id, const QSize &requestedSize, const QQuickImageProviderOptions &options); static QSize loadSize(const QSize &originalSize, const QSize &requestedSize, const QByteArray &format, const QQuickImageProviderOptions &options); static QQuickImageProviderWithOptions *checkedCast(QQuickImageProvider *provider); }; QT_END_NAMESPACE #endif // QQUICKPIXMAPCACHE_H
utf-8
1
LGPL-3 or GPL-2+
2016-2020 The Qt Company Ltd.
mir-1.8.2+dfsg/src/platform/graphics/egl_error.cpp
/* * Copyright © 2015 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2 or 3, * as published by the Free Software Foundation. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Alexandros Frantzis <alexandros.frantzis@canonical.com> */ #include "mir/graphics/egl_error.h" #include <sstream> #include <EGL/eglext.h> /* * The version of eglext in vivid-overlay is too old to contain these * defines, so provide them if missing */ #ifndef EGL_BAD_DEVICE_EXT #define EGL_BAD_DEVICE_EXT 0x322B #endif #ifndef EGL_BAD_STREAM_KHR #define EGL_BAD_STREAM_KHR 0x321B #endif #ifndef EGL_BAD_STATE_KHR #define EGL_BAD_STATE_KHR 0x321C #endif namespace { std::string to_hex_string(int n) { std::stringstream ss; ss << std::showbase << std::hex << n; return ss.str(); } struct egl_category : std::error_category { const char* name() const noexcept override { return "egl"; } std::string message(int ev) const override { #define CASE_FOR_ERROR(error) \ case error: return #error " (" + to_hex_string(error) + ")"; switch (ev) { CASE_FOR_ERROR(EGL_SUCCESS) CASE_FOR_ERROR(EGL_NOT_INITIALIZED) CASE_FOR_ERROR(EGL_BAD_ACCESS) CASE_FOR_ERROR(EGL_BAD_ALLOC) CASE_FOR_ERROR(EGL_BAD_ATTRIBUTE) CASE_FOR_ERROR(EGL_BAD_CONFIG) CASE_FOR_ERROR(EGL_BAD_CONTEXT) CASE_FOR_ERROR(EGL_BAD_CURRENT_SURFACE) CASE_FOR_ERROR(EGL_BAD_DISPLAY) CASE_FOR_ERROR(EGL_BAD_MATCH) CASE_FOR_ERROR(EGL_BAD_NATIVE_PIXMAP) CASE_FOR_ERROR(EGL_BAD_NATIVE_WINDOW) CASE_FOR_ERROR(EGL_BAD_PARAMETER) CASE_FOR_ERROR(EGL_BAD_SURFACE) CASE_FOR_ERROR(EGL_CONTEXT_LOST) CASE_FOR_ERROR(EGL_BAD_DEVICE_EXT) CASE_FOR_ERROR(EGL_BAD_STREAM_KHR) CASE_FOR_ERROR(EGL_BAD_STATE_KHR) default: return "Unknown error (" + to_hex_string(ev) + ")"; } #undef CASE_ERROR } }; struct gl_category : std::error_category { const char* name() const noexcept override { return "egl"; } std::string message(int ev) const override { #define CASE_FOR_ERROR(error) \ case error: return #error " (" + to_hex_string(error) + ")"; switch (ev) { CASE_FOR_ERROR(GL_NO_ERROR) CASE_FOR_ERROR(GL_INVALID_VALUE) CASE_FOR_ERROR(GL_INVALID_OPERATION) CASE_FOR_ERROR(GL_INVALID_ENUM) default: return "Unknown error (" + to_hex_string(ev) + ")"; } #undef CASE_ERROR } }; } std::error_category const& mir::graphics::egl_category() { static class egl_category const egl_category_instance{}; return egl_category_instance; } std::error_category const& mir::graphics::gl_category() { static class gl_category const gl_category_instance{}; return gl_category_instance; }
utf-8
1
unknown
unknown
firefox-97.0/gfx/skia/skia/include/atlastext/SkAtlasTextRenderer.h
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkPoint3.h" #include "include/core/SkRefCnt.h" #ifndef SkAtlasTextRenderer_DEFINED #define SkAtlasTextRenderer_DEFINED /** * This is the base class for a renderer implemented by the SkAtlasText client. The * SkAtlasTextContext issues texture creations, deletions, uploads, and vertex draws to the * renderer. The renderer must perform those actions in the order called to correctly render * the text drawn to SkAtlasTextTargets. */ class SK_API SkAtlasTextRenderer : public SkRefCnt { public: enum class AtlasFormat { /** Unsigned normalized 8 bit single channel format. */ kA8 }; struct SDFVertex { /** Position in device space (not normalized). The third component is w (not z). */ SkPoint3 fPosition; /** Color, same value for all four corners of a glyph quad. */ uint32_t fColor; /** Texture coordinate (in texel units, not normalized). */ int16_t fTextureCoordX; int16_t fTextureCoordY; }; virtual ~SkAtlasTextRenderer() = default; /** * Create a texture of the provided format with dimensions 'width' x 'height' * and return a unique handle. */ virtual void* createTexture(AtlasFormat, int width, int height) = 0; /** * Delete the texture with the passed handle. */ virtual void deleteTexture(void* textureHandle) = 0; /** * Place the pixel data specified by 'data' in the texture with handle * 'textureHandle' in the rectangle ['x', 'x' + 'width') x ['y', 'y' + 'height'). * 'rowBytes' specifies the byte offset between successive rows in 'data' and will always be * a multiple of the number of bytes per pixel. * The pixel format of data is the same as that of 'textureHandle'. */ virtual void setTextureData(void* textureHandle, const void* data, int x, int y, int width, int height, size_t rowBytes) = 0; /** * Draws glyphs using SDFs. The SDF data resides in 'textureHandle'. The array * 'vertices' provides interleaved device-space positions, colors, and * texture coordinates. There are are 4 * 'quadCnt' entries in 'vertices'. */ virtual void drawSDFGlyphs(void* targetHandle, void* textureHandle, const SDFVertex vertices[], int quadCnt) = 0; /** Called when a SkAtlasTextureTarget is destroyed. */ virtual void targetDeleted(void* targetHandle) = 0; }; #endif
utf-8
1
unknown
unknown
libjpeg-0.0~git20211203.966a8ed/control/blockbuffer.cpp
/************************************************************************* This project implements a complete(!) JPEG (Recommendation ITU-T T.81 | ISO/IEC 10918-1) codec, plus a library that can be used to encode and decode JPEG streams. It also implements ISO/IEC 18477 aka JPEG XT which is an extension towards intermediate, high-dynamic-range lossy and lossless coding of JPEG. In specific, it supports ISO/IEC 18477-3/-6/-7/-8 encoding. Note that only Profiles C and D of ISO/IEC 18477-7 are supported here. Check the JPEG XT reference software for a full implementation of ISO/IEC 18477-7. Copyright (C) 2012-2018 Thomas Richter, University of Stuttgart and Accusoft. (C) 2019-2020 Thomas Richter, Fraunhofer IIS. This program is available under two licenses, GPLv3 and the ITU Software licence Annex A Option 2, RAND conditions. For the full text of the GPU license option, see README.license.gpl. For the full text of the ITU license option, see README.license.itu. You may freely select between these two options. For the GPL option, please note the following: This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *************************************************************************/ /* ** ** This class pulls blocks from the frame and reconstructs from those ** quantized block lines or encodes from them. ** ** $Id: blockbuffer.cpp,v 1.20 2016/10/28 13:58:53 thor Exp $ ** */ /// Includes #include "control/bitmapctrl.hpp" #include "control/blockbuffer.hpp" #include "control/residualblockhelper.hpp" #include "interface/imagebitmap.hpp" #include "upsampling/upsamplerbase.hpp" #include "upsampling/downsamplerbase.hpp" #include "coding/quantizedrow.hpp" #include "codestream/tables.hpp" #include "codestream/rectanglerequest.hpp" #include "marker/frame.hpp" #include "marker/scan.hpp" #include "marker/component.hpp" #include "dct/dct.hpp" #include "colortrafo/colortrafo.hpp" #include "std/string.hpp" /// /// BlockBuffer::BlockBuffer BlockBuffer::BlockBuffer(class Frame *frame) : BlockCtrl(frame->EnvironOf()), m_pFrame(frame), m_pulY(NULL), m_pulCurrentY(NULL), m_ppDCT(NULL), m_ppQTop(NULL), m_ppRTop(NULL), m_pppQStream(NULL), m_pppRStream(NULL) { m_ucCount = frame->DepthOf(); m_ulPixelWidth = frame->WidthOf(); m_ulPixelHeight = frame->HeightOf(); } /// /// BlockBuffer::~BlockBuffer BlockBuffer::~BlockBuffer(void) { class QuantizedRow *row; UBYTE i; if (m_ppDCT) { for(i = 0;i < m_ucCount;i++) { delete m_ppDCT[i]; } m_pEnviron->FreeMem(m_ppDCT,m_ucCount * sizeof(class DCT *)); } if (m_pulY) m_pEnviron->FreeMem(m_pulY,m_ucCount * sizeof(ULONG)); if (m_pulCurrentY) m_pEnviron->FreeMem(m_pulCurrentY,m_ucCount * sizeof(ULONG)); if (m_ppQTop) { for(i = 0;i < m_ucCount;i++) { while((row = m_ppQTop[i])) { m_ppQTop[i] = row->NextOf(); delete row; } } m_pEnviron->FreeMem(m_ppQTop,m_ucCount * sizeof(class QuantizedRow *)); } if (m_ppRTop) { for(i = 0;i < m_ucCount;i++) { while((row = m_ppRTop[i])) { m_ppRTop[i] = row->NextOf(); delete row; } } m_pEnviron->FreeMem(m_ppRTop,m_ucCount * sizeof(class QuantizedRow *)); } if (m_pppQStream) m_pEnviron->FreeMem(m_pppQStream,m_ucCount * sizeof(class QuantizedRow **)); if (m_pppRStream) m_pEnviron->FreeMem(m_pppRStream,m_ucCount * sizeof(class QuantizedRow **)); } /// /// BlockBuffer::BuildCommon // Build common structures for encoding and decoding void BlockBuffer::BuildCommon(void) { if (m_ppDCT == NULL) { m_ppDCT = (class DCT **)m_pEnviron->AllocMem(sizeof(class DCT *) * m_ucCount); memset(m_ppDCT,0,sizeof(class DCT *) * m_ucCount); } if (m_pulY == NULL) { m_pulY = (ULONG *)m_pEnviron->AllocMem(sizeof(ULONG) * m_ucCount); memset(m_pulY,0,sizeof(ULONG) * m_ucCount); } if (m_pulCurrentY == NULL) { m_pulCurrentY = (ULONG *)m_pEnviron->AllocMem(sizeof(ULONG) * m_ucCount); memset(m_pulCurrentY,0,sizeof(ULONG) * m_ucCount); } if (m_ppQTop == NULL) { m_ppQTop = (class QuantizedRow **)m_pEnviron->AllocMem(sizeof(class QuantizedRow *) * m_ucCount); memset(m_ppQTop,0,sizeof(class QuantizedRow *) * m_ucCount); } if (m_ppRTop == NULL) { m_ppRTop = (class QuantizedRow **)m_pEnviron->AllocMem(sizeof(class QuantizedRow *) * m_ucCount); memset(m_ppRTop,0,sizeof(class QuantizedRow *) * m_ucCount); } if (m_pppQStream == NULL) { m_pppQStream = (class QuantizedRow ***)m_pEnviron->AllocMem(sizeof(class QuantizedRow **) * m_ucCount); memset(m_pppQStream,0,m_ucCount * sizeof(class QuantizedRow **)); } if (m_pppRStream == NULL) { m_pppRStream = (class QuantizedRow ***)m_pEnviron->AllocMem(sizeof(class QuantizedRow **) * m_ucCount); memset(m_pppRStream,0,m_ucCount * sizeof(class QuantizedRow **)); } } /// /// BlockBuffer::ResetStreamToStartOfScan // Make sure to reset the block control to the // start of the scan for the indicated components in the scan, // required after collecting the statistics for this scan. void BlockBuffer::ResetToStartOfScan(class Scan *scan) { if (scan) { UBYTE ccnt = scan->ComponentsInScan(); for(UBYTE i = 0;i < ccnt;i++) { class Component *comp = scan->ComponentOf(i); UBYTE idx = comp->IndexOf(); if (m_ppDCT[idx] == NULL) m_ppDCT[idx] = m_pFrame->TablesOf()->BuildDCT(comp,m_ucCount, m_pFrame->HiddenPrecisionOf()); m_pulY[idx] = 0; m_pulCurrentY[idx] = 0; m_pppQStream[idx] = NULL; m_pppRStream[idx] = NULL; } } else { // All components. for(UBYTE idx = 0;idx < m_ucCount;idx++) { class Component *comp = m_pFrame->ComponentOf(idx); if (m_ppDCT[idx] == NULL) m_ppDCT[idx] = m_pFrame->TablesOf()->BuildDCT(comp,m_ucCount, m_pFrame->HiddenPrecisionOf()); m_pulY[idx] = 0; m_pulCurrentY[idx] = 0; m_pppQStream[idx] = NULL; m_pppRStream[idx] = NULL; } } } /// /// BlockBuffer::StartMCUQuantizerRow // Start a MCU scan by initializing the quantized rows for this row // in this scan. bool BlockBuffer::StartMCUQuantizerRow(class Scan *scan) { bool more = true; UBYTE ccnt = scan->ComponentsInScan(); for(UBYTE i = 0;i < ccnt;i++) { ULONG y,ymin,ymax,width,height; class QuantizedRow **last; class Component *comp = scan->ComponentOf(i); UBYTE mcuheight = (ccnt > 1)?(comp->MCUHeightOf()):(1); UBYTE subx = comp->SubXOf(); UBYTE suby = comp->SubYOf(); UBYTE idx = comp->IndexOf(); last = m_pppQStream[idx]; width = (m_ulPixelWidth + subx - 1) / subx; height = (m_ulPixelHeight + suby - 1) / suby; ymin = m_pulY[idx]; ymax = ymin + (mcuheight << 3); if (m_ulPixelHeight > 0 && ymax > height) ymax = height; if (ymin < ymax) { m_pulCurrentY[idx] = m_pulY[idx]; // // Skip all the lines in the MCU if (last) { while(mcuheight) { assert(*last); last = &((*last)->NextOf()); mcuheight--; } } else { last = &m_ppQTop[idx]; } for(y = ymin;y < ymax;y+=8) { if (*last == NULL) { *last = new(m_pEnviron) class QuantizedRow(m_pEnviron); } (*last)->AllocateRow(width); if (y == ymin) m_pppQStream[idx] = last; last = &((*last)->NextOf()); } } else { more = false; } m_pulY[idx] = ymax; } return more; } /// /// BlockBuffer::BufferedLines // Return the number of lines available for reconstruction from this scan. ULONG BlockBuffer::BufferedLines(const struct RectangleRequest *rr) const { int i; ULONG maxlines = m_ulPixelHeight; for(i = rr->rr_usFirstComponent;i <= rr->rr_usLastComponent;i++) { class Component *comp = m_pFrame->ComponentOf(i); ULONG curline = comp->SubYOf() * (m_pulCurrentY[i] + (comp->MCUHeightOf() << 3)); if (curline >= m_ulPixelHeight) { // end of image curline = m_ulPixelHeight; } else if (curline > 0 && comp->SubYOf() > 1) { // need one extra pixel at the end for subsampling expansion curline = (curline - comp->SubYOf()) & (-8); // one additional subsampled line, actually, // and as we reconstruct always multiples of eight, round down again. } if (curline < maxlines) maxlines = curline; } return maxlines; } /// /// BlockBuffer::StartMCUResidualRow // Start a MCU scan by initializing the residuals for this row. bool BlockBuffer::StartMCUResidualRow(class Scan *scan) { bool more = true; UBYTE ccnt = scan->ComponentsInScan(); for(UBYTE j = 0;j < ccnt;j++) { ULONG y,ymin,ymax,width,height; class QuantizedRow **last; class Component *comp = scan->ComponentOf(j); UBYTE i = comp->IndexOf(); UBYTE mcuheight = (ccnt > 1)?(comp->MCUHeightOf()):(1); UBYTE subx = comp->SubXOf(); UBYTE suby = comp->SubYOf(); last = m_pppRStream[i]; width = (m_ulPixelWidth + subx - 1) / subx; height = (m_ulPixelHeight + suby - 1) / suby; ymin = m_pulY[i]; ymax = ymin + (mcuheight << 3); if (m_ulPixelHeight > 0 && ymax > height) ymax = height; if (ymin < ymax) { m_pulCurrentY[i] = m_pulY[i]; if (last) { while(mcuheight) { assert(*last); last = &((*last)->NextOf()); mcuheight--; } } else { last = &m_ppRTop[i]; } for(y = ymin;y < ymax;y+=8) { if (*last == NULL) { *last = new(m_pEnviron) class QuantizedRow(m_pEnviron); } (*last)->AllocateRow(width); if (y == ymin) m_pppRStream[i] = last; last = &((*last)->NextOf()); } } else { more = false; } m_pulY[i] = ymax; } return more; } ///
utf-8
1
GPL-3
2012-2018 Thomas Richter, University of Stuttgart and Accusoft
srt-1.4.2/srtcore/group.cpp
#include <iterator> #include "api.h" #include "group.h" using namespace std; using namespace srt::sync; using namespace srt_logging; // The SRT_DEF_VERSION is defined in core.cpp. extern const int32_t SRT_DEF_VERSION; int32_t CUDTGroup::s_tokenGen = 0; // [[using locked(this->m_GroupLock)]]; bool CUDTGroup::getBufferTimeBase(CUDT* forthesakeof, steady_clock::time_point& w_tb, bool& w_wp, steady_clock::duration& w_dr) { CUDT* master = 0; for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { CUDT* u = &gi->ps->core(); if (gi->laststatus != SRTS_CONNECTED) { HLOGC(gmlog.Debug, log << "getBufferTimeBase: skipping @" << u->m_SocketID << ": not connected, state=" << SockStatusStr(gi->laststatus)); continue; } if (u == forthesakeof) continue; // skip the member if it's the target itself if (!u->m_pRcvBuffer) continue; // Not initialized yet master = u; break; // found } // We don't have any sockets in the group, so can't get // the buffer timebase. This should be then initialized // the usual way. if (!master) return false; w_wp = master->m_pRcvBuffer->getInternalTimeBase((w_tb), (w_dr)); // Sanity check if (is_zero(w_tb)) { LOGC(gmlog.Error, log << "IPE: existing previously socket has no time base set yet!"); return false; // this will enforce initializing the time base normal way } return true; } // [[using locked(this->m_GroupLock)]]; bool CUDTGroup::applyGroupSequences(SRTSOCKET target, int32_t& w_snd_isn, int32_t& w_rcv_isn) { if (m_bConnected) // You are the first one, no need to change. { IF_HEAVY_LOGGING(string update_reason = "what?"); // Find a socket that is declared connected and is not // the socket that caused the call. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { if (gi->id == target) continue; CUDT& se = gi->ps->core(); if (!se.m_bConnected) continue; // Found it. Get the following sequences: // For sending, the sequence that is about to be sent next. // For receiving, the sequence of the latest received packet. // SndCurrSeqNo is initially set to ISN-1, this next one is // the sequence that is about to be stamped on the next sent packet // over that socket. Using this field is safer because it is volatile // and its affinity is to the same thread as the sending function. // NOTE: the groupwise scheduling sequence might have been set // already. If so, it means that it was set by either: // - the call of this function on the very first conencted socket (see below) // - the call to `sendBroadcast` or `sendBackup` // In both cases, we want THIS EXACTLY value to be reported if (m_iLastSchedSeqNo != -1) { w_snd_isn = m_iLastSchedSeqNo; IF_HEAVY_LOGGING(update_reason = "GROUPWISE snd-seq"); } else { w_snd_isn = se.m_iSndNextSeqNo; // Write it back to the groupwise scheduling sequence so that // any next connected socket will take this value as well. m_iLastSchedSeqNo = w_snd_isn; IF_HEAVY_LOGGING(update_reason = "existing socket not yet sending"); } // RcvCurrSeqNo is increased by one because it happens that at the // synchronization moment it's already past reading and delivery. // This is redundancy, so the redundant socket is connected at the moment // when the other one is already transmitting, so skipping one packet // even if later transmitted is less troublesome than requesting a // "mistakenly seen as lost" packet. w_rcv_isn = CSeqNo::incseq(se.m_iRcvCurrSeqNo); HLOGC(gmlog.Debug, log << "applyGroupSequences: @" << target << " gets seq from @" << gi->id << " rcv %" << (w_rcv_isn) << " snd %" << (w_rcv_isn) << " as " << update_reason); return false; } } // If the GROUP (!) is not connected, or no running/pending socket has been found. // // That is, given socket is the first one. // The group data should be set up with its own data. They should already be passed here // in the variables. // // Override the schedule sequence of the group in this case because whatever is set now, // it's not valid. HLOGC(gmlog.Debug, log << "applyGroupSequences: no socket found connected and transmitting, @" << target << " not changing sequences, storing snd-seq %" << (w_snd_isn)); set_currentSchedSequence(w_snd_isn); return true; } // NOTE: This function is now for DEBUG PURPOSES ONLY. // Except for presenting the extracted data in the logs, there's no use of it now. void CUDTGroup::debugMasterData(SRTSOCKET slave) { // Find at least one connection, which is running. Note that this function is called // from within a handshake process, so the socket that undergoes this process is at best // currently in SRT_GST_PENDING state and it's going to be in SRT_GST_IDLE state at the // time when the connection process is done, until the first reading/writing happens. ScopedLock cg(m_GroupLock); SRTSOCKET mpeer; steady_clock::time_point start_time; bool found = false; for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { if (gi->sndstate == SRT_GST_RUNNING) { // Found it. Get the socket's peer's ID and this socket's // Start Time. Once it's delivered, this can be used to calculate // the Master-to-Slave start time difference. mpeer = gi->ps->m_PeerID; start_time = gi->ps->core().socketStartTime(); HLOGC(gmlog.Debug, log << "getMasterData: found RUNNING master @" << gi->id << " - reporting master's peer $" << mpeer << " starting at " << FormatTime(start_time)); found = true; break; } } if (!found) { // If no running one found, then take the first socket in any other // state than broken, except the slave. This is for a case when a user // has prepared one link already, but hasn't sent anything through it yet. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { if (gi->sndstate == SRT_GST_BROKEN) continue; if (gi->id == slave) continue; // Found it. Get the socket's peer's ID and this socket's // Start Time. Once it's delivered, this can be used to calculate // the Master-to-Slave start time difference. mpeer = gi->ps->core().m_PeerID; start_time = gi->ps->core().socketStartTime(); HLOGC(gmlog.Debug, log << "getMasterData: found IDLE/PENDING master @" << gi->id << " - reporting master's peer $" << mpeer << " starting at " << FormatTime(start_time)); found = true; break; } } if (!found) { LOGC(cnlog.Debug, log << CONID() << "NO GROUP MASTER LINK found for group: $" << id()); } else { // The returned master_st is the master's start time. Calculate the // differene time. steady_clock::duration master_tdiff = m_tsStartTime - start_time; LOGC(cnlog.Debug, log << CONID() << "FOUND GROUP MASTER LINK: peer=$" << mpeer << " - start time diff: " << FormatDuration<DUNIT_S>(master_tdiff)); } } // GROUP std::list<CUDTGroup::SocketData> CUDTGroup::GroupContainer::s_NoList; CUDTGroup::gli_t CUDTGroup::add(SocketData data) { ScopedLock g(m_GroupLock); // Change the snd/rcv state of the group member to PENDING. // Default for SocketData after creation is BROKEN, which just // after releasing the m_GroupLock could be read and interpreted // as broken connection and removed before the handshake process // is done. data.sndstate = SRT_GST_PENDING; data.rcvstate = SRT_GST_PENDING; m_Group.push_back(data); gli_t end = m_Group.end(); if (m_iMaxPayloadSize == -1) { int plsize = data.ps->m_pUDT->OPT_PayloadSize(); HLOGC(gmlog.Debug, log << "CUDTGroup::add: taking MAX payload size from socket @" << data.ps->m_SocketID << ": " << plsize << " " << (plsize ? "(explicit)" : "(unspecified = fallback to 1456)")); if (plsize == 0) plsize = SRT_LIVE_MAX_PLSIZE; // It is stated that the payload size // is taken from first, and every next one // will get the same. m_iMaxPayloadSize = plsize; } return --end; } CUDTGroup::SocketData CUDTGroup::prepareData(CUDTSocket* s) { // This uses default SRT_GST_BROKEN because when the group operation is done, // then the SRT_GST_IDLE state automatically turns into SRT_GST_RUNNING. This is // recognized as an initial state of the fresh added socket to the group, // so some "initial configuration" must be done on it, after which it's // turned into SRT_GST_RUNNING, that is, it's treated as all others. When // set to SRT_GST_BROKEN, this socket is disregarded. This socket isn't cleaned // up, however, unless the status is simultaneously SRTS_BROKEN. // The order of operations is then: // - add the socket to the group in this "broken" initial state // - connect the socket (or get it extracted from accept) // - update the socket state (should be SRTS_CONNECTED) // - once the connection is established (may take time with connect), set SRT_GST_IDLE // - the next operation of send/recv will automatically turn it into SRT_GST_RUNNING SocketData sd = { s->m_SocketID, s, -1, SRTS_INIT, SRT_GST_BROKEN, SRT_GST_BROKEN, -1, -1, sockaddr_any(), sockaddr_any(), false, false, false, 0 // weight }; return sd; } CUDTGroup::CUDTGroup(SRT_GROUP_TYPE gtype) : m_pGlobal(&CUDT::s_UDTUnited) , m_GroupID(-1) , m_PeerGroupID(-1) , m_selfManaged(true) , m_bSyncOnMsgNo(false) , m_type(gtype) , m_listener() , m_iSndOldestMsgNo(SRT_MSGNO_NONE) , m_iSndAckedMsgNo(SRT_MSGNO_NONE) , m_uOPT_StabilityTimeout(CUDT::COMM_DEF_STABILITY_TIMEOUT_US) // -1 = "undefined"; will become defined with first added socket , m_iMaxPayloadSize(-1) , m_bSynRecving(true) , m_bSynSending(true) , m_bTsbPd(true) , m_bTLPktDrop(true) , m_iTsbPdDelay_us(0) // m_*EID and m_*Epolld fields will be initialized // in the constructor body. , m_iSndTimeOut(-1) , m_iRcvTimeOut(-1) , m_tsStartTime() , m_tsRcvPeerStartTime() , m_RcvBaseSeqNo(SRT_SEQNO_NONE) , m_bOpened(false) , m_bConnected(false) , m_bClosing(false) , m_iLastSchedSeqNo(SRT_SEQNO_NONE) , m_iLastSchedMsgNo(SRT_MSGNO_NONE) { setupMutex(m_GroupLock, "Group"); setupMutex(m_RcvDataLock, "RcvData"); setupCond(m_RcvDataCond, "RcvData"); m_RcvEID = m_pGlobal->m_EPoll.create(&m_RcvEpolld); m_SndEID = m_pGlobal->m_EPoll.create(&m_SndEpolld); // Set this data immediately during creation before // two or more sockets start arguing about it. m_iLastSchedSeqNo = CUDT::generateISN(); // Configure according to type switch (gtype) { case SRT_GTYPE_BROADCAST: m_selfManaged = true; break; case SRT_GTYPE_BACKUP: m_selfManaged = true; break; case SRT_GTYPE_BALANCING: m_selfManaged = true; m_bSyncOnMsgNo = true; break; case SRT_GTYPE_MULTICAST: m_selfManaged = false; break; default: break; } } CUDTGroup::~CUDTGroup() { srt_epoll_release(m_RcvEID); srt_epoll_release(m_SndEID); releaseMutex(m_GroupLock); releaseMutex(m_RcvDataLock); releaseCond(m_RcvDataCond); } void CUDTGroup::GroupContainer::erase(CUDTGroup::gli_t it) { if (it == m_LastActiveLink) { if (m_List.empty()) { LOGC(gmlog.Error, log << "IPE: GroupContainer is empty and 'erase' is called on it."); return; // this avoids any misunderstandings in iterator checks } gli_t bb = m_List.begin(); ++bb; if (bb == m_List.end()) // means: m_List.size() == 1 { // One element, this one being deleted, nothing to point to. m_LastActiveLink = null(); } else { // Set the link to the previous element IN THE RING. // We have the position pointer. // Reverse iterator is automatically decremented. std::reverse_iterator<gli_t> rt(m_LastActiveLink); if (rt == m_List.rend()) rt = m_List.rbegin(); m_LastActiveLink = rt.base(); // This operation is safe because we know that: // - the size of the container is at least 2 (0 and 1 cases are handled above) // - if m_LastActiveLink == m_List.begin(), `rt` is shifted to the opposite end. --m_LastActiveLink; } } m_List.erase(it); } void CUDTGroup::setOpt(SRT_SOCKOPT optName, const void* optval, int optlen) { HLOGC(gmlog.Debug, log << "GROUP $" << id() << " OPTION: #" << optName << " value:" << FormatBinaryString((uint8_t*)optval, optlen)); switch (optName) { case SRTO_RCVSYN: m_bSynRecving = cast_optval<bool>(optval, optlen); return; case SRTO_SNDSYN: m_bSynSending = cast_optval<bool>(optval, optlen); return; case SRTO_SNDTIMEO: m_iSndTimeOut = cast_optval<int>(optval, optlen); break; case SRTO_RCVTIMEO: m_iRcvTimeOut = cast_optval<int>(optval, optlen); break; case SRTO_GROUPSTABTIMEO: { const int val = cast_optval<int>(optval, optlen); // Search if you already have SRTO_PEERIDLETIMEO set int idletmo = CUDT::COMM_RESPONSE_TIMEOUT_MS; vector<ConfigItem>::iterator f = find_if(m_config.begin(), m_config.end(), ConfigItem::OfType(SRTO_PEERIDLETIMEO)); if (f != m_config.end()) { f->get(idletmo); // worst case, it will leave it unchanged. } if (val >= idletmo) { LOGC(qmlog.Error, log << "group option: SRTO_GROUPSTABTIMEO(" << val << ") exceeds SRTO_PEERIDLETIMEO(" << idletmo << ")"); throw CUDTException(MJ_NOTSUP, MN_INVAL, 0); } m_uOPT_StabilityTimeout = val * 1000; } break; // XXX Currently no socket groups allow any other // congestion control mode other than live. case SRTO_CONGESTION: { LOGP(gmlog.Error, "group option: SRTO_CONGESTION is only allowed as 'live' and cannot be changed"); throw CUDTException(MJ_NOTSUP, MN_INVAL, 0); } // Other options to be specifically interpreted by group may follow. default: break; } // All others must be simply stored for setting on a socket. // If the group is already open and any post-option is about // to be modified, it must be allowed and applied on all sockets. if (m_bOpened) { // There's at least one socket in the group, so only // post-options are allowed. if (!std::binary_search(srt_post_opt_list, srt_post_opt_list + SRT_SOCKOPT_NPOST, optName)) { LOGC(gmlog.Error, log << "setsockopt(group): Group is connected, this option can't be altered"); throw CUDTException(MJ_NOTSUP, MN_ISCONNECTED, 0); } HLOGC(gmlog.Debug, log << "... SPREADING to existing sockets."); // This means that there are sockets already, so apply // this option on them. ScopedLock gg(m_GroupLock); for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { gi->ps->core().setOpt(optName, optval, optlen); } } // Store the option regardless if pre or post. This will apply m_config.push_back(ConfigItem(optName, optval, optlen)); } static bool getOptDefault(SRT_SOCKOPT optname, void* optval, int& w_optlen); // unfortunately this is required to properly handle th 'default_opt != opt' // operation in the below importOption. Not required simultaneously operator==. static bool operator!=(const struct linger& l1, const struct linger& l2) { return l1.l_onoff != l2.l_onoff || l1.l_linger != l2.l_linger; } template <class ValueType> static void importOption(vector<CUDTGroup::ConfigItem>& storage, SRT_SOCKOPT optname, const ValueType& field) { ValueType default_opt = ValueType(); int default_opt_size = sizeof(ValueType); ValueType opt = field; if (!getOptDefault(optname, (&default_opt), (default_opt_size)) || default_opt != opt) { // Store the option when: // - no default for this option is found // - the option value retrieved from the field is different than default storage.push_back(CUDTGroup::ConfigItem(optname, &opt, default_opt_size)); } } // This function is called by the same premises as the CUDT::CUDT(const CUDT&) (copy constructor). // The intention is to rewrite the part that comprises settings from the socket // into the group. Note that some of the settings concern group, some others concern // only target socket, and there are also options that can't be set on a socket. void CUDTGroup::deriveSettings(CUDT* u) { // !!! IMPORTANT !!! // // This function shall ONLY be called on a newly created group // for the sake of the newly accepted socket from the group-enabled listener, // which is lazy-created for the first ever accepted socket. // Once the group is created, it should stay with the options // state as initialized here, and be changeable only in case when // the option is altered on the group. // SRTO_RCVSYN m_bSynRecving = u->m_bSynRecving; // SRTO_SNDSYN m_bSynSending = u->m_bSynSending; // SRTO_RCVTIMEO m_iRcvTimeOut = u->m_iRcvTimeOut; // SRTO_SNDTIMEO m_iSndTimeOut = u->m_iSndTimeOut; // Ok, this really is disgusting, but there's only one way // to properly do it. Would be nice to have some more universal // connection between an option symbolic name and the internals // in CUDT class, but until this is done, since now every new // option will have to be handled both in the CUDT::setOpt/getOpt // functions, and here as well. // This is about moving options from listener to the group, // to be potentially replicated on the socket. So both pre // and post options apply. #define IM(option, field) importOption(m_config, option, u->field) IM(SRTO_MSS, m_iMSS); IM(SRTO_FC, m_iFlightFlagSize); // Nonstandard importOption(m_config, SRTO_SNDBUF, u->m_iSndBufSize * (u->m_iMSS - CPacket::UDP_HDR_SIZE)); importOption(m_config, SRTO_RCVBUF, u->m_iRcvBufSize * (u->m_iMSS - CPacket::UDP_HDR_SIZE)); IM(SRTO_LINGER, m_Linger); IM(SRTO_UDP_SNDBUF, m_iUDPSndBufSize); IM(SRTO_UDP_RCVBUF, m_iUDPRcvBufSize); // SRTO_RENDEZVOUS: impossible to have it set on a listener socket. // SRTO_SNDTIMEO/RCVTIMEO: groupwise setting IM(SRTO_CONNTIMEO, m_tdConnTimeOut); IM(SRTO_DRIFTTRACER, m_bDriftTracer); // Reuseaddr: true by default and should only be true. IM(SRTO_MAXBW, m_llMaxBW); IM(SRTO_INPUTBW, m_llInputBW); IM(SRTO_OHEADBW, m_iOverheadBW); IM(SRTO_IPTOS, m_iIpToS); IM(SRTO_IPTTL, m_iIpTTL); IM(SRTO_TSBPDMODE, m_bOPT_TsbPd); IM(SRTO_RCVLATENCY, m_iOPT_TsbPdDelay); IM(SRTO_PEERLATENCY, m_iOPT_PeerTsbPdDelay); IM(SRTO_SNDDROPDELAY, m_iOPT_SndDropDelay); IM(SRTO_PAYLOADSIZE, m_zOPT_ExpPayloadSize); IM(SRTO_TLPKTDROP, m_bTLPktDrop); IM(SRTO_STREAMID, m_sStreamName); IM(SRTO_MESSAGEAPI, m_bMessageAPI); IM(SRTO_NAKREPORT, m_bRcvNakReport); IM(SRTO_MINVERSION, m_lMinimumPeerSrtVersion); IM(SRTO_ENFORCEDENCRYPTION, m_bOPT_StrictEncryption); IM(SRTO_IPV6ONLY, m_iIpV6Only); IM(SRTO_PEERIDLETIMEO, m_iOPT_PeerIdleTimeout); IM(SRTO_GROUPSTABTIMEO, m_uOPT_StabilityTimeout); IM(SRTO_PACKETFILTER, m_OPT_PktFilterConfigString); importOption(m_config, SRTO_PBKEYLEN, u->m_pCryptoControl->KeyLen()); // Passphrase is empty by default. Decipher the passphrase and // store as passphrase option if (u->m_CryptoSecret.len) { string password((const char*)u->m_CryptoSecret.str, u->m_CryptoSecret.len); m_config.push_back(ConfigItem(SRTO_PASSPHRASE, password.c_str(), password.size())); } IM(SRTO_KMREFRESHRATE, m_uKmRefreshRatePkt); IM(SRTO_KMPREANNOUNCE, m_uKmPreAnnouncePkt); string cc = u->m_CongCtl.selected_name(); if (cc != "live") { m_config.push_back(ConfigItem(SRTO_CONGESTION, cc.c_str(), cc.size())); } // NOTE: This is based on information extracted from the "semi-copy-constructor" of CUDT class. // Here should be handled all things that are options that modify the socket, but not all options // are assigned to configurable items. #undef IM } bool CUDTGroup::applyFlags(uint32_t flags, HandshakeSide hsd) { bool synconmsg = IsSet(flags, SRT_GFLAG_SYNCONMSG); if (m_type == SRT_GTYPE_BALANCING) { // We support only TRUE for this flag if (!synconmsg) { HLOGP(gmlog.Debug, "GROUP: Balancing mode implemented only with sync on msgno - overridden request"); return true; // accept, but override } // We have this flag set; change it in yourself, if needed. if (hsd == HSD_INITIATOR && !m_bSyncOnMsgNo) { // With this you can change in future the default value to false. HLOGP(gmlog.Debug, "GROUP: Balancing requrested msgno-sync, OVERRIDING original setting"); m_bSyncOnMsgNo = true; return true; } } else { if (synconmsg) { LOGP(gmlog.Error, "GROUP: non-balancing type requested sync on msgno - IPE/EPE?"); return false; } } // Ignore the flag anyway. This can change in future versions though. return true; } template <class Type> struct Value { static int fill(void* optval, int, Type value) { // XXX assert size >= sizeof(Type) ? *(Type*)optval = value; return sizeof(Type); } }; template <> inline int Value<std::string>::fill(void* optval, int len, std::string value) { if (size_t(len) < value.size()) return 0; memcpy(optval, value.c_str(), value.size()); return value.size(); } template <class V> inline int fillValue(void* optval, int len, V value) { return Value<V>::fill(optval, len, value); } static bool getOptDefault(SRT_SOCKOPT optname, void* pw_optval, int& w_optlen) { static const linger def_linger = {1, CUDT::DEF_LINGER_S}; switch (optname) { default: return false; #define RD(value) \ w_optlen = fillValue((pw_optval), w_optlen, value); \ break case SRTO_KMSTATE: case SRTO_SNDKMSTATE: case SRTO_RCVKMSTATE: RD(SRT_KM_S_UNSECURED); case SRTO_PBKEYLEN: RD(16); case SRTO_MSS: RD(CUDT::DEF_MSS); case SRTO_SNDSYN: RD(true); case SRTO_RCVSYN: RD(true); case SRTO_ISN: RD(SRT_SEQNO_NONE); case SRTO_FC: RD(CUDT::DEF_FLIGHT_SIZE); case SRTO_SNDBUF: case SRTO_RCVBUF: w_optlen = fillValue((pw_optval), w_optlen, CUDT::DEF_BUFFER_SIZE * (CUDT::DEF_MSS - CPacket::UDP_HDR_SIZE)); break; case SRTO_LINGER: RD(def_linger); case SRTO_UDP_SNDBUF: case SRTO_UDP_RCVBUF: RD(CUDT::DEF_UDP_BUFFER_SIZE); case SRTO_RENDEZVOUS: RD(false); case SRTO_SNDTIMEO: RD(-1); case SRTO_RCVTIMEO: RD(-1); case SRTO_REUSEADDR: RD(true); case SRTO_MAXBW: RD(int64_t(-1)); case SRTO_INPUTBW: RD(int64_t(-1)); case SRTO_OHEADBW: RD(0); case SRTO_STATE: RD(SRTS_INIT); case SRTO_EVENT: RD(0); case SRTO_SNDDATA: RD(0); case SRTO_RCVDATA: RD(0); case SRTO_IPTTL: RD(0); case SRTO_IPTOS: RD(0); case SRTO_SENDER: RD(false); case SRTO_TSBPDMODE: RD(false); case SRTO_LATENCY: case SRTO_RCVLATENCY: case SRTO_PEERLATENCY: RD(SRT_LIVE_DEF_LATENCY_MS); case SRTO_TLPKTDROP: RD(true); case SRTO_SNDDROPDELAY: RD(-1); case SRTO_NAKREPORT: RD(true); case SRTO_VERSION: RD(SRT_DEF_VERSION); case SRTO_PEERVERSION: RD(0); case SRTO_CONNTIMEO: RD(-1); case SRTO_DRIFTTRACER: RD(true); case SRTO_MINVERSION: RD(0); case SRTO_STREAMID: RD(std::string()); case SRTO_CONGESTION: RD(std::string()); case SRTO_MESSAGEAPI: RD(true); case SRTO_PAYLOADSIZE: RD(0); } #undef RD return true; } void CUDTGroup::getOpt(SRT_SOCKOPT optname, void* pw_optval, int& w_optlen) { // Options handled in group switch (optname) { case SRTO_RCVSYN: *(bool*)pw_optval = m_bSynRecving; w_optlen = sizeof(bool); return; case SRTO_SNDSYN: *(bool*)pw_optval = m_bSynSending; w_optlen = sizeof(bool); return; default:; // pass on } CUDTSocket* ps = 0; { // In sockets. All sockets should have all options // set the same and should represent the group state // well enough. If there are no sockets, just use default. // Group lock to protect the container itself. // Once a socket is extracted, we state it cannot be // closed without the group send/recv function or closing // being involved. ScopedLock lg(m_GroupLock); if (m_Group.empty()) { if (!getOptDefault(optname, (pw_optval), (w_optlen))) throw CUDTException(MJ_NOTSUP, MN_INVAL, 0); return; } ps = m_Group.begin()->ps; // Release the lock on the group, as it's not necessary, // as well as it might cause a deadlock when combined // with the others. } if (!ps) throw CUDTException(MJ_NOTSUP, MN_INVAL, 0); return ps->core().getOpt(optname, (pw_optval), (w_optlen)); } struct HaveState : public unary_function<pair<SRTSOCKET, SRT_SOCKSTATUS>, bool> { SRT_SOCKSTATUS s; HaveState(SRT_SOCKSTATUS ss) : s(ss) { } bool operator()(pair<SRTSOCKET, SRT_SOCKSTATUS> i) const { return i.second == s; } }; SRT_SOCKSTATUS CUDTGroup::getStatus() { typedef vector<pair<SRTSOCKET, SRT_SOCKSTATUS> > states_t; states_t states; { ScopedLock cg(m_GroupLock); for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { switch (gi->sndstate) { // Check only sndstate. If this machine is ONLY receiving, // then rcvstate will turn into SRT_GST_RUNNING, while // sndstate will remain SRT_GST_IDLE, but still this may only // happen if the socket is connected. case SRT_GST_IDLE: case SRT_GST_RUNNING: states.push_back(make_pair(gi->id, SRTS_CONNECTED)); break; case SRT_GST_BROKEN: states.push_back(make_pair(gi->id, SRTS_BROKEN)); break; default: // (pending, or whatever will be added in future) { SRT_SOCKSTATUS st = m_pGlobal->getStatus(gi->id); states.push_back(make_pair(gi->id, st)); } } } } // If at least one socket is connected, the state is connected. if (find_if(states.begin(), states.end(), HaveState(SRTS_CONNECTED)) != states.end()) return SRTS_CONNECTED; // Otherwise find at least one socket, which's state isn't broken. // If none found, return SRTS_BROKEN. states_t::iterator p = find_if(states.begin(), states.end(), not1(HaveState(SRTS_BROKEN))); if (p != states.end()) { // Return that state as group state return p->second; } return SRTS_BROKEN; } void CUDTGroup::syncWithSocket(const CUDT& core, const HandshakeSide side) { // [[using locked(m_GroupLock)]]; if (side == HSD_RESPONDER) { // On the listener side you should synchronize ISN with the incoming // socket, which is done immediately after creating the socket and // adding it to the group. On the caller side the ISN is defined in // the group directly, before any member socket is created. set_currentSchedSequence(core.ISN()); } // XXX // Might need further investigation as to whether this isn't // wrong for some cases. By having this -1 here the value will be // laziliy set from the first reading one. It is believed that // it covers all possible scenarios, that is: // // - no readers - no problem! // - have some readers and a new is attached - this is set already // - connect multiple links, but none has read yet - you'll be the first. // // Previous implementation used setting to: core.m_iPeerISN resetInitialRxSequence(); // Get the latency (possibly fixed against the opposite side) // from the first socket (core.m_iTsbPdDelay_ms), // and set it on the current socket. set_latency(core.m_iTsbPdDelay_ms * int64_t(1000)); } void CUDTGroup::close() { // Close all descriptors, then delete the group. vector<SRTSOCKET> ids; { ScopedLock g(m_GroupLock); // A non-managed group may only be closed if there are no // sockets in the group. // XXX Fortunately there are currently no non-self-managed // groups, so this error cannot ever happen, but this error // has the overall code suggesting that it's about the listener, // so either the name should be changed here, or a different code used. if (!m_selfManaged && !m_Group.empty()) throw CUDTException(MJ_NOTSUP, MN_BUSY, 0); // Copy the list of IDs into the array. for (gli_t ig = m_Group.begin(); ig != m_Group.end(); ++ig) ids.push_back(ig->id); } // Close all sockets with unlocked GroupLock for (vector<SRTSOCKET>::iterator i = ids.begin(); i != ids.end(); ++i) m_pGlobal->close(*i); // Lock the group again to clear the group data { ScopedLock g(m_GroupLock); m_Group.clear(); m_PeerGroupID = -1; // This takes care of the internal part. // The external part will be done in Global (CUDTUnited) } // Release blocked clients CSync::lock_signal(m_RcvDataCond, m_RcvDataLock); } int CUDTGroup::send(const char* buf, int len, SRT_MSGCTRL& w_mc) { switch (m_type) { default: LOGC(gslog.Error, log << "CUDTGroup::send: not implemented for type #" << m_type); throw CUDTException(MJ_SETUP, MN_INVAL, 0); case SRT_GTYPE_BROADCAST: return sendBroadcast(buf, len, (w_mc)); case SRT_GTYPE_BACKUP: return sendBackup(buf, len, (w_mc)); /* to be implemented case SRT_GTYPE_BALANCING: return sendBalancing(buf, len, (w_mc)); case SRT_GTYPE_MULTICAST: return sendMulticast(buf, len, (w_mc)); */ } } int CUDTGroup::sendBroadcast(const char* buf, int len, SRT_MSGCTRL& w_mc) { // Avoid stupid errors in the beginning. if (len <= 0) { throw CUDTException(MJ_NOTSUP, MN_INVAL, 0); } // NOTE: This is a "vector of list iterators". Every element here // is an iterator to another container. // Note that "list" is THE ONLY container in standard C++ library, // for which NO ITERATORS ARE INVALIDATED after a node at particular // iterator has been removed, except for that iterator itself. vector<gli_t> wipeme; vector<gli_t> idlers; vector<gli_t> pending; int32_t curseq = SRT_SEQNO_NONE; int rstat = -1; int stat = 0; SRT_ATR_UNUSED CUDTException cx(MJ_SUCCESS, MN_NONE, 0); vector<gli_t> sendable; ScopedLock guard(m_GroupLock); // This simply requires the payload to be sent through every socket in the group for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d) { // Check the socket state prematurely in order not to uselessly // send over a socket that is broken. CUDT* pu = 0; if (d->ps) pu = &d->ps->core(); if (!pu || pu->m_bBroken) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: socket @" << d->id << " detected +Broken - transit to BROKEN"); d->sndstate = SRT_GST_BROKEN; d->rcvstate = SRT_GST_BROKEN; } // Check socket sndstate before sending if (d->sndstate == SRT_GST_BROKEN) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: socket in BROKEN state: @" << d->id << ", sockstatus=" << SockStatusStr(d->ps ? d->ps->getStatus() : SRTS_NONEXIST)); wipeme.push_back(d); continue; } if (d->sndstate == SRT_GST_IDLE) { SRT_SOCKSTATUS st = SRTS_NONEXIST; if (d->ps) st = d->ps->getStatus(); // If the socket is already broken, move it to broken. if (int(st) >= int(SRTS_BROKEN)) { HLOGC(gslog.Debug, log << "CUDTGroup::send.$" << id() << ": @" << d->id << " became " << SockStatusStr(st) << ", WILL BE CLOSED."); wipeme.push_back(d); continue; } if (st != SRTS_CONNECTED) { HLOGC(gslog.Debug, log << "CUDTGroup::send. @" << d->id << " is still " << SockStatusStr(st) << ", skipping."); pending.push_back(d); continue; } HLOGC(gslog.Debug, log << "grp/sendBroadcast: socket in IDLE state: @" << d->id << " - will activate it"); // This is idle, we'll take care of them next time // Might be that: // - this socket is idle, while some NEXT socket is running // - we need at least one running socket to work BEFORE activating the idle one. // - if ALL SOCKETS ARE IDLE, then we simply activate the first from the list, // and all others will be activated using the ISN from the first one. idlers.push_back(d); continue; } if (d->sndstate == SRT_GST_RUNNING) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: socket in RUNNING state: @" << d->id << " - will send a payload"); sendable.push_back(d); continue; } HLOGC(gslog.Debug, log << "grp/sendBroadcast: socket @" << d->id << " not ready, state: " << StateStr(d->sndstate) << "(" << int(d->sndstate) << ") - NOT sending, SET AS PENDING"); pending.push_back(d); } vector<Sendstate> sendstates; for (vector<gli_t>::iterator snd = sendable.begin(); snd != sendable.end(); ++snd) { gli_t d = *snd; int erc = 0; // success // Remaining sndstate is SRT_GST_RUNNING. Send a payload through it. try { // This must be wrapped in try-catch because on error it throws an exception. // Possible return values are only 0, in case when len was passed 0, or a positive // >0 value that defines the size of the data that it has sent, that is, in case // of Live mode, equal to 'len'. CUDTSocket* ps = d->ps; // Lift the group lock for a while, to avoid possible deadlocks. InvertedLock ug(m_GroupLock); stat = ps->core().sendmsg2(buf, len, (w_mc)); } catch (CUDTException& e) { cx = e; stat = -1; erc = e.getErrorCode(); } if (stat != -1) { curseq = w_mc.pktseq; } const Sendstate cstate = {d, stat, erc}; sendstates.push_back(cstate); d->sndresult = stat; d->laststatus = d->ps->getStatus(); } // Ok, we have attempted to send a payload over all links // that are currently in the RUNNING state. We know that at // least one is successful if we have non-default curseq value. // Here we need to activate all links that are found as IDLE. // Some portion of logical exclusions: // // - sockets that were broken in the beginning are already wiped out // - broken sockets are checked first, so they can't be simultaneously idle // - idle sockets can't get broken because there's no operation done on them // - running sockets are the only one that could change sndstate here // - running sockets can either remain running or turn to broken // In short: Running and Broken sockets can't become idle, // although Running sockets can become Broken. // There's no certainty here as to whether at least one link was // running and it has successfully performed the operation. // Might have even happened that we had 2 running links that // got broken and 3 other links so far in idle sndstate that just connected // at that very moment. In this case we have 3 idle links to activate, // but there is no sequence base to overwrite their ISN with. If this // happens, then the first link that should be activated goes with // whatever ISN it has, whereas every next idle link should use that // exactly ISN. // // If it has additionally happened that the first link got broken at // that very moment of sending, the second one has a chance to succeed // and therefore take over the leading role in setting the ISN. If the // second one fails, too, then the only remaining idle link will simply // go with its own original sequence. // // On the opposite side the reader should know that the link is inactive // so the first received payload activates it. Activation of an idle link // means that the very first packet arriving is TAKEN AS A GOOD DEAL, that is, // no LOSSREPORT is sent even if the sequence looks like a "jumped over". // Only for activated links is the LOSSREPORT sent upon seqhole detection. // Now we can go to the idle links and attempt to send the payload // also over them. // { sendBroadcast_ActivateIdlers for (vector<gli_t>::iterator i = idlers.begin(); i != idlers.end(); ++i) { int erc = 0; gli_t d = *i; int lastseq = d->ps->core().schedSeqNo(); if (curseq != SRT_SEQNO_NONE && curseq != lastseq) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: socket @" << d->id << ": override snd sequence %" << lastseq << " with %" << curseq << " (diff by " << CSeqNo::seqcmp(curseq, lastseq) << "); SENDING PAYLOAD: " << BufferStamp(buf, len)); d->ps->core().overrideSndSeqNo(curseq); } else { HLOGC(gslog.Debug, log << "grp/sendBroadcast: socket @" << d->id << ": sequence remains with original value: %" << lastseq << "; SENDING PAYLOAD " << BufferStamp(buf, len)); } // Now send and check the status // The link could have got broken try { InvertedLock ug(m_GroupLock); stat = d->ps->core().sendmsg2(buf, len, (w_mc)); } catch (CUDTException& e) { cx = e; stat = -1; erc = e.getErrorCode(); } if (stat != -1) { d->sndstate = SRT_GST_RUNNING; // Note: this will override the sequence number // for all next iterations in this loop. curseq = w_mc.pktseq; HLOGC(gslog.Debug, log << "@" << d->id << ":... sending SUCCESSFUL %" << curseq << " MEMBER STATUS: RUNNING"); } d->sndresult = stat; d->laststatus = d->ps->getStatus(); const Sendstate cstate = {d, stat, erc}; sendstates.push_back(cstate); } if (curseq != SRT_SEQNO_NONE) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: updating current scheduling sequence %" << curseq); m_iLastSchedSeqNo = curseq; } // } // { send_CheckBrokenSockets() if (!pending.empty()) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: found pending sockets, polling them."); // These sockets if they are in pending state, they should be added to m_SndEID // at the connecting stage. CEPoll::fmap_t sready; if (m_SndEpolld->watch_empty()) { // Sanity check - weird pending reported. LOGC(gslog.Error, log << "grp/sendBroadcast: IPE: reported pending sockets, but EID is empty - wiping pending!"); copy(pending.begin(), pending.end(), back_inserter(wipeme)); } else { { InvertedLock ug(m_GroupLock); THREAD_PAUSED(); m_pGlobal->m_EPoll.swait( *m_SndEpolld, sready, 0, false /*report by retval*/); // Just check if anything happened THREAD_RESUMED(); } HLOGC(gslog.Debug, log << "grp/sendBroadcast: RDY: " << DisplayEpollResults(sready)); // sockets in EX: should be moved to wipeme. for (vector<gli_t>::iterator i = pending.begin(); i != pending.end(); ++i) { gli_t d = *i; if (CEPoll::isready(sready, d->id, SRT_EPOLL_ERR)) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: Socket @" << d->id << " reported FAILURE - moved to wiped."); // Failed socket. Move d to wipeme. Remove from eid. wipeme.push_back(d); int no_events = 0; m_pGlobal->m_EPoll.update_usock(m_SndEID, d->id, &no_events); } } // After that, all sockets that have been reported // as ready to write should be removed from EID. This // will also remove those sockets that have been added // as redundant links at the connecting stage and became // writable (connected) before this function had a chance // to check them. m_pGlobal->m_EPoll.clear_ready_usocks(*m_SndEpolld, SRT_EPOLL_CONNECT); } } // Review the wipeme sockets. // The reason why 'wipeme' is kept separately to 'broken_sockets' is that // it might theoretically happen that ps becomes NULL while the item still exists. vector<CUDTSocket*> broken_sockets; // delete all sockets that were broken at the entrance for (vector<gli_t>::iterator i = wipeme.begin(); i != wipeme.end(); ++i) { gli_t d = *i; CUDTSocket* ps = d->ps; if (!ps) { LOGC(gslog.Error, log << "grp/sendBroadcast: IPE: socket NULL at id=" << d->id << " - removing from group list"); // Closing such socket is useless, it simply won't be found in the map and // the internal facilities won't know what to do with it anyway. // Simply delete the entry. m_Group.erase(d); continue; } broken_sockets.push_back(ps); } if (!broken_sockets.empty()) // Prevent unlock-lock cycle if no broken sockets found { // Lift the group lock for a while, to avoid possible deadlocks. InvertedLock ug(m_GroupLock); for (vector<CUDTSocket*>::iterator x = broken_sockets.begin(); x != broken_sockets.end(); ++x) { CUDTSocket* ps = *x; HLOGC(gslog.Debug, log << "grp/sendBroadcast: BROKEN SOCKET @" << ps->m_SocketID << " - CLOSING AND REMOVING."); // NOTE: This does inside: ps->removeFromGroup(). // After this call, 'd' is no longer valid and *i is singular. CUDT::s_UDTUnited.close(ps); } } HLOGC(gslog.Debug, log << "grp/sendBroadcast: - wiped " << wipeme.size() << " broken sockets"); // We'll need you again. wipeme.clear(); broken_sockets.clear(); // } // { sendBroadcast_CheckBlockedLinks() // Alright, we've made an attempt to send a packet over every link. // Every operation was done through a non-blocking attempt, so // links where sending was blocked have SRT_EASYNCSND error. // Links that were successful, have the len value in state. // First thing then, find out if at least one link was successful. // This might even be one of the idlers only, this doesn't matter. // If there were any running links successful, they have set the sequence. // If there were only some reactivated idlers successful, the first // idler has defined the sequence. vector<gli_t> successful, blocked; // This iteration of the state will simply // qualify the remaining sockets into three categories: // // - successful (we only need to know if at least one did) // - blocked - if none succeeded, but some blocked, POLL & RETRY. // - wipeme - sending failed by any other reason than blocking, remove. for (vector<Sendstate>::iterator is = sendstates.begin(); is != sendstates.end(); ++is) { if (is->stat == len) { HLOGC(gslog.Debug, log << "SEND STATE link [" << (is - sendstates.begin()) << "]: SUCCESSFULLY sent " << len << " bytes"); // Successful. successful.push_back(is->d); rstat = is->stat; continue; } // Remaining are only failed. Check if again. if (is->code == SRT_EASYNCSND) { blocked.push_back(is->d); continue; } #if ENABLE_HEAVY_LOGGING string errmsg = cx.getErrorString(); LOGC(gslog.Debug, log << "SEND STATE link [" << (is - sendstates.begin()) << "]: FAILURE (result:" << is->stat << "): " << errmsg << ". Setting this socket broken status."); #endif // Turn this link broken is->d->sndstate = SRT_GST_BROKEN; } // Good, now let's realize the situation. // First, check the most optimistic scenario: at least one link succeeded. bool was_blocked = false; bool none_succeeded = false; if (!successful.empty()) { // Good. All blocked links are now qualified as broken. // You had your chance, but I can't leave you here, // there will be no further chance to reattempt sending. for (vector<gli_t>::iterator b = blocked.begin(); b != blocked.end(); ++b) { (*b)->sndstate = SRT_GST_BROKEN; } blocked.clear(); } else { none_succeeded = true; was_blocked = !blocked.empty(); } int ercode = 0; if (was_blocked) { m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); if (!m_bSynSending) { throw CUDTException(MJ_AGAIN, MN_WRAVAIL, 0); } HLOGC(gslog.Debug, log << "grp/sendBroadcast: all blocked, trying to common-block on epoll..."); // XXX TO BE REMOVED. Sockets should be subscribed in m_SndEID at connecting time // (both srt_connect and srt_accept). // None was successful, but some were blocked. It means that we // haven't sent the payload over any link so far, so we still have // a chance to retry. int modes = SRT_EPOLL_OUT | SRT_EPOLL_ERR; for (vector<gli_t>::iterator b = blocked.begin(); b != blocked.end(); ++b) { HLOGC(gslog.Debug, log << "Will block on blocked socket @" << (*b)->id << " as only blocked socket remained"); srt_epoll_add_usock(m_SndEID, (*b)->id, &modes); } const int blocklen = blocked.size(); int blst = 0; CEPoll::fmap_t sready; { // Lift the group lock for a while, to avoid possible deadlocks. InvertedLock ug(m_GroupLock); HLOGC(gslog.Debug, log << "grp/sendBroadcast: blocking on any of blocked sockets to allow sending"); // m_iSndTimeOut is -1 by default, which matches the meaning of waiting forever THREAD_PAUSED(); blst = m_pGlobal->m_EPoll.swait(*m_SndEpolld, sready, m_iSndTimeOut); THREAD_RESUMED(); // NOTE EXCEPTIONS: // - EEMPTY: won't happen, we have explicitly added sockets to EID here. // - XTIMEOUT: will be propagated as this what should be reported to API // This is the only reason why here the errors are allowed to be handled // by exceptions. } if (blst == -1) { int rno; ercode = srt_getlasterror(&rno); } else { sendable.clear(); sendstates.clear(); // Extract gli's from the whole group that have id found in the array. for (gli_t dd = m_Group.begin(); dd != m_Group.end(); ++dd) { int rdev = CEPoll::ready(sready, dd->id); if (rdev & SRT_EPOLL_ERR) { dd->sndstate = SRT_GST_BROKEN; } else if (rdev & SRT_EPOLL_OUT) sendable.push_back(dd); } for (vector<gli_t>::iterator snd = sendable.begin(); snd != sendable.end(); ++snd) { gli_t d = *snd; int erc = 0; // success // Remaining sndstate is SRT_GST_RUNNING. Send a payload through it. try { // This must be wrapped in try-catch because on error it throws an exception. // Possible return values are only 0, in case when len was passed 0, or a positive // >0 value that defines the size of the data that it has sent, that is, in case // of Live mode, equal to 'blocklen'. stat = d->ps->core().sendmsg2(buf, blocklen, (w_mc)); } catch (CUDTException& e) { cx = e; stat = -1; erc = e.getErrorCode(); } if (stat != -1) curseq = w_mc.pktseq; const Sendstate cstate = {d, stat, erc}; sendstates.push_back(cstate); d->sndresult = stat; d->laststatus = d->ps->getStatus(); } // This time only check if any were successful. // All others are wipeme. for (vector<Sendstate>::iterator is = sendstates.begin(); is != sendstates.end(); ++is) { if (is->stat == blocklen) { // Successful. successful.push_back(is->d); rstat = is->stat; was_blocked = false; none_succeeded = false; continue; } #if ENABLE_HEAVY_LOGGING string errmsg = cx.getErrorString(); HLOGC(gslog.Debug, log << "... (repeat-waited) sending FAILED (" << errmsg << "). Setting this socket broken status."); #endif // Turn this link broken is->d->sndstate = SRT_GST_BROKEN; } } } // } if (none_succeeded) { HLOGC(gslog.Debug, log << "grp/sendBroadcast: all links broken (none succeeded to send a payload)"); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); // Reparse error code, if set. // It might be set, if the last operation was failed. // If any operation succeeded, this will not be executed anyway. CodeMajor major = CodeMajor(ercode ? ercode / 1000 : MJ_CONNECTION); CodeMinor minor = CodeMinor(ercode ? ercode % 1000 : MN_CONNLOST); throw CUDTException(major, minor, 0); } // Now that at least one link has succeeded, update sending stats. m_stats.sent.Update(len); // Pity that the blocking mode only determines as to whether this function should // block or not, but the epoll flags must be updated regardless of the mode. // Now fill in the socket table. Check if the size is enough, if not, // then set the pointer to NULL and set the correct size. // Note that list::size() is linear time, however this shouldn't matter, // as with the increased number of links in the redundancy group the // impossibility of using that many of them grows exponentally. size_t grpsize = m_Group.size(); if (w_mc.grpdata_size < grpsize) { w_mc.grpdata = NULL; } size_t i = 0; bool ready_again = false; for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d, ++i) { if (w_mc.grpdata) { // Enough space to fill copyGroupData(*d, (w_mc.grpdata[i])); } // We perform this loop anyway because we still need to check if any // socket is writable. Note that the group lock will hold any write ready // updates that are performed just after a single socket update for the // group, so if any socket is actually ready at the moment when this // is performed, and this one will result in none-write-ready, this will // be fixed just after returning from this function. ready_again = ready_again | d->ps->writeReady(); } w_mc.grpdata_size = i; if (!ready_again) { m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); } return rstat; } int CUDTGroup::getGroupData(SRT_SOCKGROUPDATA* pdata, size_t* psize) { if (!psize) return CUDT::APIError(MJ_NOTSUP, MN_INVAL); ScopedLock gl(m_GroupLock); return getGroupDataIn(pdata, psize); } int CUDTGroup::getGroupDataIn(SRT_SOCKGROUPDATA* pdata, size_t* psize) { SRT_ASSERT(psize != NULL); const size_t size = *psize; // Rewrite correct size *psize = m_Group.size(); if (!pdata) { return 0; } if (m_Group.size() > size) { // Not enough space to retrieve the data. return CUDT::APIError(MJ_NOTSUP, MN_XSIZE); } size_t i = 0; for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d, ++i) { copyGroupData(*d, (pdata[i])); } return m_Group.size(); } void CUDTGroup::copyGroupData(const CUDTGroup::SocketData& source, SRT_SOCKGROUPDATA& w_target) { w_target.id = source.id; memcpy((&w_target.peeraddr), &source.peer, source.peer.size()); w_target.sockstate = source.laststatus; w_target.token = source.token; // In the internal structure the member state // is one per direction. From the user perspective // however it is used either in one direction only, // in which case the one direction that is active // matters, or in both directions, in which case // it will be always either both active or both idle. if (source.sndstate == SRT_GST_RUNNING || source.rcvstate == SRT_GST_RUNNING) { w_target.result = 0; w_target.memberstate = SRT_GST_RUNNING; } // Stats can differ per direction only // when at least in one direction it's ACTIVE. else if (source.sndstate == SRT_GST_BROKEN || source.rcvstate == SRT_GST_BROKEN) { w_target.result = -1; w_target.memberstate = SRT_GST_BROKEN; } else { // IDLE or PENDING w_target.result = 0; w_target.memberstate = source.sndstate; } w_target.weight = source.weight; } void CUDTGroup::getGroupCount(size_t& w_size, bool& w_still_alive) { ScopedLock gg(m_GroupLock); // Note: linear time, but no way to avoid it. // Fortunately the size of the redundancy group is even // in the craziest possible implementation at worst 4 members long. size_t group_list_size = 0; // In managed group, if all sockets made a failure, all // were removed, so the loop won't even run once. In // non-managed, simply no socket found here would have a // connected status. bool still_alive = false; for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { if (gi->laststatus == SRTS_CONNECTED) { still_alive = true; } ++group_list_size; } // If no socket is found connected, don't update any status. w_size = group_list_size; w_still_alive = still_alive; } void CUDTGroup::fillGroupData(SRT_MSGCTRL& w_out, // MSGCTRL to be written const SRT_MSGCTRL& in // MSGCTRL read from the data-providing socket ) { // Preserve the data that will be overwritten by assignment SRT_SOCKGROUPDATA* grpdata = w_out.grpdata; size_t grpdata_size = w_out.grpdata_size; w_out = in; // NOTE: This will write NULL to grpdata and 0 to grpdata_size! w_out.grpdata = NULL; // Make sure it's done, for any case w_out.grpdata_size = 0; // User did not wish to read the group data at all. if (!grpdata) { return; } int st = getGroupData((grpdata), (&grpdata_size)); // Always write back the size, no matter if the data were filled. w_out.grpdata_size = grpdata_size; if (st == SRT_ERROR) { // Keep NULL in grpdata return; } // Write back original data w_out.grpdata = grpdata; } struct FLookupSocketWithEvent { CUDTUnited* glob; int evtype; FLookupSocketWithEvent(CUDTUnited* g, int event_type) : glob(g) , evtype(event_type) { } typedef CUDTSocket* result_type; pair<CUDTSocket*, bool> operator()(const pair<SRTSOCKET, int>& es) { CUDTSocket* so = NULL; if ((es.second & evtype) == 0) return make_pair(so, false); so = glob->locateSocket(es.first, glob->ERH_RETURN); return make_pair(so, !!so); } }; void CUDTGroup::updateReadState(SRTSOCKET /* not sure if needed */, int32_t sequence) { bool ready = false; ScopedLock lg(m_GroupLock); int seqdiff = 0; if (m_RcvBaseSeqNo == SRT_SEQNO_NONE) { // One socket reported readiness, while no reading operation // has ever been done. Whatever the sequence number is, it will // be taken as a good deal and reading will be accepted. ready = true; } else if ((seqdiff = CSeqNo::seqcmp(sequence, m_RcvBaseSeqNo)) > 0) { // Case diff == 1: The very next. Surely read-ready. // Case diff > 1: // We have an ahead packet. There's one strict condition in which // we may believe it needs to be delivered - when KANGAROO->HORSE // transition is allowed. Stating that the time calculation is done // exactly the same way on every link in the redundancy group, when // it came to a situation that a packet from one link is ready for // extraction while it has jumped over some packet, it has surely // happened due to TLPKTDROP, and if it happened on at least one link, // we surely don't have this packet ready on any other link. // This might prove not exactly true, especially when at the moment // when this happens another link may surprisinly receive this lacking // packet, so the situation gets suddenly repaired after this function // is called, the only result of it would be that it will really get // the very next sequence, even though this function doesn't know it // yet, but surely in both cases the situation is the same: the medium // is ready for reading, no matter what packet will turn out to be // returned when reading is done. ready = true; } // When the sequence number is behind the current one, // stating that the readines wasn't checked otherwise, the reading // function will not retrieve anything ready to read just by this premise. // Even though this packet would have to be eventually extracted (and discarded). if (ready) { m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, true); } } void CUDTGroup::updateWriteState() { ScopedLock lg(m_GroupLock); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, true); } // The "app reader" version of the reading function. // This reads the packets from every socket treating them as independent // and prepared to work with the application. Then packets are sorted out // by getting the sequence number. int CUDTGroup::recv(char* buf, int len, SRT_MSGCTRL& w_mc) { typedef map<SRTSOCKET, ReadPos>::iterator pit_t; // Later iteration over it might be less efficient than // by vector, but we'll also often try to check a single id // if it was ever seen broken, so that it's skipped. set<CUDTSocket*> broken; size_t output_size = 0; for (;;) { if (!m_bOpened || !m_bConnected) { LOGC(grlog.Error, log << boolalpha << "group/recv: ERROR opened=" << m_bOpened << " connected=" << m_bConnected); throw CUDTException(MJ_CONNECTION, MN_NOCONN, 0); } // Check first the ahead packets if you have any to deliver. if (m_RcvBaseSeqNo != SRT_SEQNO_NONE && !m_Positions.empty()) { // This function also updates the group sequence pointer. ReadPos* pos = checkPacketAhead(); if (pos) { if (size_t(len) < pos->packet.size()) throw CUDTException(MJ_NOTSUP, MN_XSIZE, 0); HLOGC(grlog.Debug, log << "group/recv: delivering AHEAD packet %" << pos->mctrl.pktseq << " #" << pos->mctrl.msgno << ": " << BufferStamp(&pos->packet[0], pos->packet.size())); memcpy(buf, &pos->packet[0], pos->packet.size()); fillGroupData((w_mc), pos->mctrl); len = pos->packet.size(); pos->packet.clear(); // Update stats as per delivery m_stats.recv.Update(len); updateAvgPayloadSize(len); // We predict to have only one packet ahead, others are pending to be reported by tsbpd. // This will be "re-enabled" if the later check puts any new packet into ahead. m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, false); return len; } } // LINK QUALIFICATION NAMES: // // HORSE: Correct link, which delivers the very next sequence. // Not necessarily this link is currently active. // // KANGAROO: Got some packets dropped and the sequence number // of the packet jumps over the very next sequence and delivers // an ahead packet. // // ELEPHANT: Is not ready to read, while others are, or reading // up to the current latest delivery sequence number does not // reach this sequence and the link becomes non-readable earlier. // The above condition has ruled out one kangaroo and turned it // into a horse. // Below there's a loop that will try to extract packets. Kangaroos // will be among the polled ones because skipping them risks that // the elephants will take over the reading. Links already known as // elephants will be also polled in an attempt to revitalize the // connection that experienced just a short living choking. // // After polling we attempt to read from every link that reported // read-readiness and read at most up to the sequence equal to the // current delivery sequence. // Links that deliver a packet below that sequence will be retried // until they deliver no more packets or deliver the packet of // expected sequence. Links that don't have a record in m_Positions // and report readiness will be always read, at least to know what // sequence they currently stand on. // // Links that are already known as kangaroos will be polled, but // no reading attempt will be done. If after the reading series // it will turn out that we have no more horses, the slowest kangaroo // will be "upgraded to a horse" (the ahead link with a sequence // closest to the current delivery sequence will get its sequence // set as current delivered and its recorded ahead packet returned // as the read packet). // If we find at least one horse, the packet read from that link // will be delivered. All other link will be just ensured update // up to this sequence number, or at worst all available packets // will be read. In this case all kangaroos remain kangaroos, // until the current delivery sequence m_RcvBaseSeqNo will be lifted // to the sequence recorded for these links in m_Positions, // during the next time ahead check, after which they will become // horses. #if ENABLE_HEAVY_LOGGING std::ostringstream ds; ds << "E(" << m_RcvEID << ") "; #define HCLOG(expr) expr #else #define HCLOG(x) \ if (false) \ { \ } #endif bool still_alive = false; size_t size = 0; // You can't lock the whole group for that // action because this will result in a deadlock. // Prepare first the list of sockets to be added as connect-pending // and as read-ready, then unlock the group, and then add them to epoll. vector<SRTSOCKET> read_ready, connect_pending; { HLOGC(grlog.Debug, log << "group/recv: Reviewing member sockets to epoll-add (locking)"); ScopedLock glock(m_GroupLock); for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { ++size; // list::size loops over all elements anyway, so this hits two birds with one stone if (gi->laststatus == SRTS_CONNECTING) { HCLOG(ds << "@" << gi->id << "<pending> "); /* connect_pending.push_back(gi->id); */ continue; // don't read over a failed or pending socket } if (gi->laststatus >= SRTS_BROKEN) { broken.insert(gi->ps); } if (broken.count(gi->ps)) { HCLOG(ds << "@" << gi->id << "<broken> "); continue; } if (gi->laststatus != SRTS_CONNECTED) { HCLOG(ds << "@" << gi->id << "<unstable:" << SockStatusStr(gi->laststatus) << "> "); // Sockets in this state are ignored. We are waiting until it // achieves CONNECTING state, then it's added to write. // Or gets broken and closed in the next step. continue; } still_alive = true; // Don't skip packets that are ahead because if we have a situation // that all links are either "elephants" (do not report read readiness) // and "kangaroos" (have already delivered an ahead packet) then // omiting kangaroos will result in only elephants to be polled for // reading. Due to the strict timing requirements and ensurance that // TSBPD on every link will result in exactly the same delivery time // for a packet of given sequence, having an elephant and kangaroo in // one cage means that the elephant is simply a broken or half-broken // link (the data are not delivered, but it will get repaired soon, // enough for SRT to maintain the connection, but it will still drop // packets that didn't arrive in time), in both cases it may // potentially block the reading for an indefinite time, while // simultaneously a kangaroo might be a link that got some packets // dropped, but then it's still capable to deliver packets on time. // Note that gi->id might be a socket that was previously being polled // on write, when it's attempting to connect, but now it's connected. // This will update the socket with the new event set. read_ready.push_back(gi->id); HCLOG(ds << "@" << gi->id << "[READ] "); } } int read_modes = SRT_EPOLL_IN | SRT_EPOLL_ERR; /* Done at the connecting stage so that it won't be missed. int connect_modes = SRT_EPOLL_OUT | SRT_EPOLL_ERR; for (vector<SRTSOCKET>::iterator i = connect_pending.begin(); i != connect_pending.end(); ++i) { srt_epoll_add_usock(m_RcvEID, *i, &connect_modes); } AND this below additionally for sockets that were so far pending connection, will be now "upgraded" to readable sockets. The epoll adding function for a socket that already is in the eid container will only change the poll flags, but will not re-add it, that is, event reports that are both in old and new flags will survive the operation. */ for (vector<SRTSOCKET>::iterator i = read_ready.begin(); i != read_ready.end(); ++i) { srt_epoll_add_usock(m_RcvEID, *i, &read_modes); } HLOGC(grlog.Debug, log << "group/recv: " << ds.str() << " --> EPOLL/SWAIT"); #undef HCLOG if (!still_alive) { LOGC(grlog.Error, log << "group/recv: all links broken"); throw CUDTException(MJ_CONNECTION, MN_NOCONN, 0); } // Here we need to make an additional check. // There might be a possibility that all sockets that // were added to the reader group, are ahead. At least // surely we don't have a situation that any link contains // an ahead-read subsequent packet, because GroupCheckPacketAhead // already handled that case. // // What we can have is that every link has: // - no known seq position yet (is not registered in the position map yet) // - the position equal to the latest delivered sequence // - the ahead position // Now the situation is that we don't have any packets // waiting for delivery so we need to wait for any to report one. // XXX We support blocking mode only at the moment. // The non-blocking mode would need to simply check the readiness // with only immediate report, and read-readiness would have to // be done in background. // Poll on this descriptor until reading is available, indefinitely. CEPoll::fmap_t sready; // In blocking mode, use m_iRcvTimeOut, which's default value -1 // means to block indefinitely, also in swait(). // In non-blocking mode use 0, which means to always return immediately. int timeout = m_bSynRecving ? m_iRcvTimeOut : 0; THREAD_PAUSED(); int nready = m_pGlobal->m_EPoll.swait(*m_RcvEpolld, sready, timeout, false /*report by retval*/); THREAD_RESUMED(); HLOGC(grlog.Debug, log << "group/recv: RDY: " << DisplayEpollResults(sready)); if (nready == 0) { // This can only happen when 0 is passed as timeout and none is ready. // And 0 is passed only in non-blocking mode. So this is none ready in // non-blocking mode. throw CUDTException(MJ_AGAIN, MN_RDAVAIL, 0); } // Handle sockets of pending connection and with errors. // Nice to have something like: // broken = FilterIf(sready, [] (auto s) // { return s.second == SRT_EPOLL_ERR && (auto cs = g->locateSocket(s.first, ERH_RETURN)) // ? {cs, true} // : {nullptr, false} // }); FilterIf( /*FROM*/ sready.begin(), sready.end(), /*TO*/ std::inserter(broken, broken.begin()), /*VIA*/ FLookupSocketWithEvent(m_pGlobal, SRT_EPOLL_ERR)); // Ok, now we need to have some extra qualifications: // 1. If a socket has no registry yet, we read anyway, just // to notify the current position. We read ONLY ONE PACKET this time, // we'll worry later about adjusting it to the current group sequence // position. // 2. If a socket is already position ahead, DO NOT read from it, even // if it is ready. // The state of things whether we were able to extract the very next // sequence will be simply defined by the fact that `output` is nonempty. int32_t next_seq = m_RcvBaseSeqNo; // If this set is empty, it won't roll even once, therefore output // will be surely empty. This will be checked then same way as when // reading from every socket resulted in error. for (CEPoll::fmap_t::const_iterator i = sready.begin(); i != sready.end(); ++i) { if (i->second & SRT_EPOLL_ERR) continue; // broken already if ((i->second & SRT_EPOLL_IN) == 0) continue; // not ready for reading // Check if this socket is in aheads // If so, don't read from it, wait until the ahead is flushed. SRTSOCKET id = i->first; CUDTSocket* ps = m_pGlobal->locateSocket(id); // exception would interrupt it (SANITY) ReadPos* p = NULL; pit_t pe = m_Positions.find(id); if (pe != m_Positions.end()) { p = &pe->second; // Possible results of comparison: // x < 0: the sequence is in the past, the socket should be adjusted FIRST // x = 0: the socket should be ready to get the exactly next packet // x = 1: the case is already handled by GroupCheckPacketAhead. // x > 1: AHEAD. DO NOT READ. int seqdiff = CSeqNo::seqcmp(p->mctrl.pktseq, m_RcvBaseSeqNo); if (seqdiff > 1) { HLOGC(grlog.Debug, log << "group/recv: EPOLL: @" << id << " %" << p->mctrl.pktseq << " AHEAD %" << m_RcvBaseSeqNo << ", not reading."); continue; } } else { // The position is not known, so get the position on which // the socket is currently standing. pair<pit_t, bool> ee = m_Positions.insert(make_pair(id, ReadPos(ps->core().m_iRcvLastSkipAck))); p = &(ee.first->second); HLOGC(grlog.Debug, log << "group/recv: EPOLL: @" << id << " %" << p->mctrl.pktseq << " NEW SOCKET INSERTED"); } // Read from this socket stubbornly, until: // - reading is no longer possible (AGAIN) // - the sequence difference is >= 1 for (;;) { SRT_MSGCTRL mctrl = srt_msgctrl_default; // Read the data into the user's buffer. This is an optimistic // prediction that we'll read the right data. This will be overwritten // by "more correct data" if found more appropriate later. But we have to // copy these data anyway anywhere, even if they need to fall on the floor later. int stat; if (output_size) { // We have already the data, so this must fall on the floor char lostbuf[SRT_LIVE_MAX_PLSIZE]; stat = ps->core().receiveMessage((lostbuf), SRT_LIVE_MAX_PLSIZE, (mctrl), CUDTUnited::ERH_RETURN); HLOGC(grlog.Debug, log << "group/recv: @" << id << " IGNORED data with %" << mctrl.pktseq << " #" << mctrl.msgno << ": " << (stat <= 0 ? "(NOTHING)" : BufferStamp(lostbuf, stat))); if (stat > 0) { m_stats.recvDiscard.Update(stat); } } else { stat = ps->core().receiveMessage((buf), len, (mctrl), CUDTUnited::ERH_RETURN); HLOGC(grlog.Debug, log << "group/recv: @" << id << " EXTRACTED data with %" << mctrl.pktseq << " #" << mctrl.msgno << ": " << (stat <= 0 ? "(NOTHING)" : BufferStamp(buf, stat))); } if (stat == 0) { HLOGC(grlog.Debug, log << "group/recv: SPURIOUS epoll, ignoring"); // This is returned in case of "again". In case of errors, we have SRT_ERROR. // Do not treat this as spurious, just stop reading. break; } if (stat == SRT_ERROR) { HLOGC(grlog.Debug, log << "group/recv: @" << id << ": " << srt_getlasterror_str()); broken.insert(ps); break; } // NOTE: checks against m_RcvBaseSeqNo and decisions based on it // must NOT be done if m_RcvBaseSeqNo is SRT_SEQNO_NONE, which // means that we are about to deliver the very first packet and we // take its sequence number as a good deal. // The order must be: // - check discrepancy // - record the sequence // - check ordering. // The second one must be done always, but failed discrepancy // check should exclude the socket from any further checks. // That's why the common check for m_RcvBaseSeqNo != SRT_SEQNO_NONE can't // embrace everything below. // We need to first qualify the sequence, just for a case if (m_RcvBaseSeqNo != SRT_SEQNO_NONE && abs(m_RcvBaseSeqNo - mctrl.pktseq) > CSeqNo::m_iSeqNoTH) { // This error should be returned if the link turns out // to be the only one, or set to the group data. // err = SRT_ESECFAIL; LOGC(grlog.Error, log << "group/recv: @" << id << ": SEQUENCE DISCREPANCY: base=%" << m_RcvBaseSeqNo << " vs pkt=%" << mctrl.pktseq << ", setting ESECFAIL"); broken.insert(ps); break; } // Rewrite it to the state for a case when next reading // would not succeed. Do not insert the buffer here because // this is only required when the sequence is ahead; for that // it will be fixed later. p->mctrl.pktseq = mctrl.pktseq; if (m_RcvBaseSeqNo != SRT_SEQNO_NONE) { // Now we can safely check it. int seqdiff = CSeqNo::seqcmp(mctrl.pktseq, m_RcvBaseSeqNo); if (seqdiff <= 0) { HLOGC(grlog.Debug, log << "group/recv: @" << id << " %" << mctrl.pktseq << " #" << mctrl.msgno << " BEHIND base=%" << m_RcvBaseSeqNo << " - discarding"); // The sequence is recorded, the packet has to be discarded. // That's all. continue; } // Now we have only two possibilities: // seqdiff == 1: The very next sequence, we want to read and return the packet. // seqdiff > 1: The packet is ahead - record the ahead packet, but continue with the others. if (seqdiff > 1) { HLOGC(grlog.Debug, log << "@" << id << " %" << mctrl.pktseq << " #" << mctrl.msgno << " AHEAD base=%" << m_RcvBaseSeqNo); p->packet.assign(buf, buf + stat); p->mctrl = mctrl; break; // Don't read from that socket anymore. } } // We have seqdiff = 1, or we simply have the very first packet // which's sequence is taken as a good deal. Update the sequence // and record output. if (output_size) { HLOGC(grlog.Debug, log << "group/recv: @" << id << " %" << mctrl.pktseq << " #" << mctrl.msgno << " REDUNDANT"); break; } HLOGC(grlog.Debug, log << "group/recv: @" << id << " %" << mctrl.pktseq << " #" << mctrl.msgno << " DELIVERING"); output_size = stat; fillGroupData((w_mc), mctrl); // Update stats as per delivery m_stats.recv.Update(output_size); updateAvgPayloadSize(output_size); // Record, but do not update yet, until all sockets are handled. next_seq = mctrl.pktseq; break; } } #if ENABLE_HEAVY_LOGGING if (!broken.empty()) { std::ostringstream brks; for (set<CUDTSocket*>::iterator b = broken.begin(); b != broken.end(); ++b) brks << "@" << (*b)->m_SocketID << " "; LOGC(grlog.Debug, log << "group/recv: REMOVING BROKEN: " << brks.str()); } #endif // Now remove all broken sockets from aheads, if any. // Even if they have already delivered a packet. for (set<CUDTSocket*>::iterator di = broken.begin(); di != broken.end(); ++di) { CUDTSocket* ps = *di; m_Positions.erase(ps->m_SocketID); m_pGlobal->close(ps); } if (broken.size() >= size) // This > is for sanity check { // All broken HLOGC(grlog.Debug, log << "group/recv: All sockets broken"); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); } // May be required to be re-read. broken.clear(); if (output_size) { // We have extracted something, meaning that we have the sequence shift. // Update it now and don't do anything else with the sockets. // Sanity check if (next_seq == SRT_SEQNO_NONE) { LOGP(grlog.Error, "IPE: next_seq not set after output extracted!"); // This should never happen, but the only way to keep the code // safe an recoverable is to use the incremented sequence. By // leaving the sequence as is there's a risk of hangup. // Not doing it in case of SRT_SEQNO_NONE as it would make a valid %0. if (m_RcvBaseSeqNo != SRT_SEQNO_NONE) m_RcvBaseSeqNo = CSeqNo::incseq(m_RcvBaseSeqNo); } else { m_RcvBaseSeqNo = next_seq; } ReadPos* pos = checkPacketAhead(); if (!pos) { // Don't clear the read-readinsess state if you have a packet ahead because // if you have, the next read call will return it. m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, false); } HLOGC(grlog.Debug, log << "group/recv: successfully extracted packet size=" << output_size << " - returning"); return output_size; } HLOGC(grlog.Debug, log << "group/recv: NOT extracted anything - checking for a need to kick kangaroos"); // Check if we have any sockets left :D // Here we surely don't have any more HORSES, // only ELEPHANTS and KANGAROOS. Qualify them and // attempt to at least take advantage of KANGAROOS. // In this position all links are either: // - updated to the current position // - updated to the newest possible possition available // - not yet ready for extraction (not present in the group) // If we haven't extracted the very next sequence position, // it means that we might only have the ahead packets read, // that is, the next sequence has been dropped by all links. if (!m_Positions.empty()) { // This might notify both lingering links, which didn't // deliver the required sequence yet, and links that have // the sequence ahead. Review them, and if you find at // least one packet behind, just wait for it to be ready. // Use again the waiting function because we don't want // the general waiting procedure to skip others. set<SRTSOCKET> elephants; // const because it's `typename decltype(m_Positions)::value_type` pair<const SRTSOCKET, ReadPos>* slowest_kangaroo = 0; for (pit_t rp = m_Positions.begin(); rp != m_Positions.end(); ++rp) { // NOTE that m_RcvBaseSeqNo in this place wasn't updated // because we haven't successfully extracted anything. int seqdiff = CSeqNo::seqcmp(rp->second.mctrl.pktseq, m_RcvBaseSeqNo); if (seqdiff < 0) { elephants.insert(rp->first); } // If seqdiff == 0, we have a socket ON TRACK. else if (seqdiff > 0) { // If there's already a slowest_kangaroo, seqdiff decides if this one is slower. // Otherwise it is always slower by having no competition. seqdiff = slowest_kangaroo ? CSeqNo::seqcmp(slowest_kangaroo->second.mctrl.pktseq, rp->second.mctrl.pktseq) : 1; if (seqdiff > 0) { slowest_kangaroo = &*rp; } } } // Note that if no "slowest_kangaroo" was found, it means // that we don't have kangaroos. if (slowest_kangaroo) { // We have a slowest kangaroo. Elephants must be ignored. // Best case, they will get revived, worst case they will be // soon broken. // // As we already have the packet delivered by the slowest // kangaroo, we can simply return it. // Check how many were skipped and add them to the stats const int32_t jump = (CSeqNo(slowest_kangaroo->second.mctrl.pktseq) - CSeqNo(m_RcvBaseSeqNo)) - 1; if (jump > 0) { m_stats.recvDrop.UpdateTimes(jump, avgRcvPacketSize()); } m_RcvBaseSeqNo = slowest_kangaroo->second.mctrl.pktseq; vector<char>& pkt = slowest_kangaroo->second.packet; if (size_t(len) < pkt.size()) throw CUDTException(MJ_NOTSUP, MN_XSIZE, 0); HLOGC(grlog.Debug, log << "@" << slowest_kangaroo->first << " KANGAROO->HORSE %" << slowest_kangaroo->second.mctrl.pktseq << " #" << slowest_kangaroo->second.mctrl.msgno << ": " << BufferStamp(&pkt[0], pkt.size())); memcpy(buf, &pkt[0], pkt.size()); fillGroupData((w_mc), slowest_kangaroo->second.mctrl); len = pkt.size(); pkt.clear(); // Update stats as per delivery m_stats.recv.Update(len); updateAvgPayloadSize(len); // It is unlikely to have a packet ahead because usually having one packet jumped-ahead // clears the possibility of having aheads at all. // XXX Research if this is possible at all; if it isn't, then don't waste time on // looking for it. ReadPos* pos = checkPacketAhead(); if (!pos) { // Don't clear the read-readinsess state if you have a packet ahead because // if you have, the next read call will return it. m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, false); } return len; } HLOGC(grlog.Debug, log << "group/recv: " << (elephants.empty() ? "NO LINKS REPORTED ANY FRESHER PACKET." : "ALL LINKS ELEPHANTS.") << " Re-polling."); } else { HLOGC(grlog.Debug, log << "group/recv: POSITIONS EMPTY - Re-polling."); } } } CUDTGroup::ReadPos* CUDTGroup::checkPacketAhead() { typedef map<SRTSOCKET, ReadPos>::iterator pit_t; ReadPos* out = 0; // This map no longer maps only ahead links. // Here are all links, and whether ahead, it's defined by the sequence. for (pit_t i = m_Positions.begin(); i != m_Positions.end(); ++i) { // i->first: socket ID // i->second: ReadPos { sequence, packet } // We are not interested with the socket ID because we // aren't going to read from it - we have the packet already. ReadPos& a = i->second; const int seqdiff = CSeqNo::seqcmp(a.mctrl.pktseq, m_RcvBaseSeqNo); if (seqdiff == 1) { // The very next packet. Return it. // XXX SETTING THIS ONE IS PROBABLY A BUG. m_RcvBaseSeqNo = a.mctrl.pktseq; HLOGC(grlog.Debug, log << "group/recv: Base %" << m_RcvBaseSeqNo << " ahead delivery POSSIBLE %" << a.mctrl.pktseq << "#" << a.mctrl.msgno << " from @" << i->first << ")"); out = &a; } else if (seqdiff < 1 && !a.packet.empty()) { HLOGC(grlog.Debug, log << "group/recv: @" << i->first << " dropping collected ahead %" << a.mctrl.pktseq << "#" << a.mctrl.msgno << " with base %" << m_RcvBaseSeqNo); a.packet.clear(); } // In case when it's >1, keep it in ahead } return out; } const char* CUDTGroup::StateStr(CUDTGroup::GroupState st) { static const char* const states[] = {"PENDING", "IDLE", "RUNNING", "BROKEN"}; static const size_t size = Size(states); static const char* const unknown = "UNKNOWN"; if (size_t(st) < size) return states[st]; return unknown; } void CUDTGroup::synchronizeDrift(CUDT* cu, steady_clock::duration udrift, steady_clock::time_point newtimebase) { ScopedLock glock(m_GroupLock); bool wrap_period = false; bool anycheck = false; for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { // Skip non-connected; these will be synchronized when ready if (gi->laststatus != SRTS_CONNECTED) continue; // Skip the entity that has reported this if (cu == gi->ps->m_pUDT) continue; steady_clock::time_point this_timebase; steady_clock::duration this_udrift(0); bool wrp = gi->ps->m_pUDT->m_pRcvBuffer->getInternalTimeBase((this_timebase), (this_udrift)); udrift = std::min(udrift, this_udrift); steady_clock::time_point new_newtimebase = std::min(newtimebase, this_timebase); if (new_newtimebase != newtimebase) { wrap_period = wrp; } newtimebase = new_newtimebase; anycheck = true; } if (!anycheck) { HLOGC(grlog.Debug, log << "GROUP: synch uDRIFT NOT DONE, no other links"); return; } HLOGC(grlog.Debug, log << "GROUP: synch uDRIFT=" << FormatDuration(udrift) << " TB=" << FormatTime(newtimebase) << "(" << (wrap_period ? "" : "NO ") << "wrap period)"); // Now that we have the minimum timebase and drift calculated, apply this to every link, // INCLUDING THE REPORTER. for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { // Skip non-connected; these will be synchronized when ready if (gi->laststatus != SRTS_CONNECTED) continue; gi->ps->m_pUDT->m_pRcvBuffer->applyGroupDrift(newtimebase, wrap_period, udrift); } } void CUDTGroup::bstatsSocket(CBytePerfMon* perf, bool clear) { if (!m_bConnected) throw CUDTException(MJ_CONNECTION, MN_NOCONN, 0); if (m_bClosing) throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); const steady_clock::time_point currtime = steady_clock::now(); memset(perf, 0, sizeof *perf); ScopedLock gg(m_GroupLock); perf->msTimeStamp = count_milliseconds(currtime - m_tsStartTime); perf->pktSentUnique = m_stats.sent.local.pkts; perf->pktRecvUnique = m_stats.recv.local.pkts; perf->pktRcvDrop = m_stats.recvDrop.local.pkts; perf->byteSentUnique = m_stats.sent.local.fullBytes(); perf->byteRecvUnique = m_stats.recv.local.fullBytes(); perf->byteRcvDrop = m_stats.recvDrop.local.fullBytes(); perf->pktSentUniqueTotal = m_stats.sent.total.pkts; perf->pktRecvUniqueTotal = m_stats.recv.total.pkts; perf->pktRcvDropTotal = m_stats.recvDrop.total.pkts; perf->byteSentUniqueTotal = m_stats.sent.total.fullBytes(); perf->byteRecvUniqueTotal = m_stats.recv.total.fullBytes(); perf->byteRcvDropTotal = m_stats.recvDrop.total.fullBytes(); const double interval = static_cast<double>(count_microseconds(currtime - m_stats.tsLastSampleTime)); perf->mbpsSendRate = double(perf->byteSent) * 8.0 / interval; perf->mbpsRecvRate = double(perf->byteRecv) * 8.0 / interval; if (clear) { m_stats.reset(); } } // For sorting group members by priority struct FPriorityOrder { // returned true = "elements are in the right order" static bool check(uint16_t preceding, uint16_t succeeding) { return preceding > succeeding; } typedef CUDTGroup::gli_t gli_t; bool operator()(gli_t preceding, gli_t succeeding) { return check(preceding->weight, succeeding->weight); } }; bool CUDTGroup::send_CheckIdle(const gli_t d, vector<gli_t>& w_wipeme, vector<gli_t>& w_pending) { SRT_SOCKSTATUS st = SRTS_NONEXIST; if (d->ps) st = d->ps->getStatus(); // If the socket is already broken, move it to broken. if (int(st) >= int(SRTS_BROKEN)) { HLOGC(gslog.Debug, log << "CUDTGroup::send.$" << id() << ": @" << d->id << " became " << SockStatusStr(st) << ", WILL BE CLOSED."); w_wipeme.push_back(d); return false; } if (st != SRTS_CONNECTED) { HLOGC(gslog.Debug, log << "CUDTGroup::send. @" << d->id << " is still " << SockStatusStr(st) << ", skipping."); w_pending.push_back(d); return false; } return true; } void CUDTGroup::sendBackup_CheckIdleTime(gli_t w_d) { // Check if it was fresh set as idle, we had to wait until its sender // buffer gets empty so that we can make sure that KEEPALIVE will be the // really last sent for longer time. CUDT& u = w_d->ps->core(); if (!is_zero(u.m_tsTmpActiveTime)) { CSndBuffer* b = u.m_pSndBuffer; if (b && b->getCurrBufSize() == 0) { HLOGC(gslog.Debug, log << "grp/sendBackup: FRESH IDLE LINK reached empty buffer - setting permanent and KEEPALIVE"); u.m_tsTmpActiveTime = steady_clock::time_point(); // Send first immediate keepalive. The link is to be turn to IDLE // now so nothing will be sent to it over time and it will start // getting KEEPALIVES since now. Send the first one now to increase // probability that the link will be recognized as IDLE on the // reception side ASAP. int32_t arg = 1; w_d->ps->m_pUDT->sendCtrl(UMSG_KEEPALIVE, &arg); } } } bool CUDTGroup::sendBackup_CheckRunningStability(const gli_t d, const time_point currtime) { CUDT& u = d->ps->core(); // This link might be unstable, check its responsiveness status // NOTE: currtime - last_rsp_time: we believe this value will be always positive as // the Tk clock is believed to be monotonic. The resulting value // IMPORTANT: the socket could be potentially updated IN THE MEANTIME in another // thread AFTER (!!!) currtime has been read, but BEFORE (!!!) this value us used // for calculation - which could make the difference negative. // There's no way to avoid it because it would require making a mutex-locking for // updating the m_tsLastRspTime field. This is useless because avoiding the // negative value is relatively easy, while introducing a mutex would only add a // deadlock risk and performance degradation. bool is_unstable = false; HLOGC(gslog.Debug, log << "grp/sendBackup: CHECK STABLE: @" << d->id << ": TIMEDIFF {response= " << FormatDuration<DUNIT_MS>(currtime - u.m_tsLastRspTime) << " ACK=" << FormatDuration<DUNIT_MS>(currtime - u.m_tsLastRspAckTime) << " activation=" << (!is_zero(u.m_tsTmpActiveTime) ? FormatDuration<DUNIT_MS>(currtime - u.m_tsTmpActiveTime) : "PAST") << " unstable=" << (!is_zero(u.m_tsUnstableSince) ? FormatDuration<DUNIT_MS>(currtime - u.m_tsUnstableSince) : "NEVER") << "}"); if (currtime > u.m_tsLastRspTime) { // The last response predates the start of this function, look at the difference steady_clock::duration td_responsive = currtime - u.m_tsLastRspTime; IF_HEAVY_LOGGING(string source = "heard"); bool check_stability = true; if (!is_zero(u.m_tsTmpActiveTime) && u.m_tsTmpActiveTime < currtime) { // The link is temporary-activated. Calculate then since the activation time. // Check the last received ACK time first. This time is initialized with 'now' // at the CUDT::open call, so you can't count on the trap zero time here, but // it's still possible to check if activation time predates the ACK time. Things // are here in the following possible order: // // - ACK time (old because defined at open) // - Response time (old because the time of received handshake or keepalive counts) // ... long time nothing ... // - Activation time. // // If we have this situation, we have to wait for at least one ACK that is // newer than activation time. However, if in this situation we have a fresh // response, that is: // // - ACK time // ... // - Activation time // - Response time (because a Keepalive had a caprice to come accidentally after sending) // // We still wait for a situation that there's at least one ACK that is newer than activation. // As we DO have activation time, we need to check if there's at least // one ACK newer than activation, that is, td_acked < td_active if (u.m_tsLastRspAckTime < u.m_tsTmpActiveTime) { check_stability = false; HLOGC(gslog.Debug, log << "grp/sendBackup: link @" << d->id << " activated after ACK, " "not checking for stability"); } else { u.m_tsTmpActiveTime = steady_clock::time_point(); } } if (check_stability && count_microseconds(td_responsive) > m_uOPT_StabilityTimeout) { if (is_zero(u.m_tsUnstableSince)) { HLOGC(gslog.Debug, log << "grp/sendBackup: socket NEW UNSTABLE: @" << d->id << " last " << source << " " << FormatDuration(td_responsive) << " > " << m_uOPT_StabilityTimeout << " (stability timeout)"); // The link seems to have missed two ACKs already. // Qualify this link as unstable // Notify that it has been seen so since now u.m_tsUnstableSince = currtime; } is_unstable = true; } } if (!is_unstable) { // If stability is ok, but unstable-since was set before, reset it. HLOGC(gslog.Debug, log << "grp/sendBackup: link STABLE: @" << d->id << (!is_zero(u.m_tsUnstableSince) ? " - RESTORED" : " - CONTINUED")); u.m_tsUnstableSince = steady_clock::time_point(); is_unstable = false; } #if ENABLE_HEAVY_LOGGING // Could be set above if (is_unstable) { HLOGC(gslog.Debug, log << "grp/sendBackup: link UNSTABLE for " << FormatDuration(currtime - u.m_tsUnstableSince) << " : @" << d->id << " - will send a payload"); } else { HLOGC(gslog.Debug, log << "grp/sendBackup: socket in RUNNING state: @" << d->id << " - will send a payload"); } #endif return !is_unstable; } bool CUDTGroup::sendBackup_CheckSendStatus(gli_t d, const steady_clock::time_point& currtime ATR_UNUSED, const int stat, const int erc, const int32_t lastseq, const int32_t pktseq, CUDT& w_u, int32_t& w_curseq, vector<gli_t>& w_parallel, int& w_final_stat, set<uint16_t>& w_sendable_pri, size_t& w_nsuccessful, bool& w_is_nunstable) { bool none_succeeded = true; if (stat != -1) { if (w_curseq == SRT_SEQNO_NONE) { w_curseq = pktseq; } else if (w_curseq != lastseq) { // We believe that all running links use the same seq. // But we can do some sanity check. LOGC(gslog.Error, log << "grp/sendBackup: @" << w_u.m_SocketID << ": IPE: another running link seq discrepancy: %" << lastseq << " vs. previous %" << w_curseq << " - fixing"); // Override must be done with a sequence number greater by one. // Example: // // Link 1 before sending: curr=1114, next=1115 // After sending it reports pktseq=1115 // // Link 2 before sending: curr=1110, next=1111 (->lastseq before sending) // THIS CHECK done after sending: // -- w_curseq(1115) != lastseq(1111) // // NOW: Link 1 after sending is: // curr=1115, next=1116 // // The value of w_curseq here = 1115, while overrideSndSeqNo // calls setInitialSndSeq(seq), which sets: // - curr = seq - 1 // - next = seq // // So, in order to set curr=1115, next=1116 // this must set to 1115+1. w_u.overrideSndSeqNo(CSeqNo::incseq(w_curseq)); } // If this link is already found as unstable, // do not add it to the "w_parallel", as all links out // of these "w_parallels" will be later tried to be // shrunk to 1. Out of all links currently running we need // only 1 link STABLE, and we allow any nymber of unstable // links. if (is_zero(w_u.m_tsUnstableSince)) { w_parallel.push_back(d); } else { HLOGC(gslog.Debug, log << "grp/sendBackup: Link @" << w_u.m_SocketID << " still UNSTABLE for " << FormatDuration(currtime - w_u.m_tsUnstableSince) << ", not counting as w_parallel"); } // State it as succeeded, though. We don't know if the link // is broken until we get the connection broken confirmation, // and the instability state may wear off next time. none_succeeded = false; w_final_stat = stat; ++w_nsuccessful; w_sendable_pri.insert(d->weight); } else if (erc == SRT_EASYNCSND) { HLOGC(gslog.Debug, log << "grp/sendBackup: Link @" << w_u.m_SocketID << " DEEMED UNSTABLE (not ready to send)"); w_is_nunstable = true; } return none_succeeded; } void CUDTGroup::sendBackup_Buffering(const char* buf, const int len, int32_t& w_curseq, SRT_MSGCTRL& w_mc) { // This is required to rewrite into currentSchedSequence() property // as this value will be used as ISN when a new link is connected. int32_t oldest_buffer_seq = SRT_SEQNO_NONE; if (w_curseq != SRT_SEQNO_NONE) { HLOGC(gslog.Debug, log << "grp/sendBackup: successfully sent over running link, ADDING TO BUFFER."); // Note: the sequence number that was used to send this packet should be // recorded here. oldest_buffer_seq = addMessageToBuffer(buf, len, (w_mc)); } else { // We have to predict, which sequence number would have // to be placed on the packet about to be sent now. To // maintain consistency: // 1. If there are any packets in the sender buffer, // get the sequence of the last packet, increase it. // This must be done even if this contradicts the ISN // of all idle links because otherwise packets will get // discrepancy. if (!m_SenderBuffer.empty()) { BufferedMessage& m = m_SenderBuffer.back(); w_curseq = CSeqNo::incseq(m.mc.pktseq); // Set also this sequence to the current w_mc w_mc.pktseq = w_curseq; // XXX may need tighter revision when message mode is allowed w_mc.msgno = ++MsgNo(m.mc.msgno); oldest_buffer_seq = addMessageToBuffer(buf, len, (w_mc)); } // Note that if buffer is empty and w_curseq is (still) SRT_SEQNO_NONE, // it will have to try to send first in order to extract the data. // Note that if w_curseq is still SRT_SEQNO_NONE at this point, it means // that we have the case of the very first packet sending. // Otherwise there would be something in the buffer already. } if (oldest_buffer_seq != SRT_SEQNO_NONE) m_iLastSchedSeqNo = oldest_buffer_seq; } size_t CUDTGroup::sendBackup_CheckNeedActivate(const vector<gli_t>& idlers, const char* buf, const int len, bool& w_none_succeeded, SRT_MSGCTRL& w_mc, int32_t& w_curseq, int32_t& w_final_stat, CUDTException& w_cx, vector<Sendstate>& w_sendstates, vector<gli_t>& w_parallel, vector<gli_t>& w_wipeme, const string& activate_reason ATR_UNUSED) { int stat = -1; // If we have no stable links, activate one of idle links. HLOGC(gslog.Debug, log << "grp/sendBackup: " << activate_reason << ", trying to activate an idle link (" << idlers.size() << " available)"); size_t nactive = 0; for (vector<gli_t>::const_iterator i = idlers.begin(); i != idlers.end(); ++i) { int erc = 0; gli_t d = *i; // Now send and check the status // The link could have got broken try { if (w_curseq == SRT_SEQNO_NONE) { // This marks the fact that the given here packet // could not be sent over any link. This includes the // situation of sending the very first packet after connection. HLOGC(gslog.Debug, log << "grp/sendBackup: ... trying @" << d->id << " - sending the VERY FIRST message"); InvertedLock ug(m_GroupLock); stat = d->ps->core().sendmsg2(buf, len, (w_mc)); if (stat != -1) { // This will be no longer used, but let it stay here. // It's because if this is successful, no other links // will be tried. w_curseq = w_mc.pktseq; addMessageToBuffer(buf, len, (w_mc)); } } else { HLOGC(gslog.Debug, log << "grp/sendBackup: ... trying @" << d->id << " - resending " << m_SenderBuffer.size() << " collected messages..."); // Note: this will set the currently required packet // because it has been just freshly added to the sender buffer stat = sendBackupRexmit(d->ps->core(), (w_mc)); } ++nactive; } catch (CUDTException& e) { // This will be propagated from internal sendmsg2 call, // but that's ok - we want this sending interrupted even in half. w_cx = e; stat = -1; erc = e.getErrorCode(); } d->sndresult = stat; d->laststatus = d->ps->getStatus(); const Sendstate cstate = {d, stat, erc}; w_sendstates.push_back(cstate); if (stat != -1) { if (d->sndstate != SRT_GST_RUNNING) { steady_clock::time_point currtime = steady_clock::now(); d->ps->core().m_tsTmpActiveTime = currtime; HLOGC(gslog.Debug, log << "@" << d->id << ":... sending SUCCESSFUL #" << w_mc.msgno << " LINK ACTIVATED (pri: " << d->weight << ")."); } else { LOGC(gslog.Warn, log << "@" << d->id << ":... sending SUCCESSFUL #" << w_mc.msgno << " LINK ACTIVATED (pri: " << d->weight << ")."); } // Note: this will override the sequence number // for all next iterations in this loop. d->sndstate = SRT_GST_RUNNING; if (is_zero(d->ps->core().m_tsUnstableSince)) { w_parallel.push_back(d); } else { HLOGC(gslog.Debug, log << "grp/sendBackup: Link @" << d->id << " (idle) UNSTABLE, not counting as parallel"); } w_none_succeeded = false; w_final_stat = stat; // We've activated the link, so that's enough. break; } // Failure - move to broken those that could not be activated bool isblocked SRT_ATR_UNUSED = true; if (erc != SRT_EASYNCSND) { isblocked = false; w_wipeme.push_back(d); } // If we found a blocked link, leave it alone, however // still try to send something over another link HLOGC(gslog.Debug, log << "@" << d->id << " FAILED (" << (isblocked ? "blocked" : "ERROR") << "), trying to activate another link."); } return nactive; } void CUDTGroup::send_CheckPendingSockets(const vector<gli_t>& pending, vector<gli_t>& w_wipeme) { // If we have at least one stable link, then select a link that have the // highest priority and silence the rest. // Note: If we have one stable link, this is the situation we need. // If we have no stable links at all, there's nothing we can do anyway. // The freshly activated previously idle links don't count because we // just started them and we can't determine their stability. At least if // we have one link that is stable and the freshly activated link is actually // stable too, we'll check this next time. // if (!pending.empty()) { HLOGC(gslog.Debug, log << "grp/send*: found pending sockets, polling them."); // These sockets if they are in pending state, they should be added to m_SndEID // at the connecting stage. CEPoll::fmap_t sready; if (m_SndEpolld->watch_empty()) { // Sanity check - weird pending reported. LOGC(gslog.Error, log << "grp/send*: IPE: reported pending sockets, but EID is empty - wiping pending!"); copy(pending.begin(), pending.end(), back_inserter(w_wipeme)); } else { // Some sockets could have been closed in the meantime. if (m_SndEpolld->watch_empty()) throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); { InvertedLock ug(m_GroupLock); m_pGlobal->m_EPoll.swait( *m_SndEpolld, sready, 0, false /*report by retval*/); // Just check if anything happened } HLOGC(gslog.Debug, log << "grp/send*: RDY: " << DisplayEpollResults(sready)); // sockets in EX: should be moved to w_wipeme. for (vector<gli_t>::const_iterator i = pending.begin(); i != pending.end(); ++i) { gli_t d = *i; if (CEPoll::isready(sready, d->id, SRT_EPOLL_ERR)) { HLOGC(gslog.Debug, log << "grp/send*: Socket @" << d->id << " reported FAILURE - moved to wiped."); // Failed socket. Move d to w_wipeme. Remove from eid. w_wipeme.push_back(d); int no_events = 0; m_pGlobal->m_EPoll.update_usock(m_SndEID, d->id, &no_events); } } // After that, all sockets that have been reported // as ready to write should be removed from EID. This // will also remove those sockets that have been added // as redundant links at the connecting stage and became // writable (connected) before this function had a chance // to check them. m_pGlobal->m_EPoll.clear_ready_usocks(*m_SndEpolld, SRT_EPOLL_OUT); } } } void CUDTGroup::send_CloseBrokenSockets(vector<gli_t>& w_wipeme) { // Review the w_wipeme sockets. // The reason why 'w_wipeme' is kept separately to 'broken_sockets' is that // it might theoretically happen that ps becomes NULL while the item still exists. vector<CUDTSocket*> broken_sockets; // delete all sockets that were broken at the entrance for (vector<gli_t>::iterator i = w_wipeme.begin(); i != w_wipeme.end(); ++i) { gli_t d = *i; CUDTSocket* ps = d->ps; if (!ps) { LOGC(gslog.Error, log << "grp/sendBackup: IPE: socket NULL at id=" << d->id << " - removing from group list"); // Closing such socket is useless, it simply won't be found in the map and // the internal facilities won't know what to do with it anyway. // Simply delete the entry. m_Group.erase(d); continue; } broken_sockets.push_back(ps); } if (!broken_sockets.empty()) // Prevent unlock-lock cycle if no broken sockets found { // Lift the group lock for a while, to avoid possible deadlocks. InvertedLock ug(m_GroupLock); for (vector<CUDTSocket*>::iterator x = broken_sockets.begin(); x != broken_sockets.end(); ++x) { CUDTSocket* ps = *x; HLOGC(gslog.Debug, log << "grp/sendBackup: BROKEN SOCKET @" << ps->m_SocketID << " - CLOSING AND REMOVING."); // NOTE: This does inside: ps->removeFromGroup(). // After this call, 'd' is no longer valid and *i is singular. CUDT::s_UDTUnited.close(ps); } } HLOGC(gslog.Debug, log << "grp/sendBackup: - wiped " << w_wipeme.size() << " broken sockets"); // We'll need you again. w_wipeme.clear(); } struct FByOldestActive { typedef CUDTGroup::gli_t gli_t; bool operator()(gli_t a, gli_t b) { CUDT& x = a->ps->core(); CUDT& y = b->ps->core(); return x.m_tsTmpActiveTime < y.m_tsTmpActiveTime; } }; void CUDTGroup::sendBackup_CheckParallelLinks(const vector<gli_t>& unstable, vector<gli_t>& w_parallel, int& w_final_stat, bool& w_none_succeeded, SRT_MSGCTRL& w_mc, CUDTException& w_cx) { // In contradiction to broadcast sending, backup sending must check // the blocking state in total first. We need this information through // epoll because we didn't use all sockets to send the data hence the // blocked socket information would not be complete. // Don't do this check if sending has succeeded over at least one // stable link. This procedure is to wait for at least one write-ready // link. // // If sending succeeded also over at least one unstable link (you only have // unstable links and none other or others just got broken), continue sending // anyway. #if ENABLE_HEAVY_LOGGING // Potential problem to be checked in developer mode for (vector<gli_t>::iterator p = w_parallel.begin(); p != w_parallel.end(); ++p) { if (std::find(unstable.begin(), unstable.end(), *p) != unstable.end()) { LOGC(gslog.Debug, log << "grp/sendBackup: IPE: parallel links enclose unstable link @" << (*p)->ps->m_SocketID); } } #endif // This procedure is for a case when the packet could not be sent // over any link (hence "none succeeded"), but there are some unstable // links and no parallel links. We need to WAIT for any of the links // to become available for sending. if (w_parallel.empty() && !unstable.empty() && w_none_succeeded) { HLOGC(gslog.Debug, log << "grp/sendBackup: no parallel links and " << unstable.size() << " unstable links - checking..."); // Note: GroupLock is set already, skip locks and checks getGroupDataIn((w_mc.grpdata), (&w_mc.grpdata_size)); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); if (m_SndEpolld->watch_empty()) { // wipeme wiped, pending sockets checked, it can only mean that // all sockets are broken. HLOGC(gslog.Debug, log << "grp/sendBackup: epolld empty - all sockets broken?"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); } if (!m_bSynSending) { HLOGC(gslog.Debug, log << "grp/sendBackup: non-blocking mode - exit with no-write-ready"); throw CUDTException(MJ_AGAIN, MN_WRAVAIL, 0); } // Here is the situation that the only links left here are: // - those that failed to send (already closed and wiped out) // - those that got blockade on sending // At least, there was so far no socket through which we could // successfully send anything. // As a last resort in this situation, try to wait for any links // remaining in the group to become ready to write. CEPoll::fmap_t sready; int brdy; // This keeps the number of links that existed at the entry. // Simply notify all dead links, regardless as to whether the number // of group members decreases below. If the number of corpses reaches // this number, consider the group connection broken. size_t nlinks = m_Group.size(); size_t ndead = 0; RetryWaitBlocked: { // Some sockets could have been closed in the meantime. if (m_SndEpolld->watch_empty()) { HLOGC(gslog.Debug, log << "grp/sendBackup: no more sendable sockets - group broken"); throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); } InvertedLock ug(m_GroupLock); HLOGC(gslog.Debug, log << "grp/sendBackup: swait call to get at least one link alive up to " << m_iSndTimeOut << "us"); THREAD_PAUSED(); brdy = m_pGlobal->m_EPoll.swait(*m_SndEpolld, (sready), m_iSndTimeOut); THREAD_RESUMED(); if (brdy == 0) // SND timeout exceeded { throw CUDTException(MJ_AGAIN, MN_WRAVAIL, 0); } HLOGC(gslog.Debug, log << "grp/sendBackup: swait exited with " << brdy << " ready sockets:"); // Check if there's anything in the "error" section. // This must be cleared here before the lock on group is set again. // (This loop will not fire neither once if no failed sockets found). for (CEPoll::fmap_t::const_iterator i = sready.begin(); i != sready.end(); ++i) { if (i->second & SRT_EPOLL_ERR) { SRTSOCKET id = i->first; CUDTSocket* s = m_pGlobal->locateSocket(id); if (s) { HLOGC(gslog.Debug, log << "grp/sendBackup: swait/ex on @" << (id) << " while waiting for any writable socket - CLOSING"); CUDT::s_UDTUnited.close(s); } else { HLOGC(gslog.Debug, log << "grp/sendBackup: swait/ex on @" << (id) << " - WAS DELETED IN THE MEANTIME"); } ++ndead; } } HLOGC(gslog.Debug, log << "grp/sendBackup: swait/?close done, re-acquiring GroupLock"); } if (brdy == -1 || ndead >= nlinks) { LOGC(gslog.Error, log << "grp/sendBackup: swait=>" << brdy << " nlinks=" << nlinks << " ndead=" << ndead << " - looxlike all links broken"); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); // You can safely throw here - nothing to fill in when all sockets down. // (timeout was reported by exception in the swait call). throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); } // Ok, now check if we have at least one write-ready. // Note that the procedure of activation of a new link in case of // no stable links found embraces also rexmit-sending and status // check as well, including blocked status. // Find which one it was. This is so rare case that we can // suffer linear search. int nwaiting = 0; int nactivated ATR_UNUSED = 0; int stat = -1; for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d) { // int erc = 0; // Skip if not writable in this run if (!CEPoll::isready(sready, d->id, SRT_EPOLL_OUT)) { ++nwaiting; HLOGC(gslog.Debug, log << "grp/sendBackup: @" << d->id << " NOT ready:OUT, added as waiting"); continue; } if (d->sndstate == SRT_GST_RUNNING) { HLOGC(gslog.Debug, log << "grp/sendBackup: link @" << d->id << " RUNNING - SKIPPING from activate and resend"); continue; } try { // Note: this will set the currently required packet // because it has been just freshly added to the sender buffer stat = sendBackupRexmit(d->ps->core(), (w_mc)); ++nactivated; } catch (CUDTException& e) { // This will be propagated from internal sendmsg2 call, // but that's ok - we want this sending interrupted even in half. w_cx = e; stat = -1; // erc = e.getErrorCode(); } d->sndresult = stat; d->laststatus = d->ps->getStatus(); if (stat == -1) { // This link is no longer waiting. continue; } w_parallel.push_back(d); w_final_stat = stat; steady_clock::time_point currtime = steady_clock::now(); d->ps->core().m_tsTmpActiveTime = currtime; d->sndstate = SRT_GST_RUNNING; w_none_succeeded = false; HLOGC(gslog.Debug, log << "grp/sendBackup: after waiting, ACTIVATED link @" << d->id); break; } // If we have no links successfully activated, but at least // one link "not ready for writing", continue waiting for at // least one link ready. if (stat == -1 && nwaiting > 0) { HLOGC(gslog.Debug, log << "grp/sendBackup: still have " << nwaiting << " waiting and none succeeded, REPEAT"); goto RetryWaitBlocked; } HLOGC(gslog.Debug, log << "grp/sendBackup: " << nactivated << " links activated with " << unstable.size() << " unstable"); } // The most important principle is to keep the data being sent constantly, // even if it means temporarily full redundancy. However, if you are certain // that you have multiple stable links running at the moment, SILENCE all but // the one with highest priority. if (w_parallel.size() > 1) { sort(w_parallel.begin(), w_parallel.end(), FPriorityOrder()); steady_clock::time_point currtime = steady_clock::now(); vector<gli_t>::iterator b = w_parallel.begin(); // Additional criterion: if you have multiple links with the same weight, // check if you have at least one with m_tsTmpActiveTime == 0. If not, // sort them additionally by this time. vector<gli_t>::iterator b1 = b, e = ++b1; // Both e and b1 stand on b+1 position. // We have a guarantee that b+1 still points to a valid element. while (e != w_parallel.end()) { if ((*e)->weight != (*b)->weight) break; ++e; } if (b1 != e) { // More than 1 link with the same weight. Sorting them according // to a different criterion will not change the previous sorting order // because the elements in this range are equal according to the previous // criterion. // Here find the link with least time. The "trap" zero time matches this // requirement, occasionally. sort(b, e, FByOldestActive()); } // After finding the link to leave active, leave it behind. HLOGC(gslog.Debug, log << "grp/sendBackup: keeping parallel link @" << (*b)->id << " and silencing others:"); ++b; for (; b != w_parallel.end(); ++b) { gli_t& d = *b; if (d->sndstate != SRT_GST_RUNNING) { LOGC(gslog.Error, log << "grp/sendBackup: IPE: parallel link container contains non-running link @" << d->id); continue; } CUDT& ce = d->ps->core(); steady_clock::duration td(0); if (!is_zero(ce.m_tsTmpActiveTime) && count_microseconds(td = currtime - ce.m_tsTmpActiveTime) < ce.m_uOPT_StabilityTimeout) { HLOGC(gslog.Debug, log << "... not silencing @" << d->id << ": too early: " << FormatDuration(td) << " < " << ce.m_uOPT_StabilityTimeout << "(stability timeout)"); continue; } // Clear activation time because the link is no longer active! d->sndstate = SRT_GST_IDLE; HLOGC(gslog.Debug, log << " ... @" << d->id << " ACTIVATED: " << FormatTime(ce.m_tsTmpActiveTime)); ce.m_tsTmpActiveTime = steady_clock::time_point(); } } } int CUDTGroup::sendBackup(const char* buf, int len, SRT_MSGCTRL& w_mc) { // Avoid stupid errors in the beginning. if (len <= 0) { throw CUDTException(MJ_NOTSUP, MN_INVAL, 0); } // Live only - sorry. if (len > SRT_LIVE_MAX_PLSIZE) { LOGC(gslog.Error, log << "grp/send(backup): buffer size=" << len << " exceeds maximum allowed in live mode"); throw CUDTException(MJ_NOTSUP, MN_INVAL, 0); } // [[using assert(this->m_pSndBuffer != nullptr)]]; // NOTE: This is a "vector of list iterators". Every element here // is an iterator to another container. // Note that "list" is THE ONLY container in standard C++ library, // for which NO ITERATORS ARE INVALIDATED after a node at particular // iterator has been removed, except for that iterator itself. vector<gli_t> wipeme; vector<gli_t> idlers; vector<gli_t> pending; vector<gli_t> unstable; // We need them as sets because links at first seen as stable // may become unstable after a while vector<gli_t> sendable; int stat = 0; int final_stat = -1; SRT_ATR_UNUSED CUDTException cx(MJ_SUCCESS, MN_NONE, 0); ScopedLock guard(m_GroupLock); steady_clock::time_point currtime = steady_clock::now(); sendable.reserve(m_Group.size()); // First, check status of every link - no matter if idle or active. for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d) { // Check the socket state prematurely in order not to uselessly // send over a socket that is broken. CUDT* pu = 0; if (d->ps) pu = &d->ps->core(); if (!pu || pu->m_bBroken) { HLOGC(gslog.Debug, log << "grp/sendBackup: socket @" << d->id << " detected +Broken - transit to BROKEN"); d->sndstate = SRT_GST_BROKEN; d->rcvstate = SRT_GST_BROKEN; } // Check socket sndstate before sending if (d->sndstate == SRT_GST_BROKEN) { HLOGC(gslog.Debug, log << "grp/sendBackup: socket in BROKEN state: @" << d->id << ", sockstatus=" << SockStatusStr(d->ps ? d->ps->getStatus() : SRTS_NONEXIST)); wipeme.push_back(d); continue; } if (d->sndstate == SRT_GST_IDLE) { if (!send_CheckIdle(d, (wipeme), (pending))) continue; HLOGC(gslog.Debug, log << "grp/sendBackup: socket in IDLE state: @" << d->id << " - will activate it IF NEEDED"); // This is idle, we'll take care of them next time // Might be that: // - this socket is idle, while some NEXT socket is running // - we need at least one running socket to work BEFORE activating the idle one. // - if ALL SOCKETS ARE IDLE, then we simply activate the first from the list, // and all others will be activated using the ISN from the first one. idlers.push_back(d); sendBackup_CheckIdleTime(d); continue; } if (d->sndstate == SRT_GST_RUNNING) { if (!sendBackup_CheckRunningStability(d, (currtime))) { insert_uniq((unstable), d); } // Unstable links should still be used for sending. sendable.push_back(d); continue; } HLOGC(gslog.Debug, log << "grp/sendBackup: socket @" << d->id << " not ready, state: " << StateStr(d->sndstate) << "(" << int(d->sndstate) << ") - NOT sending, SET AS PENDING"); pending.push_back(d); } // Sort the idle sockets by priority so the highest priority idle links are checked first. sort(idlers.begin(), idlers.end(), FPriorityOrder()); vector<Sendstate> sendstates; // Ok, we've separated the unstable from sendable just to know if: // - we have any STABLE sendable (if not, we must activate a backup link) // - we have multiple stable sendable and we need to stop all but one // Normally there should be only one link with state == SRT_GST_RUNNING, but there might // be multiple links set as running when a "breaking suspection" is set on a link. bool none_succeeded = true; // be pessimistic // This should be added all sockets that are currently stable // and sending was successful. Later, all but the one with highest // priority should remain active. vector<gli_t> parallel; #if ENABLE_HEAVY_LOGGING { vector<SRTSOCKET> show_running, show_idle; for (vector<gli_t>::iterator i = sendable.begin(); i != sendable.end(); ++i) show_running.push_back((*i)->id); for (vector<gli_t>::iterator i = idlers.begin(); i != idlers.end(); ++i) show_idle.push_back((*i)->id); LOGC(gslog.Debug, log << "grp/sendBackup: RUNNING: " << PrintableMod(show_running, "@") << " IDLE: " << PrintableMod(show_idle, "@")); } #endif int32_t curseq = SRT_SEQNO_NONE; size_t nsuccessful = 0; // Collect priorities from sendable links, added only after sending is successful. // This will be used to check if any of the idlers have higher priority // and therefore need to be activated. set<uint16_t> sendable_pri; // We believe that we need to send the payload over every sendable link anyway. for (vector<gli_t>::iterator snd = sendable.begin(); snd != sendable.end(); ++snd) { gli_t d = *snd; int erc = 0; // success // Remaining sndstate is SRT_GST_RUNNING. Send a payload through it. CUDT& u = d->ps->core(); int32_t lastseq = u.schedSeqNo(); try { // This must be wrapped in try-catch because on error it throws an exception. // Possible return values are only 0, in case when len was passed 0, or a positive // >0 value that defines the size of the data that it has sent, that is, in case // of Live mode, equal to 'len'. // Lift the group lock for a while, to avoid possible deadlocks. InvertedLock ug(m_GroupLock); stat = u.sendmsg2(buf, len, (w_mc)); } catch (CUDTException& e) { cx = e; stat = -1; erc = e.getErrorCode(); } bool is_unstable = false; none_succeeded &= sendBackup_CheckSendStatus(d, currtime, stat, erc, lastseq, w_mc.pktseq, (u), (curseq), (parallel), (final_stat), (sendable_pri), (nsuccessful), (is_unstable)); if (is_unstable && is_zero(u.m_tsUnstableSince)) // Add to unstable only if it wasn't unstable already insert_uniq((unstable), d); const Sendstate cstate = {d, stat, erc}; sendstates.push_back(cstate); d->sndresult = stat; d->laststatus = d->ps->getStatus(); } // Ok, we have attempted to send a payload over all active links // We know that at least one is successful if we have non-default curmsgno // value. // Now we need to check the link that is currently defined as // main active because we can have: // - one active link only - we want to check its status // - two active links - one "main active" and one "temporarily // activated" // Here the only thing we need to decide about is: // 1. if we have at least one active and STABLE link // - if there are no stable links, activate one idle link // 2. if we have more than one active and stable link // - select those with highest priority out of them // - select the first in order from those // - silence the rest (turn them idle) // In Backup group, we have the following possibilities // - only one link active and stable (normal) // - multiple links active (and possibly one of them stable) // // We might have had a situation that sending was not possible // due to have been blocked. // // If you have any link blocked, treat it as unstable, which // means that one link out of the waiting idle must be activated. // // HOWEVER: // // Collect blocked links in order to make an additional check: // // If all links out of the unstable-running links are blocked, // perform epoll wait on them. In this situation we know that // there are no idle blocked links because IDLE LINK CAN'T BE BLOCKED, // no matter what. It's because the link may only be blocked if // the sender buffer of this socket is full, and it can't be // full if it wasn't used so far. // // This means that in case when we have no stable links, we // need to try out any link that can accept the rexmit-load. // We'll check link stability at the next sending attempt. // Here we need to activate one IDLE link, if we have // no stable links. // Some portion of logical exclusions: // // - sockets that were broken in the beginning are already wiped out // - broken sockets are checked first, so they can't be simultaneously idle // - idle sockets can't get broken because there's no operation done on them // - running sockets are the only one that could change sndstate here // - running sockets can either remain running or turn to broken // In short: Running and Broken sockets can't become idle, // although Running sockets can become Broken. // There's no certainty here as to whether at least one link was // running and it has successfully performed the operation. // Might have even happened that we had 2 running links that // got broken and 3 other links so far in idle sndstate that just connected // at that very moment (in Backup group: 1 running stable, 1 running // unstable, 3 links keeping connetion being idle). // In this case we have 3 idle links to activate one of, // but there is no message number base. If so, take the number for // the first activated link as a good deal. // // If it has additionally happened that the first link got broken at // that very moment of sending, the second one has a chance to succeed // and therefore take over the leading role in setting the leading message // number. If the second one fails, too, then the only remaining idle link // will simply go with its own original message number. // // Now we can go to the idle links and attempt to send the payload // also over them. sendBackup_Buffering(buf, len, (curseq), (w_mc)); // CHECK: no sendable that exceeds unstable // This embraces the case when there are no sendable at all. // Note that unstable links still count as sendable; they // are simply links that were qualified for sending, but: // - have exceeded response timeout // - have hit EASYNCSND error during sending bool need_activate = sendable.size() <= unstable.size(); string activate_reason; IF_HEAVY_LOGGING(activate_reason = "BY NO REASON???"); if (need_activate) { HLOGC(gslog.Debug, log << "grp/sendBackup: all " << sendable.size() << " links unstable - will activate an idle link"); IF_HEAVY_LOGGING(activate_reason = "no stable links"); } else { // Another reason to activate might be if the link with highest priority // among the idlers has a higher priority than any link currently active // (those are collected in 'sendable_pri'). Check if there are any (if // no sendable, a new link needs to be activated anyway), and if the // priority has a lower number. if (sendable_pri.empty() || (!idlers.empty() && FPriorityOrder::check(idlers[0]->weight, *sendable_pri.begin()))) { need_activate = true; #if ENABLE_HEAVY_LOGGING if (sendable_pri.empty()) { activate_reason = "no successful links found"; LOGC(gslog.Debug, log << "grp/sendBackup: no active links were successful - will activate an idle link"); } else if (idlers.empty()) { // This should be impossible. activate_reason = "WEIRD (no idle links!)"; LOGC(gslog.Debug, log << "grp/sendBackup: BY WEIRD AND IMPOSSIBLE REASON (IPE?) - will activate an idle link"); } else { // Only now we are granted that both sendable_pri and idlers are nonempty LOGC(gslog.Debug, log << "grp/sendBackup: found link pri " << idlers[0]->weight << " PREF OVER " << (*sendable_pri.begin()) << " (highest from sendable) - will activate an idle link"); activate_reason = "found higher pri link"; } #endif } else { HLOGC(gslog.Debug, log << "grp/sendBackup: sendable_pri (" << sendable_pri.size() << "): " << Printable(sendable_pri) << " first idle pri: " << (idlers.size() > 0 ? int(idlers[0]->weight) : -1) << " - will NOT activate an idle link"); } } if (need_activate) { if (idlers.empty()) { HLOGP(gslog.Debug, "grp/sendBackup: no idlers to activate, keeping only unstable links"); } else { size_t n ATR_UNUSED = sendBackup_CheckNeedActivate(idlers, buf, len, (none_succeeded), (w_mc), (curseq), (final_stat), (cx), (sendstates), (parallel), (wipeme), activate_reason); HLOGC(gslog.Debug, log << "grp/sendBackup: activated " << n << " idle links tried"); } } else { HLOGC(gslog.Debug, log << "grp/sendBackup: have sendable links, stable=" << (sendable.size() - unstable.size()) << " unstable=" << unstable.size()); } send_CheckPendingSockets(pending, (wipeme)); send_CloseBrokenSockets((wipeme)); sendBackup_CheckParallelLinks(unstable, (parallel), (final_stat), (none_succeeded), (w_mc), (cx)); if (none_succeeded) { HLOGC(gslog.Debug, log << "grp/sendBackup: all links broken (none succeeded to send a payload)"); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); // Reparse error code, if set. // It might be set, if the last operation was failed. // If any operation succeeded, this will not be executed anyway. throw CUDTException(MJ_CONNECTION, MN_CONNLOST, 0); } // Now fill in the socket table. Check if the size is enough, if not, // then set the pointer to NULL and set the correct size. // Note that list::size() is linear time, however this shouldn't matter, // as with the increased number of links in the redundancy group the // impossibility of using that many of them grows exponentally. size_t grpsize = m_Group.size(); if (w_mc.grpdata_size < grpsize) { w_mc.grpdata = NULL; } size_t i = 0; bool ready_again = false; HLOGC(gslog.Debug, log << "grp/sendBackup: copying group data"); for (gli_t d = m_Group.begin(); d != m_Group.end(); ++d, ++i) { if (w_mc.grpdata) { // Enough space to fill copyGroupData(*d, (w_mc.grpdata[i])); } // We perform this loop anyway because we still need to check if any // socket is writable. Note that the group lock will hold any write ready // updates that are performed just after a single socket update for the // group, so if any socket is actually ready at the moment when this // is performed, and this one will result in none-write-ready, this will // be fixed just after returning from this function. ready_again = ready_again | d->ps->writeReady(); } w_mc.grpdata_size = i; if (!ready_again) { m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, false); } HLOGC(gslog.Debug, log << "grp/sendBackup: successfully sent " << final_stat << " bytes, " << (ready_again ? "READY for next" : "NOT READY to send next")); return final_stat; } int32_t CUDTGroup::addMessageToBuffer(const char* buf, size_t len, SRT_MSGCTRL& w_mc) { if (m_iSndAckedMsgNo == SRT_MSGNO_NONE) { // Very first packet, just set the msgno. m_iSndAckedMsgNo = w_mc.msgno; m_iSndOldestMsgNo = w_mc.msgno; } else if (m_iSndOldestMsgNo != m_iSndAckedMsgNo) { int offset = MsgNo(m_iSndAckedMsgNo) - MsgNo(m_iSndOldestMsgNo); HLOGC(gslog.Debug, log << "addMessageToBuffer: new ACK-ed messages: #(" << m_iSndOldestMsgNo << "-" << m_iSndAckedMsgNo << ") - going to remove"); if (offset > int(m_SenderBuffer.size())) { LOGC(gslog.Error, log << "addMessageToBuffer: IPE: offset=" << offset << " exceeds buffer size=" << m_SenderBuffer.size() << " - CLEARING"); m_SenderBuffer.clear(); } else { HLOGC(gslog.Debug, log << "addMessageToBuffer: erasing " << offset << "/" << m_SenderBuffer.size() << " group-senderbuffer ACKED messages for #" << m_iSndOldestMsgNo << " - #" << m_iSndAckedMsgNo); m_SenderBuffer.erase(m_SenderBuffer.begin(), m_SenderBuffer.begin() + offset); } // Position at offset is not included m_iSndOldestMsgNo = m_iSndAckedMsgNo; } m_SenderBuffer.resize(m_SenderBuffer.size() + 1); BufferedMessage& bm = m_SenderBuffer.back(); bm.mc = w_mc; bm.copy(buf, len); HLOGC(gslog.Debug, log << "addMessageToBuffer: #" << w_mc.msgno << " size=" << len << " !" << BufferStamp(buf, len)); return m_SenderBuffer.front().mc.pktseq; } int CUDTGroup::sendBackupRexmit(CUDT& core, SRT_MSGCTRL& w_mc) { // This should resend all packets if (m_SenderBuffer.empty()) { LOGC(gslog.Fatal, log << "IPE: sendBackupRexmit: sender buffer empty"); // Although act as if it was successful, otherwise you'll get connection break return 0; } // using [[assert !m_SenderBuffer.empty()]]; // Send everything you currently have in the sender buffer. // The receiver will reject packets that it currently has. // Start from the oldest. CPacket packet; set<int> results; int stat = -1; // Make sure that the link has correctly synchronized sequence numbers. // Note that sequence numbers should be recorded in mc. int32_t curseq = m_SenderBuffer[0].mc.pktseq; size_t skip_initial = 0; if (curseq != core.schedSeqNo()) { int distance = CSeqNo::seqoff(core.schedSeqNo(), curseq); if (distance < 0) { // This may happen in case when the link to be activated is already running. // Getting sequences backwards is not allowed, as sending them makes no // sense - they are already ACK-ed or are behind the ISN. Instead, skip all // packets that are in the past towards the scheduling sequence. skip_initial = -distance; LOGC(gslog.Warn, log << "sendBackupRexmit: OVERRIDE attempt to %" << core.schedSeqNo() << " from BACKWARD %" << curseq << " - DENIED; skip " << skip_initial << " packets"); } else { // In case when the next planned sequence on this link is behind // the firstmost sequence in the backup buffer, synchronize the // sequence with it first so that they go hand-in-hand with // sequences already used by the link from which packets were // copied to the backup buffer. IF_HEAVY_LOGGING(int32_t old = core.schedSeqNo()); const bool su ATR_UNUSED = core.overrideSndSeqNo(curseq); HLOGC(gslog.Debug, log << "sendBackupRexmit: OVERRIDING seq %" << old << " with %" << curseq << (su ? " - succeeded" : " - FAILED!")); } } senderBuffer_t::iterator i = m_SenderBuffer.begin(); if (skip_initial >= m_SenderBuffer.size()) return 0; // can't return any other state, nothing was sent else if (skip_initial) i += skip_initial; // Send everything - including the packet freshly added to the buffer for (; i != m_SenderBuffer.end(); ++i) { { // XXX Not sure if the protection is right. // Analyze this and perform appropriate tests here! InvertedLock ug(m_GroupLock); // NOTE: an exception from here will interrupt the loop // and will be caught in the upper level. stat = core.sendmsg2(i->data, i->size, (i->mc)); } if (stat == -1) { // Stop sending if one sending ended up with error LOGC(gslog.Warn, log << "sendBackupRexmit: sending from buffer stopped at %" << core.schedSeqNo() << " and FAILED"); return -1; } } // Copy the contents of the last item being updated. w_mc = m_SenderBuffer.back().mc; HLOGC(gslog.Debug, log << "sendBackupRexmit: pre-sent collected %" << curseq << " - %" << w_mc.pktseq); return stat; } void CUDTGroup::ackMessage(int32_t msgno) { // The message id could not be identified, skip. if (msgno == SRT_MSGNO_CONTROL) { HLOGC(gslog.Debug, log << "ackMessage: msgno not found in ACK-ed sequence"); return; } // It's impossible to get the exact message position as the // message is allowed also to span for multiple packets. // Search since the oldest packet until you hit the first // packet with this message number. // First, you need to decrease the message number by 1. It's // because the sequence number being ACK-ed can be in the middle // of the message, while it doesn't acknowledge that the whole // message has been received. Decrease the message number so that // partial-message-acknowledgement does not swipe the whole message, // part of which may need to be retransmitted over a backup link. int offset = MsgNo(msgno) - MsgNo(m_iSndAckedMsgNo); if (offset <= 0) { HLOGC(gslog.Debug, log << "ackMessage: already acked up to msgno=" << msgno); return; } HLOGC(gslog.Debug, log << "ackMessage: updated to #" << msgno); // Update last acked. Will be picked up when adding next message. m_iSndAckedMsgNo = msgno; } void CUDTGroup::handleKeepalive(gli_t gli) { // received keepalive for that group member // In backup group it means that the link went IDLE. if (m_type == SRT_GTYPE_BACKUP) { if (gli->rcvstate == SRT_GST_RUNNING) { gli->rcvstate = SRT_GST_IDLE; HLOGC(gslog.Debug, log << "GROUP: received KEEPALIVE in @" << gli->id << " - link turning rcv=IDLE"); } // When received KEEPALIVE, the sending state should be also // turned IDLE, if the link isn't temporarily activated. The // temporarily activated link will not be measured stability anyway, // while this should clear out the problem when the transmission is // stopped and restarted after a while. This will simply set the current // link as IDLE on the sender when the peer sends a keepalive because the // data stopped coming in and it can't send ACKs therefore. // // This also shouldn't be done for the temporary activated links because // stability timeout could be exceeded for them by a reason that, for example, // the packets come with the past sequences (as they are being synchronized // the sequence per being IDLE and empty buffer), so a large portion of initial // series of packets may come with past sequence, delaying this way with ACK, // which may result not only with exceeded stability timeout (which fortunately // isn't being measured in this case), but also with receiveing keepalive // (therefore we also don't reset the link to IDLE in the temporary activation period). if (gli->sndstate == SRT_GST_RUNNING && is_zero(gli->ps->core().m_tsTmpActiveTime)) { gli->sndstate = SRT_GST_IDLE; HLOGC(gslog.Debug, log << "GROUP: received KEEPALIVE in @" << gli->id << " active=PAST - link turning snd=IDLE"); } } } void CUDTGroup::internalKeepalive(gli_t gli) { // This is in response to AGENT SENDING keepalive. This means that there's // no transmission in either direction, but the KEEPALIVE packet from the // other party could have been missed. This is to ensure that the IDLE state // is recognized early enough, before any sequence discrepancy can happen. if (m_type == SRT_GTYPE_BACKUP && gli->rcvstate == SRT_GST_RUNNING) { gli->rcvstate = SRT_GST_IDLE; // Prevent sending KEEPALIVE again in group-sending gli->ps->core().m_tsTmpActiveTime = steady_clock::time_point(); HLOGC(gslog.Debug, log << "GROUP: EXP-requested KEEPALIVE in @" << gli->id << " - link turning IDLE"); } } CUDTGroup::BufferedMessageStorage CUDTGroup::BufferedMessage::storage(SRT_LIVE_MAX_PLSIZE /*, 1000*/); int CUDTGroup::configure(const char* str) { string config = str; switch (type()) { /* TMP review stub case SRT_GTYPE_BALANCING: // config contains the algorithm name if (config == "" || config == "auto") { m_cbSelectLink.set(this, &CUDTGroup::linkSelect_window_fw); HLOGC(gmlog.Debug, log << "group(balancing): WINDOW algorithm selected"); } else if (config == "fixed") { m_cbSelectLink.set(this, &CUDTGroup::linkSelect_fixed_fw); HLOGC(gmlog.Debug, log << "group(balancing): FIXED algorithm selected"); } else { LOGC(gmlog.Error, log << "group(balancing): unknown selection algorithm '" << config << "'"); return CUDT::APIError(MJ_NOTSUP, MN_INVAL, 0); } break;*/ default: if (config == "") { // You can always call the config with empty string, // it should set defaults or do nothing, if not supported. return 0; } LOGC(gmlog.Error, log << "this group type doesn't support any configuration"); return CUDT::APIError(MJ_NOTSUP, MN_INVAL, 0); } return 0; } // Forwarder needed due to class definition order int32_t CUDTGroup::generateISN() { return CUDT::generateISN(); } void CUDTGroup::setFreshConnected(CUDTSocket* sock, int& w_token) { ScopedLock glock(m_GroupLock); HLOGC(cnlog.Debug, log << "group: Socket @" << sock->m_SocketID << " fresh connected, setting IDLE"); gli_t gi = sock->m_IncludedIter; gi->sndstate = SRT_GST_IDLE; gi->rcvstate = SRT_GST_IDLE; gi->laststatus = SRTS_CONNECTED; if (!m_bConnected) { // Switch to connected state and give appropriate signal m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_CONNECT, true); m_bConnected = true; } w_token = gi->token; } void CUDTGroup::updateLatestRcv(CUDTGroup::gli_t current) { // Currently only Backup groups use connected idle links. if (m_type != SRT_GTYPE_BACKUP) return; HLOGC(grlog.Debug, log << "updateLatestRcv: BACKUP group, updating from active link @" << current->id << " with %" << current->ps->m_pUDT->m_iRcvLastSkipAck); CUDT* source = current->ps->m_pUDT; vector<CUDT*> targets; UniqueLock lg(m_GroupLock); for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { // Skip the socket that has reported packet reception if (gi == current) { HLOGC(grlog.Debug, log << "grp: NOT updating rcv-seq on self @" << gi->id); continue; } // Don't update the state if the link is: // - PENDING - because it's not in the connected state, wait for it. // - RUNNING - because in this case it should have its own line of sequences // - BROKEN - because it doesn't make sense anymore, about to be removed if (gi->rcvstate != SRT_GST_IDLE) { HLOGC(grlog.Debug, log << "grp: NOT updating rcv-seq on @" << gi->id << " - link state:" << srt_log_grp_state[gi->rcvstate]); continue; } // Sanity check if (!gi->ps->m_pUDT->m_bConnected) { HLOGC(grlog.Debug, log << "grp: IPE: NOT updating rcv-seq on @" << gi->id << " - IDLE BUT NOT CONNECTED"); continue; } targets.push_back(gi->ps->m_pUDT); } lg.unlock(); // Do this on the unlocked group because this // operation will need receiver lock, so it might // risk a deadlock. for (size_t i = 0; i < targets.size(); ++i) { targets[i]->updateIdleLinkFrom(source); } } void CUDTGroup::activateUpdateEvent() { m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_UPDATE, true); } void CUDTGroup::addEPoll(int eid) { enterCS(m_pGlobal->m_EPoll.m_EPollLock); m_sPollID.insert(eid); leaveCS(m_pGlobal->m_EPoll.m_EPollLock); bool any_read = false; bool any_write = false; bool any_broken = false; bool any_pending = false; { // Check all member sockets ScopedLock gl(m_GroupLock); // We only need to know if there is any socket that is // ready to get a payload and ready to receive from. for (gli_t i = m_Group.begin(); i != m_Group.end(); ++i) { if (i->sndstate == SRT_GST_IDLE || i->sndstate == SRT_GST_RUNNING) { any_write |= i->ps->writeReady(); } if (i->rcvstate == SRT_GST_IDLE || i->rcvstate == SRT_GST_RUNNING) { any_read |= i->ps->readReady(); } if (i->ps->broken()) any_broken |= true; else any_pending |= true; } } // This is stupid, but we don't have any other interface to epoll // internals. Actually we don't have to check if id() is in m_sPollID // because we know it is, as we just added it. But it's not performance // critical, sockets are not being often added during transmission. if (any_read) m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_IN, true); if (any_write) m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_OUT, true); // Set broken if none is non-broken (pending, read-ready or write-ready) if (any_broken && !any_pending) m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); } void CUDTGroup::removeEPollEvents(const int eid) { // clear IO events notifications; // since this happens after the epoll ID has been removed, they cannot be set again set<int> remove; remove.insert(eid); m_pGlobal->m_EPoll.update_events(id(), remove, SRT_EPOLL_IN | SRT_EPOLL_OUT, false); } void CUDTGroup::removeEPollID(const int eid) { enterCS(m_pGlobal->m_EPoll.m_EPollLock); m_sPollID.erase(eid); leaveCS(m_pGlobal->m_EPoll.m_EPollLock); } int CUDTGroup::updateFailedLink(SRTSOCKET sock) { ScopedLock lg(m_GroupLock); int token = -1; // Check all members if they are in the pending // or connected state. int nhealthy = 0; for (gli_t i = m_Group.begin(); i != m_Group.end(); ++i) { if (i->id == sock) { // This socket. token = i->token; i->sndstate = SRT_GST_BROKEN; i->rcvstate = SRT_GST_BROKEN; continue; } if (i->sndstate < SRT_GST_BROKEN) nhealthy++; } if (!nhealthy) { // No healthy links, set ERR on epoll. HLOGC(gmlog.Debug, log << "group/updateFailedLink: All sockets broken"); m_pGlobal->m_EPoll.update_events(id(), m_sPollID, SRT_EPOLL_ERR, true); } else { HLOGC(gmlog.Debug, log << "group/updateFailedLink: Still " << nhealthy << " links in the group"); } return token; } #if ENABLE_HEAVY_LOGGING void CUDTGroup::debugGroup() { ScopedLock gg(m_GroupLock); HLOGC(gmlog.Debug, log << "GROUP MEMBER STATUS - $" << id()); for (gli_t gi = m_Group.begin(); gi != m_Group.end(); ++gi) { HLOGC(gmlog.Debug, log << " ... id { agent=@" << gi->id << " peer=@" << gi->ps->m_PeerID << " } address { agent=" << gi->agent.str() << " peer=" << gi->peer.str() << "} " << " state {snd=" << StateStr(gi->sndstate) << " rcv=" << StateStr(gi->rcvstate) << "}"); } } #endif
utf-8
1
MPL-2.0
2017-2018 Haivision Systems Inc.
genometools-1.6.2+ds/src/core/example_b.c
/* Copyright (c) 2010 Sascha Steinbiss <steinbiss@zbh.uni-hamburg.de> Copyright (c) 2010 Center for Bioinformatics, University of Hamburg Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include "example_b.h" #include "example_rep.h" #include "core/str_api.h" struct GtExampleB { GtExample parent_instance; GtStr *my_property; /* this is an allocated object we need to memory-manage */ }; static int gt_example_b_run(GtExample *e) /* hidden from outside */ { GtExampleB *eb = (GtExampleB*) e; /* downcast to specific type */ printf("%s", gt_str_get(eb->my_property)); /* run functionality */ return 0; } static void gt_example_b_delete(GtExample *e) { GtExampleB *eb = (GtExampleB*) e; /* downcast to specific type */ gt_str_delete(eb->my_property); } /* map static local method to interface */ const GtExampleClass* gt_example_b_class(void) { static const GtExampleClass ec = { sizeof (GtExampleB), gt_example_b_run, gt_example_b_delete }; return &ec; } GtExample* gt_example_b_new(void) { GtExample *e = gt_example_create(gt_example_b_class()); GtExampleB *eb = (GtExampleB*) e; /* downcast to specific type */ /* initialize private implementation member */ eb->my_property = gt_str_new_cstr("This is Example B!"); return e; }
utf-8
1
ISC
2001-2014 Stefan Kurtz 2003-2014 Gordon Gremme 2007-2014 Sascha Steinbiss 2004-2012 Stefan Bienert 2010-2011 Joachim Bonnet 2007 David Ellinghaus 2008 Johannes Fischer 2009-2014 Giorgio Gonnella 2007-2008 Thomas Jahns 2007 Malte Mader 2009 Brent Pedersen 2007 Christin Schaerfer 2007 David Schmitz-Huebsch 2003-2005 Michael E Sparks 2009 Zhihao Tang 2010-2014 Dirk Willrodt 2004-2014 Center for Bioinformatics, University of Hamburg 2014 Genome Research Ltd
critterding-1.0-beta12.1/src/gui/container.cpp
#include "text.h" #include "text_uintp.h" #include "button.h" #include "container.h" Container::Container() { isContainer = true; } void Container::draw() { if ( active ) drawChildren(); } void Container::drawChildren() { for( childit = children.begin(); childit != children.end(); childit++ ) childit->second->draw(); } Widget* Container::addWidgetPanel( const string& name, Widget* nwidget ) { children[name] = nwidget; children[name]->parent = this; children[name]->translate(0, 0); return children[name]; } Widget* Container::addWidgetText( const string& name, unsigned int posx, unsigned int posy, const string& textstring ) { Text* t = new Text(); t->parent = this; t->translate(posx, posy); t->set(textstring); t->active = true; children[name] = t; return children[name]; } Widget* Container::addWidgetText( const string& name, const string& textstring ) { Text* t = new Text(); t->parent = this; // t->translate(posx, posy); t->hcenter = true; t->vcenter = true; t->set(textstring); t->active = true; children[name] = t; return children[name]; } Widget* Container::addWidgetText( const string& name, unsigned int posx, unsigned int posy, const unsigned int* uintp ) { Text_uintp* t = new Text_uintp(); t->parent = this; t->translate(posx, posy); t->content = uintp; t->active = true; children[name] = t; return children[name]; } Widget* Container::addWidgetButton( const string& name, const Vector2i& pos, const Vector2i& dimensions, const string& textstring, const Vector2i& textpos, const cmdsettings& cmds, unsigned int responsetime, unsigned int minfresponsetime, unsigned int fresponseinterval ) { Button* t = new Button(); t->parent = this; t->translate(pos.x, pos.y); t->v_width = dimensions.x; t->v_height = dimensions.y; t->addWidgetText( "btext", textpos.x, textpos.y, textstring ); t->genEvent(1, name, cmds, responsetime, minfresponsetime, fresponseinterval); t->active = true; children[name] = t; return children[name]; } Widget* Container::addWidgetButton( const string& name, const Vector2i& pos, const Vector2i& dimensions, const string& textstring, const cmdsettings& cmds, unsigned int responsetime, unsigned int minfresponsetime, unsigned int fresponseinterval ) { Button* t = new Button(); t->parent = this; t->translate(pos.x, pos.y); t->v_width = dimensions.x; t->v_height = dimensions.y; t->addWidgetText( "btext", textstring ); t->genEvent(1, name, cmds, responsetime, minfresponsetime, fresponseinterval); t->active = true; children[name] = t; return children[name]; } bool Container::mouseOverChild(Widget** fWidget, int x, int y) { for( childit = children.begin(); childit != children.end(); childit++ ) { if ( (childit->second->isTouchable && childit->second->active && childit->second->mouseOver(x, y)) || !childit->second->isTouchable ) { // RECURSIVE INTO CONTAINERS if ( childit->second->isContainer ) { Container* c = static_cast<Container*>(childit->second); if ( c->mouseOverChild( fWidget, x, y ) ) { return true; } else if ( childit->second->isTouchable ) { *fWidget = childit->second; return true; } } else if ( childit->second->isTouchable ) { *fWidget = childit->second; return true; } } } return false; } void Container::updateAbsPosition() { absPosition.x = position.x; absPosition.y = position.y; if ( parent ) { absPosition.x += parent->absPosition.x; absPosition.y += parent->absPosition.y; } // adjust children aswell for( childit = children.begin(); childit != children.end(); childit++ ) childit->second->updateAbsPosition(); } Container::~Container() { for( childit = children.begin(); childit != children.end(); childit++ ) delete childit->second; }
utf-8
1
unknown
unknown
tnef-1.4.18/src/mapi_attr.h
/* * mapi_attr.h -- Functions for handling MAPI attributes * * Copyright (C)1999-2018 Mark Simpson <damned@theworld.com> * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, you can either send email to this * program's maintainer or write to: The Free Software Foundation, * Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA. * */ #ifndef MAPI_ATTR_H #define MAPI_ATTR_H #if HAVE_CONFIG_H # include "config.h" #endif /* HAVE_CONFIG_H */ #include "common.h" #include "mapi_types.h" #include "mapi_names.h" #define MULTI_VALUE_FLAG 0x1000 #define GUID_EXISTS_FLAG 0x8000 typedef struct { uint32 data1; uint16 data2; uint16 data3; uint8 data4[8]; } GUID; typedef struct { size_t len; union { unsigned char *buf; uint16 bytes2; uint32 bytes4; uint32 bytes8[2]; GUID guid; } data; } MAPI_Value; typedef struct { size_t len; unsigned char* data; } VarLenData; typedef struct { mapi_type type; mapi_name name; size_t num_values; MAPI_Value* values; GUID *guid; size_t num_names; VarLenData *names; } MAPI_Attr; extern MAPI_Attr** mapi_attr_read (size_t len, unsigned char *buf); extern void mapi_attr_free_list (MAPI_Attr** attrs); #endif /* MAPI_ATTR_H */
utf-8
1
GPL-2+
(c) 1999-2010 Mark Simpson <damned@world.std.com> (c) 1997,1998 Thomas Boll <tb@boll.ch> (original code)
rawtherapee-5.8/rtgui/editorpanel.h
/* * This file is part of RawTherapee. * * Copyright (c) 2004-2010 Gabor Horvath <hgabor@rawtherapee.com> * Copyright (c) 2010 Oliver Duis <www.oliverduis.de> * * RawTherapee is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RawTherapee 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 RawTherapee. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <gtkmm.h> #include "histogrampanel.h" #include "history.h" #include "imageareapanel.h" #include "profilepanel.h" #include "progressconnector.h" #include "saveasdlg.h" #include "thumbnaillistener.h" #include "../rtengine/noncopyable.h" #include "../rtengine/rtengine.h" class BatchQueueEntry; class EditorPanel; class FilePanel; class MyProgressBar; class Navigator; class Thumbnail; class ToolPanelCoordinator; struct EditorPanelIdleHelper { EditorPanel* epanel; bool destroyed; int pending; }; class RTWindow; class EditorPanel final : public Gtk::VBox, public PParamsChangeListener, public rtengine::ProgressListener, public ThumbnailListener, public HistoryBeforeLineListener, public rtengine::HistogramListener, public rtengine::NonCopyable { public: explicit EditorPanel (FilePanel* filePanel = nullptr); ~EditorPanel () override; void open (Thumbnail* tmb, rtengine::InitialImage* isrc); void setAspect (); void on_realize () override; void leftPaneButtonReleased (GdkEventButton *event); void rightPaneButtonReleased (GdkEventButton *event); void setParent (RTWindow* p) { parent = p; } void setParentWindow (Gtk::Window* p) { parentWindow = p; } void writeOptions(); void writeToolExpandedStatus (std::vector<int> &tpOpen); void showTopPanel (bool show); bool isRealized() { return realized; } // ProgressListener interface void setProgress(double p) override; void setProgressStr(const Glib::ustring& str) override; void setProgressState(bool inProcessing) override; void error(const Glib::ustring& descr) override; void error(const Glib::ustring& title, const Glib::ustring& descr); void displayError(const Glib::ustring& title, const Glib::ustring& descr); // this is called by error in the gtk thread void refreshProcessingState (bool inProcessing); // this is called by setProcessingState in the gtk thread // PParamsChangeListener interface void procParamsChanged( const rtengine::procparams::ProcParams* params, const rtengine::ProcEvent& ev, const Glib::ustring& descr, const ParamsEdited* paramsEdited = nullptr ) override; void clearParamChanges() override; // thumbnaillistener interface void procParamsChanged (Thumbnail* thm, int whoChangedIt) override; // HistoryBeforeLineListener void historyBeforeLineChanged (const rtengine::procparams::ProcParams& params) override; // HistogramListener void histogramChanged( const LUTu& histRed, const LUTu& histGreen, const LUTu& histBlue, const LUTu& histLuma, const LUTu& histToneCurve, const LUTu& histLCurve, const LUTu& histCCurve, const LUTu& histLCAM, const LUTu& histCCAM, const LUTu& histRedRaw, const LUTu& histGreenRaw, const LUTu& histBlueRaw, const LUTu& histChroma, const LUTu& histLRETI ) override; // event handlers void info_toggled (); void hideHistoryActivated (); void tbRightPanel_1_toggled (); void tbTopPanel_1_toggled (); void beforeAfterToggled (); void tbBeforeLock_toggled(); void saveAsPressed (); void queueImgPressed (); void sendToGimpPressed (); void openNextEditorImage (); void openPreviousEditorImage (); void syncFileBrowser (); void tbTopPanel_1_visible (bool visible); bool CheckSidePanelsVisibility(); void tbShowHideSidePanels_managestate(); void toggleSidePanels(); void toggleSidePanelsZoomFit(); void saveProfile (); Glib::ustring getShortName (); Glib::ustring getFileName () const; bool handleShortcutKey (GdkEventKey* event); bool getIsProcessing() const { return isProcessing; } void updateProfiles (const Glib::ustring &printerProfile, rtengine::RenderingIntent printerIntent, bool printerBPC); void updateTPVScrollbar (bool hide); void updateHistogramPosition (int oldPosition, int newPosition); void defaultMonitorProfileChanged (const Glib::ustring &profile_name, bool auto_monitor_profile); bool saveImmediately (const Glib::ustring &filename, const SaveFormat &sf); Gtk::Paned* catalogPane; private: void close (); BatchQueueEntry* createBatchQueueEntry (); bool idle_imageSaved (ProgressConnector<int> *pc, rtengine::IImagefloat* img, Glib::ustring fname, SaveFormat sf, rtengine::procparams::ProcParams &pparams); bool idle_saveImage (ProgressConnector<rtengine::IImagefloat*> *pc, Glib::ustring fname, SaveFormat sf, rtengine::procparams::ProcParams &pparams); bool idle_sendToGimp ( ProgressConnector<rtengine::IImagefloat*> *pc, Glib::ustring fname); bool idle_sentToGimp (ProgressConnector<int> *pc, rtengine::IImagefloat* img, Glib::ustring filename); void histogramProfile_toggled (); Glib::ustring lastSaveAsFileName; bool realized; MyProgressBar *progressLabel; Gtk::ToggleButton* info; Gtk::ToggleButton* hidehp; Gtk::ToggleButton* tbShowHideSidePanels; Gtk::ToggleButton* tbTopPanel_1; Gtk::ToggleButton* tbRightPanel_1; Gtk::ToggleButton* tbBeforeLock; //bool bAllSidePanelsVisible; Gtk::ToggleButton* beforeAfter; Gtk::Paned* hpanedl; Gtk::Paned* hpanedr; Gtk::Image *iHistoryShow, *iHistoryHide; Gtk::Image *iTopPanel_1_Show, *iTopPanel_1_Hide; Gtk::Image *iRightPanel_1_Show, *iRightPanel_1_Hide; Gtk::Image *iShowHideSidePanels; Gtk::Image *iShowHideSidePanels_exit; Gtk::Image *iBeforeLockON, *iBeforeLockOFF; Gtk::Paned *leftbox; Gtk::Box *leftsubbox; Gtk::Paned *vboxright; Gtk::Box *vsubboxright; Gtk::Button* queueimg; Gtk::Button* saveimgas; Gtk::Button* sendtogimp; Gtk::Button* navSync; Gtk::Button* navNext; Gtk::Button* navPrev; class ColorManagementToolbar; std::unique_ptr<ColorManagementToolbar> colorMgmtToolBar; ImageAreaPanel* iareapanel; PreviewHandler* previewHandler; PreviewHandler* beforePreviewHandler; // for the before-after view Navigator* navigator; ImageAreaPanel* beforeIarea; // for the before-after view Gtk::Box* beforeBox; Gtk::Box* afterBox; Gtk::Label* beforeLabel; Gtk::Label* afterLabel; Gtk::Box* beforeAfterBox; Gtk::Box* beforeHeaderBox; Gtk::Box* afterHeaderBox; Gtk::ToggleButton* toggleHistogramProfile; Gtk::Frame* ppframe; ProfilePanel* profilep; History* history; HistogramPanel* histogramPanel; ToolPanelCoordinator* tpc; RTWindow* parent; Gtk::Window* parentWindow; //SaveAsDialog* saveAsDialog; FilePanel* fPanel; bool firstProcessingDone; Thumbnail* openThm; // may get invalid on external delete event Glib::ustring fname; // must be saved separately int selectedFrame; rtengine::InitialImage* isrc; rtengine::StagedImageProcessor* ipc; rtengine::StagedImageProcessor* beforeIpc; // for the before-after view EditorPanelIdleHelper* epih; int err; time_t processingStartedTime; sigc::connection ShowHideSidePanelsconn; bool isProcessing; IdleRegister idle_register; };
utf-8
1
GPL-3+
2004-2011, Gabor Horvath <hgabor@rawtherapee.com>
yade-2022.01a/py/3rd-party/pygts-0.3.1/triangle.cpp
/* pygts - python package for the manipulation of triangulated surfaces * * Copyright (C) 2009 Thomas J. Duck * All rights reserved. * * Thomas J. Duck <tom.duck@dal.ca> * Department of Physics and Atmospheric Science, * Dalhousie University, Halifax, Nova Scotia, Canada, B3H 3J5 * * NOTICE * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "pygts.h" #if PYGTS_DEBUG #define SELF_CHECK \ if (!pygts_triangle_check((PyObject*)self)) { \ PyErr_SetString(PyExc_RuntimeError, "problem with self object (internal error)"); \ return NULL; \ } #else #define SELF_CHECK #endif // https://codeyarns.com/2014/03/11/how-to-selectively-ignore-a-gcc-warning/ // https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" #pragma GCC diagnostic ignored "-Wwrite-strings" #pragma GCC diagnostic ignored "-Wmisleading-indentation" #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" /*-------------------------------------------------------------------------*/ /* Methods exported to python */ static PyObject* is_ok(PygtsTriangle* self, PyObject* args) { if (pygts_triangle_is_ok(self)) { Py_INCREF(Py_True); return Py_True; } else { Py_INCREF(Py_False); return Py_False; } } static PyObject* area(PygtsTriangle* self, PyObject* args) { SELF_CHECK return Py_BuildValue("d", gts_triangle_area(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self))); } static PyObject* perimeter(PygtsTriangle* self, PyObject* args) { SELF_CHECK return Py_BuildValue("d", gts_triangle_perimeter(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self))); } static PyObject* quality(PygtsTriangle* self, PyObject* args) { SELF_CHECK return Py_BuildValue("d", gts_triangle_quality(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self))); } static PyObject* normal(PygtsTriangle* self, PyObject* args) { gdouble x, y, z; SELF_CHECK gts_triangle_normal(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self), &x, &y, &z); return Py_BuildValue("ddd", x, y, z); } static PyObject* revert(PygtsTriangle* self, PyObject* args) { SELF_CHECK gts_triangle_revert(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self)); Py_INCREF(Py_None); return Py_None; } static PyObject* orientation(PygtsTriangle* self, PyObject* args) { SELF_CHECK return Py_BuildValue("d", gts_triangle_orientation(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self))); } static PyObject* angle(PygtsTriangle* self, PyObject* args) { PyObject* t_; PygtsTriangle* t; SELF_CHECK /* Parse the args */ if (!PyArg_ParseTuple(args, "O", &t_)) { return NULL; } /* Convert to PygtsObjects */ if (!pygts_triangle_check(t_)) { PyErr_SetString(PyExc_TypeError, "expected a Triangle"); return NULL; } t = PYGTS_TRIANGLE(t_); return Py_BuildValue("d", gts_triangles_angle(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self), PYGTS_TRIANGLE_AS_GTS_TRIANGLE(t))); } static PyObject* is_compatible(PygtsTriangle* self, PyObject* args) { PyObject* t2_; PygtsTriangle* t2; GtsEdge* e; SELF_CHECK /* Parse the args */ if (!PyArg_ParseTuple(args, "O", &t2_)) { return NULL; } /* Convert to PygtsObjects */ if (!pygts_triangle_check(t2_)) { PyErr_SetString(PyExc_TypeError, "expected a Triangle"); return NULL; } t2 = PYGTS_TRIANGLE(t2_); /* Get the common edge */ if ((e = gts_triangles_common_edge(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self), PYGTS_TRIANGLE_AS_GTS_TRIANGLE(t2))) == NULL) { PyErr_SetString(PyExc_RuntimeError, "Triangles do not share common edge"); return NULL; } if (gts_triangles_are_compatible(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self), PYGTS_TRIANGLE_AS_GTS_TRIANGLE(t2), e)) { Py_INCREF(Py_True); return Py_True; } else { Py_INCREF(Py_False); return Py_False; } } static PyObject* common_edge(PygtsTriangle* self, PyObject* args) { PyObject* t2_; PygtsTriangle* t2; GtsEdge* e; PygtsEdge* edge; SELF_CHECK /* Parse the args */ if (!PyArg_ParseTuple(args, "O", &t2_)) { return NULL; } /* Convert to PygtsObjects */ if (!pygts_triangle_check(t2_)) { PyErr_SetString(PyExc_TypeError, "expected a Triangle"); return NULL; } t2 = PYGTS_TRIANGLE(t2_); /* Get the common edge */ if ((e = gts_triangles_common_edge(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self), PYGTS_TRIANGLE_AS_GTS_TRIANGLE(t2))) == NULL) { Py_INCREF(Py_None); return Py_None; } if ((edge = pygts_edge_new(GTS_EDGE(e))) == NULL) { return NULL; } return (PyObject*)edge; } static PyObject* opposite(PygtsTriangle* self, PyObject* args) { PyObject* o_; PygtsEdge* e = NULL; PygtsVertex* v = NULL; GtsVertex * vertex = NULL, *v1, *v2, *v3; GtsEdge* edge = NULL; GtsTriangle* triangle; SELF_CHECK /* Parse the args */ if (!PyArg_ParseTuple(args, "O", &o_)) { return NULL; } /* Convert to PygtsObjects */ if (pygts_edge_check(o_)) { e = PYGTS_TRIANGLE(o_); } else { if (pygts_vertex_check(o_)) { v = PYGTS_TRIANGLE(o_); } else { PyErr_SetString(PyExc_TypeError, "expected an Edge or a Vertex"); return NULL; } } /* Error check */ triangle = PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self); if (e != NULL) { edge = PYGTS_EDGE_AS_GTS_EDGE(e); if (!((triangle->e1 == edge) || (triangle->e2 == edge) || (triangle->e3 == edge))) { PyErr_SetString(PyExc_RuntimeError, "Edge not in Triangle"); return NULL; } } else { vertex = PYGTS_VERTEX_AS_GTS_VERTEX(v); gts_triangle_vertices(triangle, &v1, &v2, &v3); if (!((vertex == v1) || (vertex == v2) || (vertex == v3))) { PyErr_SetString(PyExc_RuntimeError, "Vertex not in Triangle"); return NULL; } } /* Get the opposite and return */ if (e != NULL) { vertex = gts_triangle_vertex_opposite(triangle, edge); if ((v = pygts_vertex_new(vertex)) == NULL) { return NULL; } return (PyObject*)v; } else { edge = gts_triangle_edge_opposite(triangle, vertex); if ((e = pygts_edge_new(edge)) == NULL) { return NULL; } return (PyObject*)e; } } static PyObject* vertices(PygtsTriangle* self, PyObject* args) { GtsVertex * v1_, *v2_, *v3_; PygtsObject *v1, *v2, *v3; SELF_CHECK /* Get the vertices */ gts_triangle_vertices(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self), &v1_, &v2_, &v3_); if ((v1 = pygts_vertex_new(v1_)) == NULL) { return NULL; } if ((v2 = pygts_vertex_new(v2_)) == NULL) { Py_DECREF(v1); return NULL; } if ((v3 = pygts_vertex_new(v3_)) == NULL) { Py_DECREF(v1); Py_DECREF(v2); return NULL; } return Py_BuildValue("OOO", v1, v2, v3); } static PyObject* vertex(PygtsTriangle* self, PyObject* args) { GtsVertex* v1_; PygtsObject* v1; SELF_CHECK /* Get the vertices */ v1_ = gts_triangle_vertex(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self)); if ((v1 = pygts_vertex_new(v1_)) == NULL) { return NULL; } return (PyObject*)v1; } static PyObject* circumcenter(PygtsTriangle* self, PyObject* args) { PygtsVertex* v; GtsVertex* vertex; SELF_CHECK /* Get the Vertex */ vertex = GTS_VERTEX(gts_triangle_circumcircle_center(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self), GTS_POINT_CLASS(gts_vertex_class()))); if (vertex == NULL) { Py_INCREF(Py_None); return Py_None; } if ((v = pygts_vertex_new(vertex)) == NULL) { return NULL; } return (PyObject*)v; } static PyObject* is_stabbed(PygtsTriangle* self, PyObject* args) { PyObject* p_; PygtsVertex* p; GtsObject* obj; PygtsVertex* vertex; PygtsEdge* edge; SELF_CHECK /* Parse the args */ if (!PyArg_ParseTuple(args, "O", &p_)) { return NULL; } /* Convert to PygtsObjects */ if (!pygts_point_check(p_)) { PyErr_SetString(PyExc_TypeError, "expected a Point"); return NULL; } p = PYGTS_POINT(p_); obj = gts_triangle_is_stabbed(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self), GTS_POINT(PYGTS_OBJECT(p)->gtsobj), NULL); if (obj == NULL) { Py_INCREF(Py_None); return Py_None; } if (GTS_IS_VERTEX(obj)) { if ((vertex = pygts_vertex_new(GTS_VERTEX(obj))) == NULL) { return NULL; } return (PyObject*)vertex; } if (GTS_IS_EDGE(obj)) { if ((edge = pygts_edge_new(GTS_EDGE(obj))) == NULL) { return NULL; } return (PyObject*)edge; } Py_INCREF(self); return (PyObject*)self; } static PyObject* interpolate_height(PygtsTriangle* self, PyObject* args) { PyObject* p_; PygtsPoint* p; GtsPoint point; SELF_CHECK /* Parse the args */ if (!PyArg_ParseTuple(args, "O", &p_)) { return NULL; } /* Convert to PygtsObjects */ if (!pygts_point_check(p_)) { PyErr_SetString(PyExc_TypeError, "expected a Point"); return NULL; } p = PYGTS_POINT(p_); point.x = PYGTS_POINT_AS_GTS_POINT(p)->x; point.y = PYGTS_POINT_AS_GTS_POINT(p)->y; gts_triangle_interpolate_height(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self), &point); return Py_BuildValue("d", point.z); } /* Methods table */ static PyMethodDef methods[] = { { "is_ok", (PyCFunction)is_ok, METH_NOARGS, "True if this Triangle t is non-degenerate and non-duplicate.\n" "False otherwise.\n" "\n" "Signature: t.is_ok()\n" }, { "area", (PyCFunction)area, METH_NOARGS, "Returns the area of Triangle t.\n" "\n" "Signature: t.area()\n" }, { "perimeter", (PyCFunction)perimeter, METH_NOARGS, "Returns the perimeter of Triangle t.\n" "\n" "Signature: t.perimeter()\n" }, { "quality", (PyCFunction)quality, METH_NOARGS, "Returns the quality of Triangle t.\n" "\n" "The quality of a triangle is defined as the ratio of the square\n" "root of its surface area to its perimeter relative to this same\n" "ratio for an equilateral triangle with the same area. The quality\n" "is then one for an equilateral triangle and tends to zero for a\n" "very stretched triangle." "\n" "Signature: t.quality()\n" }, { "normal", (PyCFunction)normal, METH_NOARGS, "Returns a tuple of coordinates of the oriented normal of Triangle t\n" "as the cross-product of two edges, using the left-hand rule. The\n" "normal is not normalized. If this triangle is part of a closed and\n" "oriented surface, the normal points to the outside of the surface.\n" "\n" "Signature: t.normal()\n" }, { "revert", (PyCFunction)revert, METH_NOARGS, "Changes the orientation of triangle t, turning it inside out.\n" "\n" "Signature: t.revert()\n" }, { "orientation", (PyCFunction)orientation, METH_NOARGS, "Determines orientation of the plane (x,y) projection of Triangle t\n" "\n" "Signature: t.orientation()\n" "\n" "Returns a positive value if Points p1, p2 and p3 in Triangle t\n" "appear in counterclockwise order, a negative value if they appear\n" "in clockwise order and zero if they are colinear.\n" }, { "angle", (PyCFunction)angle, METH_VARARGS, "Returns the angle (radians) between Triangles t1 and t2\n" "\n" "Signature: t1.angle(t2)\n" }, { "is_compatible", (PyCFunction)is_compatible, METH_VARARGS, "True if this triangle t1 and other t2 are compatible;\n" "otherwise False.\n" "\n" "Checks if this triangle t1 and other t2, which share a common\n" "Edge, can be part of the same surface without conflict in the\n" "surface normal orientation.\n" "\n" "Signature: t1.is_compatible(t2)\n" }, { "common_edge", (PyCFunction)common_edge, METH_VARARGS, "Returns Edge common to both this Triangle t1 and other t2.\n" "Returns None if the triangles do not share an Edge.\n" "\n" "Signature: t1.common_edge(t2)\n" }, { "opposite", (PyCFunction)opposite, METH_VARARGS, "Returns Vertex opposite to Edge e or Edge opposite to Vertex v\n" "for this Triangle t.\n" "\n" "Signature: t.opposite(e) or t.opposite(v)\n" }, { "vertices", (PyCFunction)vertices, METH_NOARGS, "Returns the three oriented set of vertices in Triangle t.\n" "\n" "Signature: t.vertices()\n" }, { "vertex", (PyCFunction)vertex, METH_NOARGS, "Returns the Vertex of this Triangle t not in t.e1.\n" "\n" "Signature: t.vertex()\n" }, { "circumcenter", (PyCFunction)circumcenter, METH_NOARGS, "Returns a Vertex at the center of the circumscribing circle of\n" "this Triangle t, or None if the circumscribing circle is not\n" "defined.\n" "\n" "Signature: t.circumcircle_center()\n" }, { "is_stabbed", (PyCFunction)is_stabbed, METH_VARARGS, "Returns the component of this Triangle t that is stabbed by a\n" "ray projecting from Point p to z=infinity. The result\n" "can be this Triangle t, one of its Edges or Vertices, or None.\n" "If the ray is contained in the plan of this Triangle then None is\n" "also returned.\n" "\n" "Signature: t.is_stabbed(p)\n" }, { "interpolate_height", (PyCFunction)interpolate_height, METH_VARARGS, "Returns the height of the plane defined by Triangle t at Point p.\n" "Only the x- and y-coordinates of p are considered.\n" "\n" "Signature: t.interpolate_height(p)\n" }, { NULL } /* Sentinel */ }; /*-------------------------------------------------------------------------*/ /* Attributes exported to python */ static PyObject* get_e1(PygtsTriangle* self, void* closure) { PygtsEdge* e1; SELF_CHECK if ((e1 = pygts_edge_new(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self)->e1)) == NULL) { return NULL; } return (PyObject*)e1; } static PyObject* get_e2(PygtsTriangle* self, void* closure) { PygtsEdge* e2; SELF_CHECK if ((e2 = pygts_edge_new(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self)->e2)) == NULL) { return NULL; } return (PyObject*)e2; } static PyObject* get_e3(PygtsTriangle* self, void* closure) { PygtsEdge* e3; SELF_CHECK if ((e3 = pygts_edge_new(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(self)->e3)) == NULL) { return NULL; } return (PyObject*)e3; } /* Methods table */ static PyGetSetDef getset[] = { { "e1", (getter)get_e1, NULL, "Edge 1", NULL }, { "e2", (getter)get_e2, NULL, "Edge 2", NULL }, { "e3", (getter)get_e3, NULL, "Edge 3", NULL }, { NULL } /* Sentinel */ }; /*-------------------------------------------------------------------------*/ /* Python type methods */ static PyObject* new_(PyTypeObject* type, PyObject* args, PyObject* kwds) { PyObject* o; PygtsObject* obj; guint alloc_gtsobj = TRUE; PyObject * o1_, *o2_, *o3_; GtsVertex * v1 = NULL, *v2 = NULL, *v3 = NULL; GtsEdge * e1 = NULL, *e2 = NULL, *e3 = NULL, *e; GtsSegment * s1, *s2, *s3; gboolean flag = FALSE; /* Flag when the args are gts.Point objects */ GtsTriangle *t, *t_; guint N; /* Parse the args */ if (kwds) { o = PyDict_GetItemString(kwds, "alloc_gtsobj"); if (o == Py_False) { alloc_gtsobj = FALSE; } if (o != NULL) { PyDict_DelItemString(kwds, "alloc_gtsobj"); } } if (kwds) { Py_INCREF(Py_False); PyDict_SetItemString(kwds, "alloc_gtsobj", Py_False); } /* Allocate the gtsobj (if needed) */ if (alloc_gtsobj) { /* Parse the args */ if ((N = PyTuple_Size(args)) < 3) { PyErr_SetString(PyExc_TypeError, "expected three Edges or three Vertices"); return NULL; } o1_ = PyTuple_GET_ITEM(args, 0); o2_ = PyTuple_GET_ITEM(args, 1); o3_ = PyTuple_GET_ITEM(args, 2); /* Convert to PygtsObjects */ if (pygts_edge_check(o1_)) { e1 = PYGTS_EDGE_AS_GTS_EDGE(o1_); } else { if (pygts_vertex_check(o1_)) { v1 = PYGTS_VERTEX_AS_GTS_VERTEX(o1_); flag = TRUE; } } if (pygts_edge_check(o2_)) { e2 = PYGTS_EDGE_AS_GTS_EDGE(o2_); } else { if (pygts_vertex_check(o2_)) { v2 = PYGTS_VERTEX_AS_GTS_VERTEX(o2_); flag = TRUE; } } if (pygts_edge_check(o3_)) { e3 = PYGTS_EDGE_AS_GTS_EDGE(o3_); } else { if (pygts_vertex_check(o3_)) { v3 = PYGTS_VERTEX_AS_GTS_VERTEX(o3_); flag = TRUE; } } /* Check for three edges or three vertices */ if (!((e1 != NULL && e2 != NULL && e3 != NULL) || (v1 != NULL && v2 != NULL && v3 != NULL))) { PyErr_SetString(PyExc_TypeError, "expected three Edges or three Vertices"); return NULL; } if ((v1 == v2 || v2 == v3 || v1 == v3) && v1 != NULL) { PyErr_SetString(PyExc_ValueError, "three Vertices must be different"); return NULL; } /* Get gts edges */ if (flag) { /* Create gts edges */ if ((e1 = gts_edge_new(gts_edge_class(), v1, v2)) == NULL) { PyErr_SetString(PyExc_MemoryError, "could not create Edge"); return NULL; } if ((e2 = gts_edge_new(gts_edge_class(), v2, v3)) == NULL) { PyErr_SetString(PyExc_MemoryError, "could not create Edge"); gts_object_destroy(GTS_OBJECT(e1)); return NULL; } if ((e3 = gts_edge_new(gts_edge_class(), v3, v1)) == NULL) { PyErr_SetString(PyExc_MemoryError, "could not create Edge"); gts_object_destroy(GTS_OBJECT(e1)); gts_object_destroy(GTS_OBJECT(e2)); return NULL; } /* Check for duplicates */ if ((e = gts_edge_is_duplicate(e1)) != NULL) { gts_object_destroy(GTS_OBJECT(e1)); e1 = e; } if ((e = gts_edge_is_duplicate(e2)) != NULL) { gts_object_destroy(GTS_OBJECT(e2)); e2 = e; } if ((e = gts_edge_is_duplicate(e3)) != NULL) { gts_object_destroy(GTS_OBJECT(e3)); e3 = e; } } /* Check that edges connect with common vertices */ s1 = GTS_SEGMENT(e1); s2 = GTS_SEGMENT(e2); s3 = GTS_SEGMENT(e3); if (!((s1->v1 == s3->v2 && s1->v2 == s2->v1 && s2->v2 == s3->v1) || (s1->v1 == s3->v2 && s1->v2 == s2->v2 && s2->v1 == s3->v1) || (s1->v1 == s3->v1 && s1->v2 == s2->v1 && s2->v2 == s3->v2) || (s1->v2 == s3->v2 && s1->v1 == s2->v1 && s2->v2 == s3->v1) || (s1->v1 == s3->v1 && s1->v2 == s2->v2 && s2->v1 == s3->v2) || (s1->v2 == s3->v2 && s1->v1 == s2->v2 && s2->v1 == s3->v1) || (s1->v2 == s3->v1 && s1->v1 == s2->v1 && s2->v2 == s3->v2) || (s1->v2 == s3->v1 && s1->v1 == s2->v2 && s2->v1 == s3->v2))) { PyErr_SetString(PyExc_RuntimeError, "Edges in triangle must connect"); if (!g_hash_table_lookup(obj_table, GTS_OBJECT(e1))) { gts_object_destroy(GTS_OBJECT(e1)); } if (!g_hash_table_lookup(obj_table, GTS_OBJECT(e1))) { gts_object_destroy(GTS_OBJECT(e2)); } if (!g_hash_table_lookup(obj_table, GTS_OBJECT(e1))) { gts_object_destroy(GTS_OBJECT(e3)); } return NULL; } /* Create the GtsTriangle */ if ((t = gts_triangle_new(gts_triangle_class(), e1, e2, e3)) == NULL) { PyErr_SetString(PyExc_MemoryError, "could not create Face"); if (!g_hash_table_lookup(obj_table, GTS_OBJECT(e1))) { gts_object_destroy(GTS_OBJECT(e1)); } if (!g_hash_table_lookup(obj_table, GTS_OBJECT(e1))) { gts_object_destroy(GTS_OBJECT(e2)); } if (!g_hash_table_lookup(obj_table, GTS_OBJECT(e1))) { gts_object_destroy(GTS_OBJECT(e3)); } return NULL; } /* Check for duplicate */ t_ = gts_triangle_is_duplicate(GTS_TRIANGLE(t)); if (t_ != NULL) { gts_object_destroy(GTS_OBJECT(t)); t = t_; } /* If corresponding PyObject found in object table, we are done */ if ((obj = (PygtsObject*)g_hash_table_lookup(obj_table, GTS_OBJECT(t))) != NULL) { Py_INCREF(obj); return (PyObject*)obj; } } /* Chain up */ obj = PYGTS_OBJECT(PygtsObjectType.tp_new(type, args, kwds)); if (alloc_gtsobj) { obj->gtsobj = GTS_OBJECT(t); pygts_object_register(PYGTS_OBJECT(obj)); } return (PyObject*)obj; } static int init(PygtsTriangle* self, PyObject* args, PyObject* kwds) { gint ret; /* Chain up */ if ((ret = PygtsObjectType.tp_init((PyObject*)self, args, kwds)) != 0) { return ret; } #if PYGTS_DEBUG if (!pygts_triangle_check((PyObject*)self)) { PyErr_SetString(PyExc_RuntimeError, "problem with self object (internal error)"); return -1; } #endif return 0; } static int compare(PyObject* o1, PyObject* o2) { GtsTriangle *t1, *t2; if (!(pygts_triangle_check(o1) && pygts_triangle_check(o2))) { return -1; } t1 = PYGTS_TRIANGLE_AS_GTS_TRIANGLE(o1); t2 = PYGTS_TRIANGLE_AS_GTS_TRIANGLE(o2); return pygts_triangle_compare(t1, t2); } #if PY_MAJOR_VERSION >= 3 static PyObject* rich_compare(PyObject* o1, PyObject* o2, int op) { if (o2 == Py_None) Py_RETURN_FALSE; switch (op) { case Py_EQ: { if (compare(o1, o2)) Py_RETURN_TRUE; Py_RETURN_FALSE; } default: Py_RETURN_NOTIMPLEMENTED; } } #endif /* Methods table */ PyTypeObject PygtsTriangleType = { PyVarObject_HEAD_INIT(NULL, 0) "gts.Triangle", /* tp_name */ sizeof(PygtsTriangle), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if PY_MAJOR_VERSION >= 3 0, #else (cmpfunc)compare, /* tp_compare */ #endif 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Triangle object", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ #if PY_MAJOR_VERSION >= 3 (richcmpfunc)rich_compare, /* tp_richcompare */ #else 0, /* tp_richcompare */ #endif 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ methods, /* tp_methods */ 0, /* tp_members */ getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)init, /* tp_init */ 0, /* tp_alloc */ (newfunc)new_ /* tp_new */ }; /*-------------------------------------------------------------------------*/ /* Pygts functions */ gboolean pygts_triangle_check(PyObject* o) { if (!PyObject_TypeCheck(o, &PygtsTriangleType)) { return FALSE; } else { #if PYGTS_DEBUG return pygts_triangle_is_ok(PYGTS_TRIANGLE(o)); #else return TRUE; #endif } } gboolean pygts_triangle_is_ok(PygtsTriangle* t) { if (!pygts_object_is_ok(PYGTS_OBJECT(t))) return FALSE; return pygts_gts_triangle_is_ok(PYGTS_TRIANGLE_AS_GTS_TRIANGLE(t)); } PygtsTriangle* pygts_triangle_new(GtsTriangle* t) { PyObject * args, *kwds; PygtsObject* triangle; /* Check for Triangle in the object table */ if ((triangle = PYGTS_OBJECT(g_hash_table_lookup(obj_table, GTS_OBJECT(t)))) != NULL) { Py_INCREF(triangle); return PYGTS_TRIANGLE(triangle); } /* Build a new Triangle */ args = Py_BuildValue("OOO", Py_None, Py_None, Py_None); kwds = Py_BuildValue("{s:O}", "alloc_gtsobj", Py_False); triangle = PYGTS_OBJECT(PygtsTriangleType.tp_new(&PygtsTriangleType, args, kwds)); Py_DECREF(args); Py_DECREF(kwds); if (triangle == NULL) { PyErr_SetString(PyExc_MemoryError, "could not create Triangle"); return NULL; } triangle->gtsobj = GTS_OBJECT(t); /* Register and return */ pygts_object_register(triangle); return PYGTS_TRIANGLE(triangle); } int pygts_triangle_compare(GtsTriangle* t1, GtsTriangle* t2) { if ((pygts_segment_compare(GTS_SEGMENT(t1->e1), GTS_SEGMENT(t2->e1)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e2), GTS_SEGMENT(t2->e2)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e3), GTS_SEGMENT(t2->e3)) == 0) || (pygts_segment_compare(GTS_SEGMENT(t1->e1), GTS_SEGMENT(t2->e3)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e2), GTS_SEGMENT(t2->e1)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e3), GTS_SEGMENT(t2->e2)) == 0) || (pygts_segment_compare(GTS_SEGMENT(t1->e1), GTS_SEGMENT(t2->e2)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e2), GTS_SEGMENT(t2->e3)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e3), GTS_SEGMENT(t2->e1)) == 0) || (pygts_segment_compare(GTS_SEGMENT(t1->e1), GTS_SEGMENT(t2->e3)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e2), GTS_SEGMENT(t2->e2)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e3), GTS_SEGMENT(t2->e1)) == 0) || (pygts_segment_compare(GTS_SEGMENT(t1->e1), GTS_SEGMENT(t2->e2)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e2), GTS_SEGMENT(t2->e1)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e3), GTS_SEGMENT(t2->e3)) == 0) || (pygts_segment_compare(GTS_SEGMENT(t1->e1), GTS_SEGMENT(t2->e1)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e2), GTS_SEGMENT(t2->e3)) == 0 && pygts_segment_compare(GTS_SEGMENT(t1->e3), GTS_SEGMENT(t2->e2)) == 0)) { return 0; } return -1; } /** * gts_triangle_is_ok: * @t: a #GtsTriangle. * * Returns: %TRUE if @t is a non-degenerate, non-duplicate triangle, * %FALSE otherwise. */ gboolean pygts_gts_triangle_is_ok(GtsTriangle* t) { g_return_val_if_fail(t != NULL, FALSE); g_return_val_if_fail(t->e1 != NULL, FALSE); g_return_val_if_fail(t->e2 != NULL, FALSE); g_return_val_if_fail(t->e3 != NULL, FALSE); g_return_val_if_fail(t->e1 != t->e2 && t->e1 != t->e3 && t->e2 != t->e3, FALSE); g_return_val_if_fail(gts_segments_touch(GTS_SEGMENT(t->e1), GTS_SEGMENT(t->e2)), FALSE); g_return_val_if_fail(gts_segments_touch(GTS_SEGMENT(t->e1), GTS_SEGMENT(t->e3)), FALSE); g_return_val_if_fail(gts_segments_touch(GTS_SEGMENT(t->e2), GTS_SEGMENT(t->e3)), FALSE); g_return_val_if_fail(GTS_SEGMENT(t->e1)->v1 != GTS_SEGMENT(t->e1)->v2, FALSE); g_return_val_if_fail(GTS_SEGMENT(t->e2)->v1 != GTS_SEGMENT(t->e2)->v2, FALSE); g_return_val_if_fail(GTS_SEGMENT(t->e3)->v1 != GTS_SEGMENT(t->e3)->v2, FALSE); /* g_return_val_if_fail (GTS_OBJECT (t)->reserved == NULL, FALSE); */ g_return_val_if_fail(!gts_triangle_is_duplicate(t), FALSE); return TRUE; } #pragma GCC diagnostic pop
utf-8
1
GPL-2
2004-2020 Yade developers <yade-dev@lists.launchpad.net> Václav Šmilauer <eudoxos@arcig.cz> Olivier Galizzi <olivier.galizzi@imag.fr> Janek Kozicki <janek@kozicki.pl> Bruno Chareyre <bruno.chareyre@hmg.inpg.fr> Anton Gladky <gladky.anton@gmail.com> Sergei Dorofeenko <dorofeenko@icp.ac.ru> Jerome Duriez <duriez@geo.hmg.inpg.fr> Vincent Richefeu <richefeu@gmail.com> Chiara Modenese <c.modenese@gmail.com> Boon Chiaweng <booncw@hotmail.com> Emanuele Catalano <catalano@hmg.inpg.fr> Luc Scholtes <lscholtes63@gmail.com> Jan Stránský <_honzik@centrum.cz> Luc Sibille <luc.sibille@univ-nantes.fr> Feng Chen <fchen3@utk.edu> Klaus Thoeni <klaus.thoeni@gmail.com> Rémi Cailletaud <remi.cailletaud@hmg.inpg.fr>
fcitx-hangul-0.3.1/src/eim.c
/*************************************************************************** * Copyright (C) 2010~2012 by CSSlayer * * wengxt@gmail.com * * * * 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; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <libintl.h> #include <iconv.h> #include <fcitx/context.h> #include <fcitx/ime.h> #include <fcitx-config/hotkey.h> #include <fcitx-config/xdg.h> #include <fcitx-utils/log.h> #include <fcitx-config/fcitx-config.h> #include <fcitx-utils/utils.h> #include <fcitx/instance.h> #include <fcitx/keys.h> #include <fcitx/hook.h> #include <hangul.h> #include "eim.h" #include "keyboard.h" #define MAX_LENGTH 40 FCITX_EXPORT_API FcitxIMClass ime = { FcitxHangulCreate, FcitxHangulDestroy }; FCITX_EXPORT_API int ABI_VERSION = FCITX_ABI_VERSION; static const FcitxHotkey FCITX_HANGUL_GRAVE[2] = { {NULL, FcitxKey_grave, FcitxKeyState_None}, {NULL, 0, 0}, }; CONFIG_DESC_DEFINE(GetHangulConfigDesc, "fcitx-hangul.desc") boolean LoadHangulConfig(FcitxHangulConfig* fs); static void SaveHangulConfig(FcitxHangulConfig* fs); static void ConfigHangul(FcitxHangul* hangul); static void FcitxHangulUpdatePreedit(FcitxHangul* hangul); static void FcitxHangulCleanLookupTable(FcitxHangul* hangul); static void FcitxHangulUpdateLookupTable(FcitxHangul* hangul, boolean checkSurrounding); static void FcitxHangulFlush(FcitxHangul* hangul); static void FcitxHangulToggleHanja(void* arg); static boolean FcitxHangulGetHanja(void* arg); static void FcitxHangulResetEvent(void* arg); static char* FcitxHangulUcs4ToUtf8(FcitxHangul* hangul, const ucschar* ucsstr, int length); static void FcitxHangulUpdateHanjaStatus(FcitxHangul* hangul); static inline void FcitxHangulFreeHanjaList(FcitxHangul* hangul) { if (hangul->hanjaList) { hanja_list_delete (hangul->hanjaList); hangul->hanjaList = NULL; } } static inline size_t ucs4_strlen(const ucschar* str) { size_t len = 0; while(*str) { len ++; str ++; } return len; } static boolean FcitxHangulOnTransition (HangulInputContext *hic, ucschar c, const ucschar *preedit, void *data) { FcitxHangul* hangul = (FcitxHangul*) data; if (!hangul->fh.autoReorder) { if (hangul_is_choseong (c)) { if (hangul_ic_has_jungseong (hic) || hangul_ic_has_jongseong (hic)) return false; } if (hangul_is_jungseong (c)) { if (hangul_ic_has_jongseong (hic)) return false; } } return true; } char* FcitxHangulUcs4ToUtf8(FcitxHangul* hangul, const ucschar* ucsstr, int length) { if (!ucsstr) return NULL; size_t ucslen; if (length < 0) ucslen = ucs4_strlen(ucsstr); else ucslen = length; size_t len = UTF8_MAX_LENGTH * ucslen; char* str = (char*) fcitx_utils_malloc0(sizeof(char) * len + 1); len *= sizeof(char); ucslen *= sizeof(ucschar); char* p = str; iconv(hangul->conv, (char**) &ucsstr, &ucslen, &p, &len); return str; } /** * @brief Reset the status. * **/ void FcitxHangulReset (void* arg) { FcitxHangul* hangul = (FcitxHangul*) arg; ustring_clear(hangul->preedit); hangul_ic_reset(hangul->ic); if (hangul->hanjaList) { FcitxHangulCleanLookupTable(hangul); } } /** * @brief Process Key Input and return the status * * @param keycode keycode from XKeyEvent * @param state state from XKeyEvent * @param count count from XKeyEvent * @return INPUT_RETURN_VALUE **/ INPUT_RETURN_VALUE FcitxHangulDoInput(void* arg, FcitxKeySym sym, unsigned int state) { FcitxHangul* hangul = (FcitxHangul*) arg; FcitxInstance* instance = hangul->owner; if (FcitxHotkeyIsHotKey(sym, state, hangul->fh.hkHanjaMode)) { if (hangul->hanjaList == NULL) { FcitxHangulUpdateLookupTable(hangul, true); } else { FcitxHangulCleanLookupTable(hangul); } return IRV_DISPLAY_MESSAGE; } if (sym == FcitxKey_Shift_L || sym == FcitxKey_Shift_R) return IRV_TO_PROCESS; FcitxGlobalConfig* config = FcitxInstanceGetGlobalConfig(hangul->owner); const FcitxHotkey* prevPage = FcitxConfigPrevPageKey(instance, config); const FcitxHotkey* nextPage = FcitxConfigNextPageKey(instance, config); int s = hangul->fh.hkHanjaMode[0].state | hangul->fh.hkHanjaMode[1].state | config->prevWord[0].state | config->prevWord[1].state | config->nextWord[0].state | config->nextWord[1].state | prevPage[0].state | prevPage[1].state | nextPage[0].state | nextPage[1].state; if (s & FcitxKeyState_Ctrl) { if (sym == FcitxKey_Control_L || sym == FcitxKey_Control_R) return IRV_TO_PROCESS; } if (s & FcitxKeyState_Alt) { if (sym == FcitxKey_Alt_L || sym == FcitxKey_Alt_R) return IRV_TO_PROCESS; } if (s & FcitxKeyState_Shift) { if (sym == FcitxKey_Shift_L || sym == FcitxKey_Shift_R) return IRV_TO_PROCESS; } if (s & FcitxKeyState_Super) { if (sym == FcitxKey_Super_L || sym == FcitxKey_Super_R) return IRV_TO_PROCESS; } if (s & FcitxKeyState_Hyper) { if (sym == FcitxKey_Hyper_L || sym == FcitxKey_Hyper_R) return IRV_TO_PROCESS; } FcitxInputState* input = FcitxInstanceGetInputState(hangul->owner); FcitxCandidateWordList* candList = FcitxInputStateGetCandidateList(input); int candSize = FcitxCandidateWordGetListSize(candList); if (candSize > 0) { if (FcitxHotkeyIsHotKey(sym, state, prevPage)) { if (FcitxCandidateWordHasPrev(candList)) { FcitxCandidateWordGetFocus(candList, true); } if (FcitxCandidateWordGoPrevPage(candList)) { FcitxCandidateWordSetType(FcitxCandidateWordGetByIndex(candList, 0), MSG_CANDIATE_CURSOR); return IRV_FLAG_UPDATE_INPUT_WINDOW; } else { return IRV_DO_NOTHING; } } else if (FcitxHotkeyIsHotKey(sym, state, nextPage)) { if (FcitxCandidateWordHasNext(candList)) { FcitxCandidateWordGetFocus(candList, true); } if (FcitxCandidateWordGoNextPage(candList)) { FcitxCandidateWordSetType(FcitxCandidateWordGetByIndex(candList, 0), MSG_CANDIATE_CURSOR); return IRV_FLAG_UPDATE_INPUT_WINDOW; } else { return IRV_DO_NOTHING; } } FcitxCandidateWord* candWord = NULL; if (FcitxHotkeyIsHotKey(sym, state, config->nextWord)) { candWord = FcitxCandidateWordGetFocus(candList, true); candWord = FcitxCandidateWordGetNext(candList, candWord); if (!candWord) { FcitxCandidateWordSetPage(candList, 0); candWord = FcitxCandidateWordGetCurrentWindow(candList); } else { FcitxCandidateWordSetFocus( candList, FcitxCandidateWordGetIndex(candList, candWord)); } } else if (FcitxHotkeyIsHotKey(sym, state, config->prevWord)) { candWord = FcitxCandidateWordGetFocus(candList, true); candWord = FcitxCandidateWordGetPrev(candList, candWord); if (!candWord) { candWord = FcitxCandidateWordGetLast(candList); } FcitxCandidateWordSetFocus( candList, FcitxCandidateWordGetIndex(candList, candWord)); } if (candWord) { FcitxCandidateWordSetType(candWord, MSG_CANDIATE_CURSOR); return IRV_FLAG_UPDATE_INPUT_WINDOW; } if (FcitxHotkeyIsHotKeyDigit(sym, state)) return IRV_TO_PROCESS; if (FcitxHotkeyIsHotKey(sym, state , FCITX_ENTER)) { do { candWord = FcitxCandidateWordGetFocus(candList, true); if (!candWord) { break; } // FcitxLog(INFO, "%d", FcitxCandidateWordGetIndex(candList, candWord)); return FcitxCandidateWordChooseByTotalIndex(candList, FcitxCandidateWordGetIndex(candList, candWord)); } while(0); return FcitxCandidateWordChooseByIndex(candList, 0); } if (!hangul->fh.hanjaMode) { FcitxHangulCleanLookupTable(hangul); } } s = FcitxKeyState_Ctrl | FcitxKeyState_Alt | FcitxKeyState_Shift | FcitxKeyState_Super | FcitxKeyState_Hyper; if (state & s) { FcitxHangulFlush (hangul); FcitxHangulUpdatePreedit(hangul); FcitxUIUpdateInputWindow(hangul->owner); return IRV_TO_PROCESS; } bool keyUsed = false; if (FcitxHotkeyIsHotKey(sym, state, FCITX_BACKSPACE)) { keyUsed = hangul_ic_backspace (hangul->ic); if (!keyUsed) { unsigned int preedit_len = ustring_length (hangul->preedit); if (preedit_len > 0) { ustring_erase (hangul->preedit, preedit_len - 1, 1); keyUsed = true; } } } else { if (ustring_length(hangul->preedit) >= MAX_LENGTH) { FcitxHangulFlush(hangul); } keyUsed = hangul_ic_process(hangul->ic, sym); boolean notFlush = false; const ucschar* str = hangul_ic_get_commit_string (hangul->ic); if (hangul->fh.wordCommit || hangul->fh.hanjaMode) { const ucschar* hic_preedit; hic_preedit = hangul_ic_get_preedit_string (hangul->ic); if (hic_preedit != NULL && hic_preedit[0] != 0) { ustring_append_ucs4 (hangul->preedit, str); } else { ustring_append_ucs4 (hangul->preedit, str); if (ustring_length (hangul->preedit) > 0) { char* commit = FcitxHangulUcs4ToUtf8(hangul, ustring_begin(hangul->preedit), ustring_length(hangul->preedit)); if (commit) { FcitxInstanceCleanInputWindowUp(hangul->owner); size_t len = fcitx_utf8_strlen(commit); if (len > 0) { char* p = fcitx_utf8_get_nth_char(commit, len - 1); if ((strcmp(p, "`") == 0 && FcitxHotkeyIsHotKey(sym, state, FCITX_HANGUL_GRAVE)) || (strcmp(p, ";") == 0 && FcitxHotkeyIsHotKey(sym, state, FCITX_SEMICOLON))) { keyUsed = false; notFlush = true; *p = 0; } } FcitxInstanceCommitString(hangul->owner, FcitxInstanceGetCurrentIC(hangul->owner), commit); free(commit); } } ustring_clear (hangul->preedit); } } else { if (str != NULL && str[0] != 0) { char* commit = FcitxHangulUcs4ToUtf8(hangul, str, -1); if (commit) { FcitxInstanceCleanInputWindowUp(hangul->owner); if ((strcmp(commit, "`") == 0 && FcitxHotkeyIsHotKey(sym, state, FCITX_HANGUL_GRAVE)) || (strcmp(commit, ";") == 0 && FcitxHotkeyIsHotKey(sym, state, FCITX_SEMICOLON))) { keyUsed = false; notFlush = true; } else { FcitxInstanceCommitString(hangul->owner, FcitxInstanceGetCurrentIC(hangul->owner), commit); } free(commit); } } } FcitxHangulGetCandWords(hangul); FcitxUIUpdateInputWindow(hangul->owner); if (!keyUsed && !notFlush) FcitxHangulFlush (hangul); } if (!keyUsed) return IRV_TO_PROCESS; else return IRV_DISPLAY_CANDWORDS; } void FcitxHangulUpdatePreedit(FcitxHangul* hangul) { FcitxInputState* input = FcitxInstanceGetInputState(hangul->owner); FcitxMessages* preedit = FcitxInputStateGetPreedit(input); FcitxMessages* clientPreedit = FcitxInputStateGetClientPreedit(input); FcitxInstanceCleanInputWindowUp(hangul->owner); FcitxInputStateSetShowCursor(input, true); const ucschar *hic_preedit = hangul_ic_get_preedit_string (hangul->ic); char* pre1 = FcitxHangulUcs4ToUtf8(hangul, ustring_begin(hangul->preedit), ustring_length(hangul->preedit)); char* pre2 = FcitxHangulUcs4ToUtf8(hangul, hic_preedit, -1); FcitxInputContext* ic = FcitxInstanceGetCurrentIC(hangul->owner); FcitxProfile* profile = FcitxInstanceGetProfile(hangul->owner); size_t preeditLen = 0; boolean clientPreeditNotAvail = (ic && ((ic->contextCaps & CAPACITY_PREEDIT) == 0 || !profile->bUsePreedit)); if (pre1 && pre1[0] != 0) { size_t len1 = strlen(pre1); if (clientPreeditNotAvail) FcitxMessagesAddMessageAtLast(preedit, MSG_INPUT, "%s", pre1); FcitxMessagesAddMessageAtLast(clientPreedit, MSG_INPUT, "%s", pre1); preeditLen += len1; } if (pre2 && pre2[0] != '\0') { size_t len2 = strlen(pre2); if (clientPreeditNotAvail) FcitxMessagesAddMessageAtLast(preedit, MSG_INPUT | MSG_HIGHLIGHT, "%s", pre2); FcitxMessagesAddMessageAtLast(clientPreedit, MSG_INPUT | MSG_HIGHLIGHT, "%s", pre2); preeditLen += len2; } FcitxInputStateSetCursorPos(input, clientPreeditNotAvail ? preeditLen : 0); FcitxInputStateSetClientCursorPos(input, preeditLen); if (pre1) free(pre1); if (pre2) free(pre2); } HanjaList* FcitxHangulLookupTable(FcitxHangul* hangul, const char* key, int method) { HanjaList* list = NULL; if (key == NULL) return NULL; switch (method) { case LOOKUP_METHOD_EXACT: if (hangul->symbolTable != NULL) list = hanja_table_match_exact (hangul->symbolTable, key); if (list == NULL) list = hanja_table_match_exact (hangul->table, key); break; case LOOKUP_METHOD_PREFIX: if (hangul->symbolTable != NULL) list = hanja_table_match_prefix (hangul->symbolTable, key); if (list == NULL) list = hanja_table_match_prefix (hangul->table, key); break; case LOOKUP_METHOD_SUFFIX: if (hangul->symbolTable != NULL) list = hanja_table_match_suffix (hangul->symbolTable, key); if (list == NULL) list = hanja_table_match_suffix (hangul->table, key); break; } return list; } #define FCITX_HANGUL_MAX(a, b) ((a) > (b)? (a) : (b)) #define FCITX_HANGUL_MIN(a, b) ((a) < (b)? (a) : (b)) #define FCITX_HANGUL_ABS(a) ((a) >= (0)? (a) : -(a)) static char* GetSubstring (const char* str, long p1, long p2) { const char* begin; const char* end; char* substring; long limit; long pos; long n; if (str == NULL || str[0] == '\0') return NULL; limit = strlen(str) + 1; p1 = FCITX_HANGUL_MAX(0, p1); p2 = FCITX_HANGUL_MAX(0, p2); pos = FCITX_HANGUL_MIN(p1, p2); n = FCITX_HANGUL_ABS(p2 - p1); if (pos + n > limit) n = limit - pos; begin = fcitx_utf8_get_nth_char ((char*)str, pos); end = fcitx_utf8_get_nth_char ((char*)begin, n); substring = strndup (begin, end - begin); return substring; } void FcitxHangulCleanLookupTable(FcitxHangul* hangul) { FcitxInstanceCleanInputWindowDown(hangul->owner); // FcitxUIUpdateInputWindow(hangul->owner); FcitxHangulFreeHanjaList(hangul); } void FcitxHangulUpdateLookupTable(FcitxHangul* hangul, boolean checkSurrounding) { char* surroundingStr = NULL; char* utf8; char* hanjaKey = NULL; LookupMethod lookupMethod = LOOKUP_METHOD_PREFIX; const ucschar* hic_preedit; UString* preedit; unsigned int cursorPos; unsigned int anchorPos; FcitxHangulFreeHanjaList(hangul); hic_preedit = hangul_ic_get_preedit_string (hangul->ic); preedit = ustring_dup (hangul->preedit); ustring_append_ucs4 (preedit, hic_preedit); if (ustring_length(preedit) > 0) { utf8 = FcitxHangulUcs4ToUtf8 (hangul, ustring_begin(preedit), ustring_length(preedit)); if (hangul->fh.wordCommit || hangul->fh.hanjaMode) { hanjaKey = utf8; lookupMethod = LOOKUP_METHOD_PREFIX; } else { char* substr; FcitxInstanceGetSurroundingText(hangul->owner, FcitxInstanceGetCurrentIC(hangul->owner), &surroundingStr, &cursorPos, &anchorPos); substr = GetSubstring (surroundingStr, (long) cursorPos - 64, cursorPos); if (substr != NULL) { asprintf(&hanjaKey, "%s%s", substr, utf8); free (utf8); free (substr); } else { hanjaKey = utf8; } lookupMethod = LOOKUP_METHOD_SUFFIX; } } else { if (checkSurrounding) { FcitxInstanceGetSurroundingText(hangul->owner, FcitxInstanceGetCurrentIC(hangul->owner), &surroundingStr, &cursorPos, &anchorPos); if (cursorPos != anchorPos) { // If we have selection in surrounding text, we use that. hanjaKey = GetSubstring(surroundingStr, cursorPos, anchorPos); lookupMethod = LOOKUP_METHOD_EXACT; } else { hanjaKey = GetSubstring (surroundingStr, (long) cursorPos - 64, cursorPos); lookupMethod = LOOKUP_METHOD_SUFFIX; } } } if (hanjaKey != NULL) { hangul->hanjaList = FcitxHangulLookupTable (hangul, hanjaKey, lookupMethod); hangul->lastLookupMethod = lookupMethod; free (hanjaKey); } ustring_delete (preedit); if (surroundingStr) free(surroundingStr); if (hangul->hanjaList) { HanjaList* list = hangul->hanjaList; if (list != NULL) { int i, n; n = hanja_list_get_size (list); FcitxInputState* input = FcitxInstanceGetInputState(hangul->owner); FcitxCandidateWordList* candList = FcitxInputStateGetCandidateList(input); FcitxGlobalConfig* config = FcitxInstanceGetGlobalConfig(hangul->owner); FcitxCandidateWordSetPageSize(candList, config->iMaxCandWord); FcitxCandidateWordSetChoose(candList, "1234567890"); FcitxCandidateWord word; FcitxCandidateWordReset(candList); for (i = 0; i < n; i++) { const char* value = hanja_list_get_nth_value (list, i); unsigned int* idx = fcitx_utils_malloc0(sizeof(unsigned int)); *idx = i; word.strWord = strdup(value); word.wordType = (i == 0) ? MSG_CANDIATE_CURSOR : MSG_INPUT; word.strExtra = NULL; word.extraType = MSG_INPUT; word.priv = idx; word.owner = hangul; word.callback = FcitxHangulGetCandWord; FcitxCandidateWordAppend(candList, &word); } FcitxCandidateWordSetFocus(candList, 0); } } } void FcitxHangulFlush(FcitxHangul* hangul) { const ucschar *str; FcitxHangulCleanLookupTable(hangul); str = hangul_ic_flush (hangul->ic); ustring_append_ucs4 (hangul->preedit, str); if (ustring_length (hangul->preedit) == 0) return; str = ustring_begin (hangul->preedit); char* utf8 = FcitxHangulUcs4ToUtf8(hangul, str, ustring_length(hangul->preedit)); if (utf8) { FcitxInstanceCommitString(hangul->owner, FcitxInstanceGetCurrentIC(hangul->owner), utf8); free(utf8); } ustring_clear(hangul->preedit); } boolean FcitxHangulInit(void* arg) { FcitxHangul* hangul = (FcitxHangul*) arg; boolean flag = true; FcitxInstanceSetContext(hangul->owner, CONTEXT_IM_KEYBOARD_LAYOUT, "us"); FcitxInstanceSetContext(hangul->owner, CONTEXT_DISABLE_AUTO_FIRST_CANDIDATE_HIGHTLIGHT, &flag); return true; } /** * @brief function DoInput has done everything for us. * * @param searchMode * @return INPUT_RETURN_VALUE **/ INPUT_RETURN_VALUE FcitxHangulGetCandWords(void* arg) { FcitxHangul* hangul = (FcitxHangul* )arg; FcitxHangulUpdatePreedit(hangul); if (hangul->fh.hanjaMode) { FcitxHangulUpdateLookupTable(hangul, false); } else { FcitxHangulCleanLookupTable(hangul); } return IRV_DISPLAY_CANDWORDS; } /** * @brief get the candidate word by index * * @param iIndex index of candidate word * @return the string of canidate word **/ INPUT_RETURN_VALUE FcitxHangulGetCandWord (void* arg, FcitxCandidateWord* candWord) { FcitxHangul* hangul = (FcitxHangul* )arg; unsigned int pos = *(unsigned int*) candWord->priv; const char* key; const char* value; const ucschar* hic_preedit; int key_len; int preedit_len; int hic_preedit_len; key = hanja_list_get_nth_key (hangul->hanjaList, pos); value = hanja_list_get_nth_value (hangul->hanjaList, pos); hic_preedit = hangul_ic_get_preedit_string (hangul->ic); if (!key || !value || !hic_preedit) return IRV_CLEAN; // FcitxLog(INFO, "%s", key); key_len = fcitx_utf8_strlen(key); preedit_len = ustring_length(hangul->preedit); hic_preedit_len = ucs4_strlen (hic_preedit); boolean surrounding = false; if (hangul->lastLookupMethod == LOOKUP_METHOD_PREFIX) { if (preedit_len == 0 && hic_preedit_len == 0) { /* remove surrounding_text */ if (key_len > 0) { FcitxInstanceDeleteSurroundingText (hangul->owner, FcitxInstanceGetCurrentIC(hangul->owner), -key_len , key_len); surrounding = true; } } else { /* remove preedit text */ if (key_len > 0) { long n = FCITX_HANGUL_MIN(key_len, preedit_len); ustring_erase (hangul->preedit, 0, n); key_len -= preedit_len; } /* remove hic preedit text */ if (key_len > 0) { hangul_ic_reset (hangul->ic); key_len -= hic_preedit_len; } } } else { /* remove hic preedit text */ if (hic_preedit_len > 0) { hangul_ic_reset (hangul->ic); key_len -= hic_preedit_len; } /* remove ibus preedit text */ if (key_len > preedit_len) { ustring_erase (hangul->preedit, 0, preedit_len); key_len -= preedit_len; } else if (key_len > 0) { ustring_erase (hangul->preedit, 0, key_len); key_len = 0; } /* remove surrounding_text */ if (LOOKUP_METHOD_EXACT != hangul->lastLookupMethod && key_len > 0) { FcitxInstanceDeleteSurroundingText (hangul->owner, FcitxInstanceGetCurrentIC(hangul->owner), -key_len , key_len); surrounding = true; } } FcitxInstanceCommitString(hangul->owner, FcitxInstanceGetCurrentIC(hangul->owner), value); if (surrounding) { FcitxInstanceCleanInputWindowUp(hangul->owner); FcitxHangulCleanLookupTable(hangul); return IRV_DISPLAY_MESSAGE; } else { return IRV_DISPLAY_CANDWORDS; } } /** * @brief initialize the extra input method * * @param arg * @return successful or not **/ void* FcitxHangulCreate (FcitxInstance* instance) { FcitxHangul* hangul = (FcitxHangul*) fcitx_utils_malloc0(sizeof(FcitxHangul)); bindtextdomain("fcitx-hangul", LOCALEDIR); bind_textdomain_codeset("fcitx-hangul", "UTF-8"); hangul->owner = instance; hangul->lastLookupMethod = LOOKUP_METHOD_PREFIX; if (!LoadHangulConfig(&hangul->fh)) { free(hangul); return NULL; } hangul->conv = iconv_open("UTF-8", "UCS-4LE"); hangul->preedit = ustring_new(); ConfigHangul(hangul); hangul->table = hanja_table_load(NULL); char* path; FILE* fp = FcitxXDGGetFileWithPrefix("hangul", "symbol.txt", "r", &path); if (fp) fclose(fp); hangul->symbolTable = hanja_table_load ( path ); free(path); hangul->ic = hangul_ic_new(keyboard[hangul->fh.keyboardLayout]); hangul_ic_connect_callback (hangul->ic, "transition", FcitxHangulOnTransition, hangul); FcitxIMIFace iface; memset(&iface, 0, sizeof(FcitxIMIFace)); iface.Init = FcitxHangulInit; iface.ResetIM = FcitxHangulReset; iface.DoInput = FcitxHangulDoInput; iface.GetCandWords = FcitxHangulGetCandWords; iface.ReloadConfig = ReloadConfigFcitxHangul; iface.OnClose = FcitxHangulOnClose; FcitxInstanceRegisterIMv2(instance, hangul, "hangul", _("Hangul"), "hangul", iface, 5, "ko" ); FcitxIMEventHook hk; hk.arg = hangul; hk.func = FcitxHangulResetEvent; FcitxInstanceRegisterResetInputHook(instance, hk); FcitxUIRegisterStatus( instance, hangul, "hanja", "", "", FcitxHangulToggleHanja, FcitxHangulGetHanja ); FcitxHangulUpdateHanjaStatus(hangul); return hangul; } void FcitxHangulOnClose(void* arg, FcitxIMCloseEventType event) { FcitxHangul* hangul = arg; if (event == CET_LostFocus) { } else if (event == CET_ChangeByInactivate) { FcitxHangulFlush(hangul); } else if (event == CET_ChangeByUser) { FcitxHangulFlush(hangul); } } void FcitxHangulToggleHanja(void* arg) { FcitxHangul* hangul = (FcitxHangul*) arg; hangul->fh.hanjaMode = !hangul->fh.hanjaMode; FcitxHangulUpdateHanjaStatus(hangul); SaveHangulConfig(&hangul->fh); } void FcitxHangulUpdateHanjaStatus(FcitxHangul* hangul) { if (hangul->fh.hanjaMode) { FcitxUISetStatusString(hangul->owner, "hanja", "\xe9\x9f\x93", _("Use Hanja")); } else { FcitxUISetStatusString(hangul->owner, "hanja", "\xed\x95\x9c", _("Use Hangul")); } FcitxHangulFlush(hangul); FcitxHangulUpdatePreedit(hangul); FcitxUIUpdateInputWindow(hangul->owner); } boolean FcitxHangulGetHanja(void* arg) { FcitxHangul* hangul = (FcitxHangul*) arg; return hangul->fh.hanjaMode; } /** * @brief Destroy the input method while unload it. * * @return int **/ void FcitxHangulDestroy (void* arg) { FcitxHangul* hangul = (FcitxHangul*) arg; hanja_table_delete(hangul->table); hanja_table_delete(hangul->symbolTable); free(arg); } /** * @brief Load the config file for fcitx-hangul * * @param Bool is reload or not **/ boolean LoadHangulConfig(FcitxHangulConfig* fs) { FcitxConfigFileDesc *configDesc = GetHangulConfigDesc(); if (!configDesc) return false; FILE *fp = FcitxXDGGetFileUserWithPrefix("conf", "fcitx-hangul.config", "r", NULL); if (!fp) { if (errno == ENOENT) SaveHangulConfig(fs); } FcitxConfigFile *cfile = FcitxConfigParseConfigFileFp(fp, configDesc); FcitxHangulConfigConfigBind(fs, cfile, configDesc); FcitxConfigBindSync(&fs->gconfig); if (fp) fclose(fp); return true; } void ConfigHangul(FcitxHangul* hangul) { FcitxLog(DEBUG, "Hangul Layout: %s", keyboard[hangul->fh.keyboardLayout]); hangul_ic_select_keyboard(hangul->ic, keyboard[hangul->fh.keyboardLayout]); } void ReloadConfigFcitxHangul(void* arg) { FcitxHangul* hangul = (FcitxHangul*) arg; LoadHangulConfig(&hangul->fh); ConfigHangul(hangul); } /** * @brief Save the config * * @return void **/ void SaveHangulConfig(FcitxHangulConfig* fa) { FcitxConfigFileDesc *configDesc = GetHangulConfigDesc(); FILE *fp = FcitxXDGGetFileUserWithPrefix("conf", "fcitx-hangul.config", "w", NULL); FcitxConfigSaveConfigFileFp(fp, &fa->gconfig, configDesc); if (fp) fclose(fp); } void FcitxHangulResetEvent(void* arg) { FcitxHangul* hangul = (FcitxHangul*) arg; FcitxIM* im = FcitxInstanceGetCurrentIM(hangul->owner); if (!im || strcmp(im->uniqueName, "hangul") != 0) { FcitxUISetStatusVisable(hangul->owner, "hanja", false); } else { FcitxUISetStatusVisable(hangul->owner, "hanja", true); } }
utf-8
1
GPL-2+
2010, 2011, 2012 CSSlayer <wengxt@gmail.com>
chromium-98.0.4758.102/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/json/string_escape.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" #include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "chrome/common/chrome_features.h" #include "extensions/common/url_pattern_set.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace extensions { const char kTestHostName[] = "com.chrome.test.native_host"; #if defined(OS_WIN) const char kTestHostPath[] = "C:\\ProgramFiles\\host.exe"; #else const char kTestHostPath[] = "/usr/bin/host"; #endif const char kTestOrigin[] = "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"; class NativeMessagingHostManifestTest : public ::testing::Test { public: void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); manifest_path_ = temp_dir_.GetPath().AppendASCII("test.json"); } protected: bool WriteManifest( const std::string& name, const std::string& path, const std::string& origin, absl::optional<std::string> supports_native_initiated_connections) { std::string supports_native_initiated_connections_snippet; if (supports_native_initiated_connections) { supports_native_initiated_connections_snippet = base::StrCat({ R"("supports_native_initiated_connections": )", *supports_native_initiated_connections, ",\n", }); } return WriteManifest(base::StringPrintf( R"({ "name": "%s", "description": "Native Messaging Test", "path": %s, "type": "stdio", %s "allowed_origins": [ "%s" ] })", name.c_str(), base::GetQuotedJSONString(path).c_str(), supports_native_initiated_connections_snippet.c_str(), origin.c_str())); } bool WriteManifest(const std::string& manifest_content) { return base::WriteFile(manifest_path_, manifest_content); } base::ScopedTempDir temp_dir_; base::FilePath manifest_path_; }; TEST_F(NativeMessagingHostManifestTest, HostNameValidation) { EXPECT_TRUE(NativeMessagingHostManifest::IsValidName("a")); EXPECT_TRUE(NativeMessagingHostManifest::IsValidName("foo")); EXPECT_TRUE(NativeMessagingHostManifest::IsValidName("foo132")); EXPECT_TRUE(NativeMessagingHostManifest::IsValidName("foo.bar")); EXPECT_TRUE(NativeMessagingHostManifest::IsValidName("foo.bar2")); EXPECT_TRUE(NativeMessagingHostManifest::IsValidName("a._.c")); EXPECT_TRUE(NativeMessagingHostManifest::IsValidName("a._.c")); EXPECT_FALSE(NativeMessagingHostManifest::IsValidName("A.b")); EXPECT_FALSE(NativeMessagingHostManifest::IsValidName("a..b")); EXPECT_FALSE(NativeMessagingHostManifest::IsValidName(".a")); EXPECT_FALSE(NativeMessagingHostManifest::IsValidName("b.")); EXPECT_FALSE(NativeMessagingHostManifest::IsValidName("a*")); } TEST_F(NativeMessagingHostManifestTest, LoadValid) { ASSERT_TRUE( WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, absl::nullopt)); std::string error_message; std::unique_ptr<NativeMessagingHostManifest> manifest = NativeMessagingHostManifest::Load(manifest_path_, &error_message); ASSERT_TRUE(manifest) << "Failed to load manifest: " << error_message; EXPECT_TRUE(error_message.empty()); EXPECT_EQ(manifest->name(), "com.chrome.test.native_host"); EXPECT_EQ(manifest->description(), "Native Messaging Test"); EXPECT_EQ(manifest->host_interface(), NativeMessagingHostManifest::HOST_INTERFACE_STDIO); EXPECT_EQ(manifest->path(), base::FilePath::FromASCII(kTestHostPath)); EXPECT_TRUE(manifest->allowed_origins().MatchesSecurityOrigin( GURL("chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"))); EXPECT_FALSE(manifest->allowed_origins().MatchesSecurityOrigin( GURL("chrome-extension://jnldjmfmopnpolahpmmgbagdohdnhkik/"))); EXPECT_FALSE(manifest->supports_native_initiated_connections()); } TEST_F(NativeMessagingHostManifestTest, LoadValid_SupportsNativeInitiatedConnections) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kOnConnectNative); ASSERT_TRUE(WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, "true")); std::string error_message; std::unique_ptr<NativeMessagingHostManifest> manifest = NativeMessagingHostManifest::Load(manifest_path_, &error_message); ASSERT_TRUE(manifest) << "Failed to load manifest: " << error_message; EXPECT_TRUE(error_message.empty()); EXPECT_TRUE(manifest->supports_native_initiated_connections()); } TEST_F(NativeMessagingHostManifestTest, LoadValid_SupportsNativeInitiatedConnectionsWithFeatureDisabled) { base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(features::kOnConnectNative); ASSERT_TRUE(WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, "true")); std::string error_message; std::unique_ptr<NativeMessagingHostManifest> manifest = NativeMessagingHostManifest::Load(manifest_path_, &error_message); ASSERT_TRUE(manifest) << "Failed to load manifest: " << error_message; EXPECT_TRUE(error_message.empty()); EXPECT_FALSE(manifest->supports_native_initiated_connections()); } TEST_F(NativeMessagingHostManifestTest, LoadValid_DoesNotSupportNativeInitiatedConnections) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kOnConnectNative); ASSERT_TRUE( WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, "false")); std::string error_message; std::unique_ptr<NativeMessagingHostManifest> manifest = NativeMessagingHostManifest::Load(manifest_path_, &error_message); ASSERT_TRUE(manifest) << "Failed to load manifest: " << error_message; EXPECT_TRUE(error_message.empty()); EXPECT_FALSE(manifest->supports_native_initiated_connections()); } TEST_F(NativeMessagingHostManifestTest, LoadValid_DoesNotSpecifySupportNativeInitiatedConnections) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kOnConnectNative); ASSERT_TRUE( WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, absl::nullopt)); std::string error_message; std::unique_ptr<NativeMessagingHostManifest> manifest = NativeMessagingHostManifest::Load(manifest_path_, &error_message); ASSERT_TRUE(manifest) << "Failed to load manifest: " << error_message; EXPECT_TRUE(error_message.empty()); EXPECT_FALSE(manifest->supports_native_initiated_connections()); } TEST_F(NativeMessagingHostManifestTest, LoadInvalidSupportsNativeInitiatedConnections) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kOnConnectNative); ASSERT_TRUE( WriteManifest(kTestHostName, kTestHostPath, kTestOrigin, "\"true\"")); std::string error_message; std::unique_ptr<NativeMessagingHostManifest> manifest = NativeMessagingHostManifest::Load(manifest_path_, &error_message); ASSERT_FALSE(manifest); EXPECT_FALSE(error_message.empty()); } TEST_F(NativeMessagingHostManifestTest, InvalidName) { ASSERT_TRUE(WriteManifest(".com.chrome.test.native_host", kTestHostPath, kTestOrigin, absl::nullopt)); std::string error_message; std::unique_ptr<NativeMessagingHostManifest> manifest = NativeMessagingHostManifest::Load(manifest_path_, &error_message); ASSERT_FALSE(manifest); EXPECT_FALSE(error_message.empty()); } // Verify that match-all origins are rejected. TEST_F(NativeMessagingHostManifestTest, MatchAllOrigin) { ASSERT_TRUE(WriteManifest(kTestHostName, kTestHostPath, "chrome-extension://*/", absl::nullopt)); std::string error_message; std::unique_ptr<NativeMessagingHostManifest> manifest = NativeMessagingHostManifest::Load(manifest_path_, &error_message); ASSERT_FALSE(manifest); EXPECT_FALSE(error_message.empty()); } } // namespace extensions
utf-8
1
BSD-3-clause
The Chromium Authors. All rights reserved.
qtcreator-6.0.2/src/plugins/cppeditor/compileroptionsbuilder.h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #pragma once #include "cppeditor_global.h" #include "projectpart.h" namespace CppEditor { enum class UsePrecompiledHeaders : char { Yes, No }; enum class UseSystemHeader : char { Yes, No }; enum class UseTweakedHeaderPaths : char { Yes, Tools, No }; enum class UseToolchainMacros : char { Yes, No }; enum class UseLanguageDefines : char { Yes, No }; enum class UseBuildSystemWarnings : char { Yes, No }; CPPEDITOR_EXPORT QStringList XclangArgs(const QStringList &args); CPPEDITOR_EXPORT QStringList clangArgsForCl(const QStringList &args); CPPEDITOR_EXPORT QStringList createLanguageOptionGcc(ProjectFile::Kind fileKind, bool objcExt); class CPPEDITOR_EXPORT CompilerOptionsBuilder { public: CompilerOptionsBuilder(const ProjectPart &projectPart, UseSystemHeader useSystemHeader = UseSystemHeader::No, UseTweakedHeaderPaths useTweakedHeaderPaths = UseTweakedHeaderPaths::No, UseLanguageDefines useLanguageDefines = UseLanguageDefines::No, UseBuildSystemWarnings useBuildSystemWarnings = UseBuildSystemWarnings::No, const QString &clangVersion = {}, const Utils::FilePath &clangIncludeDirectory = {}); virtual ~CompilerOptionsBuilder(); QStringList build(ProjectFile::Kind fileKind, UsePrecompiledHeaders usePrecompiledHeaders); QStringList options() const { return m_options; } // Add options based on project part virtual void addProjectMacros(); void addSyntaxOnly(); void addWordWidth(); void addHeaderPathOptions(); void addPrecompiledHeaderOptions(UsePrecompiledHeaders usePrecompiledHeaders); void addIncludedFiles(const QStringList &files); void addMacros(const ProjectExplorer::Macros &macros); void addTargetTriple(); void addExtraCodeModelFlags(); void addPicIfCompilerFlagsContainsIt(); void addCompilerFlags(); void addMsvcExceptions(); void enableExceptions(); void insertWrappedQtHeaders(); void insertWrappedMingwHeaders(); void addLanguageVersionAndExtensions(); void updateFileLanguage(ProjectFile::Kind fileKind); void addMsvcCompatibilityVersion(); void undefineCppLanguageFeatureMacrosForMsvc2015(); void addDefineFunctionMacrosMsvc(); void addProjectConfigFileInclude(); void undefineClangVersionMacrosForMsvc(); void addDefineFunctionMacrosQnx(); // Add custom options void add(const QString &arg, bool gccOnlyOption = false); void prepend(const QString &arg); void add(const QStringList &args, bool gccOnlyOptions = false); virtual void addExtraOptions() {} static UseToolchainMacros useToolChainMacros(); void reset(); void evaluateCompilerFlags(); bool isClStyle() const; private: void addIncludeDirOptionForPath(const ProjectExplorer::HeaderPath &path); bool excludeDefineDirective(const ProjectExplorer::Macro &macro) const; void insertWrappedHeaders(const QStringList &paths); QStringList wrappedQtHeadersIncludePath() const; QStringList wrappedMingwHeadersIncludePath() const; QByteArray msvcVersion() const; void addIncludeFile(const QString &file); private: const ProjectPart &m_projectPart; const UseSystemHeader m_useSystemHeader; const UseTweakedHeaderPaths m_useTweakedHeaderPaths; const UseLanguageDefines m_useLanguageDefines; const UseBuildSystemWarnings m_useBuildSystemWarnings; const QString m_clangVersion; const Utils::FilePath m_clangIncludeDirectory; struct { QStringList flags; bool isLanguageVersionSpecified = false; } m_compilerFlags; QStringList m_options; QString m_explicitTarget; bool m_clStyle = false; }; } // namespace CppEditor
utf-8
1
GPL-3 with Qt-1.0 exception
2008-2020 The Qt Company
phcpack-2.4.85+dfsg/src/GPU/Norms/random4_vectors.cpp
// The file random4_vectors.cpp defines the code for the functions // specified in random4_vectors.h. #include "random_numbers.h" #include "random4_vectors.h" #include "quad_double_functions.h" void random_quad_double ( double *x_hihi, double *x_lohi, double *x_hilo, double *x_lolo ) { const double eps = 2.220446049250313e-16; // 2^(-52) const double eps2 = eps*eps; const double eps3 = eps*eps2; const double r0 = random_double(); const double r1 = random_double(); const double r2 = random_double(); const double r3 = random_double(); *x_hihi = r0; *x_lohi = 0.0; *x_hilo = 0.0; *x_lolo = 0.0; qdf_inc_d(x_hihi,x_lohi,x_hilo,x_lolo,r1*eps); qdf_inc_d(x_hihi,x_lohi,x_hilo,x_lolo,r2*eps2); qdf_inc_d(x_hihi,x_lohi,x_hilo,x_lolo,r3*eps3); } void random_double4_vectors ( int dim, double *vhihi_host, double *vlohi_host, double *vhilo_host, double *vlolo_host, double *vhihi_device, double *vlohi_device, double *vhilo_device, double *vlolo_device ) { double r_hihi,r_lohi,r_hilo,r_lolo; for(int k=0; k<dim; k++) { random_quad_double(&r_hihi,&r_lohi,&r_hilo,&r_lolo); vhihi_host[k] = r_hihi; vhihi_device[k] = r_hihi; vlohi_host[k] = r_lohi; vlohi_device[k] = r_lohi; vhilo_host[k] = r_hilo; vhilo_device[k] = r_hilo; vlolo_host[k] = r_lolo; vlolo_device[k] = r_lolo; } } void random_complex4_vectors ( int dim, double *vrehihi_host, double *vrelohi_host, double *vrehilo_host, double *vrelolo_host, double *vimhihi_host, double *vimlohi_host, double *vimhilo_host, double *vimlolo_host, double *vrehihi_device, double *vrelohi_device, double *vrehilo_device, double *vrelolo_device, double *vimhihi_device, double *vimlohi_device, double *vimhilo_device, double *vimlolo_device ) { double rnd_hihi,rnd_lohi,rnd_hilo,rnd_lolo; double cosrnd_hihi,cosrnd_lohi,cosrnd_hilo,cosrnd_lolo; double sinrnd_hihi,sinrnd_lohi,sinrnd_hilo,sinrnd_lolo; for(int k=0; k<dim; k++) { random_quad_double(&rnd_hihi,&rnd_lohi,&rnd_hilo,&rnd_lolo); sinrnd_hihi = rnd_hihi; sinrnd_lohi = rnd_lohi; sinrnd_hilo = rnd_hilo; sinrnd_lolo = rnd_lolo; double y_hihi,y_lohi,y_hilo,y_lolo; // work around to compute cos qdf_sqr(sinrnd_hihi,sinrnd_lohi,sinrnd_hilo,sinrnd_lolo, &y_hihi,&y_lohi,&y_hilo,&y_lolo); qdf_minus(&y_hihi,&y_lohi,&y_hilo,&y_lolo); // y = -sin^2 qdf_inc_d(&y_hihi,&y_lohi,&y_hilo,&y_lolo,1.0); // y = 1 - sin^2 qdf_sqrt(y_hihi,y_lohi,y_hilo,y_lolo, &cosrnd_hihi,&cosrnd_lohi,&cosrnd_hilo,&cosrnd_lolo); // cos is sqrt(1-sin^2) vrehihi_host[k] = cosrnd_hihi; vrehihi_device[k] = cosrnd_hihi; vrelohi_host[k] = cosrnd_lohi; vrelohi_device[k] = cosrnd_lohi; vrehilo_host[k] = cosrnd_hilo; vrehilo_device[k] = cosrnd_hilo; vrelolo_host[k] = cosrnd_lolo; vrelolo_device[k] = cosrnd_lolo; vimhihi_host[k] = sinrnd_hihi; vimhihi_device[k] = sinrnd_hihi; vimlohi_host[k] = sinrnd_lohi; vimlohi_device[k] = sinrnd_lohi; vimhilo_host[k] = sinrnd_hilo; vimhilo_device[k] = sinrnd_hilo; vimlolo_host[k] = sinrnd_lolo; vimlolo_device[k] = sinrnd_lolo; } }
utf-8
1
GPL-3+
2013-2021 Jan Verschelde
postgresql-14-14.2/src/include/fe_utils/connect_utils.h
/*------------------------------------------------------------------------- * * Facilities for frontend code to connect to and disconnect from databases. * * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/fe_utils/connect_utils.h * *------------------------------------------------------------------------- */ #ifndef CONNECT_UTILS_H #define CONNECT_UTILS_H #include "libpq-fe.h" enum trivalue { TRI_DEFAULT, TRI_NO, TRI_YES }; /* Parameters needed by connectDatabase/connectMaintenanceDatabase */ typedef struct _connParams { /* These fields record the actual command line parameters */ const char *dbname; /* this may be a connstring! */ const char *pghost; const char *pgport; const char *pguser; enum trivalue prompt_password; /* If not NULL, this overrides the dbname obtained from command line */ /* (but *only* the DB name, not anything else in the connstring) */ const char *override_dbname; } ConnParams; extern PGconn *connectDatabase(const ConnParams *cparams, const char *progname, bool echo, bool fail_ok, bool allow_password_reuse); extern PGconn *connectMaintenanceDatabase(ConnParams *cparams, const char *progname, bool echo); extern void disconnectDatabase(PGconn *conn); #endif /* CONNECT_UTILS_H */
utf-8
1
PostgreSQL
Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group Portions Copyright (c) 1994, The Regents of the University of California
yodl-4.03.02/strvector/strvector.h
typedef struct StrVectorPair { char *d_key; char *d_value; } StrVectorPair; typedef struct StrVector { size_t d_capacity; size_t d_size; StrVectorPair **d_pair; } StrVector; void strVector_construct(StrVector *strVector); void strVector_destruct(StrVector *strVector); void strVector_add(StrVector *sv, char const *key, char const *value); int strVector_find(StrVector const *sv, char const *key); static inline StrVectorPair const *strVector_index( StrVector const *sv, size_t idx) { return sv->d_pair[idx]; }
utf-8
1
GPL-2+
1996-1999 Karel Kubat <karel@icce.rug.nl> (original author), 1996-1999, 2004-2021 Frank B. Brokken <f.b.brokken@rug.nl>, 1996-1999, Jan Nieuwenhuizen <janneke@gnu.org>
cctbx-2021.12+ds1/mmtbx/masks/atom_mask.h
#ifndef MMTBX_MASKS_ATOM_MASK_H #define MMTBX_MASKS_ATOM_MASK_H #include <mmtbx/error.h> #include <cctbx/uctbx.h> #include <cctbx/sgtbx/space_group_type.h> #include <cctbx/sgtbx/direct_space_asu/proto/direct_space_asu.h> #include <cctbx/sgtbx/direct_space_asu/proto/small_vec_math.h> #include <cctbx/miller.h> #include <scitbx/array_family/versa.h> #include <scitbx/array_family/accessors/c_interval_grid.h> #include <cctbx/maptbx/structure_factors.h> namespace mmtbx { //! Masks for bulk solvent modelling /*! Mask calculations are based on the following paper. Jiang, J.-S. & Brunger, A. T. (1994). J. Mol. Biol. 243, 100-115. "Protein hydration observed by X-ray diffraction. Solvation properties of penicillopepsin and neuraminidase crystal structures." */ namespace masks { namespace af = scitbx::af; // TODO: this needs to be removed using cctbx::sgtbx::asu::direct_space_asu; typedef af::shared< scitbx::double3 > coord_array_t; typedef af::shared< double > double_array_t; typedef af::c_interval_grid<3> asu_grid_t; typedef af::c_interval_grid<3> grid_t; //! Maximum number of mask layers const unsigned char max_n_layers = 10; // the radial shell mask contains two numbers for each point // shell number and multiplicity of the point class mask_value { static const unsigned char outside_layer = max_n_layers+10; static const unsigned char outside_multiplicity = 255U; BOOST_STATIC_ASSERT( (outside_multiplicity >0U) && (outside_multiplicity > 192U) && (outside_layer > 0U) && (outside_layer > (max_n_layers+1)) ); public: mask_value() {} mask_value(unsigned char l, unsigned char v) : layer_(l), multiplicity_(v) {} unsigned char layer() const { return layer_; } unsigned char multiplicity() const { return multiplicity_; } bool is_outside() const { return multiplicity()==outside_multiplicity; } bool is_solvent() const { return layer()>1U; } bool is_contact() const { return layer()==1; } bool is_atom() const { return multiplicity()==0U; } bool is_zero() const { return multiplicity()==0U && layer()==0U;} void set(unsigned char l, unsigned char v) {layer_=l; multiplicity_=v;} void set_outside() { this->set(outside_layer, outside_multiplicity); } void set_zero() { this->set(0,0); } void set_nearest_solvent() { layer_=2; } bool is_valid_for_fft() const { return multiplicity()<outside_multiplicity && layer()!=1U && layer()<outside_layer; } static bool is_group_compatible(unsigned group_order) { return outside_multiplicity > group_order; } private: unsigned char layer_; unsigned char multiplicity_; }; typedef mask_value data_type; namespace { BOOST_STATIC_ASSERT( sizeof(mask_value)==2 ); } typedef af::versa<data_type, grid_t > mask_array_t; typedef af::versa<data_type, asu_grid_t > mask_asu_array_t; typedef std::vector<double> shells_array_t; // TODO: to make the following work need adaptor to python for small_plain // typedef scitbx::af::small_plain<double, max_n_layers-1> shells_array_t; //! Radial shell flat solvent mask and structure factors. /*! \class atom_mask atom_mask.h mmtbx/masks/atom_mask.h This mask will have valid values only inside asymmetric unit. Outside they will be zero. Inside the asu 0 - means macromolecule, non-zero - solvent. */ class atom_mask { public: //! Allocates memory for mask calculation. /*! gridding_n_real must be compatible with the space_group. * At least the following must be true: every grid point has * to be transformed into grid point by every symmetry operator * of the group. */ atom_mask( const cctbx::uctbx::unit_cell & unit_cell, const cctbx::sgtbx::space_group &group_, const grid_t::index_type & gridding_n_real, double solvent_radius_, double shrink_truncation_radius_) : solvent_radius(solvent_radius_), shrink_truncation_radius(shrink_truncation_radius_), accessible_surface_fraction(-1.0), contact_surface_fraction(-1.0), asu(group_.type()), cell(unit_cell), group(group_), n_layers(0) { MMTBX_ASSERT( mask_value::is_group_compatible(group.order_z()) ); MMTBX_ASSERT(solvent_radius >= 0.0); MMTBX_ASSERT(shrink_truncation_radius >= 0.0); MMTBX_ASSERT(gridding_n_real.const_ref().all_gt(0)); this->full_cell_grid_size = scitbx::int3(gridding_n_real); this->determine_boundaries(); // also allocates memory // TODO: ? put more computation here, eg.: mask_asu } //! Allocates memory for mask calculation. /*! This constructor will calculate grid size appropriate for the * spacegroup based on resolution and grid_step_factor. */ atom_mask( const cctbx::uctbx::unit_cell & unit_cell, const cctbx::sgtbx::space_group &group_, double resolution, double grid_step_factor = 4.0, double solvent_radius_ = 1.11, double shrink_truncation_radius_ = 0.9) : solvent_radius(solvent_radius_), shrink_truncation_radius(shrink_truncation_radius_), accessible_surface_fraction(-1.0), contact_surface_fraction(-1.0), asu(group_.type()), cell(unit_cell), group(group_), asu_atoms(), n_layers(0) { MMTBX_ASSERT( mask_value::is_group_compatible(group.order_z()) ); MMTBX_ASSERT(solvent_radius >= 0.0); MMTBX_ASSERT(shrink_truncation_radius >= 0.0); this->determine_gridding(this->full_cell_grid_size, resolution, grid_step_factor); this->determine_boundaries(); // also allocates memory // TODO: ? put more computation here, eg.: mask_asu } // DO NOT USE!!! This For debugging purposes only. atom_mask( const cctbx::uctbx::unit_cell & unit_cell, const cctbx::sgtbx::space_group &group_, const cctbx::sgtbx::asu::direct_space_asu &asu_, double resolution, double grid_step_factor = 4.0, double solvent_radius_ = 1.11, double shrink_truncation_radius_ = 0.9) : solvent_radius(solvent_radius_), shrink_truncation_radius(shrink_truncation_radius_), accessible_surface_fraction(-1.0), contact_surface_fraction(-1.0), asu(asu_), cell(unit_cell), group(group_), asu_atoms(), n_layers(0) { MMTBX_ASSERT( mask_value::is_group_compatible(group.order_z()) ); MMTBX_ASSERT(solvent_radius >= 0.0); MMTBX_ASSERT(shrink_truncation_radius >= 0.0); this->determine_gridding(this->full_cell_grid_size, resolution, grid_step_factor); this->determine_boundaries(); // also allocates memory // TODO: ? put more computation here, eg.: mask_asu } // TODO: DO NOT USE!!! atom_mask( const cctbx::uctbx::unit_cell & unit_cell, const cctbx::sgtbx::space_group &group_, const cctbx::sgtbx::asu::direct_space_asu &asu_, const grid_t::index_type & gridding_n_real, double solvent_radius_=1.11, double shrink_truncation_radius_=0.9) : solvent_radius(solvent_radius_), shrink_truncation_radius(shrink_truncation_radius_), accessible_surface_fraction(-1.0), contact_surface_fraction(-1.0), asu(asu_), cell(unit_cell), group(group_), n_layers(0) { MMTBX_ASSERT( mask_value::is_group_compatible(group.order_z()) ); MMTBX_ASSERT(solvent_radius >= 0.0); MMTBX_ASSERT(shrink_truncation_radius >= 0.0); MMTBX_ASSERT(gridding_n_real.const_ref().all_gt(0)); this->full_cell_grid_size = scitbx::int3(gridding_n_real); this->determine_boundaries(); // also allocates memory // TODO: ? put more computation here, eg.: mask_asu } //! Clears current, and calculates new mask based on atomic data. /*! Number of masks produced is equal to shells.size() + 1. \param sites_frac array of atoms coordinates \param atom_radii array of atoms radii \param shells array of widths of radial masks */ void compute( const coord_array_t & sites_frac, const double_array_t & atom_radii, const shells_array_t &shells = shells_array_t() ); const mask_array_t & get_mask() const { return data; } af::versa<double, af::c_grid_padded<3> > mask_data_whole_uc( unsigned char layer = 0); //! Computes mask structure factors. /*! \param indices array of miller indices \param layer mask layer for wich structure factors will be caculated. Range: [1,n_solvent_layers()]. 1 - closest to the atoms; n_solvent_layers() - fartherst from the atoms. */ scitbx::af::shared< std::complex<double> > structure_factors( const scitbx::af::const_ref< cctbx::miller::index<> > &indices, unsigned char layer = 0); //! Returns x,y,z dimensions of the full cell grid. scitbx::int3 grid_size() const { return full_cell_grid_size; } size_t grid_size_1d() const { MMTBX_ASSERT( scitbx::ge_all(this->grid_size(), scitbx::int3(0,0,0)) ); return static_cast<size_t>(this->grid_size()[0]) * static_cast<size_t>(this->grid_size()[1]) * static_cast<size_t>(this->grid_size()[2]); } //! Returns asu boundaries void get_asu_boundaries(scitbx::int3 &low, scitbx::int3 &high) const; //! Returns asu boundaries expanded by shrink truncation radius void get_expanded_asu_boundaries(scitbx::int3 &low, scitbx::int3 &high) const; //! Returns asu boundaries expanded by shrink truncation radius void get_expanded_asu_boundaries(scitbx::double3 &low, scitbx::double3 &high) const; //! Returns estimated number of atoms intersecting with the asu size_t n_asu_atoms() const { return asu_atoms.size(); } //! Returns reference to direct space asymmetric unit const cctbx::sgtbx::asu::direct_space_asu &get_asu() const { return asu; } //! Returns reference to the space group const cctbx::sgtbx::space_group &space_group() const { return group; } //! Returns number of solvent layers for which mask has been computed unsigned char n_solvent_layers() { return n_layers; } //! Saves asymmetric part of the mask in xplor format void xplor_write_map(std::string const& file_name, unsigned char layer=0, bool invert = false); const double solvent_radius; const double shrink_truncation_radius; //! Solvent volume, if atom radius = vdw_radius + solvent_radius double accessible_surface_fraction; //! Solvent volume double contact_surface_fraction; // execution time in millisecs, DO NOT USE long debug_mask_asu_time, debug_atoms_to_asu_time, debug_accessible_time, debug_contact_time, debug_fft_time; bool debug_has_enclosed_box; // TODO: it should return const ref // but I do not no how to export into python scitbx::af::small<double,max_n_layers> layer_volume_fractions() const { return layer_volume_fractions_; } private: typedef std::pair< scitbx::double3, double > atom_t; typedef std::vector< atom_t > atom_array_t; void compute_contact_surface(); void compute_accessible_surface(const atom_array_t &atoms, const shells_array_t &shells = shells_array_t() ); void mask_asu(); void atoms_to_asu( const coord_array_t & sites_frac, const double_array_t & atom_radii); void determine_gridding(cctbx::sg_vec3 &grid, double resolution, double factor = 4.0) const; void determine_boundaries(); // these 3 should be some kind of safe reference const direct_space_asu asu; const cctbx::uctbx::unit_cell cell; const cctbx::sgtbx::space_group group; scitbx::int3 full_cell_grid_size, asu_low, asu_high; scitbx::double3 expanded_box[2]; atom_array_t asu_atoms; mask_array_t data; // n_layers == n_shells + 1 unsigned short n_layers; scitbx::af::small<double,max_n_layers> layer_volume_fractions_; }; // class atom_mask }} // namespace mmtbx::masks #endif
utf-8
1
BSD-3-clause
2006-2018 The Regents of the University of California, through Lawrence Berkeley National Laboratory 2005 Jacob N. Smith, Erik Mckee, Texas Agricultural 2005 Jacob N. Smith & Erik McKee 2013 Sunset Lake Software 2013-2015 Diamond Light Source 2005-2009 Jim Idle, Temporal Wave LLC 2013 Diamond Light Source, James Parkhurst & Richard Gildea 2016 STFC Rutherford Appleton Laboratory, UK. 1996 John Wiley & Sons, Inc. 2016 Lawrence Berkeley National Laboratory (LBNL) 2007-2011 Jeffrey J. Headd and Robert Immormino 2005-2009 Jim Idle, Temporal Wave LLC 2010 University of California
emscripten-3.1.3~dfsg/tests/third_party/glbook/Chapter_9/Simple_TextureCubemap/Simple_TextureCubemap.c
// // Book: OpenGL(R) ES 2.0 Programming Guide // Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner // ISBN-10: 0321502795 // ISBN-13: 9780321502797 // Publisher: Addison-Wesley Professional // URLs: http://safari.informit.com/9780321563835 // http://www.opengles-book.com // // Simple_TextureCubemap.c // // This is a simple example that draws a sphere with a cubemap image applied. // #include <stdlib.h> #include "esUtil.h" typedef struct { // Handle to a program object GLuint programObject; // Attribute locations GLint positionLoc; GLint normalLoc; // Sampler location GLint samplerLoc; // Texture handle GLuint textureId; // Vertex data int numIndices; GLfloat *vertices; GLfloat *normals; GLushort *indices; GLuint vertPosObject, vertNormalObject, indicesObject; } UserData; /// // Create a simple cubemap with a 1x1 face with a different // color for each face GLuint CreateSimpleTextureCubemap( ) { GLuint textureId; // Six 1x1 RGB faces GLubyte cubePixels[6][3] = { // Face 0 - Red 255, 0, 0, // Face 1 - Green, 0, 255, 0, // Face 3 - Blue 0, 0, 255, // Face 4 - Yellow 255, 255, 0, // Face 5 - Purple 255, 0, 255, // Face 6 - White 255, 255, 255 }; // Generate a texture object glGenTextures ( 1, &textureId ); // Bind the texture object glBindTexture ( GL_TEXTURE_CUBE_MAP, textureId ); // Load the cube face - Positive X glTexImage2D ( GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[0] ); // Load the cube face - Negative X glTexImage2D ( GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[1] ); // Load the cube face - Positive Y glTexImage2D ( GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[2] ); // Load the cube face - Negative Y glTexImage2D ( GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[3] ); // Load the cube face - Positive Z glTexImage2D ( GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[4] ); // Load the cube face - Negative Z glTexImage2D ( GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, &cubePixels[5] ); // Set the filtering mode glTexParameteri ( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri ( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); return textureId; } #include <stdio.h> /// // Initialize the shader and program object // int Init ( ESContext *esContext ) { //esContext->userData = malloc(sizeof(UserData)); UserData *userData = esContext->userData; GLbyte vShaderStr[] = "attribute vec4 a_position; \n" "attribute vec3 a_normal; \n" "varying vec3 v_normal; \n" "void main() \n" "{ \n" " gl_Position = a_position; \n" " v_normal = a_normal; \n" "} \n"; GLbyte fShaderStr[] = "precision mediump float; \n" "varying vec3 v_normal; \n" "uniform samplerCube s_texture; \n" "void main() \n" "{ \n" " gl_FragColor = textureCube( s_texture, v_normal );\n" "} \n"; // Load the shaders and get a linked program object userData->programObject = esLoadProgram ( vShaderStr, fShaderStr ); // Get the attribute locations userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" ); userData->normalLoc = glGetAttribLocation ( userData->programObject, "a_normal" ); // Get the sampler locations userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" ); // Load the texture userData->textureId = CreateSimpleTextureCubemap (); // Generate the vertex data userData->numIndices = esGenSphere ( 20, 0.75f, &userData->vertices, &userData->normals, NULL, &userData->indices ); // Generate the VBOs glGenBuffers(1, &userData->vertPosObject); glBindBuffer(GL_ARRAY_BUFFER, userData->vertPosObject); glBufferData(GL_ARRAY_BUFFER, 21 * 21 * 4 * 3, userData->vertices, GL_STATIC_DRAW ); glGenBuffers(1, &userData->vertNormalObject); glBindBuffer(GL_ARRAY_BUFFER, userData->vertNormalObject ); glBufferData(GL_ARRAY_BUFFER, 21 * 21 * 4 * 3, userData->normals, GL_STATIC_DRAW ); glGenBuffers(1, &userData->indicesObject); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, userData->indicesObject ); glBufferData(GL_ELEMENT_ARRAY_BUFFER, 2 * userData->numIndices, userData->indices, GL_STATIC_DRAW ); glClearColor ( 0.0f, 0.0f, 0.0f, 1.0f ); return GL_TRUE; } /// // Draw a triangle using the shader pair created in Init() // void Draw ( ESContext *esContext ) { UserData *userData = esContext->userData; // Set the viewport glViewport ( 0, 0, esContext->width, esContext->height ); // Clear the color buffer glClear ( GL_COLOR_BUFFER_BIT ); glCullFace ( GL_BACK ); glEnable ( GL_CULL_FACE ); // Use the program object glUseProgram ( userData->programObject ); // Load the vertex position glBindBuffer ( GL_ARRAY_BUFFER, userData->vertPosObject ); glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT, GL_FALSE, 0, 0 ); // Load the normal glBindBuffer ( GL_ARRAY_BUFFER, userData->vertNormalObject ); glVertexAttribPointer ( userData->normalLoc, 3, GL_FLOAT, GL_FALSE, 0, 0 ); glEnableVertexAttribArray ( userData->positionLoc ); glEnableVertexAttribArray ( userData->normalLoc ); // Bind the texture glActiveTexture ( GL_TEXTURE0 ); glBindTexture ( GL_TEXTURE_CUBE_MAP, userData->textureId ); // Set the sampler texture unit to 0 glUniform1i ( userData->samplerLoc, 0 ); glBindBuffer ( GL_ELEMENT_ARRAY_BUFFER, userData->indicesObject ); glDrawElements ( GL_TRIANGLES, userData->numIndices, GL_UNSIGNED_SHORT, 0 ); } /// // Cleanup // void ShutDown ( ESContext *esContext ) { UserData *userData = esContext->userData; // Delete texture object glDeleteTextures ( 1, &userData->textureId ); // Delete program object glDeleteProgram ( userData->programObject ); free ( userData->vertices ); free ( userData->normals ); //free ( esContext->userData); } int main ( int argc, char *argv[] ) { ESContext esContext; UserData userData; esInitContext ( &esContext ); esContext.userData = &userData; esCreateWindow ( &esContext, "Simple Texture Cubemap", 320, 240, ES_WINDOW_RGB ); if ( !Init ( &esContext ) ) return 0; esRegisterDrawFunc ( &esContext, Draw ); esMainLoop ( &esContext ); ShutDown ( &esContext ); }
utf-8
1
Expat or NCSA~Mozilla
2010-2022 The Emscripten Authors
qtwebengine-opensource-src-5.15.8+dfsg/src/3rdparty/chromium/ui/gfx/canvas_paint_mac.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_CANVAS_PAINT_MAC_H_ #define UI_GFX_CANVAS_PAINT_MAC_H_ #include "skia/ext/platform_canvas.h" #include "ui/gfx/canvas.h" #import <Cocoa/Cocoa.h> namespace gfx { // A class designed to translate skia painting into a region to the current // graphics context. On construction, it will set up a context for painting // into, and on destruction, it will commit it to the current context. // Note: The created context is always inialized to (0, 0, 0, 0). class GFX_EXPORT CanvasSkiaPaint : public Canvas { public: // This constructor assumes the result is opaque. explicit CanvasSkiaPaint(NSRect dirtyRect); CanvasSkiaPaint(NSRect dirtyRect, bool opaque); ~CanvasSkiaPaint() override; // If true, the data painted into the CanvasSkiaPaint is blended onto the // current context, else it is copied. void set_composite_alpha(bool composite_alpha) { composite_alpha_ = composite_alpha; } // Returns true if the invalid region is empty. The caller should call this // function to determine if anything needs painting. bool is_empty() const { return NSIsEmptyRect(rectangle_); } const NSRect& rectangle() const { return rectangle_; } private: void Init(bool opaque); NSRect rectangle_; // See description above setter. bool composite_alpha_; // Disallow copy and assign. CanvasSkiaPaint(const CanvasSkiaPaint&); CanvasSkiaPaint& operator=(const CanvasSkiaPaint&); }; } // namespace gfx #endif // UI_GFX_CANVAS_PAINT_MAC_H_
utf-8
1
LGPL-3 or GPL-2
2006-2021 The Chromium Authors 2016-2021 The Qt Company Ltd.
kate-21.08.2/addons/search/htmldelegate.h
/* SPDX-FileCopyrightText: 2011 Kåre Särs <kare.sars@iki.fi> SPDX-License-Identifier: LGPL-2.0-or-later */ #ifndef HTML_DELEGATE_H #define HTML_DELEGATE_H #include <QFont> #include <QStyledItemDelegate> class SPHtmlDelegate : public QStyledItemDelegate { Q_OBJECT public: explicit SPHtmlDelegate(QObject *parent); ~SPHtmlDelegate() override; void paint(QPainter *, const QStyleOptionViewItem &, const QModelIndex &) const override; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; void setDisplayFont(const QFont &font) { m_font = font; } private: QFont m_font; }; #endif
utf-8
1
LGPL-2+
2009, Abhishek Patil <abhishekworld@gmail.com> 2001-2003, Anders Lund <anders.lund@lund.tdcadsl.dk> 2001-2007, Anders Lund <anders@alweb.dk> 2008, Andreas Pakulat <apaku@gmx.de> 2001-2019, Christoph Cullmann <cullmann@kde.org> 2005, Dominik Haumann (dhdev@gmx.de) (documentation) 2013, Dominik Haumann <dhaumann.org> 2014, Dominik Haumann <dhaumann@kde.org> 2014-2018, Gregor Mi <codestruct@posteo.org> 2001-2014, Joseph Wenninger <jowenn@kde.org> 2011-2014, Kåre Särs <kare.sars@iki.fi> 2009-2010, Milian Wolff <mail@milianw.de> 2007, Mirko Stocker <me@misto.ch> 2007, Oswald Buddenhagen <ossi@kde.org> 2007, Robert Gruber <rgruber@users.sourceforge.net> 2002, Simon Hausmann <hausmann@kde.org> 2014, Sven Brauch <svenbrauch@gmail.com> 2010, Thomas Fjellstrom <thomas@fjellstrom.ca> 2001-2002, Daniel.Naber <daniel.naber@t-online.de> 2010, Tomáš Trnka <tomastrnka@gmx.com> 2014, Martin Sandsmark <martin.sandsmark@kde.org> 2017, by Friedrich W. H. Kossebau <kossebau@kde.org> 2017, Héctor Mesa Jiménez <hector@lcc.uma.es> 2018, Tomaz Canabrava <tcanabrava@kde.org>
dietlibc-0.34~cvs20160606/test/sprintf.c
#include <string.h> #include <stdio.h> #include <assert.h> int main() { char buf[1000]; sprintf(buf,"%d",23); assert(!strcmp(buf,"23")); sprintf(buf,"%d",5); assert(!strcmp(buf,"5")); sprintf(buf,"%.2f", 0.05); assert(!strcmp(buf,"0.05")); sprintf(buf,"%f", 9e-6); assert(!strcmp(buf,"0.000009")); sprintf(buf,"%f", 1e-2); assert(!strcmp(buf,"0.010000")); sprintf(buf,"%6d",-1); assert(!strcmp(buf," -1")); strcpy(buf,"foo "); sprintf(buf+strlen(buf),"%s","bar "); strcat(buf,"baz."); assert(!strcmp(buf,"foo bar baz.")); memset(buf,0,100); assert(snprintf(buf,1,"x")==1); assert(!strcmp(buf,"")); assert(snprintf(buf,0,"x")==1); assert(!strcmp(buf,"")); assert(sprintf(buf,"%03o",10)==3); assert(!strcmp(buf,"012")); return 0; }
utf-8
1
GPL-2+
Copyright 2001-2016 Felix von Leitner <felix-dietlibc@fefe.de>
trousers-0.3.14+fixed1/src/include/daa/bi.h
/* * Licensed Materials - Property of IBM * * trousers - An open source TCG Software Stack * * (C) Copyright International Business Machines Corp. 2006 * */ #ifndef BI_H_ #define BI_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> // for the BIGNUM definition #include <openssl/bn.h> #include "list.h" #define INLINE #undef INLINE_DECL #define INLINE_DECL static inline void * (*bi_alloc)(size_t size); // keep the list of allocated memory, usually used for the format functions extern list_ptr allocs; /************************************************************************************ TYPE DEF *************************************************************************************/ #ifdef BI_GMP #include "bi_gmp.h" #endif #ifdef BI_OPENSSL #include "bi_openssl.h" #endif /************************************************************************************ TYPE DEF *************************************************************************************/ struct _bi_array{ bi_ptr *array; int length; }; typedef struct _bi_array bi_array[1]; typedef struct _bi_array *bi_array_ptr; /*********************************************************************************** CONSTANT *************************************************************************************/ extern bi_t bi_0; extern bi_t bi_1; extern bi_t bi_2; /*********************************************************************************** TEMPORARY (WORK) *************************************************************************************/ /* extern bi_t bi_tmp; extern bi_t bi_tmp1; extern bi_t bi_tmp2; extern bi_t bi_tmp3; extern bi_t bi_tmp4; extern bi_t bi_tmp5; extern bi_t bi_tmp6; extern bi_t bi_tmp7; extern bi_t bi_tmp8; extern bi_t bi_tmp9; */ /*********************************************************************************** MACROS *************************************************************************************/ #define ALLOC_BI_ARRAY() (bi_array_ptr)malloc( sizeof( bi_array)) #if 0 #define BI_SAVE( a, b) do { bi_save( a, #a, b); } while(0); #define BI_SAVE_ARRAY( a, b) do { bi_save_array( a, #a, b); } while(0); #define BI_LOAD( a, b) do { bi_load( a, b); } while(0); #define BI_LOAD_ARRAY( a, b) do { bi_load_array( a, b); } while(0); #endif #ifdef BI_DEBUG #define DUMP_BI(field) do { \ fprintf(stderr, "%s=%s [%ld]\n", #field, bi_2_hex_char( field), bi_nbin_size(field));\ } while(0); #define DUMP_BI_ARRAY(field) do { dump_bi_array( #field, field); } while(0); #else #define DUMP_BI(field) #define DUMP_BI_ARRAY(field) #endif /* to free only defines bi_ptr */ #define FREE_BI(a) do { if( (a) != NULL) bi_free_ptr( a); } while(0); /*********************************************************************************** DUMP LIB *************************************************************************************/ char *dump_byte_array(int len, unsigned char *array); /* convert <strings> and return it into a byte array <result> of length <length> */ unsigned char *retrieve_byte_array( int *len, const char *strings); /*********************************************************************************** LIBRARY MANAGEMENT *************************************************************************************/ /* initialize the library bi_alloc_p allocation function used only for exporting a bi struct, so for bi_2_nbin if define as NULL, a stdlib malloc() will be used */ void bi_init( void * (*bi_alloc_p)(size_t size)); /* release resources used by the library */ void bi_release(void); /* return >0 if the library was initialized */ int bi_is_initialized(void); /* free the list of internally allocated memory, usually used for the format functions */ void bi_flush_memory(void); /*********************************************************************************** ALLOCATION & BASIC SETTINGS *************************************************************************************/ /* create a big integer */ bi_ptr bi_new( bi_ptr result); /* create a big integer pointer */ bi_ptr bi_new_ptr(void); /* free resources allocated to the big integer <i> */ void bi_free(const bi_ptr i); /* free resources allocated to the big integer pointer <i> */ void bi_free_ptr(const bi_ptr i); /* return the current number of bits of the number */ long bi_length( const bi_ptr res); /* create a <big integer> array */ void bi_new_array( bi_array_ptr array, const int length); /* create a <big integer> array */ void bi_new_array2( bi_array_ptr array, const int length); /* free resources allocated to the big integer <i> */ void bi_free_array(bi_array_ptr array); /* copy length pointers from the array <src, offset_src> to array <dest, offset_dest> */ void bi_copy_array(bi_array_ptr src, int offset_src, bi_array_ptr dest, int offset_dest, int length); // for debugging void dump_bi_array( char *field, const bi_array_ptr array); /*********************************************************************************** SAFE RANDOM *************************************************************************************/ bi_ptr compute_random_number( bi_ptr result, const bi_ptr element); #if 0 /*********************************************************************************** SAVE / LOAD *************************************************************************************/ /* load an big integer in the already open ("r") file */ void bi_load( bi_ptr bi, FILE *file); /* load an big integer array in the already open ("r") file */ void bi_load_array( bi_array_ptr array, FILE *file); /* save an big integer array in the already open ("w") file */ void bi_save_array( const bi_array_ptr array, const char *name, FILE *file); /* save an big integer in the already open ("w") file */ void bi_save( const bi_ptr bi,const char *name, FILE *file); #endif /*********************************************************************************** CONVERSION *************************************************************************************/ /* dump the big integer as hexadecimal */ char *bi_2_hex_char(const bi_ptr i); /* dump the big integer as decimal */ char *bi_2_dec_char(const bi_ptr i); /* set <i> to the same value as <value> */ /* <i> := <value> */ bi_ptr bi_set( bi_ptr i, const bi_ptr value); /* set <i> with the value represented by given hexadecimal <value> */ /* <i> := <value> */ bi_ptr bi_set_as_hex( bi_ptr i, const char *value); /* set <i> with the value represented by given decimal <value> */ /* <i> := <value> */ bi_ptr bi_set_as_dec( bi_ptr i, const char *value); /* set <i> with the value represented by unsigned int <value> */ /* <i> := <value> */ bi_ptr bi_set_as_si( bi_ptr result, const int value); /* return (long)bi_t */ long bi_get_si(const bi_ptr i); /* return the size of a network byte order representation of <i> */ long bi_nbin_size(const bi_ptr i); /* return a BYTE * - in network byte order - and update the length <length> */ /* the result is allocated internally */ unsigned char *bi_2_nbin( int *length, const bi_ptr i); /* return a BYTE * - in network byte order - and update the length <length> */ /* different from bi_2_nbin: you should reserve enough memory for the storage */ void bi_2_nbin1( int *length, unsigned char *, const bi_ptr i); /* return a bi_ptr that correspond to the big endian encoded BYTE array of length <n_length> */ bi_ptr bi_set_as_nbin( const unsigned long length, const unsigned char *buffer); /* convert <bi> to a byte array of length result, the beginning of this buffer is feel with '0' if needed */ void bi_2_byte_array( unsigned char *result, int length, bi_ptr bi); /* convert a bi to a openssl BIGNUM struct */ BIGNUM *bi_2_BIGNUM( const bi_ptr); /*********************************************************************************** BITS OPERATION *************************************************************************************/ /* set the bit to 1 */ bi_ptr bi_setbit( bi_ptr result, const int bit); /* <result> := <i> << <n> */ bi_ptr bi_shift_left( bi_ptr result, const bi_ptr i, const int n); /* <result> := <i> >> <n> */ bi_ptr bi_shift_right( bi_ptr result, const bi_ptr i, const int n); /*********************************************************************************** NUMBER THEORIE OPERATION *************************************************************************************/ /* create a random of length <length> bits */ /* res := random( length) */ bi_ptr bi_urandom( bi_ptr res, const long length); /* res := <n> mod <m> */ bi_ptr bi_mod(bi_ptr res, const bi_ptr n, const bi_ptr m); /* res := <n> mod <m> */ bi_ptr bi_mod_si(bi_ptr res, const bi_ptr n, const long m); /* generate prime number of <length> bits */ bi_ptr bi_generate_prime( bi_ptr i, const long length); /* return true (>0, bigger is better, but this is contextual to the plugin) if <i> is a probably prime */ int bi_is_probable_prime( const bi_ptr i); /* result := (inverse of <i>) mod <m> */ /* if the inverse exist, return >0, otherwise 0 */ int bi_invert_mod( bi_ptr result, const bi_ptr i, const bi_ptr m); /* generate a safe prime number of <length> bits */ /* by safe we mean a prime p so that (p-1)/2 is also prime */ bi_ptr bi_generate_safe_prime( bi_ptr result, const long bit_length); /* return in <result> the greatest common divisor of <a> and <b> */ /* <result> := gcd( <a>, <b>) */ bi_ptr bi_gcd( bi_ptr result, bi_ptr a, bi_ptr b); /*********************************************************************************** BASIC MATH OPERATION *************************************************************************************/ /* <result> := result++ */ bi_ptr bi_inc(bi_ptr result); /* <result> := result-- */ bi_ptr bi_dec(bi_ptr result); /* <result> := - <result> */ bi_ptr bi_negate( bi_ptr result); /* set <result> by the multiplication of <i> by the long <n> */ /* <result> := <i> * <n> */ bi_ptr bi_mul_si( bi_ptr result, const bi_ptr i, const long n); /* <result> := <i> * <n> */ bi_ptr bi_mul( bi_ptr result, const bi_ptr i, const bi_ptr n); /* set <result> by the division of <i> by the long <n> */ /* <result> := <i> / <n> */ bi_ptr bi_div_si( bi_ptr result, const bi_ptr i, const long n); /* <result> := <i> / <n> */ bi_ptr bi_div( bi_ptr result, const bi_ptr i, const bi_ptr n); /* set <result> by the addition of <i> by the long <n> */ /* <result> := <i> + <n> */ bi_ptr bi_add_si( bi_ptr result, const bi_ptr i, const long n); /* <result> := <i> + <n> */ bi_ptr bi_add( bi_ptr result, const bi_ptr i, const bi_ptr n); /* <result> := <i> - <n> */ bi_ptr bi_sub_si( bi_ptr result, const bi_ptr i, const long n); /* <result> := <i> - <n> */ bi_ptr bi_sub( bi_ptr result, const bi_ptr i, const bi_ptr n); /* <result> := ( <g> ^ <e> ) mod <m> */ bi_ptr bi_mod_exp_si( bi_ptr result, const bi_ptr g, const bi_ptr e, const long m); /* <result> := ( <g> ^ <e> ) mod <m> */ bi_ptr bi_mod_exp( bi_ptr result, const bi_ptr g, const bi_ptr e, const bi_ptr m); /* multiple-exponentiation <result> := mod( Multi( <g>i, <e>i), number of byte <m>) with 0 <= i <= <n> bi_t[] is used for commodity (bi-ptr[] need allocation for each bi_ptr, something made in the stack with bi_t) */ bi_ptr bi_multi_mod_exp( bi_ptr result, const int n, const bi_t g[], const long e[], const int m); /*********************************************************************************** COMPARAISON *************************************************************************************/ /* n1<n2 return negative value n1 = n2 return 0 n1>n2 return positive value */ int bi_cmp( const bi_ptr n1, const bi_ptr n2); /* n1<n2 return negative value n1 = n2 return 0 n1>n2 return positive value */ int bi_cmp_si( const bi_ptr n1, const int n2); /* n1 == n2 return 1 (true) else return 0 */ int bi_equals( const bi_ptr n1, const bi_ptr n2); /* n1 == n2 return 1 (true) else return 0 */ int bi_equals_si( const bi_ptr n1, const int n2); #endif /*BI_H_*/
utf-8
1
unknown
unknown
vast-2021.05.27/libvast/src/system/spawn_archive.cpp
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2018 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #include "vast/system/spawn_archive.hpp" #include "vast/defaults.hpp" #include "vast/error.hpp" #include "vast/logger.hpp" #include "vast/si_literals.hpp" #include "vast/system/archive.hpp" #include "vast/system/node.hpp" #include "vast/system/spawn_arguments.hpp" #include "vast/table_slice.hpp" #include <caf/actor.hpp> #include <caf/actor_cast.hpp> #include <caf/config_value.hpp> #include <caf/expected.hpp> #include <caf/local_actor.hpp> #include <caf/settings.hpp> #include <caf/typed_event_based_actor.hpp> using namespace vast::binary_byte_literals; namespace vast::system { caf::expected<caf::actor> spawn_archive(node_actor::stateful_pointer<node_state> self, spawn_arguments& args) { namespace sd = vast::defaults::system; if (!args.empty()) return unexpected_arguments(args); auto segments = get_or(args.inv.options, "vast.segments", sd::segments); auto max_segment_size = 1_MiB * get_or(args.inv.options, "vast.max-segment-size", sd::max_segment_size); auto handle = self->spawn(archive, args.dir / args.label, segments, max_segment_size); VAST_VERBOSE("{} spawned the archive", self); if (auto [accountant] = self->state.registry.find<accountant_actor>(); accountant) self->send(handle, accountant); return caf::actor_cast<caf::actor>(handle); } } // namespace vast::system
utf-8
1
BSD-3-clause
(c) 2014, Tenzir GmbH
libreoffice-7.3.1~rc1/xmloff/source/text/XMLSectionExport.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #include "XMLSectionExport.hxx" #include <o3tl/any.hxx> #include <rtl/ustring.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/lang/Locale.hpp> #include <com/sun/star/container/XIndexReplace.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/PropertyValues.hpp> #include <com/sun/star/text/XTextSection.hpp> #include <com/sun/star/text/SectionFileLink.hpp> #include <com/sun/star/container/XNamed.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/text/XDocumentIndex.hpp> #include <com/sun/star/text/BibliographyDataField.hpp> #include <com/sun/star/text/XTextFieldsSupplier.hpp> #include <com/sun/star/text/XChapterNumberingSupplier.hpp> #include <com/sun/star/text/ChapterFormat.hpp> #include <comphelper/base64.hxx> #include <xmloff/xmltoken.hxx> #include <xmloff/xmlnamespace.hxx> #include <xmloff/families.hxx> #include <xmloff/xmluconv.hxx> #include <xmloff/namespacemap.hxx> #include <xmloff/xmlexp.hxx> #include <xmloff/xmlement.hxx> #include <txtflde.hxx> using namespace ::com::sun::star; using namespace ::com::sun::star::text; using namespace ::com::sun::star::uno; using namespace ::std; using namespace ::xmloff::token; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::beans::PropertyValues; using ::com::sun::star::container::XIndexReplace; using ::com::sun::star::container::XNameAccess; using ::com::sun::star::container::XNamed; using ::com::sun::star::lang::Locale; XMLSectionExport::XMLSectionExport( SvXMLExport& rExp, XMLTextParagraphExport& rParaExp) : rExport(rExp) , rParaExport(rParaExp) , bHeadingDummiesExported( false ) { } void XMLSectionExport::ExportSectionStart( const Reference<XTextSection> & rSection, bool bAutoStyles) { Reference<XPropertySet> xPropertySet(rSection, UNO_QUERY); // always export section (auto) style if (bAutoStyles) { // get PropertySet and add section style GetParaExport().Add( XmlStyleFamily::TEXT_SECTION, xPropertySet ); } else { // always export section style GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_STYLE_NAME, GetParaExport().Find( XmlStyleFamily::TEXT_SECTION, xPropertySet, "" ) ); // xml:id for RDF metadata GetExport().AddAttributeXmlId(rSection); // export index or regular section Reference<XDocumentIndex> xIndex; if (GetIndex(rSection, xIndex)) { if (xIndex.is()) { // we are an index ExportIndexStart(xIndex); } else { // we are an index header ExportIndexHeaderStart(rSection); } } else { // we are not an index ExportRegularSectionStart(rSection); } } } bool XMLSectionExport::GetIndex( const Reference<XTextSection> & rSection, Reference<XDocumentIndex> & rIndex) { // first, reset result bool bRet = false; rIndex = nullptr; // get section Properties Reference<XPropertySet> xSectionPropSet(rSection, UNO_QUERY); // then check if this section happens to be inside an index if (xSectionPropSet->getPropertySetInfo()-> hasPropertyByName("DocumentIndex")) { Any aAny = xSectionPropSet->getPropertyValue("DocumentIndex"); Reference<XDocumentIndex> xDocumentIndex; aAny >>= xDocumentIndex; // OK, are we inside of an index if (xDocumentIndex.is()) { // is the enclosing index identical with "our" section? Reference<XPropertySet> xIndexPropSet(xDocumentIndex, UNO_QUERY); aAny = xIndexPropSet->getPropertyValue("ContentSection"); Reference<XTextSection> xEnclosingSection; aAny >>= xEnclosingSection; // if the enclosing section is "our" section, then we are an index! if (rSection == xEnclosingSection) { rIndex = xDocumentIndex; bRet = true; } // else: index header or regular section // is the enclosing index identical with the header section? aAny = xIndexPropSet->getPropertyValue("HeaderSection"); // now mis-named: contains header section aAny >>= xEnclosingSection; // if the enclosing section is "our" section, then we are an index! if (rSection == xEnclosingSection) { bRet = true; } // else: regular section } // else: we aren't even inside of an index } // else: we don't even know what an index is. return bRet; } void XMLSectionExport::ExportSectionEnd( const Reference<XTextSection> & rSection, bool bAutoStyles) { // no end section for styles if (bAutoStyles) return; enum XMLTokenEnum eElement = XML_TOKEN_INVALID; // export index or regular section end Reference<XDocumentIndex> xIndex; if (GetIndex(rSection, xIndex)) { if (xIndex.is()) { // index end: close index body element GetExport().EndElement( XML_NAMESPACE_TEXT, XML_INDEX_BODY, true ); GetExport().IgnorableWhitespace(); switch (MapSectionType(xIndex->getServiceName())) { case TEXT_SECTION_TYPE_TOC: eElement = XML_TABLE_OF_CONTENT; break; case TEXT_SECTION_TYPE_ILLUSTRATION: eElement = XML_ILLUSTRATION_INDEX; break; case TEXT_SECTION_TYPE_ALPHABETICAL: eElement = XML_ALPHABETICAL_INDEX; break; case TEXT_SECTION_TYPE_TABLE: eElement = XML_TABLE_INDEX; break; case TEXT_SECTION_TYPE_OBJECT: eElement = XML_OBJECT_INDEX; break; case TEXT_SECTION_TYPE_USER: eElement = XML_USER_INDEX; break; case TEXT_SECTION_TYPE_BIBLIOGRAPHY: eElement = XML_BIBLIOGRAPHY; break; default: OSL_FAIL("unknown index type"); // default: skip index! break; } } else { eElement = XML_INDEX_TITLE; } } else { eElement = XML_SECTION; } if (XML_TOKEN_INVALID != eElement) { // any old attributes? GetExport().CheckAttrList(); // element surrounded by whitespace GetExport().EndElement( XML_NAMESPACE_TEXT, eElement, true); GetExport().IgnorableWhitespace(); } else { OSL_FAIL("Need element name!"); } // else: autostyles -> ignore } void XMLSectionExport::ExportIndexStart( const Reference<XDocumentIndex> & rIndex) { // get PropertySet Reference<XPropertySet> xPropertySet(rIndex, UNO_QUERY); switch (MapSectionType(rIndex->getServiceName())) { case TEXT_SECTION_TYPE_TOC: ExportTableOfContentStart(xPropertySet); break; case TEXT_SECTION_TYPE_ILLUSTRATION: ExportIllustrationIndexStart(xPropertySet); break; case TEXT_SECTION_TYPE_ALPHABETICAL: ExportAlphabeticalIndexStart(xPropertySet); break; case TEXT_SECTION_TYPE_TABLE: ExportTableIndexStart(xPropertySet); break; case TEXT_SECTION_TYPE_OBJECT: ExportObjectIndexStart(xPropertySet); break; case TEXT_SECTION_TYPE_USER: ExportUserIndexStart(xPropertySet); break; case TEXT_SECTION_TYPE_BIBLIOGRAPHY: ExportBibliographyStart(xPropertySet); break; default: // skip index OSL_FAIL("unknown index type"); break; } } void XMLSectionExport::ExportIndexHeaderStart( const Reference<XTextSection> & rSection) { // export name, dammit! Reference<XNamed> xName(rSection, UNO_QUERY); GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_NAME, xName->getName()); // format already handled -> export only start element GetExport().StartElement( XML_NAMESPACE_TEXT, XML_INDEX_TITLE, true ); GetExport().IgnorableWhitespace(); } SvXMLEnumStringMapEntry<SectionTypeEnum> const aIndexTypeMap[] = { ENUM_STRING_MAP_ENTRY( "com.sun.star.text.ContentIndex", TEXT_SECTION_TYPE_TOC ), ENUM_STRING_MAP_ENTRY( "com.sun.star.text.DocumentIndex", TEXT_SECTION_TYPE_ALPHABETICAL ), ENUM_STRING_MAP_ENTRY( "com.sun.star.text.TableIndex", TEXT_SECTION_TYPE_TABLE ), ENUM_STRING_MAP_ENTRY( "com.sun.star.text.ObjectIndex", TEXT_SECTION_TYPE_OBJECT ), ENUM_STRING_MAP_ENTRY( "com.sun.star.text.Bibliography", TEXT_SECTION_TYPE_BIBLIOGRAPHY ), ENUM_STRING_MAP_ENTRY( "com.sun.star.text.UserIndex", TEXT_SECTION_TYPE_USER ), ENUM_STRING_MAP_ENTRY( "com.sun.star.text.IllustrationsIndex", TEXT_SECTION_TYPE_ILLUSTRATION ), { nullptr, 0, SectionTypeEnum(0) } }; enum SectionTypeEnum XMLSectionExport::MapSectionType( std::u16string_view rServiceName) { enum SectionTypeEnum eType = TEXT_SECTION_TYPE_UNKNOWN; SvXMLUnitConverter::convertEnum(eType, rServiceName, aIndexTypeMap); // TODO: index header section types, etc. return eType; } void XMLSectionExport::ExportRegularSectionStart( const Reference<XTextSection> & rSection) { // style name already handled in ExportSectionStart(...) Reference<XNamed> xName(rSection, UNO_QUERY); GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_NAME, xName->getName()); // get XPropertySet for other values Reference<XPropertySet> xPropSet(rSection, UNO_QUERY); // condition and display Any aAny = xPropSet->getPropertyValue("Condition"); OUString sCond; aAny >>= sCond; enum XMLTokenEnum eDisplay = XML_TOKEN_INVALID; if (!sCond.isEmpty()) { OUString sQValue = GetExport().GetNamespaceMap().GetQNameByKey( XML_NAMESPACE_OOOW, sCond, false ); GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_CONDITION, sQValue); eDisplay = XML_CONDITION; // #97450# store hidden-status (of conditional sections only) aAny = xPropSet->getPropertyValue("IsCurrentlyVisible"); if (! *o3tl::doAccess<bool>(aAny)) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_IS_HIDDEN, XML_TRUE); } } else { eDisplay = XML_NONE; } aAny = xPropSet->getPropertyValue("IsVisible"); if (! *o3tl::doAccess<bool>(aAny)) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_DISPLAY, eDisplay); } // protect + protection key aAny = xPropSet->getPropertyValue("IsProtected"); if (*o3tl::doAccess<bool>(aAny)) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_PROTECTED, XML_TRUE); } Sequence<sal_Int8> aPassword; xPropSet->getPropertyValue("ProtectionKey") >>= aPassword; if (aPassword.hasElements()) { OUStringBuffer aBuffer; ::comphelper::Base64::encode(aBuffer, aPassword); // in ODF 1.0/1.1 the algorithm was left unspecified so we can write anything GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_PROTECTION_KEY, aBuffer.makeStringAndClear()); if (aPassword.getLength() == 32 && GetExport().getSaneDefaultVersion() >= SvtSaveOptions::ODFSVER_012) { // attribute exists in ODF 1.2 or later; default is SHA1 so no need to write that GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_PROTECTION_KEY_DIGEST_ALGORITHM, // write the URL from ODF 1.2, not the W3C one "http://www.w3.org/2000/09/xmldsig#sha256"); } } // export element GetExport().IgnorableWhitespace(); GetExport().StartElement( XML_NAMESPACE_TEXT, XML_SECTION, true ); // data source // unfortunately, we have to test all relevant strings for non-zero length aAny = xPropSet->getPropertyValue("FileLink"); SectionFileLink aFileLink; aAny >>= aFileLink; aAny = xPropSet->getPropertyValue("LinkRegion"); OUString sRegionName; aAny >>= sRegionName; if ( !aFileLink.FileURL.isEmpty() || !aFileLink.FilterName.isEmpty() || !sRegionName.isEmpty()) { if (!aFileLink.FileURL.isEmpty()) { GetExport().AddAttribute(XML_NAMESPACE_XLINK, XML_HREF, GetExport().GetRelativeReference( aFileLink.FileURL) ); } if (!aFileLink.FilterName.isEmpty()) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_FILTER_NAME, aFileLink.FilterName); } if (!sRegionName.isEmpty()) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_SECTION_NAME, sRegionName); } SvXMLElementExport aElem(GetExport(), XML_NAMESPACE_TEXT, XML_SECTION_SOURCE, true, true); } else { // check for DDE first if (xPropSet->getPropertySetInfo()->hasPropertyByName("DDECommandFile")) { // data source DDE // unfortunately, we have to test all relevant strings for // non-zero length aAny = xPropSet->getPropertyValue("DDECommandFile"); OUString sApplication; aAny >>= sApplication; aAny = xPropSet->getPropertyValue("DDECommandType"); OUString sTopic; aAny >>= sTopic; aAny = xPropSet->getPropertyValue("DDECommandElement"); OUString sItem; aAny >>= sItem; if ( !sApplication.isEmpty() || !sTopic.isEmpty() || !sItem.isEmpty()) { GetExport().AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_APPLICATION, sApplication); GetExport().AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_TOPIC, sTopic); GetExport().AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_ITEM, sItem); aAny = xPropSet->getPropertyValue("IsAutomaticUpdate"); if (*o3tl::doAccess<bool>(aAny)) { GetExport().AddAttribute(XML_NAMESPACE_OFFICE, XML_AUTOMATIC_UPDATE, XML_TRUE); } SvXMLElementExport aElem(GetExport(), XML_NAMESPACE_OFFICE, XML_DDE_SOURCE, true, true); } // else: no DDE data source } // else: no DDE on this system } } void XMLSectionExport::ExportTableOfContentStart( const Reference<XPropertySet> & rPropertySet) { // export TOC element start ExportBaseIndexStart(XML_TABLE_OF_CONTENT, rPropertySet); // scope for table-of-content-source element { // TOC specific index source attributes: // outline-level: 1..10 sal_Int16 nLevel = sal_Int16(); if( rPropertySet->getPropertyValue("Level") >>= nLevel ) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_OUTLINE_LEVEL, OUString::number(nLevel)); } // use outline level ExportBoolean(rPropertySet, "CreateFromOutline", XML_USE_OUTLINE_LEVEL, true); // use index marks ExportBoolean(rPropertySet, "CreateFromMarks", XML_USE_INDEX_MARKS, true); // use level styles ExportBoolean(rPropertySet, "CreateFromLevelParagraphStyles", XML_USE_INDEX_SOURCE_STYLES, false); ExportBaseIndexSource(TEXT_SECTION_TYPE_TOC, rPropertySet); } ExportBaseIndexBody(TEXT_SECTION_TYPE_TOC, rPropertySet); } void XMLSectionExport::ExportObjectIndexStart( const Reference<XPropertySet> & rPropertySet) { // export index start ExportBaseIndexStart(XML_OBJECT_INDEX, rPropertySet); // scope for index source element { ExportBoolean(rPropertySet, "CreateFromOtherEmbeddedObjects", XML_USE_OTHER_OBJECTS, false); ExportBoolean(rPropertySet, "CreateFromStarCalc", XML_USE_SPREADSHEET_OBJECTS, false); ExportBoolean(rPropertySet, "CreateFromStarChart", XML_USE_CHART_OBJECTS, false); ExportBoolean(rPropertySet, "CreateFromStarDraw", XML_USE_DRAW_OBJECTS, false); ExportBoolean(rPropertySet, "CreateFromStarMath", XML_USE_MATH_OBJECTS, false); ExportBaseIndexSource(TEXT_SECTION_TYPE_OBJECT, rPropertySet); } ExportBaseIndexBody(TEXT_SECTION_TYPE_OBJECT, rPropertySet); } void XMLSectionExport::ExportIllustrationIndexStart( const Reference<XPropertySet> & rPropertySet) { // export index start ExportBaseIndexStart(XML_ILLUSTRATION_INDEX, rPropertySet); // scope for index source element { // export common attributes for illustration and table indices ExportTableAndIllustrationIndexSourceAttributes(rPropertySet); ExportBaseIndexSource(TEXT_SECTION_TYPE_ILLUSTRATION, rPropertySet); } ExportBaseIndexBody(TEXT_SECTION_TYPE_ILLUSTRATION, rPropertySet); } void XMLSectionExport::ExportTableIndexStart( const Reference<XPropertySet> & rPropertySet) { // export index start ExportBaseIndexStart(XML_TABLE_INDEX, rPropertySet); // scope for index source element { // export common attributes for illustration and table indices ExportTableAndIllustrationIndexSourceAttributes(rPropertySet); ExportBaseIndexSource(TEXT_SECTION_TYPE_TABLE, rPropertySet); } ExportBaseIndexBody(TEXT_SECTION_TYPE_TABLE, rPropertySet); } void XMLSectionExport::ExportAlphabeticalIndexStart( const Reference<XPropertySet> & rPropertySet) { // export TOC element start ExportBaseIndexStart(XML_ALPHABETICAL_INDEX, rPropertySet); // scope for table-of-content-source element { // style name (if present) Any aAny = rPropertySet->getPropertyValue("MainEntryCharacterStyleName"); OUString sStyleName; aAny >>= sStyleName; if (!sStyleName.isEmpty()) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_MAIN_ENTRY_STYLE_NAME, GetExport().EncodeStyleName( sStyleName )); } // other (boolean) attributes ExportBoolean(rPropertySet, "IsCaseSensitive", XML_IGNORE_CASE, false, true); ExportBoolean(rPropertySet, "UseAlphabeticalSeparators", XML_ALPHABETICAL_SEPARATORS, false); ExportBoolean(rPropertySet, "UseCombinedEntries", XML_COMBINE_ENTRIES, true); ExportBoolean(rPropertySet, "UseDash", XML_COMBINE_ENTRIES_WITH_DASH, false); ExportBoolean(rPropertySet, "UseKeyAsEntry", XML_USE_KEYS_AS_ENTRIES, false); ExportBoolean(rPropertySet, "UsePP", XML_COMBINE_ENTRIES_WITH_PP, true); ExportBoolean(rPropertySet, "UseUpperCase", XML_CAPITALIZE_ENTRIES, false); ExportBoolean(rPropertySet, "IsCommaSeparated", XML_COMMA_SEPARATED, false); // sort algorithm aAny = rPropertySet->getPropertyValue("SortAlgorithm"); OUString sAlgorithm; aAny >>= sAlgorithm; if (!sAlgorithm.isEmpty()) { GetExport().AddAttribute( XML_NAMESPACE_TEXT, XML_SORT_ALGORITHM, sAlgorithm ); } // locale aAny = rPropertySet->getPropertyValue("Locale"); Locale aLocale; aAny >>= aLocale; GetExport().AddLanguageTagAttributes( XML_NAMESPACE_FO, XML_NAMESPACE_STYLE, aLocale, true); ExportBaseIndexSource(TEXT_SECTION_TYPE_ALPHABETICAL, rPropertySet); } ExportBaseIndexBody(TEXT_SECTION_TYPE_ALPHABETICAL, rPropertySet); } void XMLSectionExport::ExportUserIndexStart( const Reference<XPropertySet> & rPropertySet) { // export TOC element start ExportBaseIndexStart(XML_USER_INDEX, rPropertySet); // scope for table-of-content-source element { // bool attributes ExportBoolean(rPropertySet, "CreateFromEmbeddedObjects", XML_USE_OBJECTS, false); ExportBoolean(rPropertySet, "CreateFromGraphicObjects", XML_USE_GRAPHICS, false); ExportBoolean(rPropertySet, "CreateFromMarks", XML_USE_INDEX_MARKS, false); ExportBoolean(rPropertySet, "CreateFromTables", XML_USE_TABLES, false); ExportBoolean(rPropertySet, "CreateFromTextFrames", XML_USE_FLOATING_FRAMES, false); ExportBoolean(rPropertySet, "UseLevelFromSource", XML_COPY_OUTLINE_LEVELS, false); ExportBoolean(rPropertySet, "CreateFromLevelParagraphStyles", XML_USE_INDEX_SOURCE_STYLES, false); Any aAny = rPropertySet->getPropertyValue( "UserIndexName" ); OUString sIndexName; aAny >>= sIndexName; GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_INDEX_NAME, sIndexName); ExportBaseIndexSource(TEXT_SECTION_TYPE_USER, rPropertySet); } ExportBaseIndexBody(TEXT_SECTION_TYPE_USER, rPropertySet); } void XMLSectionExport::ExportBibliographyStart( const Reference<XPropertySet> & rPropertySet) { // export TOC element start ExportBaseIndexStart(XML_BIBLIOGRAPHY, rPropertySet); // scope for table-of-content-source element { // No attributes. Fine. ExportBaseIndexSource(TEXT_SECTION_TYPE_BIBLIOGRAPHY, rPropertySet); } ExportBaseIndexBody(TEXT_SECTION_TYPE_BIBLIOGRAPHY, rPropertySet); } void XMLSectionExport::ExportBaseIndexStart( XMLTokenEnum eElement, const Reference<XPropertySet> & rPropertySet) { // protect + protection key Any aAny = rPropertySet->getPropertyValue("IsProtected"); if (*o3tl::doAccess<bool>(aAny)) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_PROTECTED, XML_TRUE); } // index name OUString sIndexName; rPropertySet->getPropertyValue("Name") >>= sIndexName; if ( !sIndexName.isEmpty() ) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_NAME, sIndexName); } // index Element start GetExport().IgnorableWhitespace(); GetExport().StartElement( XML_NAMESPACE_TEXT, eElement, false ); } const XMLTokenEnum aTypeSourceElementNameMap[] = { XML_TABLE_OF_CONTENT_SOURCE, // TOC XML_TABLE_INDEX_SOURCE, // table index XML_ILLUSTRATION_INDEX_SOURCE, // illustration index XML_OBJECT_INDEX_SOURCE, // object index XML_USER_INDEX_SOURCE, // user index XML_ALPHABETICAL_INDEX_SOURCE, // alphabetical index XML_BIBLIOGRAPHY_SOURCE // bibliography }; void XMLSectionExport::ExportBaseIndexSource( SectionTypeEnum eType, const Reference<XPropertySet> & rPropertySet) { // check type OSL_ENSURE(eType >= TEXT_SECTION_TYPE_TOC, "illegal index type"); OSL_ENSURE(eType <= TEXT_SECTION_TYPE_BIBLIOGRAPHY, "illegal index type"); Any aAny; // common attributes; not supported by bibliography if (eType != TEXT_SECTION_TYPE_BIBLIOGRAPHY) { // document or chapter index? aAny = rPropertySet->getPropertyValue("CreateFromChapter"); if (*o3tl::doAccess<bool>(aAny)) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_INDEX_SCOPE, XML_CHAPTER); } // tab-stops relative to margin? aAny = rPropertySet->getPropertyValue("IsRelativeTabstops"); if (! *o3tl::doAccess<bool>(aAny)) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_RELATIVE_TAB_STOP_POSITION, XML_FALSE); } } // the index source element (all indices) SvXMLElementExport aElem(GetExport(), XML_NAMESPACE_TEXT, GetXMLToken( aTypeSourceElementNameMap[ eType - TEXT_SECTION_TYPE_TOC]), true, true); // scope for title template (all indices) { // header style name aAny = rPropertySet->getPropertyValue("ParaStyleHeading"); OUString sStyleName; aAny >>= sStyleName; GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_STYLE_NAME, GetExport().EncodeStyleName( sStyleName )); // title template SvXMLElementExport aHeaderTemplate(GetExport(), XML_NAMESPACE_TEXT, XML_INDEX_TITLE_TEMPLATE, true, false); // title as element content aAny = rPropertySet->getPropertyValue("Title"); OUString sTitleString; aAny >>= sTitleString; GetExport().Characters(sTitleString); } // export level templates (all indices) aAny = rPropertySet->getPropertyValue("LevelFormat"); Reference<XIndexReplace> xLevelTemplates; aAny >>= xLevelTemplates; // iterate over level formats; // skip element 0 (empty template for title) sal_Int32 nLevelCount = xLevelTemplates->getCount(); for(sal_Int32 i = 1; i<nLevelCount; i++) { // get sequence Sequence<PropertyValues> aTemplateSequence; aAny = xLevelTemplates->getByIndex(i); aAny >>= aTemplateSequence; // export the sequence (abort export if an error occurred; #91214#) bool bResult = ExportIndexTemplate(eType, i, rPropertySet, aTemplateSequence); if ( !bResult ) break; } // only TOC and user index: // styles from which to build the index (LevelParagraphStyles) if ( (TEXT_SECTION_TYPE_TOC == eType) || (TEXT_SECTION_TYPE_USER == eType) ) { aAny = rPropertySet->getPropertyValue("LevelParagraphStyles"); Reference<XIndexReplace> xLevelParagraphStyles; aAny >>= xLevelParagraphStyles; ExportLevelParagraphStyles(xLevelParagraphStyles); } } void XMLSectionExport::ExportBaseIndexBody( SectionTypeEnum eType, const Reference<XPropertySet> &) { // type not used; checked anyway. OSL_ENSURE(eType >= TEXT_SECTION_TYPE_TOC, "illegal index type"); OSL_ENSURE(eType <= TEXT_SECTION_TYPE_BIBLIOGRAPHY, "illegal index type"); // export start only // any old attributes? GetExport().CheckAttrList(); // start surrounded by whitespace GetExport().IgnorableWhitespace(); GetExport().StartElement( XML_NAMESPACE_TEXT, XML_INDEX_BODY, true ); } void XMLSectionExport::ExportTableAndIllustrationIndexSourceAttributes( const Reference<XPropertySet> & rPropertySet) { // use caption Any aAny = rPropertySet->getPropertyValue("CreateFromLabels"); if (! *o3tl::doAccess<bool>(aAny)) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_USE_CAPTION, XML_FALSE); } // sequence name aAny = rPropertySet->getPropertyValue("LabelCategory"); OUString sSequenceName; aAny >>= sSequenceName; GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_CAPTION_SEQUENCE_NAME, sSequenceName); // caption format aAny = rPropertySet->getPropertyValue("LabelDisplayType"); sal_Int16 nType = 0; aAny >>= nType; GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_CAPTION_SEQUENCE_FORMAT, XMLTextFieldExport::MapReferenceType(nType)); } // map index of LevelFormats to attribute value; // level 0 is always the header const XMLTokenEnum aLevelNameTOCMap[] = { XML_TOKEN_INVALID, XML_1, XML_2, XML_3, XML_4, XML_5, XML_6, XML_7, XML_8, XML_9, XML_10, XML_TOKEN_INVALID }; const XMLTokenEnum aLevelNameTableMap[] = { XML_TOKEN_INVALID, XML__EMPTY, XML_TOKEN_INVALID }; const XMLTokenEnum aLevelNameAlphaMap[] = { XML_TOKEN_INVALID, XML_SEPARATOR, XML_1, XML_2, XML_3, XML_TOKEN_INVALID }; const XMLTokenEnum aLevelNameBibliographyMap[] = { XML_TOKEN_INVALID, XML_ARTICLE, XML_BOOK, XML_BOOKLET, XML_CONFERENCE, XML_CUSTOM1, XML_CUSTOM2, XML_CUSTOM3, XML_CUSTOM4, XML_CUSTOM5, XML_EMAIL, XML_INBOOK, XML_INCOLLECTION, XML_INPROCEEDINGS, XML_JOURNAL, XML_MANUAL, XML_MASTERSTHESIS, XML_MISC, XML_PHDTHESIS, XML_PROCEEDINGS, XML_TECHREPORT, XML_UNPUBLISHED, XML_WWW, XML_TOKEN_INVALID }; static const XMLTokenEnum* aTypeLevelNameMap[] = { aLevelNameTOCMap, // TOC aLevelNameTableMap, // table index aLevelNameTableMap, // illustration index aLevelNameTableMap, // object index aLevelNameTOCMap, // user index aLevelNameAlphaMap, // alphabetical index aLevelNameBibliographyMap // bibliography }; static const char* aLevelStylePropNameTOCMap[] = { nullptr, "ParaStyleLevel1", "ParaStyleLevel2", "ParaStyleLevel3", "ParaStyleLevel4", "ParaStyleLevel5", "ParaStyleLevel6", "ParaStyleLevel7", "ParaStyleLevel8", "ParaStyleLevel9", "ParaStyleLevel10", nullptr }; static const char* aLevelStylePropNameTableMap[] = { nullptr, "ParaStyleLevel1", nullptr }; static const char* aLevelStylePropNameAlphaMap[] = { nullptr, "ParaStyleSeparator", "ParaStyleLevel1", "ParaStyleLevel2", "ParaStyleLevel3", nullptr }; static const char* aLevelStylePropNameBibliographyMap[] = // TODO: replace with real property names, when available { nullptr, "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", "ParaStyleLevel1", nullptr }; static const char** aTypeLevelStylePropNameMap[] = { aLevelStylePropNameTOCMap, // TOC aLevelStylePropNameTableMap, // table index aLevelStylePropNameTableMap, // illustration index aLevelStylePropNameTableMap, // object index aLevelStylePropNameTOCMap, // user index aLevelStylePropNameAlphaMap, // alphabetical index aLevelStylePropNameBibliographyMap // bibliography }; const XMLTokenEnum aTypeLevelAttrMap[] = { XML_OUTLINE_LEVEL, // TOC XML_TOKEN_INVALID, // table index XML_TOKEN_INVALID, // illustration index XML_TOKEN_INVALID, // object index XML_OUTLINE_LEVEL, // user index XML_OUTLINE_LEVEL, // alphabetical index XML_BIBLIOGRAPHY_TYPE // bibliography }; const XMLTokenEnum aTypeElementNameMap[] = { XML_TABLE_OF_CONTENT_ENTRY_TEMPLATE, // TOC XML_TABLE_INDEX_ENTRY_TEMPLATE, // table index XML_ILLUSTRATION_INDEX_ENTRY_TEMPLATE, // illustration index XML_OBJECT_INDEX_ENTRY_TEMPLATE, // object index XML_USER_INDEX_ENTRY_TEMPLATE, // user index XML_ALPHABETICAL_INDEX_ENTRY_TEMPLATE, // alphabetical index XML_BIBLIOGRAPHY_ENTRY_TEMPLATE // bibliography }; bool XMLSectionExport::ExportIndexTemplate( SectionTypeEnum eType, sal_Int32 nOutlineLevel, const Reference<XPropertySet> & rPropertySet, const Sequence<Sequence<PropertyValue> > & rValues) { OSL_ENSURE(eType >= TEXT_SECTION_TYPE_TOC, "illegal index type"); OSL_ENSURE(eType <= TEXT_SECTION_TYPE_BIBLIOGRAPHY, "illegal index type"); OSL_ENSURE(nOutlineLevel >= 0, "illegal outline level"); if ( (eType >= TEXT_SECTION_TYPE_TOC) && (eType <= TEXT_SECTION_TYPE_BIBLIOGRAPHY) && (nOutlineLevel >= 0) ) { // get level name and level attribute name from aLevelNameMap; const XMLTokenEnum eLevelAttrName( aTypeLevelAttrMap[eType-TEXT_SECTION_TYPE_TOC]); const XMLTokenEnum eLevelName( aTypeLevelNameMap[eType-TEXT_SECTION_TYPE_TOC][nOutlineLevel]); // #92124#: some old documents may be broken, then they have // too many template levels; we need to recognize this and // export only as many as is legal for the respective index // type. To do this, we simply return an error flag, which // will then abort further template level exports. OSL_ENSURE(XML_TOKEN_INVALID != eLevelName, "can't find level name"); if ( XML_TOKEN_INVALID == eLevelName ) { // output level not found? Then end of templates! #91214# return false; } // output level name if ((XML_TOKEN_INVALID != eLevelName) && (XML_TOKEN_INVALID != eLevelAttrName)) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, GetXMLToken(eLevelAttrName), GetXMLToken(eLevelName)); } // paragraph level style name const char* pPropName( aTypeLevelStylePropNameMap[eType-TEXT_SECTION_TYPE_TOC][nOutlineLevel]); OSL_ENSURE(nullptr != pPropName, "can't find property name"); if (nullptr != pPropName) { Any aAny = rPropertySet->getPropertyValue( OUString::createFromAscii(pPropName)); OUString sParaStyleName; aAny >>= sParaStyleName; GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_STYLE_NAME, GetExport().EncodeStyleName( sParaStyleName )); } // template element const XMLTokenEnum eElementName( aTypeElementNameMap[eType - TEXT_SECTION_TYPE_TOC]); SvXMLElementExport aLevelTemplate(GetExport(), XML_NAMESPACE_TEXT, GetXMLToken(eElementName), true, true); // export sequence for(auto& rValue : rValues) { ExportIndexTemplateElement( eType, //i90246 rValue); } } return true; } namespace { enum TemplateTypeEnum { TOK_TTYPE_ENTRY_NUMBER, TOK_TTYPE_ENTRY_TEXT, TOK_TTYPE_TAB_STOP, TOK_TTYPE_TEXT, TOK_TTYPE_PAGE_NUMBER, TOK_TTYPE_CHAPTER_INFO, TOK_TTYPE_HYPERLINK_START, TOK_TTYPE_HYPERLINK_END, TOK_TTYPE_BIBLIOGRAPHY, TOK_TTYPE_INVALID }; enum TemplateParamEnum { TOK_TPARAM_TOKEN_TYPE, TOK_TPARAM_CHAR_STYLE, TOK_TPARAM_TAB_RIGHT_ALIGNED, TOK_TPARAM_TAB_POSITION, TOK_TPARAM_TAB_WITH_TAB, // #i21237# TOK_TPARAM_TAB_FILL_CHAR, TOK_TPARAM_TEXT, TOK_TPARAM_CHAPTER_FORMAT, TOK_TPARAM_CHAPTER_LEVEL,//i53420 TOK_TPARAM_BIBLIOGRAPHY_DATA }; } SvXMLEnumStringMapEntry<TemplateTypeEnum> const aTemplateTypeMap[] = { ENUM_STRING_MAP_ENTRY( "TokenEntryNumber", TOK_TTYPE_ENTRY_NUMBER ), ENUM_STRING_MAP_ENTRY( "TokenEntryText", TOK_TTYPE_ENTRY_TEXT ), ENUM_STRING_MAP_ENTRY( "TokenTabStop", TOK_TTYPE_TAB_STOP ), ENUM_STRING_MAP_ENTRY( "TokenText", TOK_TTYPE_TEXT ), ENUM_STRING_MAP_ENTRY( "TokenPageNumber", TOK_TTYPE_PAGE_NUMBER ), ENUM_STRING_MAP_ENTRY( "TokenChapterInfo", TOK_TTYPE_CHAPTER_INFO ), ENUM_STRING_MAP_ENTRY( "TokenHyperlinkStart", TOK_TTYPE_HYPERLINK_START ), ENUM_STRING_MAP_ENTRY( "TokenHyperlinkEnd", TOK_TTYPE_HYPERLINK_END ), ENUM_STRING_MAP_ENTRY( "TokenBibliographyDataField", TOK_TTYPE_BIBLIOGRAPHY ), { nullptr, 0, TemplateTypeEnum(0)} }; SvXMLEnumStringMapEntry<TemplateParamEnum> const aTemplateParamMap[] = { ENUM_STRING_MAP_ENTRY( "TokenType", TOK_TPARAM_TOKEN_TYPE ), ENUM_STRING_MAP_ENTRY( "CharacterStyleName", TOK_TPARAM_CHAR_STYLE ), ENUM_STRING_MAP_ENTRY( "TabStopRightAligned", TOK_TPARAM_TAB_RIGHT_ALIGNED ), ENUM_STRING_MAP_ENTRY( "TabStopPosition", TOK_TPARAM_TAB_POSITION ), ENUM_STRING_MAP_ENTRY( "TabStopFillCharacter", TOK_TPARAM_TAB_FILL_CHAR ), // #i21237# ENUM_STRING_MAP_ENTRY( "WithTab", TOK_TPARAM_TAB_WITH_TAB ), ENUM_STRING_MAP_ENTRY( "Text", TOK_TPARAM_TEXT ), ENUM_STRING_MAP_ENTRY( "ChapterFormat", TOK_TPARAM_CHAPTER_FORMAT ), ENUM_STRING_MAP_ENTRY( "ChapterLevel", TOK_TPARAM_CHAPTER_LEVEL ),//i53420 ENUM_STRING_MAP_ENTRY( "BibliographyDataField", TOK_TPARAM_BIBLIOGRAPHY_DATA ), { nullptr, 0, TemplateParamEnum(0)} }; SvXMLEnumMapEntry<sal_Int16> const aBibliographyDataFieldMap[] = { { XML_ADDRESS, BibliographyDataField::ADDRESS }, { XML_ANNOTE, BibliographyDataField::ANNOTE }, { XML_AUTHOR, BibliographyDataField::AUTHOR }, { XML_BIBLIOGRAPHY_TYPE, BibliographyDataField::BIBILIOGRAPHIC_TYPE }, { XML_BOOKTITLE, BibliographyDataField::BOOKTITLE }, { XML_CHAPTER, BibliographyDataField::CHAPTER }, { XML_CUSTOM1, BibliographyDataField::CUSTOM1 }, { XML_CUSTOM2, BibliographyDataField::CUSTOM2 }, { XML_CUSTOM3, BibliographyDataField::CUSTOM3 }, { XML_CUSTOM4, BibliographyDataField::CUSTOM4 }, { XML_CUSTOM5, BibliographyDataField::CUSTOM5 }, { XML_EDITION, BibliographyDataField::EDITION }, { XML_EDITOR, BibliographyDataField::EDITOR }, { XML_HOWPUBLISHED, BibliographyDataField::HOWPUBLISHED }, { XML_IDENTIFIER, BibliographyDataField::IDENTIFIER }, { XML_INSTITUTION, BibliographyDataField::INSTITUTION }, { XML_ISBN, BibliographyDataField::ISBN }, { XML_JOURNAL, BibliographyDataField::JOURNAL }, { XML_MONTH, BibliographyDataField::MONTH }, { XML_NOTE, BibliographyDataField::NOTE }, { XML_NUMBER, BibliographyDataField::NUMBER }, { XML_ORGANIZATIONS, BibliographyDataField::ORGANIZATIONS }, { XML_PAGES, BibliographyDataField::PAGES }, { XML_PUBLISHER, BibliographyDataField::PUBLISHER }, { XML_REPORT_TYPE, BibliographyDataField::REPORT_TYPE }, { XML_SCHOOL, BibliographyDataField::SCHOOL }, { XML_SERIES, BibliographyDataField::SERIES }, { XML_TITLE, BibliographyDataField::TITLE }, { XML_URL, BibliographyDataField::URL }, { XML_VOLUME, BibliographyDataField::VOLUME }, { XML_YEAR, BibliographyDataField::YEAR }, { XML_TOKEN_INVALID, 0 } }; void XMLSectionExport::ExportIndexTemplateElement( SectionTypeEnum eType, //i90246 const Sequence<PropertyValue> & rValues) { // variables for template values // char style OUString sCharStyle; bool bCharStyleOK = false; // text OUString sText; bool bTextOK = false; // tab position bool bRightAligned = false; // tab position sal_Int32 nTabPosition = 0; bool bTabPositionOK = false; // fill character OUString sFillChar; bool bFillCharOK = false; // chapter format sal_Int16 nChapterFormat = 0; bool bChapterFormatOK = false; // outline max level sal_Int16 nLevel = 0; bool bLevelOK = false; // Bibliography Data sal_Int16 nBibliographyData = 0; bool bBibliographyDataOK = false; // With Tab Stop #i21237# bool bWithTabStop = false; bool bWithTabStopOK = false; //i90246, the ODF version being written to is: const SvtSaveOptions::ODFSaneDefaultVersion aODFVersion = rExport.getSaneDefaultVersion(); //the above version cannot be used for old OOo (OOo 1.0) formats! // token type enum TemplateTypeEnum nTokenType = TOK_TTYPE_INVALID; for(const auto& rValue : rValues) { TemplateParamEnum nToken; if ( SvXMLUnitConverter::convertEnum( nToken, rValue.Name, aTemplateParamMap ) ) { // Only use direct and default values. // Wrong. no property states, so ignore. // if ( (beans::PropertyState_DIRECT_VALUE == rValues[i].State) || // (beans::PropertyState_DEFAULT_VALUE == rValues[i].State) ) switch (nToken) { case TOK_TPARAM_TOKEN_TYPE: { OUString sVal; rValue.Value >>= sVal; SvXMLUnitConverter::convertEnum( nTokenType, sVal, aTemplateTypeMap); break; } case TOK_TPARAM_CHAR_STYLE: // only valid, if not empty rValue.Value >>= sCharStyle; bCharStyleOK = !sCharStyle.isEmpty(); break; case TOK_TPARAM_TEXT: rValue.Value >>= sText; bTextOK = true; break; case TOK_TPARAM_TAB_RIGHT_ALIGNED: bRightAligned = *o3tl::doAccess<bool>(rValue.Value); break; case TOK_TPARAM_TAB_POSITION: rValue.Value >>= nTabPosition; bTabPositionOK = true; break; // #i21237# case TOK_TPARAM_TAB_WITH_TAB: bWithTabStop = *o3tl::doAccess<bool>(rValue.Value); bWithTabStopOK = true; break; case TOK_TPARAM_TAB_FILL_CHAR: rValue.Value >>= sFillChar; bFillCharOK = true; break; case TOK_TPARAM_CHAPTER_FORMAT: rValue.Value >>= nChapterFormat; bChapterFormatOK = true; break; //---> i53420 case TOK_TPARAM_CHAPTER_LEVEL: rValue.Value >>= nLevel; bLevelOK = true; break; case TOK_TPARAM_BIBLIOGRAPHY_DATA: rValue.Value >>= nBibliographyData; bBibliographyDataOK = true; break; } } } // convert type to token (and check validity) ... XMLTokenEnum eElement(XML_TOKEN_INVALID); sal_uInt16 nNamespace(XML_NAMESPACE_TEXT); switch(nTokenType) { case TOK_TTYPE_ENTRY_TEXT: eElement = XML_INDEX_ENTRY_TEXT; break; case TOK_TTYPE_TAB_STOP: // test validity if ( bRightAligned || bTabPositionOK || bFillCharOK ) { eElement = XML_INDEX_ENTRY_TAB_STOP; } break; case TOK_TTYPE_TEXT: // test validity if (bTextOK) { eElement = XML_INDEX_ENTRY_SPAN; } break; case TOK_TTYPE_PAGE_NUMBER: eElement = XML_INDEX_ENTRY_PAGE_NUMBER; break; case TOK_TTYPE_CHAPTER_INFO: // keyword index eElement = XML_INDEX_ENTRY_CHAPTER; break; case TOK_TTYPE_ENTRY_NUMBER: // table of content eElement = XML_INDEX_ENTRY_CHAPTER; break; case TOK_TTYPE_HYPERLINK_START: eElement = XML_INDEX_ENTRY_LINK_START; break; case TOK_TTYPE_HYPERLINK_END: eElement = XML_INDEX_ENTRY_LINK_END; break; case TOK_TTYPE_BIBLIOGRAPHY: if (bBibliographyDataOK) { eElement = XML_INDEX_ENTRY_BIBLIOGRAPHY; } break; default: ; // unknown/unimplemented template break; } if (eType != TEXT_SECTION_TYPE_TOC) { switch (nTokenType) { case TOK_TTYPE_HYPERLINK_START: case TOK_TTYPE_HYPERLINK_END: if (SvtSaveOptions::ODFSVER_012 < aODFVersion) { assert(eType == TEXT_SECTION_TYPE_ILLUSTRATION || eType == TEXT_SECTION_TYPE_OBJECT || eType == TEXT_SECTION_TYPE_TABLE || eType == TEXT_SECTION_TYPE_USER); // ODF 1.3 OFFICE-3941 nNamespace = (SvtSaveOptions::ODFSVER_013 <= aODFVersion) ? XML_NAMESPACE_TEXT : XML_NAMESPACE_LO_EXT; } else { eElement = XML_TOKEN_INVALID; // not allowed in ODF <= 1.2 } break; default: break; } } //--->i90246 //check the ODF version being exported if (aODFVersion == SvtSaveOptions::ODFSVER_011 || aODFVersion == SvtSaveOptions::ODFSVER_010) { bLevelOK = false; if (TOK_TTYPE_CHAPTER_INFO == nTokenType) { //if we are emitting for ODF 1.1 or 1.0, this information can be used for alphabetical index only //it's not permitted in other indexes if (eType != TEXT_SECTION_TYPE_ALPHABETICAL) { eElement = XML_TOKEN_INVALID; //not permitted, invalidate the element } else //maps format for 1.1 & 1.0 { // a few word here: OOo up to 2.4 uses the field chapter info in Alphabetical index // in a way different from the ODF 1.1/1.0 specification: // ODF1.1/1.0 OOo display in chapter info ODF1.2 // (used in alphabetical index only // number chapter number without pre/postfix plain-number // number-and-name chapter number without pre/postfix plus title plain-number-and-name // with issue i89791 the reading of ODF 1.1 and 1.0 was corrected // this one corrects the writing back from ODF 1.2 to ODF 1.1/1.0 // unfortunately if there is another application which interprets correctly ODF1.1/1.0, // the resulting alphabetical index will be rendered wrong by OOo 2.4 version switch( nChapterFormat ) { case ChapterFormat::DIGIT: nChapterFormat = ChapterFormat::NUMBER; break; case ChapterFormat::NO_PREFIX_SUFFIX: nChapterFormat = ChapterFormat::NAME_NUMBER; break; } } } else if (TOK_TTYPE_ENTRY_NUMBER == nTokenType) { //in case of ODF 1.1 or 1.0 the only allowed number format is "number" //so, force it... // The only expected 'foreign' nChapterFormat is // ' ChapterFormat::DIGIT', forced to 'none, since the // 'value allowed in ODF 1.1 and 1.0 is 'number' the default // this can be obtained by simply disabling the chapter format bChapterFormatOK = false; } } // ... and write Element if (eElement == XML_TOKEN_INVALID) return; // character style (for most templates) if (bCharStyleOK) { switch (nTokenType) { case TOK_TTYPE_ENTRY_TEXT: case TOK_TTYPE_TEXT: case TOK_TTYPE_PAGE_NUMBER: case TOK_TTYPE_ENTRY_NUMBER: case TOK_TTYPE_HYPERLINK_START: case TOK_TTYPE_HYPERLINK_END: case TOK_TTYPE_BIBLIOGRAPHY: case TOK_TTYPE_CHAPTER_INFO: case TOK_TTYPE_TAB_STOP: GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_STYLE_NAME, GetExport().EncodeStyleName( sCharStyle) ); break; default: ; // nothing: no character style break; } } // tab properties if (TOK_TTYPE_TAB_STOP == nTokenType) { // tab type GetExport().AddAttribute(XML_NAMESPACE_STYLE, XML_TYPE, bRightAligned ? XML_RIGHT : XML_LEFT); if (bTabPositionOK && (! bRightAligned)) { // position for left tabs (convert to measure) OUStringBuffer sBuf; GetExport().GetMM100UnitConverter().convertMeasureToXML(sBuf, nTabPosition); GetExport().AddAttribute(XML_NAMESPACE_STYLE, XML_POSITION, sBuf.makeStringAndClear()); } // fill char ("leader char") if (bFillCharOK && !sFillChar.isEmpty()) { GetExport().AddAttribute(XML_NAMESPACE_STYLE, XML_LEADER_CHAR, sFillChar); } // #i21237# if (bWithTabStopOK && ! bWithTabStop) { GetExport().AddAttribute(XML_NAMESPACE_STYLE, XML_WITH_TAB, XML_FALSE); } } // bibliography data if (TOK_TTYPE_BIBLIOGRAPHY == nTokenType) { OSL_ENSURE(bBibliographyDataOK, "need bibl data"); OUStringBuffer sBuf; if (SvXMLUnitConverter::convertEnum( sBuf, nBibliographyData, aBibliographyDataFieldMap ) ) { GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_BIBLIOGRAPHY_DATA_FIELD, sBuf.makeStringAndClear()); } } // chapter info if (TOK_TTYPE_CHAPTER_INFO == nTokenType) { OSL_ENSURE(bChapterFormatOK, "need chapter info"); GetExport().AddAttribute( XML_NAMESPACE_TEXT, XML_DISPLAY, XMLTextFieldExport::MapChapterDisplayFormat(nChapterFormat)); //---> i53420 if (bLevelOK) GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_OUTLINE_LEVEL, OUString::number(nLevel)); } //--->i53420 if (TOK_TTYPE_ENTRY_NUMBER == nTokenType) { if (bChapterFormatOK) GetExport().AddAttribute( XML_NAMESPACE_TEXT, XML_DISPLAY, XMLTextFieldExport::MapChapterDisplayFormat(nChapterFormat)); if (bLevelOK) GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_OUTLINE_LEVEL, OUString::number(nLevel)); } // export template SvXMLElementExport aTemplateElement(GetExport(), nNamespace, GetXMLToken(eElement), true, false) ; // entry text or span element: write text if (TOK_TTYPE_TEXT == nTokenType) { GetExport().Characters(sText); } } void XMLSectionExport::ExportLevelParagraphStyles( Reference<XIndexReplace> const & xLevelParagraphStyles) { // iterate over levels sal_Int32 nPLevelCount = xLevelParagraphStyles->getCount(); for(sal_Int32 nLevel = 0; nLevel < nPLevelCount; nLevel++) { Any aAny = xLevelParagraphStyles->getByIndex(nLevel); Sequence<OUString> aStyleNames; aAny >>= aStyleNames; // export only if at least one style is contained if (aStyleNames.hasElements()) { // level attribute; we count 1..10; API 0..9 sal_Int32 nLevelPlusOne = nLevel + 1; GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_OUTLINE_LEVEL, OUString::number(nLevelPlusOne)); // source styles element SvXMLElementExport aParaStyles(GetExport(), XML_NAMESPACE_TEXT, XML_INDEX_SOURCE_STYLES, true, true); // iterate over styles in this level for(const auto& rStyleName : std::as_const(aStyleNames)) { // stylename attribute GetExport().AddAttribute(XML_NAMESPACE_TEXT, XML_STYLE_NAME, GetExport().EncodeStyleName(rStyleName) ); // element SvXMLElementExport aParaStyle(GetExport(), XML_NAMESPACE_TEXT, XML_INDEX_SOURCE_STYLE, true, false); } } } } void XMLSectionExport::ExportBoolean( const Reference<XPropertySet> & rPropSet, const OUString& sPropertyName, enum XMLTokenEnum eAttributeName, bool bDefault, bool bInvert) { OSL_ENSURE(eAttributeName != XML_TOKEN_INVALID, "Need attribute name"); Any aAny = rPropSet->getPropertyValue(sPropertyName); bool bTmp = *o3tl::doAccess<bool>(aAny); // value = value ^ bInvert // omit if value == default if ( (bTmp != bInvert) != bDefault ) { // export non-default value (since default is omitted) GetExport().AddAttribute(XML_NAMESPACE_TEXT, eAttributeName, bDefault ? XML_FALSE : XML_TRUE); } } void XMLSectionExport::ExportBibliographyConfiguration(SvXMLExport& rExport) { // first: get field master (via text field supplier) Reference<XTextFieldsSupplier> xTextFieldsSupp( rExport.GetModel(), UNO_QUERY ); if ( !xTextFieldsSupp.is() ) return; static const OUStringLiteral sFieldMaster_Bibliography(u"com.sun.star.text.FieldMaster.Bibliography"); // get bibliography field master Reference<XNameAccess> xMasters = xTextFieldsSupp->getTextFieldMasters(); if ( !xMasters->hasByName(sFieldMaster_Bibliography) ) return; Any aAny = xMasters->getByName(sFieldMaster_Bibliography); Reference<XPropertySet> xPropSet; aAny >>= xPropSet; OSL_ENSURE( xPropSet.is(), "field master must have XPropSet" ); OUString sTmp; aAny = xPropSet->getPropertyValue("BracketBefore"); aAny >>= sTmp; rExport.AddAttribute(XML_NAMESPACE_TEXT, XML_PREFIX, sTmp); aAny = xPropSet->getPropertyValue("BracketAfter"); aAny >>= sTmp; rExport.AddAttribute(XML_NAMESPACE_TEXT, XML_SUFFIX, sTmp); aAny = xPropSet->getPropertyValue("IsNumberEntries"); if (*o3tl::doAccess<bool>(aAny)) { rExport.AddAttribute(XML_NAMESPACE_TEXT, XML_NUMBERED_ENTRIES, XML_TRUE); } aAny = xPropSet->getPropertyValue("IsSortByPosition"); if (! *o3tl::doAccess<bool>(aAny)) { rExport.AddAttribute(XML_NAMESPACE_TEXT, XML_SORT_BY_POSITION, XML_FALSE); } // sort algorithm aAny = xPropSet->getPropertyValue("SortAlgorithm"); OUString sAlgorithm; aAny >>= sAlgorithm; if( !sAlgorithm.isEmpty() ) { rExport.AddAttribute( XML_NAMESPACE_TEXT, XML_SORT_ALGORITHM, sAlgorithm ); } // locale aAny = xPropSet->getPropertyValue("Locale"); Locale aLocale; aAny >>= aLocale; rExport.AddLanguageTagAttributes( XML_NAMESPACE_FO, XML_NAMESPACE_STYLE, aLocale, true); // configuration element SvXMLElementExport aElement(rExport, XML_NAMESPACE_TEXT, XML_BIBLIOGRAPHY_CONFIGURATION, true, true); // sort keys aAny = xPropSet->getPropertyValue("SortKeys"); Sequence<Sequence<PropertyValue> > aKeys; aAny >>= aKeys; for(const Sequence<PropertyValue> & rKey : std::as_const(aKeys)) { for(const PropertyValue& rValue : rKey) { if (rValue.Name == "SortKey") { sal_Int16 nKey = 0; rValue.Value >>= nKey; OUStringBuffer sBuf; if (SvXMLUnitConverter::convertEnum( sBuf, nKey, aBibliographyDataFieldMap ) ) { rExport.AddAttribute(XML_NAMESPACE_TEXT, XML_KEY, sBuf.makeStringAndClear()); } } else if (rValue.Name == "IsSortAscending") { bool bTmp = *o3tl::doAccess<bool>(rValue.Value); rExport.AddAttribute(XML_NAMESPACE_TEXT, XML_SORT_ASCENDING, bTmp ? XML_TRUE : XML_FALSE); } } SvXMLElementExport aKeyElem(rExport, XML_NAMESPACE_TEXT, XML_SORT_KEY, true, true); } } bool XMLSectionExport::IsMuteSection( const Reference<XTextSection> & rSection) const { bool bRet = false; // a section is mute if // 1) it exists // 2) the SaveLinkedSections flag (at the export) is false // 3) the IsGlobalDocumentSection property is true // 4) it is not an Index if ( (!rExport.IsSaveLinkedSections()) && rSection.is() ) { // walk the section chain and set bRet if any is linked for(Reference<XTextSection> aSection(rSection); aSection.is(); aSection = aSection->getParentSection()) { // check if it is a global document section (linked or index) Reference<XPropertySet> xPropSet(aSection, UNO_QUERY); if (xPropSet.is()) { Any aAny = xPropSet->getPropertyValue("IsGlobalDocumentSection"); if ( *o3tl::doAccess<bool>(aAny) ) { Reference<XDocumentIndex> xIndex; if (! GetIndex(rSection, xIndex)) { bRet = true; // early out if result is known break; } } } // section has no properties: ignore } } // else: no section, or always save sections: default (false) return bRet; } bool XMLSectionExport::IsMuteSection( const Reference<XTextContent> & rSection, bool bDefault) const { // default: like default argument bool bRet = bDefault; Reference<XPropertySet> xPropSet(rSection->getAnchor(), UNO_QUERY); if (xPropSet.is()) { if (xPropSet->getPropertySetInfo()->hasPropertyByName("TextSection")) { Any aAny = xPropSet->getPropertyValue("TextSection"); Reference<XTextSection> xSection; aAny >>= xSection; bRet = IsMuteSection(xSection); } // else: return default } // else: return default return bRet; } bool XMLSectionExport::IsInSection( const Reference<XTextSection> & rEnclosingSection, const Reference<XTextContent> & rContent, bool bDefault) { // default: like default argument bool bRet = bDefault; OSL_ENSURE(rEnclosingSection.is(), "enclosing section expected"); Reference<XPropertySet> xPropSet(rContent, UNO_QUERY); if (xPropSet.is()) { if (xPropSet->getPropertySetInfo()->hasPropertyByName("TextSection")) { Any aAny = xPropSet->getPropertyValue("TextSection"); Reference<XTextSection> xSection; aAny >>= xSection; // now walk chain of text sections (if we have one) if (xSection.is()) { do { bRet = (rEnclosingSection == xSection); xSection = xSection->getParentSection(); } while (!bRet && xSection.is()); } else bRet = false; // no section -> can't be inside } // else: no TextSection property -> return default } // else: no XPropertySet -> return default return bRet; } void XMLSectionExport::ExportMasterDocHeadingDummies() { if( bHeadingDummiesExported ) return; Reference< XChapterNumberingSupplier > xCNSupplier( rExport.GetModel(), UNO_QUERY ); Reference< XIndexReplace > xChapterNumbering; if( xCNSupplier.is() ) xChapterNumbering = xCNSupplier->getChapterNumberingRules(); if( !xChapterNumbering.is() ) return; sal_Int32 nCount = xChapterNumbering->getCount(); for( sal_Int32 nLevel = 0; nLevel < nCount; nLevel++ ) { OUString sStyle; Sequence<PropertyValue> aProperties; xChapterNumbering->getByIndex( nLevel ) >>= aProperties; auto pProp = std::find_if(std::cbegin(aProperties), std::cend(aProperties), [](const PropertyValue& rProp) { return rProp.Name == "HeadingStyleName"; }); if (pProp != std::cend(aProperties)) pProp->Value >>= sStyle; if( !sStyle.isEmpty() ) { GetExport().AddAttribute( XML_NAMESPACE_TEXT, XML_STYLE_NAME, GetExport().EncodeStyleName( sStyle ) ); GetExport().AddAttribute( XML_NAMESPACE_TEXT, XML_LEVEL, OUString::number( nLevel + 1 ) ); SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_TEXT, XML_H, true, false ); } } bHeadingDummiesExported = true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
utf-8
1
MPL-2.0
Copyright 2000, 2010 Oracle and/or its affiliates. Copyright (c) 2000, 2010 LibreOffice contributors and/or their affiliates.
ipmctl-03.00.00.0423/DcpmPkg/driver/Protocol/Device/StorageSecurityCommand.c
/* * Copyright (c) 2018, Intel Corporation. * SPDX-License-Identifier: BSD-3-Clause */ #include <Uefi.h> #include <Library/BaseMemoryLib.h> #include <Debug.h> #include <Utility.h> #include <NvmDimmPassThru.h> #include "NvmDimmDriver.h" #include "NvmSecurity.h" #include <Protocol/StorageSecurityCommand.h> /** Supported Security Protocols & Protocol Specific parameters **/ #define SECURITY_PROTOCOL_INFORMATION 0x00 //!< Supported protocols information #define CMD_SUPPORTED_SECURITY_PROTOCOL_LIST 0x0000 //!< Retrieve supported security protocols #define SECURITY_PROTOCOL_FW_COMMANDS 0xFA //!< Vendor specific protocol #define CMD_OPCODE_MASK 0xFF00 //!< 2nd byte contains Opcode #define CMD_SUBOPCODE_MASK 0x00FF //!< 1st byte contains SubOpcode #define SUPPORTED_PROTOCOL_LIST_LENGTH 2 //!< Number of supported protocols #pragma pack(push) #pragma pack(1) typedef struct { UINT8 Reserved[6]; UINT16 Length; UINT8 Protocol[SUPPORTED_PROTOCOL_LIST_LENGTH]; } PROTOCOL_INFORMATION; #pragma pack(pop) /** Instance of StorageSecurityCommandProtocol **/ EFI_STATUS EFIAPI ReceiveData ( IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, IN UINT32 MediaId, //!< Ignored in this implementation IN UINT64 Timeout, //!< Timeout passed to PassThru protocol IN UINT8 SecurityProtocol, //!< Specifies which security protocol is being used IN UINT16 SecurityProtocolSpecificData, //!< Command Opcode & SubOpcode in case of FW commands IN UINTN PayloadBufferSize, OUT VOID *PayloadBuffer, OUT UINTN *PayloadTransferSize) { NVDIMM_ENTRY(); EFI_STATUS ReturnCode = EFI_UNSUPPORTED; UINT32 SecurityState = 0; UINT8 Opcode, SubOpcode; PROTOCOL_INFORMATION SupportedProtocolsData = { .Reserved = {0}, .Length = SUPPORTED_PROTOCOL_LIST_LENGTH, .Protocol = {SECURITY_PROTOCOL_INFORMATION, SECURITY_PROTOCOL_FW_COMMANDS} }; if (NULL == This) { ReturnCode = EFI_INVALID_PARAMETER; goto Finish; } EFI_DIMMS_DATA *Dimm = BASE_CR(This, EFI_DIMMS_DATA, StorageSecurityCommandInstance); if ((PayloadBuffer == NULL || PayloadTransferSize == NULL) && PayloadBufferSize != 0) { ReturnCode = EFI_INVALID_PARAMETER; goto Finish; } if (SecurityProtocol != SECURITY_PROTOCOL_INFORMATION && SecurityProtocol != SECURITY_PROTOCOL_FW_COMMANDS) { NVDIMM_WARN("Security protocol id %d not supported by ReceiveData function", SecurityProtocol); ReturnCode = EFI_UNSUPPORTED; goto Finish; } /** Security Protocol Information **/ if (SecurityProtocol == SECURITY_PROTOCOL_INFORMATION) { if (SecurityProtocolSpecificData == CMD_SUPPORTED_SECURITY_PROTOCOL_LIST) { NVDIMM_DBG("Retrieving supported security protocol list ..."); if (PayloadBuffer == NULL || PayloadTransferSize == NULL) { ReturnCode = EFI_INVALID_PARAMETER; goto Finish; } // check amount of data to be returned *PayloadTransferSize = sizeof(SupportedProtocolsData); if (*PayloadTransferSize > PayloadBufferSize) { NVDIMM_DBG("Buffer too small"); *PayloadTransferSize = PayloadBufferSize; ReturnCode = EFI_WARN_BUFFER_TOO_SMALL; } else { ReturnCode = EFI_SUCCESS; } CopyMem_S(PayloadBuffer, PayloadBufferSize, &SupportedProtocolsData, *PayloadTransferSize); goto Finish; } else { NVDIMM_WARN("Command not not supported: 0x%x", SecurityProtocolSpecificData); ReturnCode = EFI_UNSUPPORTED; goto Finish; } } /** FW Commands **/ if (SecurityProtocol == SECURITY_PROTOCOL_FW_COMMANDS) { Opcode = (UINT8) ((SecurityProtocolSpecificData & CMD_OPCODE_MASK) >> 8); SubOpcode = (UINT8) (SecurityProtocolSpecificData & CMD_SUBOPCODE_MASK); NVDIMM_DBG("FW command: Opcode=%x, SubOpcode=%x", Opcode, SubOpcode); if (Opcode == PtGetSecInfo) { if (SubOpcode == SubopGetSecState) { if (PayloadBuffer == NULL || PayloadTransferSize == NULL) { ReturnCode = EFI_INVALID_PARAMETER; goto Finish; } ReturnCode = GetDimmSecurityState(Dimm->pDimm, PT_TIMEOUT_INTERVAL, &SecurityState); if (EFI_ERROR(ReturnCode)) { NVDIMM_DBG("Failed on GetDimmSecurityState, status=" FORMAT_EFI_STATUS "", ReturnCode); goto Finish; } // check amount of data to be returned *PayloadTransferSize = sizeof(SecurityState); if (*PayloadTransferSize > PayloadBufferSize) { NVDIMM_DBG("Buffer too small"); *PayloadTransferSize = PayloadBufferSize; ReturnCode = EFI_WARN_BUFFER_TOO_SMALL; } // write data to return buffer CopyMem_S(PayloadBuffer, PayloadBufferSize, &SecurityState, *PayloadTransferSize); } else { //SubOpcode not supported NVDIMM_WARN("Command not supported: Opcode=%x, SubOpcode=%x", Opcode, SubOpcode); ReturnCode = EFI_UNSUPPORTED; goto Finish; } } else { //Opcode not supported NVDIMM_WARN("Command not supported: Opcode=%x, SubOpcode=%x", Opcode, SubOpcode); ReturnCode = EFI_UNSUPPORTED; goto Finish; } } Finish: NVDIMM_EXIT_I64(ReturnCode); return ReturnCode; } EFI_STATUS EFIAPI SendData ( IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, IN UINT32 MediaId, IN UINT64 Timeout, IN UINT8 SecurityProtocol, IN UINT16 SecurityProtocolSpecificData, IN UINTN PayloadBufferSize, IN VOID *PayloadBuffer) { NVDIMM_ENTRY(); EFI_STATUS ReturnCode = EFI_SUCCESS; UINT8 Opcode, SubOpcode; if (NULL == This) { ReturnCode = EFI_INVALID_PARAMETER; goto Finish; } EFI_DIMMS_DATA *Dimm = BASE_CR(This, EFI_DIMMS_DATA, StorageSecurityCommandInstance); if ((PayloadBuffer == NULL) && (PayloadBufferSize != 0)) { ReturnCode = EFI_INVALID_PARAMETER; goto Finish; } if (SecurityProtocol != SECURITY_PROTOCOL_FW_COMMANDS) { NVDIMM_DBG("Security protocol id %d not supported by SendData function", SecurityProtocol); ReturnCode = EFI_UNSUPPORTED; goto Finish; } /** FW Commands **/ if (SecurityProtocol == SECURITY_PROTOCOL_FW_COMMANDS) { Opcode = (UINT8) ((SecurityProtocolSpecificData & CMD_OPCODE_MASK) >> 8); SubOpcode = (UINT8) (SecurityProtocolSpecificData & CMD_SUBOPCODE_MASK); NVDIMM_DBG("FW command: Opcode=%x, SubOpcode=%x", Opcode, SubOpcode); if (Opcode == PtSetSecInfo) { if (SubOpcode == SubopSecEraseUnit) { /** Need to call WBINVD before secure erase **/ AsmWbinvd(); } ReturnCode = SetDimmSecurityState(Dimm->pDimm, Opcode, SubOpcode, (UINT16)PayloadBufferSize, PayloadBuffer, PT_TIMEOUT_INTERVAL); if (EFI_ERROR(ReturnCode)) { NVDIMM_DBG("Failed on SetDimmSecurityState, status=" FORMAT_EFI_STATUS "", ReturnCode); goto Finish; } if ((SubOpcode == SubopSecEraseUnit) || (SubOpcode == SubopUnlockUnit)) { /** Need to call WBINVD after unlock or secure erase **/ AsmWbinvd(); } } else { //Opcode not supported NVDIMM_WARN("Command not supported: Opcode=%x, SubOpcode=%x", Opcode, SubOpcode); ReturnCode = EFI_UNSUPPORTED; goto Finish; } } Finish: NVDIMM_EXIT_I64(ReturnCode); return ReturnCode; } EFI_STORAGE_SECURITY_COMMAND_PROTOCOL gNvmDimmDriverStorageSecurityCommand = { ReceiveData, SendData };
utf-8
1
BSD-2-clause and BSD-3-clause
2006-2019 Intel Corporation 2012-2016 Hewlett Packard Enterprise Development LP 2013-2016 Hewlett-Packard Development Company, L.P. 2010-2016 Linaro Ltd 2010-2016 Google Inc 2008-2010 Apple Inc 2011-2015 ARM Limited 2017 AMD Incorporated 2013-2017 Red Hat, Inc 2015-2016 Dell Inc 1999-2016 Igor Pavlov 2002-2013 K.Kosako 2016 Silicon Graphics, Inc 2015, The Linux Foundation 1996-1998 John D. Polstra
xwayland-22.0.99.902/xfixes/saveset.c
/* * Copyright © 2002 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> #endif #include "xfixesint.h" int ProcXFixesChangeSaveSet(ClientPtr client) { Bool toRoot, map; int result; WindowPtr pWin; REQUEST(xXFixesChangeSaveSetReq); REQUEST_SIZE_MATCH(xXFixesChangeSaveSetReq); result = dixLookupWindow(&pWin, stuff->window, client, DixManageAccess); if (result != Success) return result; if (client->clientAsMask == (CLIENT_BITS(pWin->drawable.id))) return BadMatch; if ((stuff->mode != SetModeInsert) && (stuff->mode != SetModeDelete)) { client->errorValue = stuff->mode; return BadValue; } if ((stuff->target != SaveSetNearest) && (stuff->target != SaveSetRoot)) { client->errorValue = stuff->target; return BadValue; } if ((stuff->map != SaveSetMap) && (stuff->map != SaveSetUnmap)) { client->errorValue = stuff->map; return BadValue; } toRoot = (stuff->target == SaveSetRoot); map = (stuff->map == SaveSetMap); return AlterSaveSetForClient(client, pWin, stuff->mode, toRoot, map); } int _X_COLD SProcXFixesChangeSaveSet(ClientPtr client) { REQUEST(xXFixesChangeSaveSetReq); REQUEST_SIZE_MATCH(xXFixesChangeSaveSetReq); swaps(&stuff->length); swapl(&stuff->window); return (*ProcXFixesVector[stuff->xfixesReqType]) (client); }
utf-8
1
unknown
unknown
codelite-14.0+dfsg/CodeLite/LSP/Request.cpp
#include "JSON.h" #include "LSP/Request.h" LSP::Request::Request() { m_id = Message::GetNextID(); } LSP::Request::~Request() {} JSONItem LSP::Request::ToJSON(const wxString& name, IPathConverter::Ptr_t pathConverter) const { JSONItem json = MessageWithParams::ToJSON(name, pathConverter); json.addProperty("id", GetId()); return json; } void LSP::Request::FromJSON(const JSONItem& json, IPathConverter::Ptr_t pathConverter) { wxUnusedVar(json); wxUnusedVar(pathConverter); }
utf-8
1
CodeLite
2007-2014 Eran Ifrah <eran.ifrah@gmail.com> 2011-2014 David Hart <david@codelite.co.uk> 2014-2016 The CodeLite Team
insighttoolkit5-5.2.1/Modules/Bridge/NumPy/include/itkPyBuffer.hxx
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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. * *=========================================================================*/ #ifndef itkPyBuffer_hxx #define itkPyBuffer_hxx #include "itkPyBuffer.h" #include "itkImportImageContainer.h" namespace itk { template <class TImage> PyObject * PyBuffer<TImage>::_GetArrayViewFromImage(ImageType * image) { PyObject * memoryView = NULL; Py_buffer pyBuffer; memset(&pyBuffer, 0, sizeof(Py_buffer)); Py_ssize_t len = 1; size_t pixelSize = sizeof(ComponentType); int res = 0; if (!image) { throw std::runtime_error("Input image is null"); } image->Update(); ComponentType * buffer = const_cast<ComponentType *>(reinterpret_cast<const ComponentType *>(image->GetBufferPointer())); void * itkImageBuffer = (void *)(buffer); // Computing the length of data const int numberOfComponents = image->GetNumberOfComponentsPerPixel(); SizeType size = image->GetBufferedRegion().GetSize(); for (unsigned int dim = 0; dim < ImageDimension; ++dim) { len *= size[dim]; } len *= numberOfComponents; len *= pixelSize; res = PyBuffer_FillInfo(&pyBuffer, NULL, (void *)itkImageBuffer, len, 0, PyBUF_CONTIG); memoryView = PyMemoryView_FromBuffer(&pyBuffer); PyBuffer_Release(&pyBuffer); return memoryView; } template <class TImage> const typename PyBuffer<TImage>::OutputImagePointer PyBuffer<TImage>::_GetImageViewFromArray(PyObject * arr, PyObject * shape, PyObject * numOfComponent) { PyObject * shapeseq = NULL; PyObject * item = NULL; Py_ssize_t bufferLength; Py_buffer pyBuffer; memset(&pyBuffer, 0, sizeof(Py_buffer)); SizeType size; SizeType sizeFortran; SizeValueType numberOfPixels = 1; const void * buffer; long numberOfComponents = 1; unsigned int dimension = 0; size_t pixelSize = sizeof(ComponentType); size_t len = 1; if (PyObject_GetBuffer(arr, &pyBuffer, PyBUF_ND | PyBUF_ANY_CONTIGUOUS) == -1) { PyErr_SetString(PyExc_RuntimeError, "Cannot get an instance of NumPy array."); PyBuffer_Release(&pyBuffer); return nullptr; } else { bufferLength = pyBuffer.len; buffer = pyBuffer.buf; } PyBuffer_Release(&pyBuffer); shapeseq = PySequence_Fast(shape, "expected sequence"); dimension = PySequence_Size(shape); numberOfComponents = PyInt_AsLong(numOfComponent); for (unsigned int i = 0; i < dimension; ++i) { item = PySequence_Fast_GET_ITEM(shapeseq, i); size[i] = (SizeValueType)PyInt_AsLong(item); sizeFortran[dimension - 1 - i] = (SizeValueType)PyInt_AsLong(item); numberOfPixels *= size[i]; } bool isFortranContiguous = false; if (pyBuffer.strides != NULL && pyBuffer.itemsize == pyBuffer.strides[0]) { isFortranContiguous = true; } len = numberOfPixels * numberOfComponents * pixelSize; if (bufferLength != len) { PyErr_SetString(PyExc_RuntimeError, "Size mismatch of image and Buffer."); PyBuffer_Release(&pyBuffer); Py_DECREF(shapeseq); return nullptr; } IndexType start; start.Fill(0); RegionType region; region.SetIndex(start); region.SetSize(size); if (isFortranContiguous) { region.SetSize(sizeFortran); } else { region.SetSize(size); } PointType origin; origin.Fill(0.0); SpacingType spacing; spacing.Fill(1.0); using InternalPixelType = typename TImage::InternalPixelType; using ImporterType = ImportImageContainer<SizeValueType, InternalPixelType>; typename ImporterType::Pointer importer = ImporterType::New(); constexpr bool importImageFilterWillOwnTheBuffer = false; InternalPixelType * data = (InternalPixelType *)buffer; importer->SetImportPointer(data, numberOfPixels, importImageFilterWillOwnTheBuffer); OutputImagePointer output = TImage::New(); output->SetRegions(region); output->SetOrigin(origin); output->SetSpacing(spacing); output->SetPixelContainer(importer); output->SetNumberOfComponentsPerPixel(numberOfComponents); Py_DECREF(shapeseq); PyBuffer_Release(&pyBuffer); return output; } } // namespace itk #endif
utf-8
1
unknown
unknown
svt-av1-0.9.0+dfsg/Source/Lib/Encoder/Codec/EbTransforms.c
/* * Copyright(c) 2019 Intel Corporation * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at https://www.aomedia.org/license/software-license. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at https://www.aomedia.org/license/patent-license. */ #include <stdlib.h> #include "EbTransforms.h" #include "aom_dsp_rtcd.h" static const int8_t *fwd_txfm_range_mult2_list[TXFM_TYPES] = {fdct4_range_mult2, fdct8_range_mult2, fdct16_range_mult2, fdct32_range_mult2, fdct64_range_mult2, fadst4_range_mult2, fadst8_range_mult2, fadst16_range_mult2, fadst32_range_mult2, fidtx4_range_mult2, fidtx8_range_mult2, fidtx16_range_mult2, fidtx32_range_mult2, fidtx64_range_mult2}; static const int8_t *fwd_txfm_shift_ls[TX_SIZES_ALL] = { fwd_shift_4x4, fwd_shift_8x8, fwd_shift_16x16, fwd_shift_32x32, fwd_shift_64x64, fwd_shift_4x8, fwd_shift_8x4, fwd_shift_8x16, fwd_shift_16x8, fwd_shift_16x32, fwd_shift_32x16, fwd_shift_32x64, fwd_shift_64x32, fwd_shift_4x16, fwd_shift_16x4, fwd_shift_8x32, fwd_shift_32x8, fwd_shift_16x64, fwd_shift_64x16, }; /***************************** * Defines *****************************/ #define BETA_P 1 #define BETA_N 3 /******************************************** * Constants ********************************************/ #define ALPHA_0000 0 #define ALPHA_0050 50 #define ALPHA_0100 100 #define ALPHA_0200 200 #define ALPHA_0300 300 #define ALPHA_0500 500 #define ALPHA_1000 1000 void svt_av1_gen_fwd_stage_range(int8_t *stage_range_col, int8_t *stage_range_row, const Txfm2dFlipCfg *cfg, int32_t bd) { // Take the shift from the larger dimension in the rectangular case. const int8_t *shift = cfg->shift; // i < MAX_TXFM_STAGE_NUM will mute above array bounds warning for (int32_t i = 0; i < cfg->stage_num_col && i < MAX_TXFM_STAGE_NUM; ++i) stage_range_col[i] = (int8_t)(cfg->stage_range_col[i] + shift[0] + bd + 1); // i < MAX_TXFM_STAGE_NUM will mute above array bounds warning for (int32_t i = 0; i < cfg->stage_num_row && i < MAX_TXFM_STAGE_NUM; ++i) stage_range_row[i] = (int8_t)(cfg->stage_range_row[i] + shift[0] + shift[1] + bd + 1); } #define range_check(stage, input, buf, size, bit) \ do { \ } while (0) void svt_av1_fdct4_new(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[4]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[3]; bf1[1] = input[1] + input[2]; bf1[2] = -input[2] + input[1]; bf1[3] = -input[3] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[1] = half_btf(-cospi[32], bf0[1], cospi[32], bf0[0], cos_bit); bf1[2] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); bf1[3] = half_btf(cospi[48], bf0[3], -cospi[16], bf0[2], cos_bit); // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[2]; bf1[2] = bf0[1]; bf1[3] = bf0[3]; } void svt_av1_fdct8_new(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[8]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[7]; bf1[1] = input[1] + input[6]; bf1[2] = input[2] + input[5]; bf1[3] = input[3] + input[4]; bf1[4] = -input[4] + input[3]; bf1[5] = -input[5] + input[2]; bf1[6] = -input[6] + input[1]; bf1[7] = -input[7] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[2] = -bf0[2] + bf0[1]; bf1[3] = -bf0[3] + bf0[0]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; // stage 3 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[1] = half_btf(-cospi[32], bf0[1], cospi[32], bf0[0], cos_bit); bf1[2] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); bf1[3] = half_btf(cospi[48], bf0[3], -cospi[16], bf0[2], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[5] = -bf0[5] + bf0[4]; bf1[6] = -bf0[6] + bf0[7]; bf1[7] = bf0[7] + bf0[6]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[5] = half_btf(cospi[24], bf0[5], cospi[40], bf0[6], cos_bit); bf1[6] = half_btf(cospi[24], bf0[6], -cospi[40], bf0[5], cos_bit); bf1[7] = half_btf(cospi[56], bf0[7], -cospi[8], bf0[4], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[4]; bf1[2] = bf0[2]; bf1[3] = bf0[6]; bf1[4] = bf0[1]; bf1[5] = bf0[5]; bf1[6] = bf0[3]; bf1[7] = bf0[7]; } void svt_av1_fdct16_new(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[16]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[15]; bf1[1] = input[1] + input[14]; bf1[2] = input[2] + input[13]; bf1[3] = input[3] + input[12]; bf1[4] = input[4] + input[11]; bf1[5] = input[5] + input[10]; bf1[6] = input[6] + input[9]; bf1[7] = input[7] + input[8]; bf1[8] = -input[8] + input[7]; bf1[9] = -input[9] + input[6]; bf1[10] = -input[10] + input[5]; bf1[11] = -input[11] + input[4]; bf1[12] = -input[12] + input[3]; bf1[13] = -input[13] + input[2]; bf1[14] = -input[14] + input[1]; bf1[15] = -input[15] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[7]; bf1[1] = bf0[1] + bf0[6]; bf1[2] = bf0[2] + bf0[5]; bf1[3] = bf0[3] + bf0[4]; bf1[4] = -bf0[4] + bf0[3]; bf1[5] = -bf0[5] + bf0[2]; bf1[6] = -bf0[6] + bf0[1]; bf1[7] = -bf0[7] + bf0[0]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(-cospi[32], bf0[10], cospi[32], bf0[13], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[12], cos_bit); bf1[12] = half_btf(cospi[32], bf0[12], cospi[32], bf0[11], cos_bit); bf1[13] = half_btf(cospi[32], bf0[13], cospi[32], bf0[10], cos_bit); bf1[14] = bf0[14]; bf1[15] = bf0[15]; // stage 3 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[2] = -bf0[2] + bf0[1]; bf1[3] = -bf0[3] + bf0[0]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; bf1[8] = bf0[8] + bf0[11]; bf1[9] = bf0[9] + bf0[10]; bf1[10] = -bf0[10] + bf0[9]; bf1[11] = -bf0[11] + bf0[8]; bf1[12] = -bf0[12] + bf0[15]; bf1[13] = -bf0[13] + bf0[14]; bf1[14] = bf0[14] + bf0[13]; bf1[15] = bf0[15] + bf0[12]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[1] = half_btf(-cospi[32], bf0[1], cospi[32], bf0[0], cos_bit); bf1[2] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); bf1[3] = half_btf(cospi[48], bf0[3], -cospi[16], bf0[2], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[5] = -bf0[5] + bf0[4]; bf1[6] = -bf0[6] + bf0[7]; bf1[7] = bf0[7] + bf0[6]; bf1[8] = bf0[8]; bf1[9] = half_btf(-cospi[16], bf0[9], cospi[48], bf0[14], cos_bit); bf1[10] = half_btf(-cospi[48], bf0[10], -cospi[16], bf0[13], cos_bit); bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = half_btf(cospi[48], bf0[13], -cospi[16], bf0[10], cos_bit); bf1[14] = half_btf(cospi[16], bf0[14], cospi[48], bf0[9], cos_bit); bf1[15] = bf0[15]; // stage 5 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[5] = half_btf(cospi[24], bf0[5], cospi[40], bf0[6], cos_bit); bf1[6] = half_btf(cospi[24], bf0[6], -cospi[40], bf0[5], cos_bit); bf1[7] = half_btf(cospi[56], bf0[7], -cospi[8], bf0[4], cos_bit); bf1[8] = bf0[8] + bf0[9]; bf1[9] = -bf0[9] + bf0[8]; bf1[10] = -bf0[10] + bf0[11]; bf1[11] = bf0[11] + bf0[10]; bf1[12] = bf0[12] + bf0[13]; bf1[13] = -bf0[13] + bf0[12]; bf1[14] = -bf0[14] + bf0[15]; bf1[15] = bf0[15] + bf0[14]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = half_btf(cospi[60], bf0[8], cospi[4], bf0[15], cos_bit); bf1[9] = half_btf(cospi[28], bf0[9], cospi[36], bf0[14], cos_bit); bf1[10] = half_btf(cospi[44], bf0[10], cospi[20], bf0[13], cos_bit); bf1[11] = half_btf(cospi[12], bf0[11], cospi[52], bf0[12], cos_bit); bf1[12] = half_btf(cospi[12], bf0[12], -cospi[52], bf0[11], cos_bit); bf1[13] = half_btf(cospi[44], bf0[13], -cospi[20], bf0[10], cos_bit); bf1[14] = half_btf(cospi[28], bf0[14], -cospi[36], bf0[9], cos_bit); bf1[15] = half_btf(cospi[60], bf0[15], -cospi[4], bf0[8], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[8]; bf1[2] = bf0[4]; bf1[3] = bf0[12]; bf1[4] = bf0[2]; bf1[5] = bf0[10]; bf1[6] = bf0[6]; bf1[7] = bf0[14]; bf1[8] = bf0[1]; bf1[9] = bf0[9]; bf1[10] = bf0[5]; bf1[11] = bf0[13]; bf1[12] = bf0[3]; bf1[13] = bf0[11]; bf1[14] = bf0[7]; bf1[15] = bf0[15]; } void svt_av1_fdct32_new(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[32]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[31]; bf1[1] = input[1] + input[30]; bf1[2] = input[2] + input[29]; bf1[3] = input[3] + input[28]; bf1[4] = input[4] + input[27]; bf1[5] = input[5] + input[26]; bf1[6] = input[6] + input[25]; bf1[7] = input[7] + input[24]; bf1[8] = input[8] + input[23]; bf1[9] = input[9] + input[22]; bf1[10] = input[10] + input[21]; bf1[11] = input[11] + input[20]; bf1[12] = input[12] + input[19]; bf1[13] = input[13] + input[18]; bf1[14] = input[14] + input[17]; bf1[15] = input[15] + input[16]; bf1[16] = -input[16] + input[15]; bf1[17] = -input[17] + input[14]; bf1[18] = -input[18] + input[13]; bf1[19] = -input[19] + input[12]; bf1[20] = -input[20] + input[11]; bf1[21] = -input[21] + input[10]; bf1[22] = -input[22] + input[9]; bf1[23] = -input[23] + input[8]; bf1[24] = -input[24] + input[7]; bf1[25] = -input[25] + input[6]; bf1[26] = -input[26] + input[5]; bf1[27] = -input[27] + input[4]; bf1[28] = -input[28] + input[3]; bf1[29] = -input[29] + input[2]; bf1[30] = -input[30] + input[1]; bf1[31] = -input[31] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[15]; bf1[1] = bf0[1] + bf0[14]; bf1[2] = bf0[2] + bf0[13]; bf1[3] = bf0[3] + bf0[12]; bf1[4] = bf0[4] + bf0[11]; bf1[5] = bf0[5] + bf0[10]; bf1[6] = bf0[6] + bf0[9]; bf1[7] = bf0[7] + bf0[8]; bf1[8] = -bf0[8] + bf0[7]; bf1[9] = -bf0[9] + bf0[6]; bf1[10] = -bf0[10] + bf0[5]; bf1[11] = -bf0[11] + bf0[4]; bf1[12] = -bf0[12] + bf0[3]; bf1[13] = -bf0[13] + bf0[2]; bf1[14] = -bf0[14] + bf0[1]; bf1[15] = -bf0[15] + bf0[0]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = bf0[18]; bf1[19] = bf0[19]; bf1[20] = half_btf(-cospi[32], bf0[20], cospi[32], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[32], bf0[21], cospi[32], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[32], bf0[22], cospi[32], bf0[25], cos_bit); bf1[23] = half_btf(-cospi[32], bf0[23], cospi[32], bf0[24], cos_bit); bf1[24] = half_btf(cospi[32], bf0[24], cospi[32], bf0[23], cos_bit); bf1[25] = half_btf(cospi[32], bf0[25], cospi[32], bf0[22], cos_bit); bf1[26] = half_btf(cospi[32], bf0[26], cospi[32], bf0[21], cos_bit); bf1[27] = half_btf(cospi[32], bf0[27], cospi[32], bf0[20], cos_bit); bf1[28] = bf0[28]; bf1[29] = bf0[29]; bf1[30] = bf0[30]; bf1[31] = bf0[31]; // stage 3 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[7]; bf1[1] = bf0[1] + bf0[6]; bf1[2] = bf0[2] + bf0[5]; bf1[3] = bf0[3] + bf0[4]; bf1[4] = -bf0[4] + bf0[3]; bf1[5] = -bf0[5] + bf0[2]; bf1[6] = -bf0[6] + bf0[1]; bf1[7] = -bf0[7] + bf0[0]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(-cospi[32], bf0[10], cospi[32], bf0[13], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[12], cos_bit); bf1[12] = half_btf(cospi[32], bf0[12], cospi[32], bf0[11], cos_bit); bf1[13] = half_btf(cospi[32], bf0[13], cospi[32], bf0[10], cos_bit); bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[23]; bf1[17] = bf0[17] + bf0[22]; bf1[18] = bf0[18] + bf0[21]; bf1[19] = bf0[19] + bf0[20]; bf1[20] = -bf0[20] + bf0[19]; bf1[21] = -bf0[21] + bf0[18]; bf1[22] = -bf0[22] + bf0[17]; bf1[23] = -bf0[23] + bf0[16]; bf1[24] = -bf0[24] + bf0[31]; bf1[25] = -bf0[25] + bf0[30]; bf1[26] = -bf0[26] + bf0[29]; bf1[27] = -bf0[27] + bf0[28]; bf1[28] = bf0[28] + bf0[27]; bf1[29] = bf0[29] + bf0[26]; bf1[30] = bf0[30] + bf0[25]; bf1[31] = bf0[31] + bf0[24]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[2] = -bf0[2] + bf0[1]; bf1[3] = -bf0[3] + bf0[0]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; bf1[8] = bf0[8] + bf0[11]; bf1[9] = bf0[9] + bf0[10]; bf1[10] = -bf0[10] + bf0[9]; bf1[11] = -bf0[11] + bf0[8]; bf1[12] = -bf0[12] + bf0[15]; bf1[13] = -bf0[13] + bf0[14]; bf1[14] = bf0[14] + bf0[13]; bf1[15] = bf0[15] + bf0[12]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = half_btf(-cospi[16], bf0[18], cospi[48], bf0[29], cos_bit); bf1[19] = half_btf(-cospi[16], bf0[19], cospi[48], bf0[28], cos_bit); bf1[20] = half_btf(-cospi[48], bf0[20], -cospi[16], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[48], bf0[21], -cospi[16], bf0[26], cos_bit); bf1[22] = bf0[22]; bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = bf0[25]; bf1[26] = half_btf(cospi[48], bf0[26], -cospi[16], bf0[21], cos_bit); bf1[27] = half_btf(cospi[48], bf0[27], -cospi[16], bf0[20], cos_bit); bf1[28] = half_btf(cospi[16], bf0[28], cospi[48], bf0[19], cos_bit); bf1[29] = half_btf(cospi[16], bf0[29], cospi[48], bf0[18], cos_bit); bf1[30] = bf0[30]; bf1[31] = bf0[31]; // stage 5 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[1] = half_btf(-cospi[32], bf0[1], cospi[32], bf0[0], cos_bit); bf1[2] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); bf1[3] = half_btf(cospi[48], bf0[3], -cospi[16], bf0[2], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[5] = -bf0[5] + bf0[4]; bf1[6] = -bf0[6] + bf0[7]; bf1[7] = bf0[7] + bf0[6]; bf1[8] = bf0[8]; bf1[9] = half_btf(-cospi[16], bf0[9], cospi[48], bf0[14], cos_bit); bf1[10] = half_btf(-cospi[48], bf0[10], -cospi[16], bf0[13], cos_bit); bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = half_btf(cospi[48], bf0[13], -cospi[16], bf0[10], cos_bit); bf1[14] = half_btf(cospi[16], bf0[14], cospi[48], bf0[9], cos_bit); bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[19]; bf1[17] = bf0[17] + bf0[18]; bf1[18] = -bf0[18] + bf0[17]; bf1[19] = -bf0[19] + bf0[16]; bf1[20] = -bf0[20] + bf0[23]; bf1[21] = -bf0[21] + bf0[22]; bf1[22] = bf0[22] + bf0[21]; bf1[23] = bf0[23] + bf0[20]; bf1[24] = bf0[24] + bf0[27]; bf1[25] = bf0[25] + bf0[26]; bf1[26] = -bf0[26] + bf0[25]; bf1[27] = -bf0[27] + bf0[24]; bf1[28] = -bf0[28] + bf0[31]; bf1[29] = -bf0[29] + bf0[30]; bf1[30] = bf0[30] + bf0[29]; bf1[31] = bf0[31] + bf0[28]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[5] = half_btf(cospi[24], bf0[5], cospi[40], bf0[6], cos_bit); bf1[6] = half_btf(cospi[24], bf0[6], -cospi[40], bf0[5], cos_bit); bf1[7] = half_btf(cospi[56], bf0[7], -cospi[8], bf0[4], cos_bit); bf1[8] = bf0[8] + bf0[9]; bf1[9] = -bf0[9] + bf0[8]; bf1[10] = -bf0[10] + bf0[11]; bf1[11] = bf0[11] + bf0[10]; bf1[12] = bf0[12] + bf0[13]; bf1[13] = -bf0[13] + bf0[12]; bf1[14] = -bf0[14] + bf0[15]; bf1[15] = bf0[15] + bf0[14]; bf1[16] = bf0[16]; bf1[17] = half_btf(-cospi[8], bf0[17], cospi[56], bf0[30], cos_bit); bf1[18] = half_btf(-cospi[56], bf0[18], -cospi[8], bf0[29], cos_bit); bf1[19] = bf0[19]; bf1[20] = bf0[20]; bf1[21] = half_btf(-cospi[40], bf0[21], cospi[24], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[24], bf0[22], -cospi[40], bf0[25], cos_bit); bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = half_btf(cospi[24], bf0[25], -cospi[40], bf0[22], cos_bit); bf1[26] = half_btf(cospi[40], bf0[26], cospi[24], bf0[21], cos_bit); bf1[27] = bf0[27]; bf1[28] = bf0[28]; bf1[29] = half_btf(cospi[56], bf0[29], -cospi[8], bf0[18], cos_bit); bf1[30] = half_btf(cospi[8], bf0[30], cospi[56], bf0[17], cos_bit); bf1[31] = bf0[31]; // stage 7 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = half_btf(cospi[60], bf0[8], cospi[4], bf0[15], cos_bit); bf1[9] = half_btf(cospi[28], bf0[9], cospi[36], bf0[14], cos_bit); bf1[10] = half_btf(cospi[44], bf0[10], cospi[20], bf0[13], cos_bit); bf1[11] = half_btf(cospi[12], bf0[11], cospi[52], bf0[12], cos_bit); bf1[12] = half_btf(cospi[12], bf0[12], -cospi[52], bf0[11], cos_bit); bf1[13] = half_btf(cospi[44], bf0[13], -cospi[20], bf0[10], cos_bit); bf1[14] = half_btf(cospi[28], bf0[14], -cospi[36], bf0[9], cos_bit); bf1[15] = half_btf(cospi[60], bf0[15], -cospi[4], bf0[8], cos_bit); bf1[16] = bf0[16] + bf0[17]; bf1[17] = -bf0[17] + bf0[16]; bf1[18] = -bf0[18] + bf0[19]; bf1[19] = bf0[19] + bf0[18]; bf1[20] = bf0[20] + bf0[21]; bf1[21] = -bf0[21] + bf0[20]; bf1[22] = -bf0[22] + bf0[23]; bf1[23] = bf0[23] + bf0[22]; bf1[24] = bf0[24] + bf0[25]; bf1[25] = -bf0[25] + bf0[24]; bf1[26] = -bf0[26] + bf0[27]; bf1[27] = bf0[27] + bf0[26]; bf1[28] = bf0[28] + bf0[29]; bf1[29] = -bf0[29] + bf0[28]; bf1[30] = -bf0[30] + bf0[31]; bf1[31] = bf0[31] + bf0[30]; // stage 8 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = bf0[10]; bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = bf0[13]; bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = half_btf(cospi[62], bf0[16], cospi[2], bf0[31], cos_bit); bf1[17] = half_btf(cospi[30], bf0[17], cospi[34], bf0[30], cos_bit); bf1[18] = half_btf(cospi[46], bf0[18], cospi[18], bf0[29], cos_bit); bf1[19] = half_btf(cospi[14], bf0[19], cospi[50], bf0[28], cos_bit); bf1[20] = half_btf(cospi[54], bf0[20], cospi[10], bf0[27], cos_bit); bf1[21] = half_btf(cospi[22], bf0[21], cospi[42], bf0[26], cos_bit); bf1[22] = half_btf(cospi[38], bf0[22], cospi[26], bf0[25], cos_bit); bf1[23] = half_btf(cospi[6], bf0[23], cospi[58], bf0[24], cos_bit); bf1[24] = half_btf(cospi[6], bf0[24], -cospi[58], bf0[23], cos_bit); bf1[25] = half_btf(cospi[38], bf0[25], -cospi[26], bf0[22], cos_bit); bf1[26] = half_btf(cospi[22], bf0[26], -cospi[42], bf0[21], cos_bit); bf1[27] = half_btf(cospi[54], bf0[27], -cospi[10], bf0[20], cos_bit); bf1[28] = half_btf(cospi[14], bf0[28], -cospi[50], bf0[19], cos_bit); bf1[29] = half_btf(cospi[46], bf0[29], -cospi[18], bf0[18], cos_bit); bf1[30] = half_btf(cospi[30], bf0[30], -cospi[34], bf0[17], cos_bit); bf1[31] = half_btf(cospi[62], bf0[31], -cospi[2], bf0[16], cos_bit); // stage 9 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[16]; bf1[2] = bf0[8]; bf1[3] = bf0[24]; bf1[4] = bf0[4]; bf1[5] = bf0[20]; bf1[6] = bf0[12]; bf1[7] = bf0[28]; bf1[8] = bf0[2]; bf1[9] = bf0[18]; bf1[10] = bf0[10]; bf1[11] = bf0[26]; bf1[12] = bf0[6]; bf1[13] = bf0[22]; bf1[14] = bf0[14]; bf1[15] = bf0[30]; bf1[16] = bf0[1]; bf1[17] = bf0[17]; bf1[18] = bf0[9]; bf1[19] = bf0[25]; bf1[20] = bf0[5]; bf1[21] = bf0[21]; bf1[22] = bf0[13]; bf1[23] = bf0[29]; bf1[24] = bf0[3]; bf1[25] = bf0[19]; bf1[26] = bf0[11]; bf1[27] = bf0[27]; bf1[28] = bf0[7]; bf1[29] = bf0[23]; bf1[30] = bf0[15]; bf1[31] = bf0[31]; } void svt_av1_fdct64_new(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[64]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[63]; bf1[1] = input[1] + input[62]; bf1[2] = input[2] + input[61]; bf1[3] = input[3] + input[60]; bf1[4] = input[4] + input[59]; bf1[5] = input[5] + input[58]; bf1[6] = input[6] + input[57]; bf1[7] = input[7] + input[56]; bf1[8] = input[8] + input[55]; bf1[9] = input[9] + input[54]; bf1[10] = input[10] + input[53]; bf1[11] = input[11] + input[52]; bf1[12] = input[12] + input[51]; bf1[13] = input[13] + input[50]; bf1[14] = input[14] + input[49]; bf1[15] = input[15] + input[48]; bf1[16] = input[16] + input[47]; bf1[17] = input[17] + input[46]; bf1[18] = input[18] + input[45]; bf1[19] = input[19] + input[44]; bf1[20] = input[20] + input[43]; bf1[21] = input[21] + input[42]; bf1[22] = input[22] + input[41]; bf1[23] = input[23] + input[40]; bf1[24] = input[24] + input[39]; bf1[25] = input[25] + input[38]; bf1[26] = input[26] + input[37]; bf1[27] = input[27] + input[36]; bf1[28] = input[28] + input[35]; bf1[29] = input[29] + input[34]; bf1[30] = input[30] + input[33]; bf1[31] = input[31] + input[32]; bf1[32] = -input[32] + input[31]; bf1[33] = -input[33] + input[30]; bf1[34] = -input[34] + input[29]; bf1[35] = -input[35] + input[28]; bf1[36] = -input[36] + input[27]; bf1[37] = -input[37] + input[26]; bf1[38] = -input[38] + input[25]; bf1[39] = -input[39] + input[24]; bf1[40] = -input[40] + input[23]; bf1[41] = -input[41] + input[22]; bf1[42] = -input[42] + input[21]; bf1[43] = -input[43] + input[20]; bf1[44] = -input[44] + input[19]; bf1[45] = -input[45] + input[18]; bf1[46] = -input[46] + input[17]; bf1[47] = -input[47] + input[16]; bf1[48] = -input[48] + input[15]; bf1[49] = -input[49] + input[14]; bf1[50] = -input[50] + input[13]; bf1[51] = -input[51] + input[12]; bf1[52] = -input[52] + input[11]; bf1[53] = -input[53] + input[10]; bf1[54] = -input[54] + input[9]; bf1[55] = -input[55] + input[8]; bf1[56] = -input[56] + input[7]; bf1[57] = -input[57] + input[6]; bf1[58] = -input[58] + input[5]; bf1[59] = -input[59] + input[4]; bf1[60] = -input[60] + input[3]; bf1[61] = -input[61] + input[2]; bf1[62] = -input[62] + input[1]; bf1[63] = -input[63] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[31]; bf1[1] = bf0[1] + bf0[30]; bf1[2] = bf0[2] + bf0[29]; bf1[3] = bf0[3] + bf0[28]; bf1[4] = bf0[4] + bf0[27]; bf1[5] = bf0[5] + bf0[26]; bf1[6] = bf0[6] + bf0[25]; bf1[7] = bf0[7] + bf0[24]; bf1[8] = bf0[8] + bf0[23]; bf1[9] = bf0[9] + bf0[22]; bf1[10] = bf0[10] + bf0[21]; bf1[11] = bf0[11] + bf0[20]; bf1[12] = bf0[12] + bf0[19]; bf1[13] = bf0[13] + bf0[18]; bf1[14] = bf0[14] + bf0[17]; bf1[15] = bf0[15] + bf0[16]; bf1[16] = -bf0[16] + bf0[15]; bf1[17] = -bf0[17] + bf0[14]; bf1[18] = -bf0[18] + bf0[13]; bf1[19] = -bf0[19] + bf0[12]; bf1[20] = -bf0[20] + bf0[11]; bf1[21] = -bf0[21] + bf0[10]; bf1[22] = -bf0[22] + bf0[9]; bf1[23] = -bf0[23] + bf0[8]; bf1[24] = -bf0[24] + bf0[7]; bf1[25] = -bf0[25] + bf0[6]; bf1[26] = -bf0[26] + bf0[5]; bf1[27] = -bf0[27] + bf0[4]; bf1[28] = -bf0[28] + bf0[3]; bf1[29] = -bf0[29] + bf0[2]; bf1[30] = -bf0[30] + bf0[1]; bf1[31] = -bf0[31] + bf0[0]; bf1[32] = bf0[32]; bf1[33] = bf0[33]; bf1[34] = bf0[34]; bf1[35] = bf0[35]; bf1[36] = bf0[36]; bf1[37] = bf0[37]; bf1[38] = bf0[38]; bf1[39] = bf0[39]; bf1[40] = half_btf(-cospi[32], bf0[40], cospi[32], bf0[55], cos_bit); bf1[41] = half_btf(-cospi[32], bf0[41], cospi[32], bf0[54], cos_bit); bf1[42] = half_btf(-cospi[32], bf0[42], cospi[32], bf0[53], cos_bit); bf1[43] = half_btf(-cospi[32], bf0[43], cospi[32], bf0[52], cos_bit); bf1[44] = half_btf(-cospi[32], bf0[44], cospi[32], bf0[51], cos_bit); bf1[45] = half_btf(-cospi[32], bf0[45], cospi[32], bf0[50], cos_bit); bf1[46] = half_btf(-cospi[32], bf0[46], cospi[32], bf0[49], cos_bit); bf1[47] = half_btf(-cospi[32], bf0[47], cospi[32], bf0[48], cos_bit); bf1[48] = half_btf(cospi[32], bf0[48], cospi[32], bf0[47], cos_bit); bf1[49] = half_btf(cospi[32], bf0[49], cospi[32], bf0[46], cos_bit); bf1[50] = half_btf(cospi[32], bf0[50], cospi[32], bf0[45], cos_bit); bf1[51] = half_btf(cospi[32], bf0[51], cospi[32], bf0[44], cos_bit); bf1[52] = half_btf(cospi[32], bf0[52], cospi[32], bf0[43], cos_bit); bf1[53] = half_btf(cospi[32], bf0[53], cospi[32], bf0[42], cos_bit); bf1[54] = half_btf(cospi[32], bf0[54], cospi[32], bf0[41], cos_bit); bf1[55] = half_btf(cospi[32], bf0[55], cospi[32], bf0[40], cos_bit); bf1[56] = bf0[56]; bf1[57] = bf0[57]; bf1[58] = bf0[58]; bf1[59] = bf0[59]; bf1[60] = bf0[60]; bf1[61] = bf0[61]; bf1[62] = bf0[62]; bf1[63] = bf0[63]; // stage 3 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[15]; bf1[1] = bf0[1] + bf0[14]; bf1[2] = bf0[2] + bf0[13]; bf1[3] = bf0[3] + bf0[12]; bf1[4] = bf0[4] + bf0[11]; bf1[5] = bf0[5] + bf0[10]; bf1[6] = bf0[6] + bf0[9]; bf1[7] = bf0[7] + bf0[8]; bf1[8] = -bf0[8] + bf0[7]; bf1[9] = -bf0[9] + bf0[6]; bf1[10] = -bf0[10] + bf0[5]; bf1[11] = -bf0[11] + bf0[4]; bf1[12] = -bf0[12] + bf0[3]; bf1[13] = -bf0[13] + bf0[2]; bf1[14] = -bf0[14] + bf0[1]; bf1[15] = -bf0[15] + bf0[0]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = bf0[18]; bf1[19] = bf0[19]; bf1[20] = half_btf(-cospi[32], bf0[20], cospi[32], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[32], bf0[21], cospi[32], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[32], bf0[22], cospi[32], bf0[25], cos_bit); bf1[23] = half_btf(-cospi[32], bf0[23], cospi[32], bf0[24], cos_bit); bf1[24] = half_btf(cospi[32], bf0[24], cospi[32], bf0[23], cos_bit); bf1[25] = half_btf(cospi[32], bf0[25], cospi[32], bf0[22], cos_bit); bf1[26] = half_btf(cospi[32], bf0[26], cospi[32], bf0[21], cos_bit); bf1[27] = half_btf(cospi[32], bf0[27], cospi[32], bf0[20], cos_bit); bf1[28] = bf0[28]; bf1[29] = bf0[29]; bf1[30] = bf0[30]; bf1[31] = bf0[31]; bf1[32] = bf0[32] + bf0[47]; bf1[33] = bf0[33] + bf0[46]; bf1[34] = bf0[34] + bf0[45]; bf1[35] = bf0[35] + bf0[44]; bf1[36] = bf0[36] + bf0[43]; bf1[37] = bf0[37] + bf0[42]; bf1[38] = bf0[38] + bf0[41]; bf1[39] = bf0[39] + bf0[40]; bf1[40] = -bf0[40] + bf0[39]; bf1[41] = -bf0[41] + bf0[38]; bf1[42] = -bf0[42] + bf0[37]; bf1[43] = -bf0[43] + bf0[36]; bf1[44] = -bf0[44] + bf0[35]; bf1[45] = -bf0[45] + bf0[34]; bf1[46] = -bf0[46] + bf0[33]; bf1[47] = -bf0[47] + bf0[32]; bf1[48] = -bf0[48] + bf0[63]; bf1[49] = -bf0[49] + bf0[62]; bf1[50] = -bf0[50] + bf0[61]; bf1[51] = -bf0[51] + bf0[60]; bf1[52] = -bf0[52] + bf0[59]; bf1[53] = -bf0[53] + bf0[58]; bf1[54] = -bf0[54] + bf0[57]; bf1[55] = -bf0[55] + bf0[56]; bf1[56] = bf0[56] + bf0[55]; bf1[57] = bf0[57] + bf0[54]; bf1[58] = bf0[58] + bf0[53]; bf1[59] = bf0[59] + bf0[52]; bf1[60] = bf0[60] + bf0[51]; bf1[61] = bf0[61] + bf0[50]; bf1[62] = bf0[62] + bf0[49]; bf1[63] = bf0[63] + bf0[48]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[7]; bf1[1] = bf0[1] + bf0[6]; bf1[2] = bf0[2] + bf0[5]; bf1[3] = bf0[3] + bf0[4]; bf1[4] = -bf0[4] + bf0[3]; bf1[5] = -bf0[5] + bf0[2]; bf1[6] = -bf0[6] + bf0[1]; bf1[7] = -bf0[7] + bf0[0]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(-cospi[32], bf0[10], cospi[32], bf0[13], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[12], cos_bit); bf1[12] = half_btf(cospi[32], bf0[12], cospi[32], bf0[11], cos_bit); bf1[13] = half_btf(cospi[32], bf0[13], cospi[32], bf0[10], cos_bit); bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[23]; bf1[17] = bf0[17] + bf0[22]; bf1[18] = bf0[18] + bf0[21]; bf1[19] = bf0[19] + bf0[20]; bf1[20] = -bf0[20] + bf0[19]; bf1[21] = -bf0[21] + bf0[18]; bf1[22] = -bf0[22] + bf0[17]; bf1[23] = -bf0[23] + bf0[16]; bf1[24] = -bf0[24] + bf0[31]; bf1[25] = -bf0[25] + bf0[30]; bf1[26] = -bf0[26] + bf0[29]; bf1[27] = -bf0[27] + bf0[28]; bf1[28] = bf0[28] + bf0[27]; bf1[29] = bf0[29] + bf0[26]; bf1[30] = bf0[30] + bf0[25]; bf1[31] = bf0[31] + bf0[24]; bf1[32] = bf0[32]; bf1[33] = bf0[33]; bf1[34] = bf0[34]; bf1[35] = bf0[35]; bf1[36] = half_btf(-cospi[16], bf0[36], cospi[48], bf0[59], cos_bit); bf1[37] = half_btf(-cospi[16], bf0[37], cospi[48], bf0[58], cos_bit); bf1[38] = half_btf(-cospi[16], bf0[38], cospi[48], bf0[57], cos_bit); bf1[39] = half_btf(-cospi[16], bf0[39], cospi[48], bf0[56], cos_bit); bf1[40] = half_btf(-cospi[48], bf0[40], -cospi[16], bf0[55], cos_bit); bf1[41] = half_btf(-cospi[48], bf0[41], -cospi[16], bf0[54], cos_bit); bf1[42] = half_btf(-cospi[48], bf0[42], -cospi[16], bf0[53], cos_bit); bf1[43] = half_btf(-cospi[48], bf0[43], -cospi[16], bf0[52], cos_bit); bf1[44] = bf0[44]; bf1[45] = bf0[45]; bf1[46] = bf0[46]; bf1[47] = bf0[47]; bf1[48] = bf0[48]; bf1[49] = bf0[49]; bf1[50] = bf0[50]; bf1[51] = bf0[51]; bf1[52] = half_btf(cospi[48], bf0[52], -cospi[16], bf0[43], cos_bit); bf1[53] = half_btf(cospi[48], bf0[53], -cospi[16], bf0[42], cos_bit); bf1[54] = half_btf(cospi[48], bf0[54], -cospi[16], bf0[41], cos_bit); bf1[55] = half_btf(cospi[48], bf0[55], -cospi[16], bf0[40], cos_bit); bf1[56] = half_btf(cospi[16], bf0[56], cospi[48], bf0[39], cos_bit); bf1[57] = half_btf(cospi[16], bf0[57], cospi[48], bf0[38], cos_bit); bf1[58] = half_btf(cospi[16], bf0[58], cospi[48], bf0[37], cos_bit); bf1[59] = half_btf(cospi[16], bf0[59], cospi[48], bf0[36], cos_bit); bf1[60] = bf0[60]; bf1[61] = bf0[61]; bf1[62] = bf0[62]; bf1[63] = bf0[63]; // stage 5 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[2] = -bf0[2] + bf0[1]; bf1[3] = -bf0[3] + bf0[0]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; bf1[8] = bf0[8] + bf0[11]; bf1[9] = bf0[9] + bf0[10]; bf1[10] = -bf0[10] + bf0[9]; bf1[11] = -bf0[11] + bf0[8]; bf1[12] = -bf0[12] + bf0[15]; bf1[13] = -bf0[13] + bf0[14]; bf1[14] = bf0[14] + bf0[13]; bf1[15] = bf0[15] + bf0[12]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = half_btf(-cospi[16], bf0[18], cospi[48], bf0[29], cos_bit); bf1[19] = half_btf(-cospi[16], bf0[19], cospi[48], bf0[28], cos_bit); bf1[20] = half_btf(-cospi[48], bf0[20], -cospi[16], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[48], bf0[21], -cospi[16], bf0[26], cos_bit); bf1[22] = bf0[22]; bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = bf0[25]; bf1[26] = half_btf(cospi[48], bf0[26], -cospi[16], bf0[21], cos_bit); bf1[27] = half_btf(cospi[48], bf0[27], -cospi[16], bf0[20], cos_bit); bf1[28] = half_btf(cospi[16], bf0[28], cospi[48], bf0[19], cos_bit); bf1[29] = half_btf(cospi[16], bf0[29], cospi[48], bf0[18], cos_bit); bf1[30] = bf0[30]; bf1[31] = bf0[31]; bf1[32] = bf0[32] + bf0[39]; bf1[33] = bf0[33] + bf0[38]; bf1[34] = bf0[34] + bf0[37]; bf1[35] = bf0[35] + bf0[36]; bf1[36] = -bf0[36] + bf0[35]; bf1[37] = -bf0[37] + bf0[34]; bf1[38] = -bf0[38] + bf0[33]; bf1[39] = -bf0[39] + bf0[32]; bf1[40] = -bf0[40] + bf0[47]; bf1[41] = -bf0[41] + bf0[46]; bf1[42] = -bf0[42] + bf0[45]; bf1[43] = -bf0[43] + bf0[44]; bf1[44] = bf0[44] + bf0[43]; bf1[45] = bf0[45] + bf0[42]; bf1[46] = bf0[46] + bf0[41]; bf1[47] = bf0[47] + bf0[40]; bf1[48] = bf0[48] + bf0[55]; bf1[49] = bf0[49] + bf0[54]; bf1[50] = bf0[50] + bf0[53]; bf1[51] = bf0[51] + bf0[52]; bf1[52] = -bf0[52] + bf0[51]; bf1[53] = -bf0[53] + bf0[50]; bf1[54] = -bf0[54] + bf0[49]; bf1[55] = -bf0[55] + bf0[48]; bf1[56] = -bf0[56] + bf0[63]; bf1[57] = -bf0[57] + bf0[62]; bf1[58] = -bf0[58] + bf0[61]; bf1[59] = -bf0[59] + bf0[60]; bf1[60] = bf0[60] + bf0[59]; bf1[61] = bf0[61] + bf0[58]; bf1[62] = bf0[62] + bf0[57]; bf1[63] = bf0[63] + bf0[56]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[1] = half_btf(-cospi[32], bf0[1], cospi[32], bf0[0], cos_bit); bf1[2] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); bf1[3] = half_btf(cospi[48], bf0[3], -cospi[16], bf0[2], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[5] = -bf0[5] + bf0[4]; bf1[6] = -bf0[6] + bf0[7]; bf1[7] = bf0[7] + bf0[6]; bf1[8] = bf0[8]; bf1[9] = half_btf(-cospi[16], bf0[9], cospi[48], bf0[14], cos_bit); bf1[10] = half_btf(-cospi[48], bf0[10], -cospi[16], bf0[13], cos_bit); bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = half_btf(cospi[48], bf0[13], -cospi[16], bf0[10], cos_bit); bf1[14] = half_btf(cospi[16], bf0[14], cospi[48], bf0[9], cos_bit); bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[19]; bf1[17] = bf0[17] + bf0[18]; bf1[18] = -bf0[18] + bf0[17]; bf1[19] = -bf0[19] + bf0[16]; bf1[20] = -bf0[20] + bf0[23]; bf1[21] = -bf0[21] + bf0[22]; bf1[22] = bf0[22] + bf0[21]; bf1[23] = bf0[23] + bf0[20]; bf1[24] = bf0[24] + bf0[27]; bf1[25] = bf0[25] + bf0[26]; bf1[26] = -bf0[26] + bf0[25]; bf1[27] = -bf0[27] + bf0[24]; bf1[28] = -bf0[28] + bf0[31]; bf1[29] = -bf0[29] + bf0[30]; bf1[30] = bf0[30] + bf0[29]; bf1[31] = bf0[31] + bf0[28]; bf1[32] = bf0[32]; bf1[33] = bf0[33]; bf1[34] = half_btf(-cospi[8], bf0[34], cospi[56], bf0[61], cos_bit); bf1[35] = half_btf(-cospi[8], bf0[35], cospi[56], bf0[60], cos_bit); bf1[36] = half_btf(-cospi[56], bf0[36], -cospi[8], bf0[59], cos_bit); bf1[37] = half_btf(-cospi[56], bf0[37], -cospi[8], bf0[58], cos_bit); bf1[38] = bf0[38]; bf1[39] = bf0[39]; bf1[40] = bf0[40]; bf1[41] = bf0[41]; bf1[42] = half_btf(-cospi[40], bf0[42], cospi[24], bf0[53], cos_bit); bf1[43] = half_btf(-cospi[40], bf0[43], cospi[24], bf0[52], cos_bit); bf1[44] = half_btf(-cospi[24], bf0[44], -cospi[40], bf0[51], cos_bit); bf1[45] = half_btf(-cospi[24], bf0[45], -cospi[40], bf0[50], cos_bit); bf1[46] = bf0[46]; bf1[47] = bf0[47]; bf1[48] = bf0[48]; bf1[49] = bf0[49]; bf1[50] = half_btf(cospi[24], bf0[50], -cospi[40], bf0[45], cos_bit); bf1[51] = half_btf(cospi[24], bf0[51], -cospi[40], bf0[44], cos_bit); bf1[52] = half_btf(cospi[40], bf0[52], cospi[24], bf0[43], cos_bit); bf1[53] = half_btf(cospi[40], bf0[53], cospi[24], bf0[42], cos_bit); bf1[54] = bf0[54]; bf1[55] = bf0[55]; bf1[56] = bf0[56]; bf1[57] = bf0[57]; bf1[58] = half_btf(cospi[56], bf0[58], -cospi[8], bf0[37], cos_bit); bf1[59] = half_btf(cospi[56], bf0[59], -cospi[8], bf0[36], cos_bit); bf1[60] = half_btf(cospi[8], bf0[60], cospi[56], bf0[35], cos_bit); bf1[61] = half_btf(cospi[8], bf0[61], cospi[56], bf0[34], cos_bit); bf1[62] = bf0[62]; bf1[63] = bf0[63]; // stage 7 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[5] = half_btf(cospi[24], bf0[5], cospi[40], bf0[6], cos_bit); bf1[6] = half_btf(cospi[24], bf0[6], -cospi[40], bf0[5], cos_bit); bf1[7] = half_btf(cospi[56], bf0[7], -cospi[8], bf0[4], cos_bit); bf1[8] = bf0[8] + bf0[9]; bf1[9] = -bf0[9] + bf0[8]; bf1[10] = -bf0[10] + bf0[11]; bf1[11] = bf0[11] + bf0[10]; bf1[12] = bf0[12] + bf0[13]; bf1[13] = -bf0[13] + bf0[12]; bf1[14] = -bf0[14] + bf0[15]; bf1[15] = bf0[15] + bf0[14]; bf1[16] = bf0[16]; bf1[17] = half_btf(-cospi[8], bf0[17], cospi[56], bf0[30], cos_bit); bf1[18] = half_btf(-cospi[56], bf0[18], -cospi[8], bf0[29], cos_bit); bf1[19] = bf0[19]; bf1[20] = bf0[20]; bf1[21] = half_btf(-cospi[40], bf0[21], cospi[24], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[24], bf0[22], -cospi[40], bf0[25], cos_bit); bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = half_btf(cospi[24], bf0[25], -cospi[40], bf0[22], cos_bit); bf1[26] = half_btf(cospi[40], bf0[26], cospi[24], bf0[21], cos_bit); bf1[27] = bf0[27]; bf1[28] = bf0[28]; bf1[29] = half_btf(cospi[56], bf0[29], -cospi[8], bf0[18], cos_bit); bf1[30] = half_btf(cospi[8], bf0[30], cospi[56], bf0[17], cos_bit); bf1[31] = bf0[31]; bf1[32] = bf0[32] + bf0[35]; bf1[33] = bf0[33] + bf0[34]; bf1[34] = -bf0[34] + bf0[33]; bf1[35] = -bf0[35] + bf0[32]; bf1[36] = -bf0[36] + bf0[39]; bf1[37] = -bf0[37] + bf0[38]; bf1[38] = bf0[38] + bf0[37]; bf1[39] = bf0[39] + bf0[36]; bf1[40] = bf0[40] + bf0[43]; bf1[41] = bf0[41] + bf0[42]; bf1[42] = -bf0[42] + bf0[41]; bf1[43] = -bf0[43] + bf0[40]; bf1[44] = -bf0[44] + bf0[47]; bf1[45] = -bf0[45] + bf0[46]; bf1[46] = bf0[46] + bf0[45]; bf1[47] = bf0[47] + bf0[44]; bf1[48] = bf0[48] + bf0[51]; bf1[49] = bf0[49] + bf0[50]; bf1[50] = -bf0[50] + bf0[49]; bf1[51] = -bf0[51] + bf0[48]; bf1[52] = -bf0[52] + bf0[55]; bf1[53] = -bf0[53] + bf0[54]; bf1[54] = bf0[54] + bf0[53]; bf1[55] = bf0[55] + bf0[52]; bf1[56] = bf0[56] + bf0[59]; bf1[57] = bf0[57] + bf0[58]; bf1[58] = -bf0[58] + bf0[57]; bf1[59] = -bf0[59] + bf0[56]; bf1[60] = -bf0[60] + bf0[63]; bf1[61] = -bf0[61] + bf0[62]; bf1[62] = bf0[62] + bf0[61]; bf1[63] = bf0[63] + bf0[60]; // stage 8 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = half_btf(cospi[60], bf0[8], cospi[4], bf0[15], cos_bit); bf1[9] = half_btf(cospi[28], bf0[9], cospi[36], bf0[14], cos_bit); bf1[10] = half_btf(cospi[44], bf0[10], cospi[20], bf0[13], cos_bit); bf1[11] = half_btf(cospi[12], bf0[11], cospi[52], bf0[12], cos_bit); bf1[12] = half_btf(cospi[12], bf0[12], -cospi[52], bf0[11], cos_bit); bf1[13] = half_btf(cospi[44], bf0[13], -cospi[20], bf0[10], cos_bit); bf1[14] = half_btf(cospi[28], bf0[14], -cospi[36], bf0[9], cos_bit); bf1[15] = half_btf(cospi[60], bf0[15], -cospi[4], bf0[8], cos_bit); bf1[16] = bf0[16] + bf0[17]; bf1[17] = -bf0[17] + bf0[16]; bf1[18] = -bf0[18] + bf0[19]; bf1[19] = bf0[19] + bf0[18]; bf1[20] = bf0[20] + bf0[21]; bf1[21] = -bf0[21] + bf0[20]; bf1[22] = -bf0[22] + bf0[23]; bf1[23] = bf0[23] + bf0[22]; bf1[24] = bf0[24] + bf0[25]; bf1[25] = -bf0[25] + bf0[24]; bf1[26] = -bf0[26] + bf0[27]; bf1[27] = bf0[27] + bf0[26]; bf1[28] = bf0[28] + bf0[29]; bf1[29] = -bf0[29] + bf0[28]; bf1[30] = -bf0[30] + bf0[31]; bf1[31] = bf0[31] + bf0[30]; bf1[32] = bf0[32]; bf1[33] = half_btf(-cospi[4], bf0[33], cospi[60], bf0[62], cos_bit); bf1[34] = half_btf(-cospi[60], bf0[34], -cospi[4], bf0[61], cos_bit); bf1[35] = bf0[35]; bf1[36] = bf0[36]; bf1[37] = half_btf(-cospi[36], bf0[37], cospi[28], bf0[58], cos_bit); bf1[38] = half_btf(-cospi[28], bf0[38], -cospi[36], bf0[57], cos_bit); bf1[39] = bf0[39]; bf1[40] = bf0[40]; bf1[41] = half_btf(-cospi[20], bf0[41], cospi[44], bf0[54], cos_bit); bf1[42] = half_btf(-cospi[44], bf0[42], -cospi[20], bf0[53], cos_bit); bf1[43] = bf0[43]; bf1[44] = bf0[44]; bf1[45] = half_btf(-cospi[52], bf0[45], cospi[12], bf0[50], cos_bit); bf1[46] = half_btf(-cospi[12], bf0[46], -cospi[52], bf0[49], cos_bit); bf1[47] = bf0[47]; bf1[48] = bf0[48]; bf1[49] = half_btf(cospi[12], bf0[49], -cospi[52], bf0[46], cos_bit); bf1[50] = half_btf(cospi[52], bf0[50], cospi[12], bf0[45], cos_bit); bf1[51] = bf0[51]; bf1[52] = bf0[52]; bf1[53] = half_btf(cospi[44], bf0[53], -cospi[20], bf0[42], cos_bit); bf1[54] = half_btf(cospi[20], bf0[54], cospi[44], bf0[41], cos_bit); bf1[55] = bf0[55]; bf1[56] = bf0[56]; bf1[57] = half_btf(cospi[28], bf0[57], -cospi[36], bf0[38], cos_bit); bf1[58] = half_btf(cospi[36], bf0[58], cospi[28], bf0[37], cos_bit); bf1[59] = bf0[59]; bf1[60] = bf0[60]; bf1[61] = half_btf(cospi[60], bf0[61], -cospi[4], bf0[34], cos_bit); bf1[62] = half_btf(cospi[4], bf0[62], cospi[60], bf0[33], cos_bit); bf1[63] = bf0[63]; // stage 9 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = bf0[10]; bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = bf0[13]; bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = half_btf(cospi[62], bf0[16], cospi[2], bf0[31], cos_bit); bf1[17] = half_btf(cospi[30], bf0[17], cospi[34], bf0[30], cos_bit); bf1[18] = half_btf(cospi[46], bf0[18], cospi[18], bf0[29], cos_bit); bf1[19] = half_btf(cospi[14], bf0[19], cospi[50], bf0[28], cos_bit); bf1[20] = half_btf(cospi[54], bf0[20], cospi[10], bf0[27], cos_bit); bf1[21] = half_btf(cospi[22], bf0[21], cospi[42], bf0[26], cos_bit); bf1[22] = half_btf(cospi[38], bf0[22], cospi[26], bf0[25], cos_bit); bf1[23] = half_btf(cospi[6], bf0[23], cospi[58], bf0[24], cos_bit); bf1[24] = half_btf(cospi[6], bf0[24], -cospi[58], bf0[23], cos_bit); bf1[25] = half_btf(cospi[38], bf0[25], -cospi[26], bf0[22], cos_bit); bf1[26] = half_btf(cospi[22], bf0[26], -cospi[42], bf0[21], cos_bit); bf1[27] = half_btf(cospi[54], bf0[27], -cospi[10], bf0[20], cos_bit); bf1[28] = half_btf(cospi[14], bf0[28], -cospi[50], bf0[19], cos_bit); bf1[29] = half_btf(cospi[46], bf0[29], -cospi[18], bf0[18], cos_bit); bf1[30] = half_btf(cospi[30], bf0[30], -cospi[34], bf0[17], cos_bit); bf1[31] = half_btf(cospi[62], bf0[31], -cospi[2], bf0[16], cos_bit); bf1[32] = bf0[32] + bf0[33]; bf1[33] = -bf0[33] + bf0[32]; bf1[34] = -bf0[34] + bf0[35]; bf1[35] = bf0[35] + bf0[34]; bf1[36] = bf0[36] + bf0[37]; bf1[37] = -bf0[37] + bf0[36]; bf1[38] = -bf0[38] + bf0[39]; bf1[39] = bf0[39] + bf0[38]; bf1[40] = bf0[40] + bf0[41]; bf1[41] = -bf0[41] + bf0[40]; bf1[42] = -bf0[42] + bf0[43]; bf1[43] = bf0[43] + bf0[42]; bf1[44] = bf0[44] + bf0[45]; bf1[45] = -bf0[45] + bf0[44]; bf1[46] = -bf0[46] + bf0[47]; bf1[47] = bf0[47] + bf0[46]; bf1[48] = bf0[48] + bf0[49]; bf1[49] = -bf0[49] + bf0[48]; bf1[50] = -bf0[50] + bf0[51]; bf1[51] = bf0[51] + bf0[50]; bf1[52] = bf0[52] + bf0[53]; bf1[53] = -bf0[53] + bf0[52]; bf1[54] = -bf0[54] + bf0[55]; bf1[55] = bf0[55] + bf0[54]; bf1[56] = bf0[56] + bf0[57]; bf1[57] = -bf0[57] + bf0[56]; bf1[58] = -bf0[58] + bf0[59]; bf1[59] = bf0[59] + bf0[58]; bf1[60] = bf0[60] + bf0[61]; bf1[61] = -bf0[61] + bf0[60]; bf1[62] = -bf0[62] + bf0[63]; bf1[63] = bf0[63] + bf0[62]; // stage 10 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = bf0[10]; bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = bf0[13]; bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = bf0[18]; bf1[19] = bf0[19]; bf1[20] = bf0[20]; bf1[21] = bf0[21]; bf1[22] = bf0[22]; bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = bf0[25]; bf1[26] = bf0[26]; bf1[27] = bf0[27]; bf1[28] = bf0[28]; bf1[29] = bf0[29]; bf1[30] = bf0[30]; bf1[31] = bf0[31]; bf1[32] = half_btf(cospi[63], bf0[32], cospi[1], bf0[63], cos_bit); bf1[33] = half_btf(cospi[31], bf0[33], cospi[33], bf0[62], cos_bit); bf1[34] = half_btf(cospi[47], bf0[34], cospi[17], bf0[61], cos_bit); bf1[35] = half_btf(cospi[15], bf0[35], cospi[49], bf0[60], cos_bit); bf1[36] = half_btf(cospi[55], bf0[36], cospi[9], bf0[59], cos_bit); bf1[37] = half_btf(cospi[23], bf0[37], cospi[41], bf0[58], cos_bit); bf1[38] = half_btf(cospi[39], bf0[38], cospi[25], bf0[57], cos_bit); bf1[39] = half_btf(cospi[7], bf0[39], cospi[57], bf0[56], cos_bit); bf1[40] = half_btf(cospi[59], bf0[40], cospi[5], bf0[55], cos_bit); bf1[41] = half_btf(cospi[27], bf0[41], cospi[37], bf0[54], cos_bit); bf1[42] = half_btf(cospi[43], bf0[42], cospi[21], bf0[53], cos_bit); bf1[43] = half_btf(cospi[11], bf0[43], cospi[53], bf0[52], cos_bit); bf1[44] = half_btf(cospi[51], bf0[44], cospi[13], bf0[51], cos_bit); bf1[45] = half_btf(cospi[19], bf0[45], cospi[45], bf0[50], cos_bit); bf1[46] = half_btf(cospi[35], bf0[46], cospi[29], bf0[49], cos_bit); bf1[47] = half_btf(cospi[3], bf0[47], cospi[61], bf0[48], cos_bit); bf1[48] = half_btf(cospi[3], bf0[48], -cospi[61], bf0[47], cos_bit); bf1[49] = half_btf(cospi[35], bf0[49], -cospi[29], bf0[46], cos_bit); bf1[50] = half_btf(cospi[19], bf0[50], -cospi[45], bf0[45], cos_bit); bf1[51] = half_btf(cospi[51], bf0[51], -cospi[13], bf0[44], cos_bit); bf1[52] = half_btf(cospi[11], bf0[52], -cospi[53], bf0[43], cos_bit); bf1[53] = half_btf(cospi[43], bf0[53], -cospi[21], bf0[42], cos_bit); bf1[54] = half_btf(cospi[27], bf0[54], -cospi[37], bf0[41], cos_bit); bf1[55] = half_btf(cospi[59], bf0[55], -cospi[5], bf0[40], cos_bit); bf1[56] = half_btf(cospi[7], bf0[56], -cospi[57], bf0[39], cos_bit); bf1[57] = half_btf(cospi[39], bf0[57], -cospi[25], bf0[38], cos_bit); bf1[58] = half_btf(cospi[23], bf0[58], -cospi[41], bf0[37], cos_bit); bf1[59] = half_btf(cospi[55], bf0[59], -cospi[9], bf0[36], cos_bit); bf1[60] = half_btf(cospi[15], bf0[60], -cospi[49], bf0[35], cos_bit); bf1[61] = half_btf(cospi[47], bf0[61], -cospi[17], bf0[34], cos_bit); bf1[62] = half_btf(cospi[31], bf0[62], -cospi[33], bf0[33], cos_bit); bf1[63] = half_btf(cospi[63], bf0[63], -cospi[1], bf0[32], cos_bit); // stage 11 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[32]; bf1[2] = bf0[16]; bf1[3] = bf0[48]; bf1[4] = bf0[8]; bf1[5] = bf0[40]; bf1[6] = bf0[24]; bf1[7] = bf0[56]; bf1[8] = bf0[4]; bf1[9] = bf0[36]; bf1[10] = bf0[20]; bf1[11] = bf0[52]; bf1[12] = bf0[12]; bf1[13] = bf0[44]; bf1[14] = bf0[28]; bf1[15] = bf0[60]; bf1[16] = bf0[2]; bf1[17] = bf0[34]; bf1[18] = bf0[18]; bf1[19] = bf0[50]; bf1[20] = bf0[10]; bf1[21] = bf0[42]; bf1[22] = bf0[26]; bf1[23] = bf0[58]; bf1[24] = bf0[6]; bf1[25] = bf0[38]; bf1[26] = bf0[22]; bf1[27] = bf0[54]; bf1[28] = bf0[14]; bf1[29] = bf0[46]; bf1[30] = bf0[30]; bf1[31] = bf0[62]; bf1[32] = bf0[1]; bf1[33] = bf0[33]; bf1[34] = bf0[17]; bf1[35] = bf0[49]; bf1[36] = bf0[9]; bf1[37] = bf0[41]; bf1[38] = bf0[25]; bf1[39] = bf0[57]; bf1[40] = bf0[5]; bf1[41] = bf0[37]; bf1[42] = bf0[21]; bf1[43] = bf0[53]; bf1[44] = bf0[13]; bf1[45] = bf0[45]; bf1[46] = bf0[29]; bf1[47] = bf0[61]; bf1[48] = bf0[3]; bf1[49] = bf0[35]; bf1[50] = bf0[19]; bf1[51] = bf0[51]; bf1[52] = bf0[11]; bf1[53] = bf0[43]; bf1[54] = bf0[27]; bf1[55] = bf0[59]; bf1[56] = bf0[7]; bf1[57] = bf0[39]; bf1[58] = bf0[23]; bf1[59] = bf0[55]; bf1[60] = bf0[15]; bf1[61] = bf0[47]; bf1[62] = bf0[31]; bf1[63] = bf0[63]; } void svt_av1_fadst4_new(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; int32_t bit = cos_bit; const int32_t *sinpi = sinpi_arr(bit); int32_t x0, x1, x2, x3; int32_t s0, s1, s2, s3, s4, s5, s6, s7; // stage 0 x0 = input[0]; x1 = input[1]; x2 = input[2]; x3 = input[3]; if (!(x0 | x1 | x2 | x3)) { output[0] = output[1] = output[2] = output[3] = 0; return; } //// stage 1 //s0 = range_check_value(sinpi[1] * x0, bit + stage_range[1]); //s1 = range_check_value(sinpi[4] * x0, bit + stage_range[1]); //s2 = range_check_value(sinpi[2] * x1, bit + stage_range[1]); //s3 = range_check_value(sinpi[1] * x1, bit + stage_range[1]); //s4 = range_check_value(sinpi[3] * x2, bit + stage_range[1]); //s5 = range_check_value(sinpi[4] * x3, bit + stage_range[1]); //s6 = range_check_value(sinpi[2] * x3, bit + stage_range[1]); //s7 = range_check_value(x0 + x1, stage_range[1]); //// stage 2 //s7 = range_check_value(s7 - x3, stage_range[2]); //// stage 3 //x0 = range_check_value(s0 + s2, bit + stage_range[3]); //x1 = range_check_value(sinpi[3] * s7, bit + stage_range[3]); //x2 = range_check_value(s1 - s3, bit + stage_range[3]); //x3 = range_check_value(s4, bit + stage_range[3]); //// stage 4 //x0 = range_check_value(x0 + s5, bit + stage_range[4]); //x2 = range_check_value(x2 + s6, bit + stage_range[4]); //// stage 5 //s0 = range_check_value(x0 + x3, bit + stage_range[5]); //s1 = range_check_value(x1, bit + stage_range[5]); //s2 = range_check_value(x2 - x3, bit + stage_range[5]); //s3 = range_check_value(x2 - x0, bit + stage_range[5]); //// stage 6 //s3 = range_check_value(s3 + x3, bit + stage_range[6]); // stage 1 s0 = sinpi[1] * x0; s1 = sinpi[4] * x0; s2 = sinpi[2] * x1; s3 = sinpi[1] * x1; s4 = sinpi[3] * x2; s5 = sinpi[4] * x3; s6 = sinpi[2] * x3; s7 = x0 + x1; // stage 2 s7 = s7 - x3; // stage 3 x0 = s0 + s2; x1 = sinpi[3] * s7; x2 = s1 - s3; x3 = s4; // stage 4 x0 = x0 + s5; x2 = x2 + s6; // stage 5 s0 = x0 + x3; s1 = x1; s2 = x2 - x3; s3 = x2 - x0; // stage 6 s3 = s3 + x3; // 1-D transform scaling factor is sqrt(2). output[0] = round_shift(s0, bit); output[1] = round_shift(s1, bit); output[2] = round_shift(s2, bit); output[3] = round_shift(s3, bit); } void svt_av1_fadst8_new(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[8]; // stage 0; // stage 1; assert(output != input); bf1 = output; bf1[0] = input[0]; bf1[1] = -input[7]; bf1[2] = -input[3]; bf1[3] = input[4]; bf1[4] = -input[1]; bf1[5] = input[6]; bf1[6] = input[2]; bf1[7] = -input[5]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = half_btf(cospi[32], bf0[2], cospi[32], bf0[3], cos_bit); bf1[3] = half_btf(cospi[32], bf0[2], -cospi[32], bf0[3], cos_bit); bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[7], cos_bit); bf1[7] = half_btf(cospi[32], bf0[6], -cospi[32], bf0[7], cos_bit); // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[2]; bf1[1] = bf0[1] + bf0[3]; bf1[2] = bf0[0] - bf0[2]; bf1[3] = bf0[1] - bf0[3]; bf1[4] = bf0[4] + bf0[6]; bf1[5] = bf0[5] + bf0[7]; bf1[6] = bf0[4] - bf0[6]; bf1[7] = bf0[5] - bf0[7]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[16], bf0[4], cospi[48], bf0[5], cos_bit); bf1[5] = half_btf(cospi[48], bf0[4], -cospi[16], bf0[5], cos_bit); bf1[6] = half_btf(-cospi[48], bf0[6], cospi[16], bf0[7], cos_bit); bf1[7] = half_btf(cospi[16], bf0[6], cospi[48], bf0[7], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[4]; bf1[1] = bf0[1] + bf0[5]; bf1[2] = bf0[2] + bf0[6]; bf1[3] = bf0[3] + bf0[7]; bf1[4] = bf0[0] - bf0[4]; bf1[5] = bf0[1] - bf0[5]; bf1[6] = bf0[2] - bf0[6]; bf1[7] = bf0[3] - bf0[7]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[4], bf0[0], cospi[60], bf0[1], cos_bit); bf1[1] = half_btf(cospi[60], bf0[0], -cospi[4], bf0[1], cos_bit); bf1[2] = half_btf(cospi[20], bf0[2], cospi[44], bf0[3], cos_bit); bf1[3] = half_btf(cospi[44], bf0[2], -cospi[20], bf0[3], cos_bit); bf1[4] = half_btf(cospi[36], bf0[4], cospi[28], bf0[5], cos_bit); bf1[5] = half_btf(cospi[28], bf0[4], -cospi[36], bf0[5], cos_bit); bf1[6] = half_btf(cospi[52], bf0[6], cospi[12], bf0[7], cos_bit); bf1[7] = half_btf(cospi[12], bf0[6], -cospi[52], bf0[7], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[1]; bf1[1] = bf0[6]; bf1[2] = bf0[3]; bf1[3] = bf0[4]; bf1[4] = bf0[5]; bf1[5] = bf0[2]; bf1[6] = bf0[7]; bf1[7] = bf0[0]; } void svt_av1_fadst16_new(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[16]; // stage 0; // stage 1; assert(output != input); bf1 = output; bf1[0] = input[0]; bf1[1] = -input[15]; bf1[2] = -input[7]; bf1[3] = input[8]; bf1[4] = -input[3]; bf1[5] = input[12]; bf1[6] = input[4]; bf1[7] = -input[11]; bf1[8] = -input[1]; bf1[9] = input[14]; bf1[10] = input[6]; bf1[11] = -input[9]; bf1[12] = input[2]; bf1[13] = -input[13]; bf1[14] = -input[5]; bf1[15] = input[10]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = half_btf(cospi[32], bf0[2], cospi[32], bf0[3], cos_bit); bf1[3] = half_btf(cospi[32], bf0[2], -cospi[32], bf0[3], cos_bit); bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[7], cos_bit); bf1[7] = half_btf(cospi[32], bf0[6], -cospi[32], bf0[7], cos_bit); bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(cospi[32], bf0[10], cospi[32], bf0[11], cos_bit); bf1[11] = half_btf(cospi[32], bf0[10], -cospi[32], bf0[11], cos_bit); bf1[12] = bf0[12]; bf1[13] = bf0[13]; bf1[14] = half_btf(cospi[32], bf0[14], cospi[32], bf0[15], cos_bit); bf1[15] = half_btf(cospi[32], bf0[14], -cospi[32], bf0[15], cos_bit); // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[2]; bf1[1] = bf0[1] + bf0[3]; bf1[2] = bf0[0] - bf0[2]; bf1[3] = bf0[1] - bf0[3]; bf1[4] = bf0[4] + bf0[6]; bf1[5] = bf0[5] + bf0[7]; bf1[6] = bf0[4] - bf0[6]; bf1[7] = bf0[5] - bf0[7]; bf1[8] = bf0[8] + bf0[10]; bf1[9] = bf0[9] + bf0[11]; bf1[10] = bf0[8] - bf0[10]; bf1[11] = bf0[9] - bf0[11]; bf1[12] = bf0[12] + bf0[14]; bf1[13] = bf0[13] + bf0[15]; bf1[14] = bf0[12] - bf0[14]; bf1[15] = bf0[13] - bf0[15]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[16], bf0[4], cospi[48], bf0[5], cos_bit); bf1[5] = half_btf(cospi[48], bf0[4], -cospi[16], bf0[5], cos_bit); bf1[6] = half_btf(-cospi[48], bf0[6], cospi[16], bf0[7], cos_bit); bf1[7] = half_btf(cospi[16], bf0[6], cospi[48], bf0[7], cos_bit); bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = bf0[10]; bf1[11] = bf0[11]; bf1[12] = half_btf(cospi[16], bf0[12], cospi[48], bf0[13], cos_bit); bf1[13] = half_btf(cospi[48], bf0[12], -cospi[16], bf0[13], cos_bit); bf1[14] = half_btf(-cospi[48], bf0[14], cospi[16], bf0[15], cos_bit); bf1[15] = half_btf(cospi[16], bf0[14], cospi[48], bf0[15], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[4]; bf1[1] = bf0[1] + bf0[5]; bf1[2] = bf0[2] + bf0[6]; bf1[3] = bf0[3] + bf0[7]; bf1[4] = bf0[0] - bf0[4]; bf1[5] = bf0[1] - bf0[5]; bf1[6] = bf0[2] - bf0[6]; bf1[7] = bf0[3] - bf0[7]; bf1[8] = bf0[8] + bf0[12]; bf1[9] = bf0[9] + bf0[13]; bf1[10] = bf0[10] + bf0[14]; bf1[11] = bf0[11] + bf0[15]; bf1[12] = bf0[8] - bf0[12]; bf1[13] = bf0[9] - bf0[13]; bf1[14] = bf0[10] - bf0[14]; bf1[15] = bf0[11] - bf0[15]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = half_btf(cospi[8], bf0[8], cospi[56], bf0[9], cos_bit); bf1[9] = half_btf(cospi[56], bf0[8], -cospi[8], bf0[9], cos_bit); bf1[10] = half_btf(cospi[40], bf0[10], cospi[24], bf0[11], cos_bit); bf1[11] = half_btf(cospi[24], bf0[10], -cospi[40], bf0[11], cos_bit); bf1[12] = half_btf(-cospi[56], bf0[12], cospi[8], bf0[13], cos_bit); bf1[13] = half_btf(cospi[8], bf0[12], cospi[56], bf0[13], cos_bit); bf1[14] = half_btf(-cospi[24], bf0[14], cospi[40], bf0[15], cos_bit); bf1[15] = half_btf(cospi[40], bf0[14], cospi[24], bf0[15], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[8]; bf1[1] = bf0[1] + bf0[9]; bf1[2] = bf0[2] + bf0[10]; bf1[3] = bf0[3] + bf0[11]; bf1[4] = bf0[4] + bf0[12]; bf1[5] = bf0[5] + bf0[13]; bf1[6] = bf0[6] + bf0[14]; bf1[7] = bf0[7] + bf0[15]; bf1[8] = bf0[0] - bf0[8]; bf1[9] = bf0[1] - bf0[9]; bf1[10] = bf0[2] - bf0[10]; bf1[11] = bf0[3] - bf0[11]; bf1[12] = bf0[4] - bf0[12]; bf1[13] = bf0[5] - bf0[13]; bf1[14] = bf0[6] - bf0[14]; bf1[15] = bf0[7] - bf0[15]; // stage 8 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[2], bf0[0], cospi[62], bf0[1], cos_bit); bf1[1] = half_btf(cospi[62], bf0[0], -cospi[2], bf0[1], cos_bit); bf1[2] = half_btf(cospi[10], bf0[2], cospi[54], bf0[3], cos_bit); bf1[3] = half_btf(cospi[54], bf0[2], -cospi[10], bf0[3], cos_bit); bf1[4] = half_btf(cospi[18], bf0[4], cospi[46], bf0[5], cos_bit); bf1[5] = half_btf(cospi[46], bf0[4], -cospi[18], bf0[5], cos_bit); bf1[6] = half_btf(cospi[26], bf0[6], cospi[38], bf0[7], cos_bit); bf1[7] = half_btf(cospi[38], bf0[6], -cospi[26], bf0[7], cos_bit); bf1[8] = half_btf(cospi[34], bf0[8], cospi[30], bf0[9], cos_bit); bf1[9] = half_btf(cospi[30], bf0[8], -cospi[34], bf0[9], cos_bit); bf1[10] = half_btf(cospi[42], bf0[10], cospi[22], bf0[11], cos_bit); bf1[11] = half_btf(cospi[22], bf0[10], -cospi[42], bf0[11], cos_bit); bf1[12] = half_btf(cospi[50], bf0[12], cospi[14], bf0[13], cos_bit); bf1[13] = half_btf(cospi[14], bf0[12], -cospi[50], bf0[13], cos_bit); bf1[14] = half_btf(cospi[58], bf0[14], cospi[6], bf0[15], cos_bit); bf1[15] = half_btf(cospi[6], bf0[14], -cospi[58], bf0[15], cos_bit); // stage 9 bf0 = step; bf1 = output; bf1[0] = bf0[1]; bf1[1] = bf0[14]; bf1[2] = bf0[3]; bf1[3] = bf0[12]; bf1[4] = bf0[5]; bf1[5] = bf0[10]; bf1[6] = bf0[7]; bf1[7] = bf0[8]; bf1[8] = bf0[9]; bf1[9] = bf0[6]; bf1[10] = bf0[11]; bf1[11] = bf0[4]; bf1[12] = bf0[13]; bf1[13] = bf0[2]; bf1[14] = bf0[15]; bf1[15] = bf0[0]; } void av1_fadst32_new(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[32]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[31]; bf1[1] = input[0]; bf1[2] = input[29]; bf1[3] = input[2]; bf1[4] = input[27]; bf1[5] = input[4]; bf1[6] = input[25]; bf1[7] = input[6]; bf1[8] = input[23]; bf1[9] = input[8]; bf1[10] = input[21]; bf1[11] = input[10]; bf1[12] = input[19]; bf1[13] = input[12]; bf1[14] = input[17]; bf1[15] = input[14]; bf1[16] = input[15]; bf1[17] = input[16]; bf1[18] = input[13]; bf1[19] = input[18]; bf1[20] = input[11]; bf1[21] = input[20]; bf1[22] = input[9]; bf1[23] = input[22]; bf1[24] = input[7]; bf1[25] = input[24]; bf1[26] = input[5]; bf1[27] = input[26]; bf1[28] = input[3]; bf1[29] = input[28]; bf1[30] = input[1]; bf1[31] = input[30]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[1], bf0[0], cospi[63], bf0[1], cos_bit); bf1[1] = half_btf(-cospi[1], bf0[1], cospi[63], bf0[0], cos_bit); bf1[2] = half_btf(cospi[5], bf0[2], cospi[59], bf0[3], cos_bit); bf1[3] = half_btf(-cospi[5], bf0[3], cospi[59], bf0[2], cos_bit); bf1[4] = half_btf(cospi[9], bf0[4], cospi[55], bf0[5], cos_bit); bf1[5] = half_btf(-cospi[9], bf0[5], cospi[55], bf0[4], cos_bit); bf1[6] = half_btf(cospi[13], bf0[6], cospi[51], bf0[7], cos_bit); bf1[7] = half_btf(-cospi[13], bf0[7], cospi[51], bf0[6], cos_bit); bf1[8] = half_btf(cospi[17], bf0[8], cospi[47], bf0[9], cos_bit); bf1[9] = half_btf(-cospi[17], bf0[9], cospi[47], bf0[8], cos_bit); bf1[10] = half_btf(cospi[21], bf0[10], cospi[43], bf0[11], cos_bit); bf1[11] = half_btf(-cospi[21], bf0[11], cospi[43], bf0[10], cos_bit); bf1[12] = half_btf(cospi[25], bf0[12], cospi[39], bf0[13], cos_bit); bf1[13] = half_btf(-cospi[25], bf0[13], cospi[39], bf0[12], cos_bit); bf1[14] = half_btf(cospi[29], bf0[14], cospi[35], bf0[15], cos_bit); bf1[15] = half_btf(-cospi[29], bf0[15], cospi[35], bf0[14], cos_bit); bf1[16] = half_btf(cospi[33], bf0[16], cospi[31], bf0[17], cos_bit); bf1[17] = half_btf(-cospi[33], bf0[17], cospi[31], bf0[16], cos_bit); bf1[18] = half_btf(cospi[37], bf0[18], cospi[27], bf0[19], cos_bit); bf1[19] = half_btf(-cospi[37], bf0[19], cospi[27], bf0[18], cos_bit); bf1[20] = half_btf(cospi[41], bf0[20], cospi[23], bf0[21], cos_bit); bf1[21] = half_btf(-cospi[41], bf0[21], cospi[23], bf0[20], cos_bit); bf1[22] = half_btf(cospi[45], bf0[22], cospi[19], bf0[23], cos_bit); bf1[23] = half_btf(-cospi[45], bf0[23], cospi[19], bf0[22], cos_bit); bf1[24] = half_btf(cospi[49], bf0[24], cospi[15], bf0[25], cos_bit); bf1[25] = half_btf(-cospi[49], bf0[25], cospi[15], bf0[24], cos_bit); bf1[26] = half_btf(cospi[53], bf0[26], cospi[11], bf0[27], cos_bit); bf1[27] = half_btf(-cospi[53], bf0[27], cospi[11], bf0[26], cos_bit); bf1[28] = half_btf(cospi[57], bf0[28], cospi[7], bf0[29], cos_bit); bf1[29] = half_btf(-cospi[57], bf0[29], cospi[7], bf0[28], cos_bit); bf1[30] = half_btf(cospi[61], bf0[30], cospi[3], bf0[31], cos_bit); bf1[31] = half_btf(-cospi[61], bf0[31], cospi[3], bf0[30], cos_bit); // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[16]; bf1[1] = bf0[1] + bf0[17]; bf1[2] = bf0[2] + bf0[18]; bf1[3] = bf0[3] + bf0[19]; bf1[4] = bf0[4] + bf0[20]; bf1[5] = bf0[5] + bf0[21]; bf1[6] = bf0[6] + bf0[22]; bf1[7] = bf0[7] + bf0[23]; bf1[8] = bf0[8] + bf0[24]; bf1[9] = bf0[9] + bf0[25]; bf1[10] = bf0[10] + bf0[26]; bf1[11] = bf0[11] + bf0[27]; bf1[12] = bf0[12] + bf0[28]; bf1[13] = bf0[13] + bf0[29]; bf1[14] = bf0[14] + bf0[30]; bf1[15] = bf0[15] + bf0[31]; bf1[16] = -bf0[16] + bf0[0]; bf1[17] = -bf0[17] + bf0[1]; bf1[18] = -bf0[18] + bf0[2]; bf1[19] = -bf0[19] + bf0[3]; bf1[20] = -bf0[20] + bf0[4]; bf1[21] = -bf0[21] + bf0[5]; bf1[22] = -bf0[22] + bf0[6]; bf1[23] = -bf0[23] + bf0[7]; bf1[24] = -bf0[24] + bf0[8]; bf1[25] = -bf0[25] + bf0[9]; bf1[26] = -bf0[26] + bf0[10]; bf1[27] = -bf0[27] + bf0[11]; bf1[28] = -bf0[28] + bf0[12]; bf1[29] = -bf0[29] + bf0[13]; bf1[30] = -bf0[30] + bf0[14]; bf1[31] = -bf0[31] + bf0[15]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = bf0[10]; bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = bf0[13]; bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = half_btf(cospi[4], bf0[16], cospi[60], bf0[17], cos_bit); bf1[17] = half_btf(-cospi[4], bf0[17], cospi[60], bf0[16], cos_bit); bf1[18] = half_btf(cospi[20], bf0[18], cospi[44], bf0[19], cos_bit); bf1[19] = half_btf(-cospi[20], bf0[19], cospi[44], bf0[18], cos_bit); bf1[20] = half_btf(cospi[36], bf0[20], cospi[28], bf0[21], cos_bit); bf1[21] = half_btf(-cospi[36], bf0[21], cospi[28], bf0[20], cos_bit); bf1[22] = half_btf(cospi[52], bf0[22], cospi[12], bf0[23], cos_bit); bf1[23] = half_btf(-cospi[52], bf0[23], cospi[12], bf0[22], cos_bit); bf1[24] = half_btf(-cospi[60], bf0[24], cospi[4], bf0[25], cos_bit); bf1[25] = half_btf(cospi[60], bf0[25], cospi[4], bf0[24], cos_bit); bf1[26] = half_btf(-cospi[44], bf0[26], cospi[20], bf0[27], cos_bit); bf1[27] = half_btf(cospi[44], bf0[27], cospi[20], bf0[26], cos_bit); bf1[28] = half_btf(-cospi[28], bf0[28], cospi[36], bf0[29], cos_bit); bf1[29] = half_btf(cospi[28], bf0[29], cospi[36], bf0[28], cos_bit); bf1[30] = half_btf(-cospi[12], bf0[30], cospi[52], bf0[31], cos_bit); bf1[31] = half_btf(cospi[12], bf0[31], cospi[52], bf0[30], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[8]; bf1[1] = bf0[1] + bf0[9]; bf1[2] = bf0[2] + bf0[10]; bf1[3] = bf0[3] + bf0[11]; bf1[4] = bf0[4] + bf0[12]; bf1[5] = bf0[5] + bf0[13]; bf1[6] = bf0[6] + bf0[14]; bf1[7] = bf0[7] + bf0[15]; bf1[8] = -bf0[8] + bf0[0]; bf1[9] = -bf0[9] + bf0[1]; bf1[10] = -bf0[10] + bf0[2]; bf1[11] = -bf0[11] + bf0[3]; bf1[12] = -bf0[12] + bf0[4]; bf1[13] = -bf0[13] + bf0[5]; bf1[14] = -bf0[14] + bf0[6]; bf1[15] = -bf0[15] + bf0[7]; bf1[16] = bf0[16] + bf0[24]; bf1[17] = bf0[17] + bf0[25]; bf1[18] = bf0[18] + bf0[26]; bf1[19] = bf0[19] + bf0[27]; bf1[20] = bf0[20] + bf0[28]; bf1[21] = bf0[21] + bf0[29]; bf1[22] = bf0[22] + bf0[30]; bf1[23] = bf0[23] + bf0[31]; bf1[24] = -bf0[24] + bf0[16]; bf1[25] = -bf0[25] + bf0[17]; bf1[26] = -bf0[26] + bf0[18]; bf1[27] = -bf0[27] + bf0[19]; bf1[28] = -bf0[28] + bf0[20]; bf1[29] = -bf0[29] + bf0[21]; bf1[30] = -bf0[30] + bf0[22]; bf1[31] = -bf0[31] + bf0[23]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = half_btf(cospi[8], bf0[8], cospi[56], bf0[9], cos_bit); bf1[9] = half_btf(-cospi[8], bf0[9], cospi[56], bf0[8], cos_bit); bf1[10] = half_btf(cospi[40], bf0[10], cospi[24], bf0[11], cos_bit); bf1[11] = half_btf(-cospi[40], bf0[11], cospi[24], bf0[10], cos_bit); bf1[12] = half_btf(-cospi[56], bf0[12], cospi[8], bf0[13], cos_bit); bf1[13] = half_btf(cospi[56], bf0[13], cospi[8], bf0[12], cos_bit); bf1[14] = half_btf(-cospi[24], bf0[14], cospi[40], bf0[15], cos_bit); bf1[15] = half_btf(cospi[24], bf0[15], cospi[40], bf0[14], cos_bit); bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = bf0[18]; bf1[19] = bf0[19]; bf1[20] = bf0[20]; bf1[21] = bf0[21]; bf1[22] = bf0[22]; bf1[23] = bf0[23]; bf1[24] = half_btf(cospi[8], bf0[24], cospi[56], bf0[25], cos_bit); bf1[25] = half_btf(-cospi[8], bf0[25], cospi[56], bf0[24], cos_bit); bf1[26] = half_btf(cospi[40], bf0[26], cospi[24], bf0[27], cos_bit); bf1[27] = half_btf(-cospi[40], bf0[27], cospi[24], bf0[26], cos_bit); bf1[28] = half_btf(-cospi[56], bf0[28], cospi[8], bf0[29], cos_bit); bf1[29] = half_btf(cospi[56], bf0[29], cospi[8], bf0[28], cos_bit); bf1[30] = half_btf(-cospi[24], bf0[30], cospi[40], bf0[31], cos_bit); bf1[31] = half_btf(cospi[24], bf0[31], cospi[40], bf0[30], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[4]; bf1[1] = bf0[1] + bf0[5]; bf1[2] = bf0[2] + bf0[6]; bf1[3] = bf0[3] + bf0[7]; bf1[4] = -bf0[4] + bf0[0]; bf1[5] = -bf0[5] + bf0[1]; bf1[6] = -bf0[6] + bf0[2]; bf1[7] = -bf0[7] + bf0[3]; bf1[8] = bf0[8] + bf0[12]; bf1[9] = bf0[9] + bf0[13]; bf1[10] = bf0[10] + bf0[14]; bf1[11] = bf0[11] + bf0[15]; bf1[12] = -bf0[12] + bf0[8]; bf1[13] = -bf0[13] + bf0[9]; bf1[14] = -bf0[14] + bf0[10]; bf1[15] = -bf0[15] + bf0[11]; bf1[16] = bf0[16] + bf0[20]; bf1[17] = bf0[17] + bf0[21]; bf1[18] = bf0[18] + bf0[22]; bf1[19] = bf0[19] + bf0[23]; bf1[20] = -bf0[20] + bf0[16]; bf1[21] = -bf0[21] + bf0[17]; bf1[22] = -bf0[22] + bf0[18]; bf1[23] = -bf0[23] + bf0[19]; bf1[24] = bf0[24] + bf0[28]; bf1[25] = bf0[25] + bf0[29]; bf1[26] = bf0[26] + bf0[30]; bf1[27] = bf0[27] + bf0[31]; bf1[28] = -bf0[28] + bf0[24]; bf1[29] = -bf0[29] + bf0[25]; bf1[30] = -bf0[30] + bf0[26]; bf1[31] = -bf0[31] + bf0[27]; // stage 8 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[16], bf0[4], cospi[48], bf0[5], cos_bit); bf1[5] = half_btf(-cospi[16], bf0[5], cospi[48], bf0[4], cos_bit); bf1[6] = half_btf(-cospi[48], bf0[6], cospi[16], bf0[7], cos_bit); bf1[7] = half_btf(cospi[48], bf0[7], cospi[16], bf0[6], cos_bit); bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = bf0[10]; bf1[11] = bf0[11]; bf1[12] = half_btf(cospi[16], bf0[12], cospi[48], bf0[13], cos_bit); bf1[13] = half_btf(-cospi[16], bf0[13], cospi[48], bf0[12], cos_bit); bf1[14] = half_btf(-cospi[48], bf0[14], cospi[16], bf0[15], cos_bit); bf1[15] = half_btf(cospi[48], bf0[15], cospi[16], bf0[14], cos_bit); bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = bf0[18]; bf1[19] = bf0[19]; bf1[20] = half_btf(cospi[16], bf0[20], cospi[48], bf0[21], cos_bit); bf1[21] = half_btf(-cospi[16], bf0[21], cospi[48], bf0[20], cos_bit); bf1[22] = half_btf(-cospi[48], bf0[22], cospi[16], bf0[23], cos_bit); bf1[23] = half_btf(cospi[48], bf0[23], cospi[16], bf0[22], cos_bit); bf1[24] = bf0[24]; bf1[25] = bf0[25]; bf1[26] = bf0[26]; bf1[27] = bf0[27]; bf1[28] = half_btf(cospi[16], bf0[28], cospi[48], bf0[29], cos_bit); bf1[29] = half_btf(-cospi[16], bf0[29], cospi[48], bf0[28], cos_bit); bf1[30] = half_btf(-cospi[48], bf0[30], cospi[16], bf0[31], cos_bit); bf1[31] = half_btf(cospi[48], bf0[31], cospi[16], bf0[30], cos_bit); // stage 9 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[2]; bf1[1] = bf0[1] + bf0[3]; bf1[2] = -bf0[2] + bf0[0]; bf1[3] = -bf0[3] + bf0[1]; bf1[4] = bf0[4] + bf0[6]; bf1[5] = bf0[5] + bf0[7]; bf1[6] = -bf0[6] + bf0[4]; bf1[7] = -bf0[7] + bf0[5]; bf1[8] = bf0[8] + bf0[10]; bf1[9] = bf0[9] + bf0[11]; bf1[10] = -bf0[10] + bf0[8]; bf1[11] = -bf0[11] + bf0[9]; bf1[12] = bf0[12] + bf0[14]; bf1[13] = bf0[13] + bf0[15]; bf1[14] = -bf0[14] + bf0[12]; bf1[15] = -bf0[15] + bf0[13]; bf1[16] = bf0[16] + bf0[18]; bf1[17] = bf0[17] + bf0[19]; bf1[18] = -bf0[18] + bf0[16]; bf1[19] = -bf0[19] + bf0[17]; bf1[20] = bf0[20] + bf0[22]; bf1[21] = bf0[21] + bf0[23]; bf1[22] = -bf0[22] + bf0[20]; bf1[23] = -bf0[23] + bf0[21]; bf1[24] = bf0[24] + bf0[26]; bf1[25] = bf0[25] + bf0[27]; bf1[26] = -bf0[26] + bf0[24]; bf1[27] = -bf0[27] + bf0[25]; bf1[28] = bf0[28] + bf0[30]; bf1[29] = bf0[29] + bf0[31]; bf1[30] = -bf0[30] + bf0[28]; bf1[31] = -bf0[31] + bf0[29]; // stage 10 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = half_btf(cospi[32], bf0[2], cospi[32], bf0[3], cos_bit); bf1[3] = half_btf(-cospi[32], bf0[3], cospi[32], bf0[2], cos_bit); bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[7], cos_bit); bf1[7] = half_btf(-cospi[32], bf0[7], cospi[32], bf0[6], cos_bit); bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(cospi[32], bf0[10], cospi[32], bf0[11], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[10], cos_bit); bf1[12] = bf0[12]; bf1[13] = bf0[13]; bf1[14] = half_btf(cospi[32], bf0[14], cospi[32], bf0[15], cos_bit); bf1[15] = half_btf(-cospi[32], bf0[15], cospi[32], bf0[14], cos_bit); bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = half_btf(cospi[32], bf0[18], cospi[32], bf0[19], cos_bit); bf1[19] = half_btf(-cospi[32], bf0[19], cospi[32], bf0[18], cos_bit); bf1[20] = bf0[20]; bf1[21] = bf0[21]; bf1[22] = half_btf(cospi[32], bf0[22], cospi[32], bf0[23], cos_bit); bf1[23] = half_btf(-cospi[32], bf0[23], cospi[32], bf0[22], cos_bit); bf1[24] = bf0[24]; bf1[25] = bf0[25]; bf1[26] = half_btf(cospi[32], bf0[26], cospi[32], bf0[27], cos_bit); bf1[27] = half_btf(-cospi[32], bf0[27], cospi[32], bf0[26], cos_bit); bf1[28] = bf0[28]; bf1[29] = bf0[29]; bf1[30] = half_btf(cospi[32], bf0[30], cospi[32], bf0[31], cos_bit); bf1[31] = half_btf(-cospi[32], bf0[31], cospi[32], bf0[30], cos_bit); // stage 11 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = -bf0[16]; bf1[2] = bf0[24]; bf1[3] = -bf0[8]; bf1[4] = bf0[12]; bf1[5] = -bf0[28]; bf1[6] = bf0[20]; bf1[7] = -bf0[4]; bf1[8] = bf0[6]; bf1[9] = -bf0[22]; bf1[10] = bf0[30]; bf1[11] = -bf0[14]; bf1[12] = bf0[10]; bf1[13] = -bf0[26]; bf1[14] = bf0[18]; bf1[15] = -bf0[2]; bf1[16] = bf0[3]; bf1[17] = -bf0[19]; bf1[18] = bf0[27]; bf1[19] = -bf0[11]; bf1[20] = bf0[15]; bf1[21] = -bf0[31]; bf1[22] = bf0[23]; bf1[23] = -bf0[7]; bf1[24] = bf0[5]; bf1[25] = -bf0[21]; bf1[26] = bf0[29]; bf1[27] = -bf0[13]; bf1[28] = bf0[9]; bf1[29] = -bf0[25]; bf1[30] = bf0[17]; bf1[31] = -bf0[1]; } void svt_av1_fidentity4_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 4; ++i) output[i] = round_shift((int64_t)input[i] * new_sqrt2, new_sqrt2_bits); assert(stage_range[0] + new_sqrt2_bits <= 32); } void svt_av1_fidentity8_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 8; ++i) output[i] = input[i] * 2; } void svt_av1_fidentity16_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 16; ++i) output[i] = round_shift((int64_t)input[i] * 2 * new_sqrt2, new_sqrt2_bits); assert(stage_range[0] + new_sqrt2_bits <= 32); } void svt_av1_fidentity32_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 32; ++i) output[i] = input[i] * 4; } void av1_fidentity64_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 64; ++i) output[i] = round_shift((int64_t)input[i] * 4 * new_sqrt2, new_sqrt2_bits); assert(stage_range[0] + new_sqrt2_bits <= 32); } static INLINE TxfmFunc fwd_txfm_type_to_func(TxfmType txfmtype) { switch (txfmtype) { case TXFM_TYPE_DCT4: return svt_av1_fdct4_new; case TXFM_TYPE_DCT8: return svt_av1_fdct8_new; case TXFM_TYPE_DCT16: return svt_av1_fdct16_new; case TXFM_TYPE_DCT32: return svt_av1_fdct32_new; case TXFM_TYPE_DCT64: return svt_av1_fdct64_new; case TXFM_TYPE_ADST4: return svt_av1_fadst4_new; case TXFM_TYPE_ADST8: return svt_av1_fadst8_new; case TXFM_TYPE_ADST16: return svt_av1_fadst16_new; case TXFM_TYPE_ADST32: return av1_fadst32_new; case TXFM_TYPE_IDENTITY4: return svt_av1_fidentity4_c; case TXFM_TYPE_IDENTITY8: return svt_av1_fidentity8_c; case TXFM_TYPE_IDENTITY16: return svt_av1_fidentity16_c; case TXFM_TYPE_IDENTITY32: return svt_av1_fidentity32_c; case TXFM_TYPE_IDENTITY64: return av1_fidentity64_c; default: assert(0); return NULL; } } //fwd_txfm2d_c static INLINE void av1_tranform_two_d_core_c(int16_t *input, uint32_t input_stride, int32_t *output, const Txfm2dFlipCfg *cfg, int32_t *buf, uint8_t bit_depth) { int32_t c, r; // Note when assigning txfm_size_col, we use the txfm_size from the // row configuration and vice versa. This is intentionally done to // accurately perform rectangular transforms. When the transform is // rectangular, the number of columns will be the same as the // txfm_size stored in the row cfg struct. It will make no difference // for square transforms. const int32_t txfm_size_col = tx_size_wide[cfg->tx_size]; const int32_t txfm_size_row = tx_size_high[cfg->tx_size]; // Take the shift from the larger dimension in the rectangular case. const int8_t *shift = cfg->shift; const int32_t rect_type = get_rect_tx_log_ratio(txfm_size_col, txfm_size_row); int8_t stage_range_col[MAX_TXFM_STAGE_NUM]; int8_t stage_range_row[MAX_TXFM_STAGE_NUM]; assert(cfg->stage_num_col <= MAX_TXFM_STAGE_NUM); assert(cfg->stage_num_row <= MAX_TXFM_STAGE_NUM); svt_av1_gen_fwd_stage_range(stage_range_col, stage_range_row, cfg, bit_depth); const int8_t cos_bit_col = cfg->cos_bit_col; const int8_t cos_bit_row = cfg->cos_bit_row; const TxfmFunc txfm_func_col = fwd_txfm_type_to_func(cfg->txfm_type_col); const TxfmFunc txfm_func_row = fwd_txfm_type_to_func(cfg->txfm_type_row); ASSERT(txfm_func_col != NULL); ASSERT(txfm_func_row != NULL); // use output buffer as temp buffer int32_t *temp_in = output; int32_t *temp_out = output + txfm_size_row; // Columns for (c = 0; c < txfm_size_col; ++c) { if (cfg->ud_flip == 0) for (r = 0; r < txfm_size_row; ++r) temp_in[r] = input[r * input_stride + c]; else { for (r = 0; r < txfm_size_row; ++r) // flip upside down temp_in[r] = input[(txfm_size_row - r - 1) * input_stride + c]; } svt_av1_round_shift_array_c( temp_in, txfm_size_row, -shift[0]); // NM svt_av1_round_shift_array_c txfm_func_col(temp_in, temp_out, cos_bit_col, stage_range_col); svt_av1_round_shift_array_c( temp_out, txfm_size_row, -shift[1]); // NM svt_av1_round_shift_array_c if (cfg->lr_flip == 0) { for (r = 0; r < txfm_size_row; ++r) buf[r * txfm_size_col + c] = temp_out[r]; } else { for (r = 0; r < txfm_size_row; ++r) // flip from left to right buf[r * txfm_size_col + (txfm_size_col - c - 1)] = temp_out[r]; } } // Rows for (r = 0; r < txfm_size_row; ++r) { txfm_func_row( buf + r * txfm_size_col, output + r * txfm_size_col, cos_bit_row, stage_range_row); svt_av1_round_shift_array_c(output + r * txfm_size_col, txfm_size_col, -shift[2]); if (abs(rect_type) == 1) { // Multiply everything by Sqrt2 if the transform is rectangular and the // size difference is a factor of 2. for (c = 0; c < txfm_size_col; ++c) { output[r * txfm_size_col + c] = round_shift( (int64_t)output[r * txfm_size_col + c] * new_sqrt2, new_sqrt2_bits); } } } } static INLINE void set_fwd_txfm_non_scale_range(Txfm2dFlipCfg *cfg) { av1_zero(cfg->stage_range_col); av1_zero(cfg->stage_range_row); const int8_t *range_mult2_col = fwd_txfm_range_mult2_list[cfg->txfm_type_col]; if (cfg->txfm_type_col != TXFM_TYPE_INVALID) { int stage_num_col = cfg->stage_num_col; for (int i = 0; i < stage_num_col; ++i) cfg->stage_range_col[i] = (range_mult2_col[i] + 1) >> 1; } if (cfg->txfm_type_row != TXFM_TYPE_INVALID) { int stage_num_row = cfg->stage_num_row; const int8_t *range_mult2_row = fwd_txfm_range_mult2_list[cfg->txfm_type_row]; for (int i = 0; i < stage_num_row; ++i) { cfg->stage_range_row[i] = (range_mult2_col[cfg->stage_num_col - 1] + range_mult2_row[i] + 1) >> 1; } } } void av1_transform_config(TxType tx_type, TxSize tx_size, Txfm2dFlipCfg *cfg) { assert(cfg != NULL); cfg->tx_size = tx_size; set_flip_cfg(tx_type, cfg); const TxType1D tx_type_1d_col = vtx_tab[tx_type]; const TxType1D tx_type_1d_row = htx_tab[tx_type]; const int32_t txw_idx = tx_size_wide_log2[tx_size] - tx_size_wide_log2[0]; const int32_t txh_idx = tx_size_high_log2[tx_size] - tx_size_high_log2[0]; cfg->shift = fwd_txfm_shift_ls[tx_size]; cfg->cos_bit_col = fwd_cos_bit_col[txw_idx][txh_idx]; cfg->cos_bit_row = fwd_cos_bit_row[txw_idx][txh_idx]; cfg->txfm_type_col = av1_txfm_type_ls[txh_idx][tx_type_1d_col]; cfg->txfm_type_row = av1_txfm_type_ls[txw_idx][tx_type_1d_row]; cfg->stage_num_col = av1_txfm_stage_num_list[cfg->txfm_type_col]; cfg->stage_num_row = av1_txfm_stage_num_list[cfg->txfm_type_row]; set_fwd_txfm_non_scale_range(cfg); } static uint64_t energy_computation(int32_t *coeff, uint32_t coeff_stride, uint32_t area_width, uint32_t area_height) { uint64_t prediction_distortion = 0; for (uint32_t row_index = 0; row_index < area_height; ++row_index) { for (uint32_t column_index = 0; column_index < area_width; ++column_index) prediction_distortion += (int64_t)SQR((int64_t)(coeff[column_index])); coeff += coeff_stride; } return prediction_distortion; } uint64_t svt_handle_transform64x64_c(int32_t *output) { uint64_t three_quad_energy; // top - right 32x32 area. three_quad_energy = energy_computation(output + 32, 64, 32, 32); //bottom 64x32 area. three_quad_energy += energy_computation(output + 32 * 64, 64, 64, 32); // zero out top-right 32x32 area. for (int32_t row = 0; row < 32; ++row) memset(output + row * 64 + 32, 0, 32 * sizeof(*output)); // zero out the bottom 64x32 area. memset(output + 32 * 64, 0, 32 * 64 * sizeof(*output)); // Re-pack non-zero coeffs in the first 32x32 indices. for (int32_t row = 1; row < 32; ++row) svt_memcpy_c(output + row * 32, output + row * 64, 32 * sizeof(*output)); return three_quad_energy; } void svt_av1_transform_two_d_64x64_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[64 * 64]; Txfm2dFlipCfg cfg; //av1_get_fwd_txfm_cfg av1_transform_config(transform_type, TX_64X64, &cfg); //fwd_txfm2d_c av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_transform_two_d_32x32_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 32]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_32X32, &cfg); av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_transform_two_d_16x16_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X16, &cfg); av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_transform_two_d_8x8_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 8]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_8X8, &cfg); av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_transform_two_d_4x4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[4 * 4]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_4X4, &cfg); av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } /********************************************************************* * Calculate CBF *********************************************************************/ void svt_av1_fwd_txfm2d_64x32_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[64 * 32]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_64X32, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } uint64_t svt_handle_transform64x32_c(int32_t *output) { // top - right 32x32 area. const uint64_t three_quad_energy = energy_computation(output + 32, 64, 32, 32); // zero out right 32x32 area. for (int32_t row = 0; row < 32; ++row) memset(output + row * 64 + 32, 0, 32 * sizeof(*output)); // Re-pack non-zero coeffs in the first 32x32 indices. for (int32_t row = 1; row < 32; ++row) svt_memcpy_c(output + row * 32, output + row * 64, 32 * sizeof(*output)); return three_quad_energy; } void svt_av1_fwd_txfm2d_32x64_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 64]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_32X64, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } uint64_t svt_handle_transform32x64_c(int32_t *output) { //bottom 32x32 area. const uint64_t three_quad_energy = energy_computation(output + 32 * 32, 32, 32, 32); // zero out the bottom 32x32 area. memset(output + 32 * 32, 0, 32 * 32 * sizeof(*output)); return three_quad_energy; } void svt_av1_fwd_txfm2d_64x16_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[64 * 16]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_64X16, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } uint64_t svt_handle_transform64x16_c(int32_t *output) { // top - right 32x16 area. const uint64_t three_quad_energy = energy_computation(output + 32, 64, 32, 16); // zero out right 32x16 area. for (int32_t row = 0; row < 16; ++row) memset(output + row * 64 + 32, 0, 32 * sizeof(*output)); // Re-pack non-zero coeffs in the first 32x16 indices. for (int32_t row = 1; row < 16; ++row) svt_memcpy_c(output + row * 32, output + row * 64, 32 * sizeof(*output)); return three_quad_energy; } void svt_av1_fwd_txfm2d_16x64_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 64]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_16X64, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } uint64_t svt_handle_transform16x64_c(int32_t *output) { //bottom 16x32 area. const uint64_t three_quad_energy = energy_computation(output + 16 * 32, 16, 16, 32); // zero out the bottom 16x32 area. memset(output + 16 * 32, 0, 16 * 32 * sizeof(*output)); return three_quad_energy; } uint64_t handle_transform16x64_N2_N4_c(int32_t *output) { (void)output; return 0; } uint64_t handle_transform32x64_N2_N4_c(int32_t *output) { (void)output; return 0; } uint64_t handle_transform64x16_N2_N4_c(int32_t *output) { // Re-pack non-zero coeffs in the first 32x16 indices. for (int32_t row = 1; row < 16; ++row) svt_memcpy_c(output + row * 32, output + row * 64, 32 * sizeof(*output)); return 0; } uint64_t handle_transform64x32_N2_N4_c(int32_t *output) { // Re-pack non-zero coeffs in the first 32x32 indices. for (int32_t row = 1; row < 32; ++row) svt_memcpy_c(output + row * 32, output + row * 64, 32 * sizeof(*output)); return 0; } uint64_t handle_transform64x64_N2_N4_c(int32_t *output) { // Re-pack non-zero coeffs in the first 32x32 indices. for (int32_t row = 1; row < 32; ++row) svt_memcpy_c(output + row * 32, output + row * 64, 32 * sizeof(*output)); return 0; } void svt_av1_fwd_txfm2d_32x16_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 16]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_32X16, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x32_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 32]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_16X32, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x8_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 8]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_16X8, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_8x16_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 16]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_8X16, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_32x8_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 8]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_32X8, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_8x32_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 32]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_8X32, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 4]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_16X4, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_4x16_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[4 * 16]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_4X16, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_8x4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 4]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_8X4, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_4x8_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[4 * 8]; Txfm2dFlipCfg cfg; /*av1_get_fwd_txfm_cfg*/ av1_transform_config(transform_type, TX_4X8, &cfg); /*fwd_txfm2d_c*/ av1_tranform_two_d_core_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } static EbErrorType av1_estimate_transform_N2(int16_t *residual_buffer, uint32_t residual_stride, int32_t *coeff_buffer, uint32_t coeff_stride, TxSize transform_size, uint64_t *three_quad_energy, uint32_t bit_depth, TxType transform_type, PlaneType component_type) { EbErrorType return_error = EB_ErrorNone; (void)coeff_stride; (void)component_type; switch (transform_size) { case TX_64X32: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_64x32_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_64x32_N2_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform64x32_N2_N4(coeff_buffer); break; case TX_32X64: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_32x64_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_32x64_N2_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform32x64_N2_N4(coeff_buffer); break; case TX_64X16: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_64x16_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_64x16_N2_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform64x16_N2_N4(coeff_buffer); break; case TX_16X64: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_16x64_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_16x64_N2_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform16x64_N2_N4(coeff_buffer); break; case TX_32X16: // TTK if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_32x16_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_32x16_N2_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_16X32: if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_16x32_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_16x32_N2_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_16X8: svt_av1_fwd_txfm2d_16x8_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X16: svt_av1_fwd_txfm2d_8x16_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_32X8: if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_32x8_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_32x8_N2_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X32: if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_8x32_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_8x32_N2_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_16X4: svt_av1_fwd_txfm2d_16x4_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_4X16: svt_av1_fwd_txfm2d_4x16_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X4: svt_av1_fwd_txfm2d_8x4_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_4X8: svt_av1_fwd_txfm2d_4x8_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_64X64: svt_av1_fwd_txfm2d_64x64_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform64x64_N2_N4(coeff_buffer); break; case TX_32X32: if (transform_type == V_DCT || transform_type == H_DCT || transform_type == V_ADST || transform_type == H_ADST || transform_type == V_FLIPADST || transform_type == H_FLIPADST) // Tahani: I believe those cases are never hit av1_transform_two_d_32x32_N2_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else { svt_av1_fwd_txfm2d_32x32_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); } break; case TX_16X16: svt_av1_fwd_txfm2d_16x16_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X8: svt_av1_fwd_txfm2d_8x8_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_4X4: svt_av1_fwd_txfm2d_4x4_N2( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; default: assert(0); break; } return return_error; } static EbErrorType av1_estimate_transform_N4(int16_t *residual_buffer, uint32_t residual_stride, int32_t *coeff_buffer, uint32_t coeff_stride, TxSize transform_size, uint64_t *three_quad_energy, uint32_t bit_depth, TxType transform_type, PlaneType component_type) { EbErrorType return_error = EB_ErrorNone; (void)coeff_stride; (void)component_type; switch (transform_size) { case TX_64X32: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_64x32_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_64x32_N4_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform64x32_N2_N4(coeff_buffer); break; case TX_32X64: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_32x64_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_32x64_N4_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform32x64_N2_N4(coeff_buffer); break; case TX_64X16: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_64x16_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_64x16_N4_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform64x16_N2_N4(coeff_buffer); break; case TX_16X64: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_16x64_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_16x64_N4_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform16x64_N2_N4(coeff_buffer); break; case TX_32X16: // TTK if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_32x16_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_32x16_N4_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_16X32: if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_16x32_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_16x32_N4_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_16X8: svt_av1_fwd_txfm2d_16x8_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X16: svt_av1_fwd_txfm2d_8x16_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_32X8: if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_32x8_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_32x8_N4_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X32: if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_8x32_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_8x32_N4_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_16X4: svt_av1_fwd_txfm2d_16x4_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_4X16: svt_av1_fwd_txfm2d_4x16_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X4: svt_av1_fwd_txfm2d_8x4_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_4X8: svt_av1_fwd_txfm2d_4x8_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_64X64: svt_av1_fwd_txfm2d_64x64_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = handle_transform64x64_N2_N4(coeff_buffer); break; case TX_32X32: if (transform_type == V_DCT || transform_type == H_DCT || transform_type == V_ADST || transform_type == H_ADST || transform_type == V_FLIPADST || transform_type == H_FLIPADST) // Tahani: I believe those cases are never hit av1_transform_two_d_32x32_N4_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else { svt_av1_fwd_txfm2d_32x32_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); } break; case TX_16X16: svt_av1_fwd_txfm2d_16x16_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X8: svt_av1_fwd_txfm2d_8x8_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_4X4: svt_av1_fwd_txfm2d_4x4_N4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; default: assert(0); break; } return return_error; } static EbErrorType av1_estimate_transform_ONLY_DC(int16_t *residual_buffer, uint32_t residual_stride, int32_t *coeff_buffer, uint32_t coeff_stride, TxSize transform_size, uint64_t *three_quad_energy, uint32_t bit_depth, TxType transform_type, PlaneType component_type) { EbErrorType return_error = av1_estimate_transform_N4(residual_buffer, residual_stride, coeff_buffer, coeff_stride, transform_size, three_quad_energy, bit_depth, transform_type, component_type); for (int i = 1; i < (tx_size_wide[transform_size] * tx_size_high[transform_size]); i++) { if (i % tx_size_wide[transform_size] < (tx_size_wide[transform_size] >> 2) || i / tx_size_wide[transform_size] < (tx_size_high[transform_size] >> 2)) { coeff_buffer[i] = 0; } } return return_error; } EbErrorType av1_estimate_transform_default(int16_t *residual_buffer, uint32_t residual_stride, int32_t *coeff_buffer, uint32_t coeff_stride, TxSize transform_size, uint64_t *three_quad_energy, uint32_t bit_depth, TxType transform_type, PlaneType component_type) { EbErrorType return_error = EB_ErrorNone; (void)coeff_stride; (void)component_type; switch (transform_size) { case TX_64X32: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_64x32( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_64x32_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = svt_handle_transform64x32(coeff_buffer); break; case TX_32X64: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_32x64( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_32x64_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = svt_handle_transform32x64(coeff_buffer); break; case TX_64X16: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_64x16( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_64x16_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = svt_handle_transform64x16(coeff_buffer); break; case TX_16X64: if (transform_type == DCT_DCT) svt_av1_fwd_txfm2d_16x64( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_16x64_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = svt_handle_transform16x64(coeff_buffer); break; case TX_32X16: // TTK if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_32x16( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_32x16_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_16X32: if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_16x32( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_16x32_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_16X8: svt_av1_fwd_txfm2d_16x8( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X16: svt_av1_fwd_txfm2d_8x16( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_32X8: if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_32x8( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_32x8_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X32: if ((transform_type == DCT_DCT) || (transform_type == IDTX)) svt_av1_fwd_txfm2d_8x32( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else svt_av1_fwd_txfm2d_8x32_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_16X4: svt_av1_fwd_txfm2d_16x4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_4X16: svt_av1_fwd_txfm2d_4x16( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X4: svt_av1_fwd_txfm2d_8x4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_4X8: svt_av1_fwd_txfm2d_4x8( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_64X64: svt_av1_fwd_txfm2d_64x64( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); *three_quad_energy = svt_handle_transform64x64(coeff_buffer); break; case TX_32X32: if (transform_type == V_DCT || transform_type == H_DCT || transform_type == V_ADST || transform_type == H_ADST || transform_type == V_FLIPADST || transform_type == H_FLIPADST) // Tahani: I believe those cases are never hit svt_av1_transform_two_d_32x32_c( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); else { svt_av1_fwd_txfm2d_32x32( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); } break; case TX_16X16: svt_av1_fwd_txfm2d_16x16( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_8X8: svt_av1_fwd_txfm2d_8x8( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; case TX_4X4: svt_av1_fwd_txfm2d_4x4( residual_buffer, coeff_buffer, residual_stride, transform_type, bit_depth); break; default: assert(0); break; } return return_error; } /********************************************************************* * Transform * Note there is an implicit assumption that TU Size <= PU Size, * which is different than the HEVC requirements. *********************************************************************/ EbErrorType av1_estimate_transform(int16_t *residual_buffer, uint32_t residual_stride, int32_t *coeff_buffer, uint32_t coeff_stride, TxSize transform_size, uint64_t *three_quad_energy, uint32_t bit_depth, TxType transform_type, PlaneType component_type, EB_TRANS_COEFF_SHAPE trans_coeff_shape) { (void)trans_coeff_shape; (void)coeff_stride; (void)component_type; switch (trans_coeff_shape) { case DEFAULT_SHAPE: return av1_estimate_transform_default(residual_buffer, residual_stride, coeff_buffer, coeff_stride, transform_size, three_quad_energy, bit_depth, transform_type, component_type); case N2_SHAPE: return av1_estimate_transform_N2(residual_buffer, residual_stride, coeff_buffer, coeff_stride, transform_size, three_quad_energy, bit_depth, transform_type, component_type); case N4_SHAPE: return av1_estimate_transform_N4(residual_buffer, residual_stride, coeff_buffer, coeff_stride, transform_size, three_quad_energy, bit_depth, transform_type, component_type); case ONLY_DC_SHAPE: return av1_estimate_transform_ONLY_DC(residual_buffer, residual_stride, coeff_buffer, coeff_stride, transform_size, three_quad_energy, bit_depth, transform_type, component_type); } assert(0); return EB_ErrorBadParameter; } // PF_N4 static void highbd_fwd_txfm_64x64_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_64x64_N4(src_diff, dst_coeff, diff_stride, DCT_DCT, bd); } static void highbd_fwd_txfm_32x64_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_32x64_N4(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, bd); } static void highbd_fwd_txfm_64x32_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_64x32_N4(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, bd); } static void highbd_fwd_txfm_16x64_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_16x64_N4(src_diff, dst_coeff, diff_stride, DCT_DCT, bd); } static void highbd_fwd_txfm_64x16_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_64x16_N4(src_diff, dst_coeff, diff_stride, DCT_DCT, bd); } static void highbd_fwd_txfm_32x32_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_32x32_N4(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_16x16_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_16x16_N4(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_8x8_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_8x8_N4(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_4x8_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_4x8_N4( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_8x4_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_8x4_N4( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_8x16_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_8x16_N4(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_16x8_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_16x8_N4(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_16x32_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_16x32_N4( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_32x16_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_32x16_N4( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_4x16_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_4x16(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_16x4_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_16x4_N4( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_8x32_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_8x32_N4( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_32x8_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_32x8_N4( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } //PF_N2 static void highbd_fwd_txfm_64x64_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_64x64_N2(src_diff, dst_coeff, diff_stride, DCT_DCT, bd); } static void highbd_fwd_txfm_32x64_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_32x64_N2(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, bd); } static void highbd_fwd_txfm_64x32_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_64x32_N2(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, bd); } static void highbd_fwd_txfm_16x64_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_16x64_N2(src_diff, dst_coeff, diff_stride, DCT_DCT, bd); } static void highbd_fwd_txfm_64x16_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_64x16_N2(src_diff, dst_coeff, diff_stride, DCT_DCT, bd); } static void highbd_fwd_txfm_32x32_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_32x32_N2(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_16x16_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_16x16_N2(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_8x8_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_8x8_N2(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_4x8_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_4x8_N2( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_8x4_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_8x4_N2( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_8x16_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_8x16_N2(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_16x8_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_16x8_N2(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_16x32_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_16x32_N2( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_32x16_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_32x16_N2( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_4x16_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_4x16(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_16x4_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_16x4_N2( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_8x32_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_8x32_N2( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_32x8_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_32x8_N2( src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_64x64(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_64x64(src_diff, dst_coeff, diff_stride, DCT_DCT, bd); } static void highbd_fwd_txfm_32x64(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_32x64(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, bd); } static void highbd_fwd_txfm_64x32(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_64x32(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, bd); } static void highbd_fwd_txfm_16x64(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_16x64(src_diff, dst_coeff, diff_stride, DCT_DCT, bd); } static void highbd_fwd_txfm_64x16(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(txfm_param->tx_type == DCT_DCT); int32_t * dst_coeff = (int32_t *)coeff; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_64x16(src_diff, dst_coeff, diff_stride, DCT_DCT, bd); } static void highbd_fwd_txfm_32x32(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_32x32(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_16x16(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_16x16(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_8x8(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_8x8(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_4x8(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_4x8(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_8x4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_8x4(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_8x16(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_8x16(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_16x8(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t * dst_coeff = (int32_t *)coeff; const TxType tx_type = txfm_param->tx_type; const int bd = txfm_param->bd; svt_av1_fwd_txfm2d_16x8(src_diff, dst_coeff, diff_stride, tx_type, bd); } static void highbd_fwd_txfm_16x32(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_16x32(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_32x16(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_32x16(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_4x16(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_4x16(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_16x4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_16x4(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_8x32(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_8x32(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } static void highbd_fwd_txfm_32x8(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { int32_t *dst_coeff = (int32_t *)coeff; svt_av1_fwd_txfm2d_32x8(src_diff, dst_coeff, diff_stride, txfm_param->tx_type, txfm_param->bd); } void svt_av1_highbd_fwd_txfm_n4(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(av1_ext_tx_used[txfm_param->tx_set_type][txfm_param->tx_type]); const TxSize tx_size = txfm_param->tx_size; switch (tx_size) { case TX_64X64: highbd_fwd_txfm_64x64_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X64: highbd_fwd_txfm_32x64_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_64X32: highbd_fwd_txfm_64x32_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X64: highbd_fwd_txfm_16x64_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_64X16: highbd_fwd_txfm_64x16_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X32: highbd_fwd_txfm_32x32_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X16: highbd_fwd_txfm_16x16_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X8: highbd_fwd_txfm_8x8_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_4X8: highbd_fwd_txfm_4x8_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X4: highbd_fwd_txfm_8x4_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X16: highbd_fwd_txfm_8x16_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X8: highbd_fwd_txfm_16x8_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X32: highbd_fwd_txfm_16x32_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X16: highbd_fwd_txfm_32x16_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_4X4: //hack highbd_fwd_txfm_4x4(src_diff, coeff, diff_stride, txfm_param); break; case TX_4X16: highbd_fwd_txfm_4x16_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X4: highbd_fwd_txfm_16x4_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X32: highbd_fwd_txfm_8x32_n4(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X8: highbd_fwd_txfm_32x8_n4(src_diff, coeff, diff_stride, txfm_param); break; default: assert(0); break; } } void svt_av1_highbd_fwd_txfm_n2(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(av1_ext_tx_used[txfm_param->tx_set_type][txfm_param->tx_type]); const TxSize tx_size = txfm_param->tx_size; switch (tx_size) { case TX_64X64: highbd_fwd_txfm_64x64_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X64: highbd_fwd_txfm_32x64_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_64X32: highbd_fwd_txfm_64x32_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X64: highbd_fwd_txfm_16x64_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_64X16: highbd_fwd_txfm_64x16_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X32: highbd_fwd_txfm_32x32_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X16: highbd_fwd_txfm_16x16_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X8: highbd_fwd_txfm_8x8_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_4X8: highbd_fwd_txfm_4x8_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X4: highbd_fwd_txfm_8x4_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X16: highbd_fwd_txfm_8x16_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X8: highbd_fwd_txfm_16x8_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X32: highbd_fwd_txfm_16x32_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X16: highbd_fwd_txfm_32x16_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_4X4: //hack highbd_fwd_txfm_4x4(src_diff, coeff, diff_stride, txfm_param); break; case TX_4X16: highbd_fwd_txfm_4x16_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X4: highbd_fwd_txfm_16x4_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X32: highbd_fwd_txfm_8x32_n2(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X8: highbd_fwd_txfm_32x8_n2(src_diff, coeff, diff_stride, txfm_param); break; default: assert(0); break; } } void svt_av1_highbd_fwd_txfm(int16_t *src_diff, TranLow *coeff, int diff_stride, TxfmParam *txfm_param) { assert(av1_ext_tx_used[txfm_param->tx_set_type][txfm_param->tx_type]); const TxSize tx_size = txfm_param->tx_size; switch (tx_size) { case TX_64X64: highbd_fwd_txfm_64x64(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X64: highbd_fwd_txfm_32x64(src_diff, coeff, diff_stride, txfm_param); break; case TX_64X32: highbd_fwd_txfm_64x32(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X64: highbd_fwd_txfm_16x64(src_diff, coeff, diff_stride, txfm_param); break; case TX_64X16: highbd_fwd_txfm_64x16(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X32: highbd_fwd_txfm_32x32(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X16: highbd_fwd_txfm_16x16(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X8: highbd_fwd_txfm_8x8(src_diff, coeff, diff_stride, txfm_param); break; case TX_4X8: highbd_fwd_txfm_4x8(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X4: highbd_fwd_txfm_8x4(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X16: highbd_fwd_txfm_8x16(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X8: highbd_fwd_txfm_16x8(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X32: highbd_fwd_txfm_16x32(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X16: highbd_fwd_txfm_32x16(src_diff, coeff, diff_stride, txfm_param); break; case TX_4X4: //hack highbd_fwd_txfm_4x4(src_diff, coeff, diff_stride, txfm_param); break; case TX_4X16: highbd_fwd_txfm_4x16(src_diff, coeff, diff_stride, txfm_param); break; case TX_16X4: highbd_fwd_txfm_16x4(src_diff, coeff, diff_stride, txfm_param); break; case TX_8X32: highbd_fwd_txfm_8x32(src_diff, coeff, diff_stride, txfm_param); break; case TX_32X8: highbd_fwd_txfm_32x8(src_diff, coeff, diff_stride, txfm_param); break; default: assert(0); break; } } void svt_av1_wht_fwd_txfm(int16_t *src_diff, int bw, int32_t *coeff, TxSize tx_size, EB_TRANS_COEFF_SHAPE pf_shape, int bit_depth, int is_hbd) { TxfmParam txfm_param; txfm_param.tx_type = DCT_DCT; txfm_param.tx_size = tx_size; txfm_param.lossless = 0; txfm_param.tx_set_type = EXT_TX_SET_ALL16; txfm_param.bd = bit_depth; txfm_param.is_hbd = is_hbd; switch (pf_shape) { case N4_SHAPE: svt_av1_highbd_fwd_txfm_n4(src_diff, coeff, bw, &txfm_param); break; case N2_SHAPE: svt_av1_highbd_fwd_txfm_n2(src_diff, coeff, bw, &txfm_param); break; default: svt_av1_highbd_fwd_txfm(src_diff, coeff, bw, &txfm_param); } } void svt_av1_fidentity16_N2_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 8; ++i) output[i] = round_shift((int64_t)input[i] * 2 * new_sqrt2, new_sqrt2_bits); assert(stage_range[0] + new_sqrt2_bits <= 32); } void svt_av1_fadst16_new_N2(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[16]; // stage 0; // stage 1; assert(output != input); bf1 = output; bf1[0] = input[0]; bf1[1] = -input[15]; bf1[2] = -input[7]; bf1[3] = input[8]; bf1[4] = -input[3]; bf1[5] = input[12]; bf1[6] = input[4]; bf1[7] = -input[11]; bf1[8] = -input[1]; bf1[9] = input[14]; bf1[10] = input[6]; bf1[11] = -input[9]; bf1[12] = input[2]; bf1[13] = -input[13]; bf1[14] = -input[5]; bf1[15] = input[10]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = half_btf(cospi[32], bf0[2], cospi[32], bf0[3], cos_bit); bf1[3] = half_btf(cospi[32], bf0[2], -cospi[32], bf0[3], cos_bit); bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[7], cos_bit); bf1[7] = half_btf(cospi[32], bf0[6], -cospi[32], bf0[7], cos_bit); bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(cospi[32], bf0[10], cospi[32], bf0[11], cos_bit); bf1[11] = half_btf(cospi[32], bf0[10], -cospi[32], bf0[11], cos_bit); bf1[12] = bf0[12]; bf1[13] = bf0[13]; bf1[14] = half_btf(cospi[32], bf0[14], cospi[32], bf0[15], cos_bit); bf1[15] = half_btf(cospi[32], bf0[14], -cospi[32], bf0[15], cos_bit); // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[2]; bf1[1] = bf0[1] + bf0[3]; bf1[2] = bf0[0] - bf0[2]; bf1[3] = bf0[1] - bf0[3]; bf1[4] = bf0[4] + bf0[6]; bf1[5] = bf0[5] + bf0[7]; bf1[6] = bf0[4] - bf0[6]; bf1[7] = bf0[5] - bf0[7]; bf1[8] = bf0[8] + bf0[10]; bf1[9] = bf0[9] + bf0[11]; bf1[10] = bf0[8] - bf0[10]; bf1[11] = bf0[9] - bf0[11]; bf1[12] = bf0[12] + bf0[14]; bf1[13] = bf0[13] + bf0[15]; bf1[14] = bf0[12] - bf0[14]; bf1[15] = bf0[13] - bf0[15]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[16], bf0[4], cospi[48], bf0[5], cos_bit); bf1[5] = half_btf(cospi[48], bf0[4], -cospi[16], bf0[5], cos_bit); bf1[6] = half_btf(-cospi[48], bf0[6], cospi[16], bf0[7], cos_bit); bf1[7] = half_btf(cospi[16], bf0[6], cospi[48], bf0[7], cos_bit); bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = bf0[10]; bf1[11] = bf0[11]; bf1[12] = half_btf(cospi[16], bf0[12], cospi[48], bf0[13], cos_bit); bf1[13] = half_btf(cospi[48], bf0[12], -cospi[16], bf0[13], cos_bit); bf1[14] = half_btf(-cospi[48], bf0[14], cospi[16], bf0[15], cos_bit); bf1[15] = half_btf(cospi[16], bf0[14], cospi[48], bf0[15], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[4]; bf1[1] = bf0[1] + bf0[5]; bf1[2] = bf0[2] + bf0[6]; bf1[3] = bf0[3] + bf0[7]; bf1[4] = bf0[0] - bf0[4]; bf1[5] = bf0[1] - bf0[5]; bf1[6] = bf0[2] - bf0[6]; bf1[7] = bf0[3] - bf0[7]; bf1[8] = bf0[8] + bf0[12]; bf1[9] = bf0[9] + bf0[13]; bf1[10] = bf0[10] + bf0[14]; bf1[11] = bf0[11] + bf0[15]; bf1[12] = bf0[8] - bf0[12]; bf1[13] = bf0[9] - bf0[13]; bf1[14] = bf0[10] - bf0[14]; bf1[15] = bf0[11] - bf0[15]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = half_btf(cospi[8], bf0[8], cospi[56], bf0[9], cos_bit); bf1[9] = half_btf(cospi[56], bf0[8], -cospi[8], bf0[9], cos_bit); bf1[10] = half_btf(cospi[40], bf0[10], cospi[24], bf0[11], cos_bit); bf1[11] = half_btf(cospi[24], bf0[10], -cospi[40], bf0[11], cos_bit); bf1[12] = half_btf(-cospi[56], bf0[12], cospi[8], bf0[13], cos_bit); bf1[13] = half_btf(cospi[8], bf0[12], cospi[56], bf0[13], cos_bit); bf1[14] = half_btf(-cospi[24], bf0[14], cospi[40], bf0[15], cos_bit); bf1[15] = half_btf(cospi[40], bf0[14], cospi[24], bf0[15], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[8]; bf1[1] = bf0[1] + bf0[9]; bf1[2] = bf0[2] + bf0[10]; bf1[3] = bf0[3] + bf0[11]; bf1[4] = bf0[4] + bf0[12]; bf1[5] = bf0[5] + bf0[13]; bf1[6] = bf0[6] + bf0[14]; bf1[7] = bf0[7] + bf0[15]; bf1[8] = bf0[0] - bf0[8]; bf1[9] = bf0[1] - bf0[9]; bf1[10] = bf0[2] - bf0[10]; bf1[11] = bf0[3] - bf0[11]; bf1[12] = bf0[4] - bf0[12]; bf1[13] = bf0[5] - bf0[13]; bf1[14] = bf0[6] - bf0[14]; bf1[15] = bf0[7] - bf0[15]; // stage 8 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[1] = half_btf(cospi[62], bf0[0], -cospi[2], bf0[1], cos_bit); bf1[3] = half_btf(cospi[54], bf0[2], -cospi[10], bf0[3], cos_bit); bf1[5] = half_btf(cospi[46], bf0[4], -cospi[18], bf0[5], cos_bit); bf1[7] = half_btf(cospi[38], bf0[6], -cospi[26], bf0[7], cos_bit); bf1[8] = half_btf(cospi[34], bf0[8], cospi[30], bf0[9], cos_bit); bf1[10] = half_btf(cospi[42], bf0[10], cospi[22], bf0[11], cos_bit); bf1[12] = half_btf(cospi[50], bf0[12], cospi[14], bf0[13], cos_bit); bf1[14] = half_btf(cospi[58], bf0[14], cospi[6], bf0[15], cos_bit); // stage 9 bf0 = step; bf1 = output; bf1[0] = bf0[1]; bf1[1] = bf0[14]; bf1[2] = bf0[3]; bf1[3] = bf0[12]; bf1[4] = bf0[5]; bf1[5] = bf0[10]; bf1[6] = bf0[7]; bf1[7] = bf0[8]; } void svt_av1_fdct16_new_N2(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[16]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[15]; bf1[1] = input[1] + input[14]; bf1[2] = input[2] + input[13]; bf1[3] = input[3] + input[12]; bf1[4] = input[4] + input[11]; bf1[5] = input[5] + input[10]; bf1[6] = input[6] + input[9]; bf1[7] = input[7] + input[8]; bf1[8] = -input[8] + input[7]; bf1[9] = -input[9] + input[6]; bf1[10] = -input[10] + input[5]; bf1[11] = -input[11] + input[4]; bf1[12] = -input[12] + input[3]; bf1[13] = -input[13] + input[2]; bf1[14] = -input[14] + input[1]; bf1[15] = -input[15] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[7]; bf1[1] = bf0[1] + bf0[6]; bf1[2] = bf0[2] + bf0[5]; bf1[3] = bf0[3] + bf0[4]; bf1[4] = -bf0[4] + bf0[3]; bf1[5] = -bf0[5] + bf0[2]; bf1[6] = -bf0[6] + bf0[1]; bf1[7] = -bf0[7] + bf0[0]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(-cospi[32], bf0[10], cospi[32], bf0[13], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[12], cos_bit); bf1[12] = half_btf(cospi[32], bf0[12], cospi[32], bf0[11], cos_bit); bf1[13] = half_btf(cospi[32], bf0[13], cospi[32], bf0[10], cos_bit); bf1[14] = bf0[14]; bf1[15] = bf0[15]; // stage 3 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[2] = -bf0[2] + bf0[1]; bf1[3] = -bf0[3] + bf0[0]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; bf1[8] = bf0[8] + bf0[11]; bf1[9] = bf0[9] + bf0[10]; bf1[10] = -bf0[10] + bf0[9]; bf1[11] = -bf0[11] + bf0[8]; bf1[12] = -bf0[12] + bf0[15]; bf1[13] = -bf0[13] + bf0[14]; bf1[14] = bf0[14] + bf0[13]; bf1[15] = bf0[15] + bf0[12]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[2] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[5] = -bf0[5] + bf0[4]; bf1[6] = -bf0[6] + bf0[7]; bf1[7] = bf0[7] + bf0[6]; bf1[8] = bf0[8]; bf1[9] = half_btf(-cospi[16], bf0[9], cospi[48], bf0[14], cos_bit); bf1[10] = half_btf(-cospi[48], bf0[10], -cospi[16], bf0[13], cos_bit); bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = half_btf(cospi[48], bf0[13], -cospi[16], bf0[10], cos_bit); bf1[14] = half_btf(cospi[16], bf0[14], cospi[48], bf0[9], cos_bit); bf1[15] = bf0[15]; // stage 5 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[6] = half_btf(cospi[24], bf0[6], -cospi[40], bf0[5], cos_bit); bf1[8] = bf0[8] + bf0[9]; bf1[9] = -bf0[9] + bf0[8]; bf1[10] = -bf0[10] + bf0[11]; bf1[11] = bf0[11] + bf0[10]; bf1[12] = bf0[12] + bf0[13]; bf1[13] = -bf0[13] + bf0[12]; bf1[14] = -bf0[14] + bf0[15]; bf1[15] = bf0[15] + bf0[14]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = bf0[4]; bf1[6] = bf0[6]; bf1[8] = half_btf(cospi[60], bf0[8], cospi[4], bf0[15], cos_bit); bf1[10] = half_btf(cospi[44], bf0[10], cospi[20], bf0[13], cos_bit); bf1[12] = half_btf(cospi[12], bf0[12], -cospi[52], bf0[11], cos_bit); bf1[14] = half_btf(cospi[28], bf0[14], -cospi[36], bf0[9], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[8]; bf1[2] = bf0[4]; bf1[3] = bf0[12]; bf1[4] = bf0[2]; bf1[5] = bf0[10]; bf1[6] = bf0[6]; bf1[7] = bf0[14]; } void svt_av1_fidentity8_N2_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 4; ++i) output[i] = input[i] * 2; } void svt_av1_fadst8_new_N2(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[8]; // stage 0; // stage 1; assert(output != input); bf1 = output; bf1[0] = input[0]; bf1[1] = -input[7]; bf1[2] = -input[3]; bf1[3] = input[4]; bf1[4] = -input[1]; bf1[5] = input[6]; bf1[6] = input[2]; bf1[7] = -input[5]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = half_btf(cospi[32], bf0[2], cospi[32], bf0[3], cos_bit); bf1[3] = half_btf(cospi[32], bf0[2], -cospi[32], bf0[3], cos_bit); bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[7], cos_bit); bf1[7] = half_btf(cospi[32], bf0[6], -cospi[32], bf0[7], cos_bit); // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[2]; bf1[1] = bf0[1] + bf0[3]; bf1[2] = bf0[0] - bf0[2]; bf1[3] = bf0[1] - bf0[3]; bf1[4] = bf0[4] + bf0[6]; bf1[5] = bf0[5] + bf0[7]; bf1[6] = bf0[4] - bf0[6]; bf1[7] = bf0[5] - bf0[7]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[16], bf0[4], cospi[48], bf0[5], cos_bit); bf1[5] = half_btf(cospi[48], bf0[4], -cospi[16], bf0[5], cos_bit); bf1[6] = half_btf(-cospi[48], bf0[6], cospi[16], bf0[7], cos_bit); bf1[7] = half_btf(cospi[16], bf0[6], cospi[48], bf0[7], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[4]; bf1[1] = bf0[1] + bf0[5]; bf1[2] = bf0[2] + bf0[6]; bf1[3] = bf0[3] + bf0[7]; bf1[4] = bf0[0] - bf0[4]; bf1[5] = bf0[1] - bf0[5]; bf1[6] = bf0[2] - bf0[6]; bf1[7] = bf0[3] - bf0[7]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[1] = half_btf(cospi[60], bf0[0], -cospi[4], bf0[1], cos_bit); bf1[3] = half_btf(cospi[44], bf0[2], -cospi[20], bf0[3], cos_bit); bf1[4] = half_btf(cospi[36], bf0[4], cospi[28], bf0[5], cos_bit); bf1[6] = half_btf(cospi[52], bf0[6], cospi[12], bf0[7], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[1]; bf1[1] = bf0[6]; bf1[2] = bf0[3]; bf1[3] = bf0[4]; } void svt_av1_fdct8_new_N2(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[8]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[7]; bf1[1] = input[1] + input[6]; bf1[2] = input[2] + input[5]; bf1[3] = input[3] + input[4]; bf1[4] = -input[4] + input[3]; bf1[5] = -input[5] + input[2]; bf1[6] = -input[6] + input[1]; bf1[7] = -input[7] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[2] = -bf0[2] + bf0[1]; bf1[3] = -bf0[3] + bf0[0]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; // stage 3 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[2] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[5] = -bf0[5] + bf0[4]; bf1[6] = -bf0[6] + bf0[7]; bf1[7] = bf0[7] + bf0[6]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[6] = half_btf(cospi[24], bf0[6], -cospi[40], bf0[5], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[4]; bf1[2] = bf0[2]; bf1[3] = bf0[6]; } void svt_av1_fidentity4_N2_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; output[0] = round_shift((int64_t)input[0] * new_sqrt2, new_sqrt2_bits); output[1] = round_shift((int64_t)input[1] * new_sqrt2, new_sqrt2_bits); assert(stage_range[0] + new_sqrt2_bits <= 32); } void svt_av1_fadst4_new_N2(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; int32_t bit = cos_bit; const int32_t *sinpi = sinpi_arr(bit); int32_t x0, x1, x2, x3; int32_t s0, s2, s4, s5, s7; // stage 0 x0 = input[0]; x1 = input[1]; x2 = input[2]; x3 = input[3]; if (!(x0 | x1 | x2 | x3)) { output[0] = output[1] = output[2] = output[3] = 0; return; } // stage 1 s0 = sinpi[1] * x0; s2 = sinpi[2] * x1; s4 = sinpi[3] * x2; s5 = sinpi[4] * x3; s7 = x0 + x1; // stage 2 s7 = s7 - x3; // stage 3 x0 = s0 + s2; x1 = sinpi[3] * s7; // stage 4 x0 = x0 + s5; // stage 5 s0 = x0 + s4; // 1-D transform scaling factor is sqrt(2). output[0] = round_shift(s0, bit); output[1] = round_shift(x1, bit); } void svt_av1_fdct4_new_N2(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0; int32_t step[4]; // stage 1; bf0 = step; bf0[0] = input[0] + input[3]; bf0[1] = input[1] + input[2]; bf0[2] = -input[2] + input[1]; bf0[3] = -input[3] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); output[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); output[1] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); } void svt_av1_fdct32_new_N2(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[32]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[31]; bf1[1] = input[1] + input[30]; bf1[2] = input[2] + input[29]; bf1[3] = input[3] + input[28]; bf1[4] = input[4] + input[27]; bf1[5] = input[5] + input[26]; bf1[6] = input[6] + input[25]; bf1[7] = input[7] + input[24]; bf1[8] = input[8] + input[23]; bf1[9] = input[9] + input[22]; bf1[10] = input[10] + input[21]; bf1[11] = input[11] + input[20]; bf1[12] = input[12] + input[19]; bf1[13] = input[13] + input[18]; bf1[14] = input[14] + input[17]; bf1[15] = input[15] + input[16]; bf1[16] = -input[16] + input[15]; bf1[17] = -input[17] + input[14]; bf1[18] = -input[18] + input[13]; bf1[19] = -input[19] + input[12]; bf1[20] = -input[20] + input[11]; bf1[21] = -input[21] + input[10]; bf1[22] = -input[22] + input[9]; bf1[23] = -input[23] + input[8]; bf1[24] = -input[24] + input[7]; bf1[25] = -input[25] + input[6]; bf1[26] = -input[26] + input[5]; bf1[27] = -input[27] + input[4]; bf1[28] = -input[28] + input[3]; bf1[29] = -input[29] + input[2]; bf1[30] = -input[30] + input[1]; bf1[31] = -input[31] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[15]; bf1[1] = bf0[1] + bf0[14]; bf1[2] = bf0[2] + bf0[13]; bf1[3] = bf0[3] + bf0[12]; bf1[4] = bf0[4] + bf0[11]; bf1[5] = bf0[5] + bf0[10]; bf1[6] = bf0[6] + bf0[9]; bf1[7] = bf0[7] + bf0[8]; bf1[8] = -bf0[8] + bf0[7]; bf1[9] = -bf0[9] + bf0[6]; bf1[10] = -bf0[10] + bf0[5]; bf1[11] = -bf0[11] + bf0[4]; bf1[12] = -bf0[12] + bf0[3]; bf1[13] = -bf0[13] + bf0[2]; bf1[14] = -bf0[14] + bf0[1]; bf1[15] = -bf0[15] + bf0[0]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = bf0[18]; bf1[19] = bf0[19]; bf1[20] = half_btf(-cospi[32], bf0[20], cospi[32], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[32], bf0[21], cospi[32], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[32], bf0[22], cospi[32], bf0[25], cos_bit); bf1[23] = half_btf(-cospi[32], bf0[23], cospi[32], bf0[24], cos_bit); bf1[24] = half_btf(cospi[32], bf0[24], cospi[32], bf0[23], cos_bit); bf1[25] = half_btf(cospi[32], bf0[25], cospi[32], bf0[22], cos_bit); bf1[26] = half_btf(cospi[32], bf0[26], cospi[32], bf0[21], cos_bit); bf1[27] = half_btf(cospi[32], bf0[27], cospi[32], bf0[20], cos_bit); bf1[28] = bf0[28]; bf1[29] = bf0[29]; bf1[30] = bf0[30]; bf1[31] = bf0[31]; // stage 3 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[7]; bf1[1] = bf0[1] + bf0[6]; bf1[2] = bf0[2] + bf0[5]; bf1[3] = bf0[3] + bf0[4]; bf1[4] = -bf0[4] + bf0[3]; bf1[5] = -bf0[5] + bf0[2]; bf1[6] = -bf0[6] + bf0[1]; bf1[7] = -bf0[7] + bf0[0]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(-cospi[32], bf0[10], cospi[32], bf0[13], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[12], cos_bit); bf1[12] = half_btf(cospi[32], bf0[12], cospi[32], bf0[11], cos_bit); bf1[13] = half_btf(cospi[32], bf0[13], cospi[32], bf0[10], cos_bit); bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[23]; bf1[17] = bf0[17] + bf0[22]; bf1[18] = bf0[18] + bf0[21]; bf1[19] = bf0[19] + bf0[20]; bf1[20] = -bf0[20] + bf0[19]; bf1[21] = -bf0[21] + bf0[18]; bf1[22] = -bf0[22] + bf0[17]; bf1[23] = -bf0[23] + bf0[16]; bf1[24] = -bf0[24] + bf0[31]; bf1[25] = -bf0[25] + bf0[30]; bf1[26] = -bf0[26] + bf0[29]; bf1[27] = -bf0[27] + bf0[28]; bf1[28] = bf0[28] + bf0[27]; bf1[29] = bf0[29] + bf0[26]; bf1[30] = bf0[30] + bf0[25]; bf1[31] = bf0[31] + bf0[24]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[2] = -bf0[2] + bf0[1]; bf1[3] = -bf0[3] + bf0[0]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; bf1[8] = bf0[8] + bf0[11]; bf1[9] = bf0[9] + bf0[10]; bf1[10] = -bf0[10] + bf0[9]; bf1[11] = -bf0[11] + bf0[8]; bf1[12] = -bf0[12] + bf0[15]; bf1[13] = -bf0[13] + bf0[14]; bf1[14] = bf0[14] + bf0[13]; bf1[15] = bf0[15] + bf0[12]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = half_btf(-cospi[16], bf0[18], cospi[48], bf0[29], cos_bit); bf1[19] = half_btf(-cospi[16], bf0[19], cospi[48], bf0[28], cos_bit); bf1[20] = half_btf(-cospi[48], bf0[20], -cospi[16], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[48], bf0[21], -cospi[16], bf0[26], cos_bit); bf1[22] = bf0[22]; bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = bf0[25]; bf1[26] = half_btf(cospi[48], bf0[26], -cospi[16], bf0[21], cos_bit); bf1[27] = half_btf(cospi[48], bf0[27], -cospi[16], bf0[20], cos_bit); bf1[28] = half_btf(cospi[16], bf0[28], cospi[48], bf0[19], cos_bit); bf1[29] = half_btf(cospi[16], bf0[29], cospi[48], bf0[18], cos_bit); bf1[30] = bf0[30]; bf1[31] = bf0[31]; // stage 5 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[2] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[5] = -bf0[5] + bf0[4]; bf1[6] = -bf0[6] + bf0[7]; bf1[7] = bf0[7] + bf0[6]; bf1[8] = bf0[8]; bf1[9] = half_btf(-cospi[16], bf0[9], cospi[48], bf0[14], cos_bit); bf1[10] = half_btf(-cospi[48], bf0[10], -cospi[16], bf0[13], cos_bit); bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = half_btf(cospi[48], bf0[13], -cospi[16], bf0[10], cos_bit); bf1[14] = half_btf(cospi[16], bf0[14], cospi[48], bf0[9], cos_bit); bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[19]; bf1[17] = bf0[17] + bf0[18]; bf1[18] = -bf0[18] + bf0[17]; bf1[19] = -bf0[19] + bf0[16]; bf1[20] = -bf0[20] + bf0[23]; bf1[21] = -bf0[21] + bf0[22]; bf1[22] = bf0[22] + bf0[21]; bf1[23] = bf0[23] + bf0[20]; bf1[24] = bf0[24] + bf0[27]; bf1[25] = bf0[25] + bf0[26]; bf1[26] = -bf0[26] + bf0[25]; bf1[27] = -bf0[27] + bf0[24]; bf1[28] = -bf0[28] + bf0[31]; bf1[29] = -bf0[29] + bf0[30]; bf1[30] = bf0[30] + bf0[29]; bf1[31] = bf0[31] + bf0[28]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[6] = half_btf(cospi[24], bf0[6], -cospi[40], bf0[5], cos_bit); bf1[8] = bf0[8] + bf0[9]; bf1[9] = -bf0[9] + bf0[8]; bf1[10] = -bf0[10] + bf0[11]; bf1[11] = bf0[11] + bf0[10]; bf1[12] = bf0[12] + bf0[13]; bf1[13] = -bf0[13] + bf0[12]; bf1[14] = -bf0[14] + bf0[15]; bf1[15] = bf0[15] + bf0[14]; bf1[16] = bf0[16]; bf1[17] = half_btf(-cospi[8], bf0[17], cospi[56], bf0[30], cos_bit); bf1[18] = half_btf(-cospi[56], bf0[18], -cospi[8], bf0[29], cos_bit); bf1[19] = bf0[19]; bf1[20] = bf0[20]; bf1[21] = half_btf(-cospi[40], bf0[21], cospi[24], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[24], bf0[22], -cospi[40], bf0[25], cos_bit); bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = half_btf(cospi[24], bf0[25], -cospi[40], bf0[22], cos_bit); bf1[26] = half_btf(cospi[40], bf0[26], cospi[24], bf0[21], cos_bit); bf1[27] = bf0[27]; bf1[28] = bf0[28]; bf1[29] = half_btf(cospi[56], bf0[29], -cospi[8], bf0[18], cos_bit); bf1[30] = half_btf(cospi[8], bf0[30], cospi[56], bf0[17], cos_bit); bf1[31] = bf0[31]; // stage 7 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = bf0[4]; bf1[6] = bf0[6]; bf1[8] = half_btf(cospi[60], bf0[8], cospi[4], bf0[15], cos_bit); bf1[10] = half_btf(cospi[44], bf0[10], cospi[20], bf0[13], cos_bit); bf1[12] = half_btf(cospi[12], bf0[12], -cospi[52], bf0[11], cos_bit); bf1[14] = half_btf(cospi[28], bf0[14], -cospi[36], bf0[9], cos_bit); bf1[16] = bf0[16] + bf0[17]; bf1[17] = -bf0[17] + bf0[16]; bf1[18] = -bf0[18] + bf0[19]; bf1[19] = bf0[19] + bf0[18]; bf1[20] = bf0[20] + bf0[21]; bf1[21] = -bf0[21] + bf0[20]; bf1[22] = -bf0[22] + bf0[23]; bf1[23] = bf0[23] + bf0[22]; bf1[24] = bf0[24] + bf0[25]; bf1[25] = -bf0[25] + bf0[24]; bf1[26] = -bf0[26] + bf0[27]; bf1[27] = bf0[27] + bf0[26]; bf1[28] = bf0[28] + bf0[29]; bf1[29] = -bf0[29] + bf0[28]; bf1[30] = -bf0[30] + bf0[31]; bf1[31] = bf0[31] + bf0[30]; // stage 8 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = bf0[4]; bf1[6] = bf0[6]; bf1[8] = bf0[8]; bf1[10] = bf0[10]; bf1[12] = bf0[12]; bf1[14] = bf0[14]; bf1[16] = half_btf(cospi[62], bf0[16], cospi[2], bf0[31], cos_bit); bf1[18] = half_btf(cospi[46], bf0[18], cospi[18], bf0[29], cos_bit); bf1[20] = half_btf(cospi[54], bf0[20], cospi[10], bf0[27], cos_bit); bf1[22] = half_btf(cospi[38], bf0[22], cospi[26], bf0[25], cos_bit); bf1[24] = half_btf(cospi[6], bf0[24], -cospi[58], bf0[23], cos_bit); bf1[26] = half_btf(cospi[22], bf0[26], -cospi[42], bf0[21], cos_bit); bf1[28] = half_btf(cospi[14], bf0[28], -cospi[50], bf0[19], cos_bit); bf1[30] = half_btf(cospi[30], bf0[30], -cospi[34], bf0[17], cos_bit); // stage 9 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[16]; bf1[2] = bf0[8]; bf1[3] = bf0[24]; bf1[4] = bf0[4]; bf1[5] = bf0[20]; bf1[6] = bf0[12]; bf1[7] = bf0[28]; bf1[8] = bf0[2]; bf1[9] = bf0[18]; bf1[10] = bf0[10]; bf1[11] = bf0[26]; bf1[12] = bf0[6]; bf1[13] = bf0[22]; bf1[14] = bf0[14]; bf1[15] = bf0[30]; } void svt_av1_fidentity32_N2_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 16; ++i) output[i] = input[i] * 4; } void svt_av1_fdct64_new_N2(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[64]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[63]; bf1[1] = input[1] + input[62]; bf1[2] = input[2] + input[61]; bf1[3] = input[3] + input[60]; bf1[4] = input[4] + input[59]; bf1[5] = input[5] + input[58]; bf1[6] = input[6] + input[57]; bf1[7] = input[7] + input[56]; bf1[8] = input[8] + input[55]; bf1[9] = input[9] + input[54]; bf1[10] = input[10] + input[53]; bf1[11] = input[11] + input[52]; bf1[12] = input[12] + input[51]; bf1[13] = input[13] + input[50]; bf1[14] = input[14] + input[49]; bf1[15] = input[15] + input[48]; bf1[16] = input[16] + input[47]; bf1[17] = input[17] + input[46]; bf1[18] = input[18] + input[45]; bf1[19] = input[19] + input[44]; bf1[20] = input[20] + input[43]; bf1[21] = input[21] + input[42]; bf1[22] = input[22] + input[41]; bf1[23] = input[23] + input[40]; bf1[24] = input[24] + input[39]; bf1[25] = input[25] + input[38]; bf1[26] = input[26] + input[37]; bf1[27] = input[27] + input[36]; bf1[28] = input[28] + input[35]; bf1[29] = input[29] + input[34]; bf1[30] = input[30] + input[33]; bf1[31] = input[31] + input[32]; bf1[32] = -input[32] + input[31]; bf1[33] = -input[33] + input[30]; bf1[34] = -input[34] + input[29]; bf1[35] = -input[35] + input[28]; bf1[36] = -input[36] + input[27]; bf1[37] = -input[37] + input[26]; bf1[38] = -input[38] + input[25]; bf1[39] = -input[39] + input[24]; bf1[40] = -input[40] + input[23]; bf1[41] = -input[41] + input[22]; bf1[42] = -input[42] + input[21]; bf1[43] = -input[43] + input[20]; bf1[44] = -input[44] + input[19]; bf1[45] = -input[45] + input[18]; bf1[46] = -input[46] + input[17]; bf1[47] = -input[47] + input[16]; bf1[48] = -input[48] + input[15]; bf1[49] = -input[49] + input[14]; bf1[50] = -input[50] + input[13]; bf1[51] = -input[51] + input[12]; bf1[52] = -input[52] + input[11]; bf1[53] = -input[53] + input[10]; bf1[54] = -input[54] + input[9]; bf1[55] = -input[55] + input[8]; bf1[56] = -input[56] + input[7]; bf1[57] = -input[57] + input[6]; bf1[58] = -input[58] + input[5]; bf1[59] = -input[59] + input[4]; bf1[60] = -input[60] + input[3]; bf1[61] = -input[61] + input[2]; bf1[62] = -input[62] + input[1]; bf1[63] = -input[63] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[31]; bf1[1] = bf0[1] + bf0[30]; bf1[2] = bf0[2] + bf0[29]; bf1[3] = bf0[3] + bf0[28]; bf1[4] = bf0[4] + bf0[27]; bf1[5] = bf0[5] + bf0[26]; bf1[6] = bf0[6] + bf0[25]; bf1[7] = bf0[7] + bf0[24]; bf1[8] = bf0[8] + bf0[23]; bf1[9] = bf0[9] + bf0[22]; bf1[10] = bf0[10] + bf0[21]; bf1[11] = bf0[11] + bf0[20]; bf1[12] = bf0[12] + bf0[19]; bf1[13] = bf0[13] + bf0[18]; bf1[14] = bf0[14] + bf0[17]; bf1[15] = bf0[15] + bf0[16]; bf1[16] = -bf0[16] + bf0[15]; bf1[17] = -bf0[17] + bf0[14]; bf1[18] = -bf0[18] + bf0[13]; bf1[19] = -bf0[19] + bf0[12]; bf1[20] = -bf0[20] + bf0[11]; bf1[21] = -bf0[21] + bf0[10]; bf1[22] = -bf0[22] + bf0[9]; bf1[23] = -bf0[23] + bf0[8]; bf1[24] = -bf0[24] + bf0[7]; bf1[25] = -bf0[25] + bf0[6]; bf1[26] = -bf0[26] + bf0[5]; bf1[27] = -bf0[27] + bf0[4]; bf1[28] = -bf0[28] + bf0[3]; bf1[29] = -bf0[29] + bf0[2]; bf1[30] = -bf0[30] + bf0[1]; bf1[31] = -bf0[31] + bf0[0]; bf1[32] = bf0[32]; bf1[33] = bf0[33]; bf1[34] = bf0[34]; bf1[35] = bf0[35]; bf1[36] = bf0[36]; bf1[37] = bf0[37]; bf1[38] = bf0[38]; bf1[39] = bf0[39]; bf1[40] = half_btf(-cospi[32], bf0[40], cospi[32], bf0[55], cos_bit); bf1[41] = half_btf(-cospi[32], bf0[41], cospi[32], bf0[54], cos_bit); bf1[42] = half_btf(-cospi[32], bf0[42], cospi[32], bf0[53], cos_bit); bf1[43] = half_btf(-cospi[32], bf0[43], cospi[32], bf0[52], cos_bit); bf1[44] = half_btf(-cospi[32], bf0[44], cospi[32], bf0[51], cos_bit); bf1[45] = half_btf(-cospi[32], bf0[45], cospi[32], bf0[50], cos_bit); bf1[46] = half_btf(-cospi[32], bf0[46], cospi[32], bf0[49], cos_bit); bf1[47] = half_btf(-cospi[32], bf0[47], cospi[32], bf0[48], cos_bit); bf1[48] = half_btf(cospi[32], bf0[48], cospi[32], bf0[47], cos_bit); bf1[49] = half_btf(cospi[32], bf0[49], cospi[32], bf0[46], cos_bit); bf1[50] = half_btf(cospi[32], bf0[50], cospi[32], bf0[45], cos_bit); bf1[51] = half_btf(cospi[32], bf0[51], cospi[32], bf0[44], cos_bit); bf1[52] = half_btf(cospi[32], bf0[52], cospi[32], bf0[43], cos_bit); bf1[53] = half_btf(cospi[32], bf0[53], cospi[32], bf0[42], cos_bit); bf1[54] = half_btf(cospi[32], bf0[54], cospi[32], bf0[41], cos_bit); bf1[55] = half_btf(cospi[32], bf0[55], cospi[32], bf0[40], cos_bit); bf1[56] = bf0[56]; bf1[57] = bf0[57]; bf1[58] = bf0[58]; bf1[59] = bf0[59]; bf1[60] = bf0[60]; bf1[61] = bf0[61]; bf1[62] = bf0[62]; bf1[63] = bf0[63]; // stage 3 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[15]; bf1[1] = bf0[1] + bf0[14]; bf1[2] = bf0[2] + bf0[13]; bf1[3] = bf0[3] + bf0[12]; bf1[4] = bf0[4] + bf0[11]; bf1[5] = bf0[5] + bf0[10]; bf1[6] = bf0[6] + bf0[9]; bf1[7] = bf0[7] + bf0[8]; bf1[8] = -bf0[8] + bf0[7]; bf1[9] = -bf0[9] + bf0[6]; bf1[10] = -bf0[10] + bf0[5]; bf1[11] = -bf0[11] + bf0[4]; bf1[12] = -bf0[12] + bf0[3]; bf1[13] = -bf0[13] + bf0[2]; bf1[14] = -bf0[14] + bf0[1]; bf1[15] = -bf0[15] + bf0[0]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = bf0[18]; bf1[19] = bf0[19]; bf1[20] = half_btf(-cospi[32], bf0[20], cospi[32], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[32], bf0[21], cospi[32], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[32], bf0[22], cospi[32], bf0[25], cos_bit); bf1[23] = half_btf(-cospi[32], bf0[23], cospi[32], bf0[24], cos_bit); bf1[24] = half_btf(cospi[32], bf0[24], cospi[32], bf0[23], cos_bit); bf1[25] = half_btf(cospi[32], bf0[25], cospi[32], bf0[22], cos_bit); bf1[26] = half_btf(cospi[32], bf0[26], cospi[32], bf0[21], cos_bit); bf1[27] = half_btf(cospi[32], bf0[27], cospi[32], bf0[20], cos_bit); bf1[28] = bf0[28]; bf1[29] = bf0[29]; bf1[30] = bf0[30]; bf1[31] = bf0[31]; bf1[32] = bf0[32] + bf0[47]; bf1[33] = bf0[33] + bf0[46]; bf1[34] = bf0[34] + bf0[45]; bf1[35] = bf0[35] + bf0[44]; bf1[36] = bf0[36] + bf0[43]; bf1[37] = bf0[37] + bf0[42]; bf1[38] = bf0[38] + bf0[41]; bf1[39] = bf0[39] + bf0[40]; bf1[40] = -bf0[40] + bf0[39]; bf1[41] = -bf0[41] + bf0[38]; bf1[42] = -bf0[42] + bf0[37]; bf1[43] = -bf0[43] + bf0[36]; bf1[44] = -bf0[44] + bf0[35]; bf1[45] = -bf0[45] + bf0[34]; bf1[46] = -bf0[46] + bf0[33]; bf1[47] = -bf0[47] + bf0[32]; bf1[48] = -bf0[48] + bf0[63]; bf1[49] = -bf0[49] + bf0[62]; bf1[50] = -bf0[50] + bf0[61]; bf1[51] = -bf0[51] + bf0[60]; bf1[52] = -bf0[52] + bf0[59]; bf1[53] = -bf0[53] + bf0[58]; bf1[54] = -bf0[54] + bf0[57]; bf1[55] = -bf0[55] + bf0[56]; bf1[56] = bf0[56] + bf0[55]; bf1[57] = bf0[57] + bf0[54]; bf1[58] = bf0[58] + bf0[53]; bf1[59] = bf0[59] + bf0[52]; bf1[60] = bf0[60] + bf0[51]; bf1[61] = bf0[61] + bf0[50]; bf1[62] = bf0[62] + bf0[49]; bf1[63] = bf0[63] + bf0[48]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[7]; bf1[1] = bf0[1] + bf0[6]; bf1[2] = bf0[2] + bf0[5]; bf1[3] = bf0[3] + bf0[4]; bf1[4] = -bf0[4] + bf0[3]; bf1[5] = -bf0[5] + bf0[2]; bf1[6] = -bf0[6] + bf0[1]; bf1[7] = -bf0[7] + bf0[0]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(-cospi[32], bf0[10], cospi[32], bf0[13], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[12], cos_bit); bf1[12] = half_btf(cospi[32], bf0[12], cospi[32], bf0[11], cos_bit); bf1[13] = half_btf(cospi[32], bf0[13], cospi[32], bf0[10], cos_bit); bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[23]; bf1[17] = bf0[17] + bf0[22]; bf1[18] = bf0[18] + bf0[21]; bf1[19] = bf0[19] + bf0[20]; bf1[20] = -bf0[20] + bf0[19]; bf1[21] = -bf0[21] + bf0[18]; bf1[22] = -bf0[22] + bf0[17]; bf1[23] = -bf0[23] + bf0[16]; bf1[24] = -bf0[24] + bf0[31]; bf1[25] = -bf0[25] + bf0[30]; bf1[26] = -bf0[26] + bf0[29]; bf1[27] = -bf0[27] + bf0[28]; bf1[28] = bf0[28] + bf0[27]; bf1[29] = bf0[29] + bf0[26]; bf1[30] = bf0[30] + bf0[25]; bf1[31] = bf0[31] + bf0[24]; bf1[32] = bf0[32]; bf1[33] = bf0[33]; bf1[34] = bf0[34]; bf1[35] = bf0[35]; bf1[36] = half_btf(-cospi[16], bf0[36], cospi[48], bf0[59], cos_bit); bf1[37] = half_btf(-cospi[16], bf0[37], cospi[48], bf0[58], cos_bit); bf1[38] = half_btf(-cospi[16], bf0[38], cospi[48], bf0[57], cos_bit); bf1[39] = half_btf(-cospi[16], bf0[39], cospi[48], bf0[56], cos_bit); bf1[40] = half_btf(-cospi[48], bf0[40], -cospi[16], bf0[55], cos_bit); bf1[41] = half_btf(-cospi[48], bf0[41], -cospi[16], bf0[54], cos_bit); bf1[42] = half_btf(-cospi[48], bf0[42], -cospi[16], bf0[53], cos_bit); bf1[43] = half_btf(-cospi[48], bf0[43], -cospi[16], bf0[52], cos_bit); bf1[44] = bf0[44]; bf1[45] = bf0[45]; bf1[46] = bf0[46]; bf1[47] = bf0[47]; bf1[48] = bf0[48]; bf1[49] = bf0[49]; bf1[50] = bf0[50]; bf1[51] = bf0[51]; bf1[52] = half_btf(cospi[48], bf0[52], -cospi[16], bf0[43], cos_bit); bf1[53] = half_btf(cospi[48], bf0[53], -cospi[16], bf0[42], cos_bit); bf1[54] = half_btf(cospi[48], bf0[54], -cospi[16], bf0[41], cos_bit); bf1[55] = half_btf(cospi[48], bf0[55], -cospi[16], bf0[40], cos_bit); bf1[56] = half_btf(cospi[16], bf0[56], cospi[48], bf0[39], cos_bit); bf1[57] = half_btf(cospi[16], bf0[57], cospi[48], bf0[38], cos_bit); bf1[58] = half_btf(cospi[16], bf0[58], cospi[48], bf0[37], cos_bit); bf1[59] = half_btf(cospi[16], bf0[59], cospi[48], bf0[36], cos_bit); bf1[60] = bf0[60]; bf1[61] = bf0[61]; bf1[62] = bf0[62]; bf1[63] = bf0[63]; // stage 5 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[2] = -bf0[2] + bf0[1]; bf1[3] = -bf0[3] + bf0[0]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; bf1[8] = bf0[8] + bf0[11]; bf1[9] = bf0[9] + bf0[10]; bf1[10] = -bf0[10] + bf0[9]; bf1[11] = -bf0[11] + bf0[8]; bf1[12] = -bf0[12] + bf0[15]; bf1[13] = -bf0[13] + bf0[14]; bf1[14] = bf0[14] + bf0[13]; bf1[15] = bf0[15] + bf0[12]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = half_btf(-cospi[16], bf0[18], cospi[48], bf0[29], cos_bit); bf1[19] = half_btf(-cospi[16], bf0[19], cospi[48], bf0[28], cos_bit); bf1[20] = half_btf(-cospi[48], bf0[20], -cospi[16], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[48], bf0[21], -cospi[16], bf0[26], cos_bit); bf1[22] = bf0[22]; bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = bf0[25]; bf1[26] = half_btf(cospi[48], bf0[26], -cospi[16], bf0[21], cos_bit); bf1[27] = half_btf(cospi[48], bf0[27], -cospi[16], bf0[20], cos_bit); bf1[28] = half_btf(cospi[16], bf0[28], cospi[48], bf0[19], cos_bit); bf1[29] = half_btf(cospi[16], bf0[29], cospi[48], bf0[18], cos_bit); bf1[30] = bf0[30]; bf1[31] = bf0[31]; bf1[32] = bf0[32] + bf0[39]; bf1[33] = bf0[33] + bf0[38]; bf1[34] = bf0[34] + bf0[37]; bf1[35] = bf0[35] + bf0[36]; bf1[36] = -bf0[36] + bf0[35]; bf1[37] = -bf0[37] + bf0[34]; bf1[38] = -bf0[38] + bf0[33]; bf1[39] = -bf0[39] + bf0[32]; bf1[40] = -bf0[40] + bf0[47]; bf1[41] = -bf0[41] + bf0[46]; bf1[42] = -bf0[42] + bf0[45]; bf1[43] = -bf0[43] + bf0[44]; bf1[44] = bf0[44] + bf0[43]; bf1[45] = bf0[45] + bf0[42]; bf1[46] = bf0[46] + bf0[41]; bf1[47] = bf0[47] + bf0[40]; bf1[48] = bf0[48] + bf0[55]; bf1[49] = bf0[49] + bf0[54]; bf1[50] = bf0[50] + bf0[53]; bf1[51] = bf0[51] + bf0[52]; bf1[52] = -bf0[52] + bf0[51]; bf1[53] = -bf0[53] + bf0[50]; bf1[54] = -bf0[54] + bf0[49]; bf1[55] = -bf0[55] + bf0[48]; bf1[56] = -bf0[56] + bf0[63]; bf1[57] = -bf0[57] + bf0[62]; bf1[58] = -bf0[58] + bf0[61]; bf1[59] = -bf0[59] + bf0[60]; bf1[60] = bf0[60] + bf0[59]; bf1[61] = bf0[61] + bf0[58]; bf1[62] = bf0[62] + bf0[57]; bf1[63] = bf0[63] + bf0[56]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[2] = half_btf(cospi[48], bf0[2], cospi[16], bf0[3], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[5] = -bf0[5] + bf0[4]; bf1[6] = -bf0[6] + bf0[7]; bf1[7] = bf0[7] + bf0[6]; bf1[8] = bf0[8]; bf1[9] = half_btf(-cospi[16], bf0[9], cospi[48], bf0[14], cos_bit); bf1[10] = half_btf(-cospi[48], bf0[10], -cospi[16], bf0[13], cos_bit); bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = half_btf(cospi[48], bf0[13], -cospi[16], bf0[10], cos_bit); bf1[14] = half_btf(cospi[16], bf0[14], cospi[48], bf0[9], cos_bit); bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[19]; bf1[17] = bf0[17] + bf0[18]; bf1[18] = -bf0[18] + bf0[17]; bf1[19] = -bf0[19] + bf0[16]; bf1[20] = -bf0[20] + bf0[23]; bf1[21] = -bf0[21] + bf0[22]; bf1[22] = bf0[22] + bf0[21]; bf1[23] = bf0[23] + bf0[20]; bf1[24] = bf0[24] + bf0[27]; bf1[25] = bf0[25] + bf0[26]; bf1[26] = -bf0[26] + bf0[25]; bf1[27] = -bf0[27] + bf0[24]; bf1[28] = -bf0[28] + bf0[31]; bf1[29] = -bf0[29] + bf0[30]; bf1[30] = bf0[30] + bf0[29]; bf1[31] = bf0[31] + bf0[28]; bf1[32] = bf0[32]; bf1[33] = bf0[33]; bf1[34] = half_btf(-cospi[8], bf0[34], cospi[56], bf0[61], cos_bit); bf1[35] = half_btf(-cospi[8], bf0[35], cospi[56], bf0[60], cos_bit); bf1[36] = half_btf(-cospi[56], bf0[36], -cospi[8], bf0[59], cos_bit); bf1[37] = half_btf(-cospi[56], bf0[37], -cospi[8], bf0[58], cos_bit); bf1[38] = bf0[38]; bf1[39] = bf0[39]; bf1[40] = bf0[40]; bf1[41] = bf0[41]; bf1[42] = half_btf(-cospi[40], bf0[42], cospi[24], bf0[53], cos_bit); bf1[43] = half_btf(-cospi[40], bf0[43], cospi[24], bf0[52], cos_bit); bf1[44] = half_btf(-cospi[24], bf0[44], -cospi[40], bf0[51], cos_bit); bf1[45] = half_btf(-cospi[24], bf0[45], -cospi[40], bf0[50], cos_bit); bf1[46] = bf0[46]; bf1[47] = bf0[47]; bf1[48] = bf0[48]; bf1[49] = bf0[49]; bf1[50] = half_btf(cospi[24], bf0[50], -cospi[40], bf0[45], cos_bit); bf1[51] = half_btf(cospi[24], bf0[51], -cospi[40], bf0[44], cos_bit); bf1[52] = half_btf(cospi[40], bf0[52], cospi[24], bf0[43], cos_bit); bf1[53] = half_btf(cospi[40], bf0[53], cospi[24], bf0[42], cos_bit); bf1[54] = bf0[54]; bf1[55] = bf0[55]; bf1[56] = bf0[56]; bf1[57] = bf0[57]; bf1[58] = half_btf(cospi[56], bf0[58], -cospi[8], bf0[37], cos_bit); bf1[59] = half_btf(cospi[56], bf0[59], -cospi[8], bf0[36], cos_bit); bf1[60] = half_btf(cospi[8], bf0[60], cospi[56], bf0[35], cos_bit); bf1[61] = half_btf(cospi[8], bf0[61], cospi[56], bf0[34], cos_bit); bf1[62] = bf0[62]; bf1[63] = bf0[63]; // stage 7 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[6] = half_btf(cospi[24], bf0[6], -cospi[40], bf0[5], cos_bit); bf1[8] = bf0[8] + bf0[9]; bf1[9] = -bf0[9] + bf0[8]; bf1[10] = -bf0[10] + bf0[11]; bf1[11] = bf0[11] + bf0[10]; bf1[12] = bf0[12] + bf0[13]; bf1[13] = -bf0[13] + bf0[12]; bf1[14] = -bf0[14] + bf0[15]; bf1[15] = bf0[15] + bf0[14]; bf1[16] = bf0[16]; bf1[17] = half_btf(-cospi[8], bf0[17], cospi[56], bf0[30], cos_bit); bf1[18] = half_btf(-cospi[56], bf0[18], -cospi[8], bf0[29], cos_bit); bf1[19] = bf0[19]; bf1[20] = bf0[20]; bf1[21] = half_btf(-cospi[40], bf0[21], cospi[24], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[24], bf0[22], -cospi[40], bf0[25], cos_bit); bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = half_btf(cospi[24], bf0[25], -cospi[40], bf0[22], cos_bit); bf1[26] = half_btf(cospi[40], bf0[26], cospi[24], bf0[21], cos_bit); bf1[27] = bf0[27]; bf1[28] = bf0[28]; bf1[29] = half_btf(cospi[56], bf0[29], -cospi[8], bf0[18], cos_bit); bf1[30] = half_btf(cospi[8], bf0[30], cospi[56], bf0[17], cos_bit); bf1[31] = bf0[31]; bf1[32] = bf0[32] + bf0[35]; bf1[33] = bf0[33] + bf0[34]; bf1[34] = -bf0[34] + bf0[33]; bf1[35] = -bf0[35] + bf0[32]; bf1[36] = -bf0[36] + bf0[39]; bf1[37] = -bf0[37] + bf0[38]; bf1[38] = bf0[38] + bf0[37]; bf1[39] = bf0[39] + bf0[36]; bf1[40] = bf0[40] + bf0[43]; bf1[41] = bf0[41] + bf0[42]; bf1[42] = -bf0[42] + bf0[41]; bf1[43] = -bf0[43] + bf0[40]; bf1[44] = -bf0[44] + bf0[47]; bf1[45] = -bf0[45] + bf0[46]; bf1[46] = bf0[46] + bf0[45]; bf1[47] = bf0[47] + bf0[44]; bf1[48] = bf0[48] + bf0[51]; bf1[49] = bf0[49] + bf0[50]; bf1[50] = -bf0[50] + bf0[49]; bf1[51] = -bf0[51] + bf0[48]; bf1[52] = -bf0[52] + bf0[55]; bf1[53] = -bf0[53] + bf0[54]; bf1[54] = bf0[54] + bf0[53]; bf1[55] = bf0[55] + bf0[52]; bf1[56] = bf0[56] + bf0[59]; bf1[57] = bf0[57] + bf0[58]; bf1[58] = -bf0[58] + bf0[57]; bf1[59] = -bf0[59] + bf0[56]; bf1[60] = -bf0[60] + bf0[63]; bf1[61] = -bf0[61] + bf0[62]; bf1[62] = bf0[62] + bf0[61]; bf1[63] = bf0[63] + bf0[60]; // stage 8 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = bf0[4]; bf1[6] = bf0[6]; bf1[8] = half_btf(cospi[60], bf0[8], cospi[4], bf0[15], cos_bit); bf1[10] = half_btf(cospi[44], bf0[10], cospi[20], bf0[13], cos_bit); bf1[12] = half_btf(cospi[12], bf0[12], -cospi[52], bf0[11], cos_bit); bf1[14] = half_btf(cospi[28], bf0[14], -cospi[36], bf0[9], cos_bit); bf1[16] = bf0[16] + bf0[17]; bf1[17] = -bf0[17] + bf0[16]; bf1[18] = -bf0[18] + bf0[19]; bf1[19] = bf0[19] + bf0[18]; bf1[20] = bf0[20] + bf0[21]; bf1[21] = -bf0[21] + bf0[20]; bf1[22] = -bf0[22] + bf0[23]; bf1[23] = bf0[23] + bf0[22]; bf1[24] = bf0[24] + bf0[25]; bf1[25] = -bf0[25] + bf0[24]; bf1[26] = -bf0[26] + bf0[27]; bf1[27] = bf0[27] + bf0[26]; bf1[28] = bf0[28] + bf0[29]; bf1[29] = -bf0[29] + bf0[28]; bf1[30] = -bf0[30] + bf0[31]; bf1[31] = bf0[31] + bf0[30]; bf1[32] = bf0[32]; bf1[33] = half_btf(-cospi[4], bf0[33], cospi[60], bf0[62], cos_bit); bf1[34] = half_btf(-cospi[60], bf0[34], -cospi[4], bf0[61], cos_bit); bf1[35] = bf0[35]; bf1[36] = bf0[36]; bf1[37] = half_btf(-cospi[36], bf0[37], cospi[28], bf0[58], cos_bit); bf1[38] = half_btf(-cospi[28], bf0[38], -cospi[36], bf0[57], cos_bit); bf1[39] = bf0[39]; bf1[40] = bf0[40]; bf1[41] = half_btf(-cospi[20], bf0[41], cospi[44], bf0[54], cos_bit); bf1[42] = half_btf(-cospi[44], bf0[42], -cospi[20], bf0[53], cos_bit); bf1[43] = bf0[43]; bf1[44] = bf0[44]; bf1[45] = half_btf(-cospi[52], bf0[45], cospi[12], bf0[50], cos_bit); bf1[46] = half_btf(-cospi[12], bf0[46], -cospi[52], bf0[49], cos_bit); bf1[47] = bf0[47]; bf1[48] = bf0[48]; bf1[49] = half_btf(cospi[12], bf0[49], -cospi[52], bf0[46], cos_bit); bf1[50] = half_btf(cospi[52], bf0[50], cospi[12], bf0[45], cos_bit); bf1[51] = bf0[51]; bf1[52] = bf0[52]; bf1[53] = half_btf(cospi[44], bf0[53], -cospi[20], bf0[42], cos_bit); bf1[54] = half_btf(cospi[20], bf0[54], cospi[44], bf0[41], cos_bit); bf1[55] = bf0[55]; bf1[56] = bf0[56]; bf1[57] = half_btf(cospi[28], bf0[57], -cospi[36], bf0[38], cos_bit); bf1[58] = half_btf(cospi[36], bf0[58], cospi[28], bf0[37], cos_bit); bf1[59] = bf0[59]; bf1[60] = bf0[60]; bf1[61] = half_btf(cospi[60], bf0[61], -cospi[4], bf0[34], cos_bit); bf1[62] = half_btf(cospi[4], bf0[62], cospi[60], bf0[33], cos_bit); bf1[63] = bf0[63]; // stage 9 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = bf0[4]; bf1[6] = bf0[6]; bf1[8] = bf0[8]; bf1[10] = bf0[10]; bf1[12] = bf0[12]; bf1[14] = bf0[14]; bf1[16] = half_btf(cospi[62], bf0[16], cospi[2], bf0[31], cos_bit); bf1[18] = half_btf(cospi[46], bf0[18], cospi[18], bf0[29], cos_bit); bf1[20] = half_btf(cospi[54], bf0[20], cospi[10], bf0[27], cos_bit); bf1[22] = half_btf(cospi[38], bf0[22], cospi[26], bf0[25], cos_bit); bf1[24] = half_btf(cospi[6], bf0[24], -cospi[58], bf0[23], cos_bit); bf1[26] = half_btf(cospi[22], bf0[26], -cospi[42], bf0[21], cos_bit); bf1[28] = half_btf(cospi[14], bf0[28], -cospi[50], bf0[19], cos_bit); bf1[30] = half_btf(cospi[30], bf0[30], -cospi[34], bf0[17], cos_bit); bf1[32] = bf0[32] + bf0[33]; bf1[33] = -bf0[33] + bf0[32]; bf1[34] = -bf0[34] + bf0[35]; bf1[35] = bf0[35] + bf0[34]; bf1[36] = bf0[36] + bf0[37]; bf1[37] = -bf0[37] + bf0[36]; bf1[38] = -bf0[38] + bf0[39]; bf1[39] = bf0[39] + bf0[38]; bf1[40] = bf0[40] + bf0[41]; bf1[41] = -bf0[41] + bf0[40]; bf1[42] = -bf0[42] + bf0[43]; bf1[43] = bf0[43] + bf0[42]; bf1[44] = bf0[44] + bf0[45]; bf1[45] = -bf0[45] + bf0[44]; bf1[46] = -bf0[46] + bf0[47]; bf1[47] = bf0[47] + bf0[46]; bf1[48] = bf0[48] + bf0[49]; bf1[49] = -bf0[49] + bf0[48]; bf1[50] = -bf0[50] + bf0[51]; bf1[51] = bf0[51] + bf0[50]; bf1[52] = bf0[52] + bf0[53]; bf1[53] = -bf0[53] + bf0[52]; bf1[54] = -bf0[54] + bf0[55]; bf1[55] = bf0[55] + bf0[54]; bf1[56] = bf0[56] + bf0[57]; bf1[57] = -bf0[57] + bf0[56]; bf1[58] = -bf0[58] + bf0[59]; bf1[59] = bf0[59] + bf0[58]; bf1[60] = bf0[60] + bf0[61]; bf1[61] = -bf0[61] + bf0[60]; bf1[62] = -bf0[62] + bf0[63]; bf1[63] = bf0[63] + bf0[62]; // stage 10 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[2] = bf0[2]; bf1[4] = bf0[4]; bf1[6] = bf0[6]; bf1[8] = bf0[8]; bf1[10] = bf0[10]; bf1[12] = bf0[12]; bf1[14] = bf0[14]; bf1[16] = bf0[16]; bf1[18] = bf0[18]; bf1[20] = bf0[20]; bf1[22] = bf0[22]; bf1[24] = bf0[24]; bf1[26] = bf0[26]; bf1[28] = bf0[28]; bf1[30] = bf0[30]; bf1[32] = half_btf(cospi[63], bf0[32], cospi[1], bf0[63], cos_bit); bf1[34] = half_btf(cospi[47], bf0[34], cospi[17], bf0[61], cos_bit); bf1[36] = half_btf(cospi[55], bf0[36], cospi[9], bf0[59], cos_bit); bf1[38] = half_btf(cospi[39], bf0[38], cospi[25], bf0[57], cos_bit); bf1[40] = half_btf(cospi[59], bf0[40], cospi[5], bf0[55], cos_bit); bf1[42] = half_btf(cospi[43], bf0[42], cospi[21], bf0[53], cos_bit); bf1[44] = half_btf(cospi[51], bf0[44], cospi[13], bf0[51], cos_bit); bf1[46] = half_btf(cospi[35], bf0[46], cospi[29], bf0[49], cos_bit); bf1[48] = half_btf(cospi[3], bf0[48], -cospi[61], bf0[47], cos_bit); bf1[50] = half_btf(cospi[19], bf0[50], -cospi[45], bf0[45], cos_bit); bf1[52] = half_btf(cospi[11], bf0[52], -cospi[53], bf0[43], cos_bit); bf1[54] = half_btf(cospi[27], bf0[54], -cospi[37], bf0[41], cos_bit); bf1[56] = half_btf(cospi[7], bf0[56], -cospi[57], bf0[39], cos_bit); bf1[58] = half_btf(cospi[23], bf0[58], -cospi[41], bf0[37], cos_bit); bf1[60] = half_btf(cospi[15], bf0[60], -cospi[49], bf0[35], cos_bit); bf1[62] = half_btf(cospi[31], bf0[62], -cospi[33], bf0[33], cos_bit); // stage 11 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[32]; bf1[2] = bf0[16]; bf1[3] = bf0[48]; bf1[4] = bf0[8]; bf1[5] = bf0[40]; bf1[6] = bf0[24]; bf1[7] = bf0[56]; bf1[8] = bf0[4]; bf1[9] = bf0[36]; bf1[10] = bf0[20]; bf1[11] = bf0[52]; bf1[12] = bf0[12]; bf1[13] = bf0[44]; bf1[14] = bf0[28]; bf1[15] = bf0[60]; bf1[16] = bf0[2]; bf1[17] = bf0[34]; bf1[18] = bf0[18]; bf1[19] = bf0[50]; bf1[20] = bf0[10]; bf1[21] = bf0[42]; bf1[22] = bf0[26]; bf1[23] = bf0[58]; bf1[24] = bf0[6]; bf1[25] = bf0[38]; bf1[26] = bf0[22]; bf1[27] = bf0[54]; bf1[28] = bf0[14]; bf1[29] = bf0[46]; bf1[30] = bf0[30]; bf1[31] = bf0[62]; } void av1_fidentity64_N2_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 32; ++i) output[i] = round_shift((int64_t)input[i] * 4 * new_sqrt2, new_sqrt2_bits); assert(stage_range[0] + new_sqrt2_bits <= 32); } static INLINE TxfmFunc fwd_txfm_type_to_func_N2(TxfmType txfmtype) { switch (txfmtype) { case TXFM_TYPE_DCT4: return svt_av1_fdct4_new_N2; case TXFM_TYPE_DCT8: return svt_av1_fdct8_new_N2; case TXFM_TYPE_DCT16: return svt_av1_fdct16_new_N2; case TXFM_TYPE_DCT32: return svt_av1_fdct32_new_N2; case TXFM_TYPE_DCT64: return svt_av1_fdct64_new_N2; case TXFM_TYPE_ADST4: return svt_av1_fadst4_new_N2; case TXFM_TYPE_ADST8: return svt_av1_fadst8_new_N2; case TXFM_TYPE_ADST16: return svt_av1_fadst16_new_N2; case TXFM_TYPE_ADST32: return av1_fadst32_new; case TXFM_TYPE_IDENTITY4: return svt_av1_fidentity4_N2_c; case TXFM_TYPE_IDENTITY8: return svt_av1_fidentity8_N2_c; case TXFM_TYPE_IDENTITY16: return svt_av1_fidentity16_N2_c; case TXFM_TYPE_IDENTITY32: return svt_av1_fidentity32_N2_c; case TXFM_TYPE_IDENTITY64: return av1_fidentity64_N2_c; default: assert(0); return NULL; } } static INLINE void av1_tranform_two_d_core_N2_c(int16_t *input, uint32_t input_stride, int32_t *output, const Txfm2dFlipCfg *cfg, int32_t *buf, uint8_t bit_depth) { int32_t c, r; // Note when assigning txfm_size_col, we use the txfm_size from the // row configuration and vice versa. This is intentionally done to // accurately perform rectangular transforms. When the transform is // rectangular, the number of columns will be the same as the // txfm_size stored in the row cfg struct. It will make no difference // for square transforms. const int32_t txfm_size_col = tx_size_wide[cfg->tx_size]; const int32_t txfm_size_row = tx_size_high[cfg->tx_size]; // Take the shift from the larger dimension in the rectangular case. const int8_t *shift = cfg->shift; const int32_t rect_type = get_rect_tx_log_ratio(txfm_size_col, txfm_size_row); int8_t stage_range_col[MAX_TXFM_STAGE_NUM]; int8_t stage_range_row[MAX_TXFM_STAGE_NUM]; assert(cfg->stage_num_col <= MAX_TXFM_STAGE_NUM); assert(cfg->stage_num_row <= MAX_TXFM_STAGE_NUM); svt_av1_gen_fwd_stage_range(stage_range_col, stage_range_row, cfg, bit_depth); const int8_t cos_bit_col = cfg->cos_bit_col; const int8_t cos_bit_row = cfg->cos_bit_row; const TxfmFunc txfm_func_col = fwd_txfm_type_to_func_N2(cfg->txfm_type_col); const TxfmFunc txfm_func_row = fwd_txfm_type_to_func_N2(cfg->txfm_type_row); ASSERT(txfm_func_col != NULL); ASSERT(txfm_func_row != NULL); // use output buffer as temp buffer int32_t *temp_in = output; int32_t *temp_out = output + txfm_size_row; // Columns for (c = 0; c < txfm_size_col; ++c) { if (cfg->ud_flip == 0) for (r = 0; r < txfm_size_row; ++r) temp_in[r] = input[r * input_stride + c]; else { for (r = 0; r < txfm_size_row; ++r) // flip upside down temp_in[r] = input[(txfm_size_row - r - 1) * input_stride + c]; } svt_av1_round_shift_array_c( temp_in, txfm_size_row, -shift[0]); // NM svt_av1_round_shift_array_c txfm_func_col(temp_in, temp_out, cos_bit_col, stage_range_col); svt_av1_round_shift_array_c( temp_out, txfm_size_row / 2, -shift[1]); // NM svt_av1_round_shift_array_c if (cfg->lr_flip == 0) { for (r = 0; r < txfm_size_row; ++r) buf[r * txfm_size_col + c] = temp_out[r]; } else { for (r = 0; r < txfm_size_row; ++r) // flip from left to right buf[r * txfm_size_col + (txfm_size_col - c - 1)] = temp_out[r]; } } // Rows for (r = 0; r < txfm_size_row / 2; ++r) { txfm_func_row( buf + r * txfm_size_col, output + r * txfm_size_col, cos_bit_row, stage_range_row); svt_av1_round_shift_array_c(output + r * txfm_size_col, txfm_size_col / 2, -shift[2]); if (abs(rect_type) == 1) { // Multiply everything by Sqrt2 if the transform is rectangular and the // size difference is a factor of 2. for (c = 0; c < txfm_size_col / 2; ++c) { output[r * txfm_size_col + c] = round_shift( (int64_t)output[r * txfm_size_col + c] * new_sqrt2, new_sqrt2_bits); } } } for (int i = 0; i < (txfm_size_col * txfm_size_row); i++) { if (i % txfm_size_col >= (txfm_size_col >> 1) || i / txfm_size_col >= (txfm_size_row >> 1)) { output[i] = 0; } } } void av1_transform_two_d_64x64_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[64 * 64]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_64X64, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void av1_transform_two_d_32x32_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 32]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_32X32, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void av1_transform_two_d_16x16_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X16, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void av1_transform_two_d_8x8_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 8]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_8X8, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void av1_transform_two_d_4x4_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[4 * 4]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_4X4, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_64x32_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[64 * 32]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_64X32, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_32x64_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 64]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_32X64, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_64x16_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[64 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_64X16, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x64_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 64]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X64, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_32x16_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_32X16, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x32_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 32]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X32, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x8_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 8]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X8, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_8x16_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_8X16, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_32x8_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 8]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_32X8, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_8x32_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 32]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_8X32, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x4_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 4]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X4, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_4x16_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[4 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_4X16, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_8x4_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 4]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_8X4, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_4x8_N2_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[4 * 8]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_4X8, &cfg); av1_tranform_two_d_core_N2_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fdct4_new_N4(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi = cospi_arr(cos_bit); int32_t step[2]; // stage 1; step[0] = input[0] + input[3]; step[1] = input[1] + input[2]; output[0] = half_btf(cospi[32], step[0], cospi[32], step[1], cos_bit); } void svt_av1_fadst4_new_N4(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; int32_t bit = cos_bit; const int32_t *sinpi = sinpi_arr(bit); int32_t x0, x1, x2, x3; int32_t s0, s2, s4, s5; // stage 0 x0 = input[0]; x1 = input[1]; x2 = input[2]; x3 = input[3]; if (!(x0 | x1 | x2 | x3)) { output[0] = output[1] = output[2] = output[3] = 0; return; } // stage 1 s0 = sinpi[1] * x0; s2 = sinpi[2] * x1; s4 = sinpi[3] * x2; s5 = sinpi[4] * x3; // stage 3 x0 = s0 + s2; // stage 4 x0 = x0 + s5; // stage 5 s0 = x0 + s4; // 1-D transform scaling factor is sqrt(2). output[0] = round_shift(s0, bit); } void svt_av1_fidentity4_N4_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; output[0] = round_shift((int64_t)input[0] * new_sqrt2, new_sqrt2_bits); assert(stage_range[0] + new_sqrt2_bits <= 32); } void svt_av1_fdct8_new_N4(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[8]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[7]; bf1[1] = input[1] + input[6]; bf1[2] = input[2] + input[5]; bf1[3] = input[3] + input[4]; bf1[4] = -input[4] + input[3]; bf1[5] = -input[5] + input[2]; bf1[6] = -input[6] + input[1]; bf1[7] = -input[7] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; // stage 3 bf0 = step; bf1 = output; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[7] = bf0[7] + bf0[6]; // stage 4 bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[4]; } void svt_av1_fadst8_new_N4(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[8]; // stage 0; // stage 1; assert(output != input); bf1 = output; bf1[0] = input[0]; bf1[1] = -input[7]; bf1[2] = -input[3]; bf1[3] = input[4]; bf1[4] = -input[1]; bf1[5] = input[6]; bf1[6] = input[2]; bf1[7] = -input[5]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = half_btf(cospi[32], bf0[2], cospi[32], bf0[3], cos_bit); bf1[3] = half_btf(cospi[32], bf0[2], -cospi[32], bf0[3], cos_bit); bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[7], cos_bit); bf1[7] = half_btf(cospi[32], bf0[6], -cospi[32], bf0[7], cos_bit); // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[2]; bf1[1] = bf0[1] + bf0[3]; bf1[2] = bf0[0] - bf0[2]; bf1[3] = bf0[1] - bf0[3]; bf1[4] = bf0[4] + bf0[6]; bf1[5] = bf0[5] + bf0[7]; bf1[6] = bf0[4] - bf0[6]; bf1[7] = bf0[5] - bf0[7]; // stage 4 bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[16], bf0[4], cospi[48], bf0[5], cos_bit); bf1[5] = half_btf(cospi[48], bf0[4], -cospi[16], bf0[5], cos_bit); bf1[6] = half_btf(-cospi[48], bf0[6], cospi[16], bf0[7], cos_bit); bf1[7] = half_btf(cospi[16], bf0[6], cospi[48], bf0[7], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[4]; bf1[1] = bf0[1] + bf0[5]; bf1[6] = bf0[2] - bf0[6]; bf1[7] = bf0[3] - bf0[7]; // stage 6 bf0 = output; bf1 = step; bf1[1] = half_btf(cospi[60], bf0[0], -cospi[4], bf0[1], cos_bit); bf1[6] = half_btf(cospi[52], bf0[6], cospi[12], bf0[7], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[1]; bf1[1] = bf0[6]; } void svt_av1_fidentity8_N4_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 2; ++i) output[i] = input[i] * 2; } void svt_av1_fdct16_new_N4(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[16]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[15]; bf1[1] = input[1] + input[14]; bf1[2] = input[2] + input[13]; bf1[3] = input[3] + input[12]; bf1[4] = input[4] + input[11]; bf1[5] = input[5] + input[10]; bf1[6] = input[6] + input[9]; bf1[7] = input[7] + input[8]; bf1[8] = -input[8] + input[7]; bf1[9] = -input[9] + input[6]; bf1[10] = -input[10] + input[5]; bf1[11] = -input[11] + input[4]; bf1[12] = -input[12] + input[3]; bf1[13] = -input[13] + input[2]; bf1[14] = -input[14] + input[1]; bf1[15] = -input[15] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[7]; bf1[1] = bf0[1] + bf0[6]; bf1[2] = bf0[2] + bf0[5]; bf1[3] = bf0[3] + bf0[4]; bf1[4] = -bf0[4] + bf0[3]; bf1[5] = -bf0[5] + bf0[2]; bf1[6] = -bf0[6] + bf0[1]; bf1[7] = -bf0[7] + bf0[0]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(-cospi[32], bf0[10], cospi[32], bf0[13], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[12], cos_bit); bf1[12] = half_btf(cospi[32], bf0[12], cospi[32], bf0[11], cos_bit); bf1[13] = half_btf(cospi[32], bf0[13], cospi[32], bf0[10], cos_bit); bf1[14] = bf0[14]; bf1[15] = bf0[15]; // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; bf1[8] = bf0[8] + bf0[11]; bf1[9] = bf0[9] + bf0[10]; bf1[10] = -bf0[10] + bf0[9]; bf1[11] = -bf0[11] + bf0[8]; bf1[12] = -bf0[12] + bf0[15]; bf1[13] = -bf0[13] + bf0[14]; bf1[14] = bf0[14] + bf0[13]; bf1[15] = bf0[15] + bf0[12]; // stage 4 bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[7] = bf0[7] + bf0[6]; bf1[8] = bf0[8]; bf1[9] = half_btf(-cospi[16], bf0[9], cospi[48], bf0[14], cos_bit); bf1[10] = half_btf(-cospi[48], bf0[10], -cospi[16], bf0[13], cos_bit); bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = half_btf(cospi[48], bf0[13], -cospi[16], bf0[10], cos_bit); bf1[14] = half_btf(cospi[16], bf0[14], cospi[48], bf0[9], cos_bit); bf1[15] = bf0[15]; // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[8] = bf0[8] + bf0[9]; bf1[11] = bf0[11] + bf0[10]; bf1[12] = bf0[12] + bf0[13]; bf1[15] = bf0[15] + bf0[14]; // stage 6 bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[4] = bf0[4]; bf1[8] = half_btf(cospi[60], bf0[8], cospi[4], bf0[15], cos_bit); bf1[12] = half_btf(cospi[12], bf0[12], -cospi[52], bf0[11], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[8]; bf1[2] = bf0[4]; bf1[3] = bf0[12]; } void svt_av1_fadst16_new_N4(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[16]; // stage 0; // stage 1; assert(output != input); bf1 = output; bf1[0] = input[0]; bf1[1] = -input[15]; bf1[2] = -input[7]; bf1[3] = input[8]; bf1[4] = -input[3]; bf1[5] = input[12]; bf1[6] = input[4]; bf1[7] = -input[11]; bf1[8] = -input[1]; bf1[9] = input[14]; bf1[10] = input[6]; bf1[11] = -input[9]; bf1[12] = input[2]; bf1[13] = -input[13]; bf1[14] = -input[5]; bf1[15] = input[10]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = half_btf(cospi[32], bf0[2], cospi[32], bf0[3], cos_bit); bf1[3] = half_btf(cospi[32], bf0[2], -cospi[32], bf0[3], cos_bit); bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[7], cos_bit); bf1[7] = half_btf(cospi[32], bf0[6], -cospi[32], bf0[7], cos_bit); bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(cospi[32], bf0[10], cospi[32], bf0[11], cos_bit); bf1[11] = half_btf(cospi[32], bf0[10], -cospi[32], bf0[11], cos_bit); bf1[12] = bf0[12]; bf1[13] = bf0[13]; bf1[14] = half_btf(cospi[32], bf0[14], cospi[32], bf0[15], cos_bit); bf1[15] = half_btf(cospi[32], bf0[14], -cospi[32], bf0[15], cos_bit); // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[2]; bf1[1] = bf0[1] + bf0[3]; bf1[2] = bf0[0] - bf0[2]; bf1[3] = bf0[1] - bf0[3]; bf1[4] = bf0[4] + bf0[6]; bf1[5] = bf0[5] + bf0[7]; bf1[6] = bf0[4] - bf0[6]; bf1[7] = bf0[5] - bf0[7]; bf1[8] = bf0[8] + bf0[10]; bf1[9] = bf0[9] + bf0[11]; bf1[10] = bf0[8] - bf0[10]; bf1[11] = bf0[9] - bf0[11]; bf1[12] = bf0[12] + bf0[14]; bf1[13] = bf0[13] + bf0[15]; bf1[14] = bf0[12] - bf0[14]; bf1[15] = bf0[13] - bf0[15]; // stage 4 bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = half_btf(cospi[16], bf0[4], cospi[48], bf0[5], cos_bit); bf1[5] = half_btf(cospi[48], bf0[4], -cospi[16], bf0[5], cos_bit); bf1[6] = half_btf(-cospi[48], bf0[6], cospi[16], bf0[7], cos_bit); bf1[7] = half_btf(cospi[16], bf0[6], cospi[48], bf0[7], cos_bit); bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = bf0[10]; bf1[11] = bf0[11]; bf1[12] = half_btf(cospi[16], bf0[12], cospi[48], bf0[13], cos_bit); bf1[13] = half_btf(cospi[48], bf0[12], -cospi[16], bf0[13], cos_bit); bf1[14] = half_btf(-cospi[48], bf0[14], cospi[16], bf0[15], cos_bit); bf1[15] = half_btf(cospi[16], bf0[14], cospi[48], bf0[15], cos_bit); // stage 5 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[4]; bf1[1] = bf0[1] + bf0[5]; bf1[2] = bf0[2] + bf0[6]; bf1[3] = bf0[3] + bf0[7]; bf1[4] = bf0[0] - bf0[4]; bf1[5] = bf0[1] - bf0[5]; bf1[6] = bf0[2] - bf0[6]; bf1[7] = bf0[3] - bf0[7]; bf1[8] = bf0[8] + bf0[12]; bf1[9] = bf0[9] + bf0[13]; bf1[10] = bf0[10] + bf0[14]; bf1[11] = bf0[11] + bf0[15]; bf1[12] = bf0[8] - bf0[12]; bf1[13] = bf0[9] - bf0[13]; bf1[14] = bf0[10] - bf0[14]; bf1[15] = bf0[11] - bf0[15]; // stage 6 bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[1] = bf0[1]; bf1[2] = bf0[2]; bf1[3] = bf0[3]; bf1[4] = bf0[4]; bf1[5] = bf0[5]; bf1[6] = bf0[6]; bf1[7] = bf0[7]; bf1[8] = half_btf(cospi[8], bf0[8], cospi[56], bf0[9], cos_bit); bf1[9] = half_btf(cospi[56], bf0[8], -cospi[8], bf0[9], cos_bit); bf1[10] = half_btf(cospi[40], bf0[10], cospi[24], bf0[11], cos_bit); bf1[11] = half_btf(cospi[24], bf0[10], -cospi[40], bf0[11], cos_bit); bf1[12] = half_btf(-cospi[56], bf0[12], cospi[8], bf0[13], cos_bit); bf1[13] = half_btf(cospi[8], bf0[12], cospi[56], bf0[13], cos_bit); bf1[14] = half_btf(-cospi[24], bf0[14], cospi[40], bf0[15], cos_bit); bf1[15] = half_btf(cospi[40], bf0[14], cospi[24], bf0[15], cos_bit); // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[8]; bf1[1] = bf0[1] + bf0[9]; bf1[2] = bf0[2] + bf0[10]; bf1[3] = bf0[3] + bf0[11]; bf1[12] = bf0[4] - bf0[12]; bf1[13] = bf0[5] - bf0[13]; bf1[14] = bf0[6] - bf0[14]; bf1[15] = bf0[7] - bf0[15]; // stage 8 bf0 = output; bf1 = step; bf1[1] = half_btf(cospi[62], bf0[0], -cospi[2], bf0[1], cos_bit); bf1[3] = half_btf(cospi[54], bf0[2], -cospi[10], bf0[3], cos_bit); bf1[12] = half_btf(cospi[50], bf0[12], cospi[14], bf0[13], cos_bit); bf1[14] = half_btf(cospi[58], bf0[14], cospi[6], bf0[15], cos_bit); // stage 9 bf0 = step; bf1 = output; bf1[0] = bf0[1]; bf1[1] = bf0[14]; bf1[2] = bf0[3]; bf1[3] = bf0[12]; } void svt_av1_fidentity16_N4_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 4; ++i) output[i] = round_shift((int64_t)input[i] * 2 * new_sqrt2, new_sqrt2_bits); assert(stage_range[0] + new_sqrt2_bits <= 32); } void svt_av1_fdct32_new_N4(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[32]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[31]; bf1[1] = input[1] + input[30]; bf1[2] = input[2] + input[29]; bf1[3] = input[3] + input[28]; bf1[4] = input[4] + input[27]; bf1[5] = input[5] + input[26]; bf1[6] = input[6] + input[25]; bf1[7] = input[7] + input[24]; bf1[8] = input[8] + input[23]; bf1[9] = input[9] + input[22]; bf1[10] = input[10] + input[21]; bf1[11] = input[11] + input[20]; bf1[12] = input[12] + input[19]; bf1[13] = input[13] + input[18]; bf1[14] = input[14] + input[17]; bf1[15] = input[15] + input[16]; bf1[16] = -input[16] + input[15]; bf1[17] = -input[17] + input[14]; bf1[18] = -input[18] + input[13]; bf1[19] = -input[19] + input[12]; bf1[20] = -input[20] + input[11]; bf1[21] = -input[21] + input[10]; bf1[22] = -input[22] + input[9]; bf1[23] = -input[23] + input[8]; bf1[24] = -input[24] + input[7]; bf1[25] = -input[25] + input[6]; bf1[26] = -input[26] + input[5]; bf1[27] = -input[27] + input[4]; bf1[28] = -input[28] + input[3]; bf1[29] = -input[29] + input[2]; bf1[30] = -input[30] + input[1]; bf1[31] = -input[31] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[15]; bf1[1] = bf0[1] + bf0[14]; bf1[2] = bf0[2] + bf0[13]; bf1[3] = bf0[3] + bf0[12]; bf1[4] = bf0[4] + bf0[11]; bf1[5] = bf0[5] + bf0[10]; bf1[6] = bf0[6] + bf0[9]; bf1[7] = bf0[7] + bf0[8]; bf1[8] = -bf0[8] + bf0[7]; bf1[9] = -bf0[9] + bf0[6]; bf1[10] = -bf0[10] + bf0[5]; bf1[11] = -bf0[11] + bf0[4]; bf1[12] = -bf0[12] + bf0[3]; bf1[13] = -bf0[13] + bf0[2]; bf1[14] = -bf0[14] + bf0[1]; bf1[15] = -bf0[15] + bf0[0]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = bf0[18]; bf1[19] = bf0[19]; bf1[20] = half_btf(-cospi[32], bf0[20], cospi[32], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[32], bf0[21], cospi[32], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[32], bf0[22], cospi[32], bf0[25], cos_bit); bf1[23] = half_btf(-cospi[32], bf0[23], cospi[32], bf0[24], cos_bit); bf1[24] = half_btf(cospi[32], bf0[24], cospi[32], bf0[23], cos_bit); bf1[25] = half_btf(cospi[32], bf0[25], cospi[32], bf0[22], cos_bit); bf1[26] = half_btf(cospi[32], bf0[26], cospi[32], bf0[21], cos_bit); bf1[27] = half_btf(cospi[32], bf0[27], cospi[32], bf0[20], cos_bit); bf1[28] = bf0[28]; bf1[29] = bf0[29]; bf1[30] = bf0[30]; bf1[31] = bf0[31]; // stage 3 bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[7]; bf1[1] = bf0[1] + bf0[6]; bf1[2] = bf0[2] + bf0[5]; bf1[3] = bf0[3] + bf0[4]; bf1[4] = -bf0[4] + bf0[3]; bf1[5] = -bf0[5] + bf0[2]; bf1[6] = -bf0[6] + bf0[1]; bf1[7] = -bf0[7] + bf0[0]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(-cospi[32], bf0[10], cospi[32], bf0[13], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[12], cos_bit); bf1[12] = half_btf(cospi[32], bf0[12], cospi[32], bf0[11], cos_bit); bf1[13] = half_btf(cospi[32], bf0[13], cospi[32], bf0[10], cos_bit); bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[23]; bf1[17] = bf0[17] + bf0[22]; bf1[18] = bf0[18] + bf0[21]; bf1[19] = bf0[19] + bf0[20]; bf1[20] = -bf0[20] + bf0[19]; bf1[21] = -bf0[21] + bf0[18]; bf1[22] = -bf0[22] + bf0[17]; bf1[23] = -bf0[23] + bf0[16]; bf1[24] = -bf0[24] + bf0[31]; bf1[25] = -bf0[25] + bf0[30]; bf1[26] = -bf0[26] + bf0[29]; bf1[27] = -bf0[27] + bf0[28]; bf1[28] = bf0[28] + bf0[27]; bf1[29] = bf0[29] + bf0[26]; bf1[30] = bf0[30] + bf0[25]; bf1[31] = bf0[31] + bf0[24]; // stage 4 bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; bf1[8] = bf0[8] + bf0[11]; bf1[9] = bf0[9] + bf0[10]; bf1[10] = -bf0[10] + bf0[9]; bf1[11] = -bf0[11] + bf0[8]; bf1[12] = -bf0[12] + bf0[15]; bf1[13] = -bf0[13] + bf0[14]; bf1[14] = bf0[14] + bf0[13]; bf1[15] = bf0[15] + bf0[12]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = half_btf(-cospi[16], bf0[18], cospi[48], bf0[29], cos_bit); bf1[19] = half_btf(-cospi[16], bf0[19], cospi[48], bf0[28], cos_bit); bf1[20] = half_btf(-cospi[48], bf0[20], -cospi[16], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[48], bf0[21], -cospi[16], bf0[26], cos_bit); bf1[22] = bf0[22]; bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = bf0[25]; bf1[26] = half_btf(cospi[48], bf0[26], -cospi[16], bf0[21], cos_bit); bf1[27] = half_btf(cospi[48], bf0[27], -cospi[16], bf0[20], cos_bit); bf1[28] = half_btf(cospi[16], bf0[28], cospi[48], bf0[19], cos_bit); bf1[29] = half_btf(cospi[16], bf0[29], cospi[48], bf0[18], cos_bit); bf1[30] = bf0[30]; bf1[31] = bf0[31]; // stage 5 bf0 = step; bf1 = output; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[7] = bf0[7] + bf0[6]; bf1[8] = bf0[8]; bf1[9] = half_btf(-cospi[16], bf0[9], cospi[48], bf0[14], cos_bit); bf1[10] = half_btf(-cospi[48], bf0[10], -cospi[16], bf0[13], cos_bit); bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = half_btf(cospi[48], bf0[13], -cospi[16], bf0[10], cos_bit); bf1[14] = half_btf(cospi[16], bf0[14], cospi[48], bf0[9], cos_bit); bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[19]; bf1[17] = bf0[17] + bf0[18]; bf1[18] = -bf0[18] + bf0[17]; bf1[19] = -bf0[19] + bf0[16]; bf1[20] = -bf0[20] + bf0[23]; bf1[21] = -bf0[21] + bf0[22]; bf1[22] = bf0[22] + bf0[21]; bf1[23] = bf0[23] + bf0[20]; bf1[24] = bf0[24] + bf0[27]; bf1[25] = bf0[25] + bf0[26]; bf1[26] = -bf0[26] + bf0[25]; bf1[27] = -bf0[27] + bf0[24]; bf1[28] = -bf0[28] + bf0[31]; bf1[29] = -bf0[29] + bf0[30]; bf1[30] = bf0[30] + bf0[29]; bf1[31] = bf0[31] + bf0[28]; // stage 6 bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[8] = bf0[8] + bf0[9]; bf1[11] = bf0[11] + bf0[10]; bf1[12] = bf0[12] + bf0[13]; bf1[15] = bf0[15] + bf0[14]; bf1[16] = bf0[16]; bf1[17] = half_btf(-cospi[8], bf0[17], cospi[56], bf0[30], cos_bit); bf1[18] = half_btf(-cospi[56], bf0[18], -cospi[8], bf0[29], cos_bit); bf1[19] = bf0[19]; bf1[20] = bf0[20]; bf1[21] = half_btf(-cospi[40], bf0[21], cospi[24], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[24], bf0[22], -cospi[40], bf0[25], cos_bit); bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = half_btf(cospi[24], bf0[25], -cospi[40], bf0[22], cos_bit); bf1[26] = half_btf(cospi[40], bf0[26], cospi[24], bf0[21], cos_bit); bf1[27] = bf0[27]; bf1[28] = bf0[28]; bf1[29] = half_btf(cospi[56], bf0[29], -cospi[8], bf0[18], cos_bit); bf1[30] = half_btf(cospi[8], bf0[30], cospi[56], bf0[17], cos_bit); bf1[31] = bf0[31]; // stage 7 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[4] = bf0[4]; bf1[8] = half_btf(cospi[60], bf0[8], cospi[4], bf0[15], cos_bit); bf1[12] = half_btf(cospi[12], bf0[12], -cospi[52], bf0[11], cos_bit); bf1[16] = bf0[16] + bf0[17]; bf1[19] = bf0[19] + bf0[18]; bf1[20] = bf0[20] + bf0[21]; bf1[23] = bf0[23] + bf0[22]; bf1[24] = bf0[24] + bf0[25]; bf1[27] = bf0[27] + bf0[26]; bf1[28] = bf0[28] + bf0[29]; bf1[31] = bf0[31] + bf0[30]; // stage 8 bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[4] = bf0[4]; bf1[8] = bf0[8]; bf1[12] = bf0[12]; bf1[16] = half_btf(cospi[62], bf0[16], cospi[2], bf0[31], cos_bit); bf1[20] = half_btf(cospi[54], bf0[20], cospi[10], bf0[27], cos_bit); bf1[24] = half_btf(cospi[6], bf0[24], -cospi[58], bf0[23], cos_bit); bf1[28] = half_btf(cospi[14], bf0[28], -cospi[50], bf0[19], cos_bit); // stage 9 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[16]; bf1[2] = bf0[8]; bf1[3] = bf0[24]; bf1[4] = bf0[4]; bf1[5] = bf0[20]; bf1[6] = bf0[12]; bf1[7] = bf0[28]; } void svt_av1_fidentity32_N4_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 8; ++i) output[i] = input[i] * 4; } void svt_av1_fdct64_new_N4(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; const int32_t *cospi; int32_t *bf0, *bf1; int32_t step[64]; // stage 0; // stage 1; bf1 = output; bf1[0] = input[0] + input[63]; bf1[1] = input[1] + input[62]; bf1[2] = input[2] + input[61]; bf1[3] = input[3] + input[60]; bf1[4] = input[4] + input[59]; bf1[5] = input[5] + input[58]; bf1[6] = input[6] + input[57]; bf1[7] = input[7] + input[56]; bf1[8] = input[8] + input[55]; bf1[9] = input[9] + input[54]; bf1[10] = input[10] + input[53]; bf1[11] = input[11] + input[52]; bf1[12] = input[12] + input[51]; bf1[13] = input[13] + input[50]; bf1[14] = input[14] + input[49]; bf1[15] = input[15] + input[48]; bf1[16] = input[16] + input[47]; bf1[17] = input[17] + input[46]; bf1[18] = input[18] + input[45]; bf1[19] = input[19] + input[44]; bf1[20] = input[20] + input[43]; bf1[21] = input[21] + input[42]; bf1[22] = input[22] + input[41]; bf1[23] = input[23] + input[40]; bf1[24] = input[24] + input[39]; bf1[25] = input[25] + input[38]; bf1[26] = input[26] + input[37]; bf1[27] = input[27] + input[36]; bf1[28] = input[28] + input[35]; bf1[29] = input[29] + input[34]; bf1[30] = input[30] + input[33]; bf1[31] = input[31] + input[32]; bf1[32] = -input[32] + input[31]; bf1[33] = -input[33] + input[30]; bf1[34] = -input[34] + input[29]; bf1[35] = -input[35] + input[28]; bf1[36] = -input[36] + input[27]; bf1[37] = -input[37] + input[26]; bf1[38] = -input[38] + input[25]; bf1[39] = -input[39] + input[24]; bf1[40] = -input[40] + input[23]; bf1[41] = -input[41] + input[22]; bf1[42] = -input[42] + input[21]; bf1[43] = -input[43] + input[20]; bf1[44] = -input[44] + input[19]; bf1[45] = -input[45] + input[18]; bf1[46] = -input[46] + input[17]; bf1[47] = -input[47] + input[16]; bf1[48] = -input[48] + input[15]; bf1[49] = -input[49] + input[14]; bf1[50] = -input[50] + input[13]; bf1[51] = -input[51] + input[12]; bf1[52] = -input[52] + input[11]; bf1[53] = -input[53] + input[10]; bf1[54] = -input[54] + input[9]; bf1[55] = -input[55] + input[8]; bf1[56] = -input[56] + input[7]; bf1[57] = -input[57] + input[6]; bf1[58] = -input[58] + input[5]; bf1[59] = -input[59] + input[4]; bf1[60] = -input[60] + input[3]; bf1[61] = -input[61] + input[2]; bf1[62] = -input[62] + input[1]; bf1[63] = -input[63] + input[0]; // stage 2 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[31]; bf1[1] = bf0[1] + bf0[30]; bf1[2] = bf0[2] + bf0[29]; bf1[3] = bf0[3] + bf0[28]; bf1[4] = bf0[4] + bf0[27]; bf1[5] = bf0[5] + bf0[26]; bf1[6] = bf0[6] + bf0[25]; bf1[7] = bf0[7] + bf0[24]; bf1[8] = bf0[8] + bf0[23]; bf1[9] = bf0[9] + bf0[22]; bf1[10] = bf0[10] + bf0[21]; bf1[11] = bf0[11] + bf0[20]; bf1[12] = bf0[12] + bf0[19]; bf1[13] = bf0[13] + bf0[18]; bf1[14] = bf0[14] + bf0[17]; bf1[15] = bf0[15] + bf0[16]; bf1[16] = -bf0[16] + bf0[15]; bf1[17] = -bf0[17] + bf0[14]; bf1[18] = -bf0[18] + bf0[13]; bf1[19] = -bf0[19] + bf0[12]; bf1[20] = -bf0[20] + bf0[11]; bf1[21] = -bf0[21] + bf0[10]; bf1[22] = -bf0[22] + bf0[9]; bf1[23] = -bf0[23] + bf0[8]; bf1[24] = -bf0[24] + bf0[7]; bf1[25] = -bf0[25] + bf0[6]; bf1[26] = -bf0[26] + bf0[5]; bf1[27] = -bf0[27] + bf0[4]; bf1[28] = -bf0[28] + bf0[3]; bf1[29] = -bf0[29] + bf0[2]; bf1[30] = -bf0[30] + bf0[1]; bf1[31] = -bf0[31] + bf0[0]; bf1[32] = bf0[32]; bf1[33] = bf0[33]; bf1[34] = bf0[34]; bf1[35] = bf0[35]; bf1[36] = bf0[36]; bf1[37] = bf0[37]; bf1[38] = bf0[38]; bf1[39] = bf0[39]; bf1[40] = half_btf(-cospi[32], bf0[40], cospi[32], bf0[55], cos_bit); bf1[41] = half_btf(-cospi[32], bf0[41], cospi[32], bf0[54], cos_bit); bf1[42] = half_btf(-cospi[32], bf0[42], cospi[32], bf0[53], cos_bit); bf1[43] = half_btf(-cospi[32], bf0[43], cospi[32], bf0[52], cos_bit); bf1[44] = half_btf(-cospi[32], bf0[44], cospi[32], bf0[51], cos_bit); bf1[45] = half_btf(-cospi[32], bf0[45], cospi[32], bf0[50], cos_bit); bf1[46] = half_btf(-cospi[32], bf0[46], cospi[32], bf0[49], cos_bit); bf1[47] = half_btf(-cospi[32], bf0[47], cospi[32], bf0[48], cos_bit); bf1[48] = half_btf(cospi[32], bf0[48], cospi[32], bf0[47], cos_bit); bf1[49] = half_btf(cospi[32], bf0[49], cospi[32], bf0[46], cos_bit); bf1[50] = half_btf(cospi[32], bf0[50], cospi[32], bf0[45], cos_bit); bf1[51] = half_btf(cospi[32], bf0[51], cospi[32], bf0[44], cos_bit); bf1[52] = half_btf(cospi[32], bf0[52], cospi[32], bf0[43], cos_bit); bf1[53] = half_btf(cospi[32], bf0[53], cospi[32], bf0[42], cos_bit); bf1[54] = half_btf(cospi[32], bf0[54], cospi[32], bf0[41], cos_bit); bf1[55] = half_btf(cospi[32], bf0[55], cospi[32], bf0[40], cos_bit); bf1[56] = bf0[56]; bf1[57] = bf0[57]; bf1[58] = bf0[58]; bf1[59] = bf0[59]; bf1[60] = bf0[60]; bf1[61] = bf0[61]; bf1[62] = bf0[62]; bf1[63] = bf0[63]; // stage 3 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[15]; bf1[1] = bf0[1] + bf0[14]; bf1[2] = bf0[2] + bf0[13]; bf1[3] = bf0[3] + bf0[12]; bf1[4] = bf0[4] + bf0[11]; bf1[5] = bf0[5] + bf0[10]; bf1[6] = bf0[6] + bf0[9]; bf1[7] = bf0[7] + bf0[8]; bf1[8] = -bf0[8] + bf0[7]; bf1[9] = -bf0[9] + bf0[6]; bf1[10] = -bf0[10] + bf0[5]; bf1[11] = -bf0[11] + bf0[4]; bf1[12] = -bf0[12] + bf0[3]; bf1[13] = -bf0[13] + bf0[2]; bf1[14] = -bf0[14] + bf0[1]; bf1[15] = -bf0[15] + bf0[0]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = bf0[18]; bf1[19] = bf0[19]; bf1[20] = half_btf(-cospi[32], bf0[20], cospi[32], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[32], bf0[21], cospi[32], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[32], bf0[22], cospi[32], bf0[25], cos_bit); bf1[23] = half_btf(-cospi[32], bf0[23], cospi[32], bf0[24], cos_bit); bf1[24] = half_btf(cospi[32], bf0[24], cospi[32], bf0[23], cos_bit); bf1[25] = half_btf(cospi[32], bf0[25], cospi[32], bf0[22], cos_bit); bf1[26] = half_btf(cospi[32], bf0[26], cospi[32], bf0[21], cos_bit); bf1[27] = half_btf(cospi[32], bf0[27], cospi[32], bf0[20], cos_bit); bf1[28] = bf0[28]; bf1[29] = bf0[29]; bf1[30] = bf0[30]; bf1[31] = bf0[31]; bf1[32] = bf0[32] + bf0[47]; bf1[33] = bf0[33] + bf0[46]; bf1[34] = bf0[34] + bf0[45]; bf1[35] = bf0[35] + bf0[44]; bf1[36] = bf0[36] + bf0[43]; bf1[37] = bf0[37] + bf0[42]; bf1[38] = bf0[38] + bf0[41]; bf1[39] = bf0[39] + bf0[40]; bf1[40] = -bf0[40] + bf0[39]; bf1[41] = -bf0[41] + bf0[38]; bf1[42] = -bf0[42] + bf0[37]; bf1[43] = -bf0[43] + bf0[36]; bf1[44] = -bf0[44] + bf0[35]; bf1[45] = -bf0[45] + bf0[34]; bf1[46] = -bf0[46] + bf0[33]; bf1[47] = -bf0[47] + bf0[32]; bf1[48] = -bf0[48] + bf0[63]; bf1[49] = -bf0[49] + bf0[62]; bf1[50] = -bf0[50] + bf0[61]; bf1[51] = -bf0[51] + bf0[60]; bf1[52] = -bf0[52] + bf0[59]; bf1[53] = -bf0[53] + bf0[58]; bf1[54] = -bf0[54] + bf0[57]; bf1[55] = -bf0[55] + bf0[56]; bf1[56] = bf0[56] + bf0[55]; bf1[57] = bf0[57] + bf0[54]; bf1[58] = bf0[58] + bf0[53]; bf1[59] = bf0[59] + bf0[52]; bf1[60] = bf0[60] + bf0[51]; bf1[61] = bf0[61] + bf0[50]; bf1[62] = bf0[62] + bf0[49]; bf1[63] = bf0[63] + bf0[48]; // stage 4 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0] + bf0[7]; bf1[1] = bf0[1] + bf0[6]; bf1[2] = bf0[2] + bf0[5]; bf1[3] = bf0[3] + bf0[4]; bf1[4] = -bf0[4] + bf0[3]; bf1[5] = -bf0[5] + bf0[2]; bf1[6] = -bf0[6] + bf0[1]; bf1[7] = -bf0[7] + bf0[0]; bf1[8] = bf0[8]; bf1[9] = bf0[9]; bf1[10] = half_btf(-cospi[32], bf0[10], cospi[32], bf0[13], cos_bit); bf1[11] = half_btf(-cospi[32], bf0[11], cospi[32], bf0[12], cos_bit); bf1[12] = half_btf(cospi[32], bf0[12], cospi[32], bf0[11], cos_bit); bf1[13] = half_btf(cospi[32], bf0[13], cospi[32], bf0[10], cos_bit); bf1[14] = bf0[14]; bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[23]; bf1[17] = bf0[17] + bf0[22]; bf1[18] = bf0[18] + bf0[21]; bf1[19] = bf0[19] + bf0[20]; bf1[20] = -bf0[20] + bf0[19]; bf1[21] = -bf0[21] + bf0[18]; bf1[22] = -bf0[22] + bf0[17]; bf1[23] = -bf0[23] + bf0[16]; bf1[24] = -bf0[24] + bf0[31]; bf1[25] = -bf0[25] + bf0[30]; bf1[26] = -bf0[26] + bf0[29]; bf1[27] = -bf0[27] + bf0[28]; bf1[28] = bf0[28] + bf0[27]; bf1[29] = bf0[29] + bf0[26]; bf1[30] = bf0[30] + bf0[25]; bf1[31] = bf0[31] + bf0[24]; bf1[32] = bf0[32]; bf1[33] = bf0[33]; bf1[34] = bf0[34]; bf1[35] = bf0[35]; bf1[36] = half_btf(-cospi[16], bf0[36], cospi[48], bf0[59], cos_bit); bf1[37] = half_btf(-cospi[16], bf0[37], cospi[48], bf0[58], cos_bit); bf1[38] = half_btf(-cospi[16], bf0[38], cospi[48], bf0[57], cos_bit); bf1[39] = half_btf(-cospi[16], bf0[39], cospi[48], bf0[56], cos_bit); bf1[40] = half_btf(-cospi[48], bf0[40], -cospi[16], bf0[55], cos_bit); bf1[41] = half_btf(-cospi[48], bf0[41], -cospi[16], bf0[54], cos_bit); bf1[42] = half_btf(-cospi[48], bf0[42], -cospi[16], bf0[53], cos_bit); bf1[43] = half_btf(-cospi[48], bf0[43], -cospi[16], bf0[52], cos_bit); bf1[44] = bf0[44]; bf1[45] = bf0[45]; bf1[46] = bf0[46]; bf1[47] = bf0[47]; bf1[48] = bf0[48]; bf1[49] = bf0[49]; bf1[50] = bf0[50]; bf1[51] = bf0[51]; bf1[52] = half_btf(cospi[48], bf0[52], -cospi[16], bf0[43], cos_bit); bf1[53] = half_btf(cospi[48], bf0[53], -cospi[16], bf0[42], cos_bit); bf1[54] = half_btf(cospi[48], bf0[54], -cospi[16], bf0[41], cos_bit); bf1[55] = half_btf(cospi[48], bf0[55], -cospi[16], bf0[40], cos_bit); bf1[56] = half_btf(cospi[16], bf0[56], cospi[48], bf0[39], cos_bit); bf1[57] = half_btf(cospi[16], bf0[57], cospi[48], bf0[38], cos_bit); bf1[58] = half_btf(cospi[16], bf0[58], cospi[48], bf0[37], cos_bit); bf1[59] = half_btf(cospi[16], bf0[59], cospi[48], bf0[36], cos_bit); bf1[60] = bf0[60]; bf1[61] = bf0[61]; bf1[62] = bf0[62]; bf1[63] = bf0[63]; // stage 5 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0] + bf0[3]; bf1[1] = bf0[1] + bf0[2]; bf1[4] = bf0[4]; bf1[5] = half_btf(-cospi[32], bf0[5], cospi[32], bf0[6], cos_bit); bf1[6] = half_btf(cospi[32], bf0[6], cospi[32], bf0[5], cos_bit); bf1[7] = bf0[7]; bf1[8] = bf0[8] + bf0[11]; bf1[9] = bf0[9] + bf0[10]; bf1[10] = -bf0[10] + bf0[9]; bf1[11] = -bf0[11] + bf0[8]; bf1[12] = -bf0[12] + bf0[15]; bf1[13] = -bf0[13] + bf0[14]; bf1[14] = bf0[14] + bf0[13]; bf1[15] = bf0[15] + bf0[12]; bf1[16] = bf0[16]; bf1[17] = bf0[17]; bf1[18] = half_btf(-cospi[16], bf0[18], cospi[48], bf0[29], cos_bit); bf1[19] = half_btf(-cospi[16], bf0[19], cospi[48], bf0[28], cos_bit); bf1[20] = half_btf(-cospi[48], bf0[20], -cospi[16], bf0[27], cos_bit); bf1[21] = half_btf(-cospi[48], bf0[21], -cospi[16], bf0[26], cos_bit); bf1[22] = bf0[22]; bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = bf0[25]; bf1[26] = half_btf(cospi[48], bf0[26], -cospi[16], bf0[21], cos_bit); bf1[27] = half_btf(cospi[48], bf0[27], -cospi[16], bf0[20], cos_bit); bf1[28] = half_btf(cospi[16], bf0[28], cospi[48], bf0[19], cos_bit); bf1[29] = half_btf(cospi[16], bf0[29], cospi[48], bf0[18], cos_bit); bf1[30] = bf0[30]; bf1[31] = bf0[31]; bf1[32] = bf0[32] + bf0[39]; bf1[33] = bf0[33] + bf0[38]; bf1[34] = bf0[34] + bf0[37]; bf1[35] = bf0[35] + bf0[36]; bf1[36] = -bf0[36] + bf0[35]; bf1[37] = -bf0[37] + bf0[34]; bf1[38] = -bf0[38] + bf0[33]; bf1[39] = -bf0[39] + bf0[32]; bf1[40] = -bf0[40] + bf0[47]; bf1[41] = -bf0[41] + bf0[46]; bf1[42] = -bf0[42] + bf0[45]; bf1[43] = -bf0[43] + bf0[44]; bf1[44] = bf0[44] + bf0[43]; bf1[45] = bf0[45] + bf0[42]; bf1[46] = bf0[46] + bf0[41]; bf1[47] = bf0[47] + bf0[40]; bf1[48] = bf0[48] + bf0[55]; bf1[49] = bf0[49] + bf0[54]; bf1[50] = bf0[50] + bf0[53]; bf1[51] = bf0[51] + bf0[52]; bf1[52] = -bf0[52] + bf0[51]; bf1[53] = -bf0[53] + bf0[50]; bf1[54] = -bf0[54] + bf0[49]; bf1[55] = -bf0[55] + bf0[48]; bf1[56] = -bf0[56] + bf0[63]; bf1[57] = -bf0[57] + bf0[62]; bf1[58] = -bf0[58] + bf0[61]; bf1[59] = -bf0[59] + bf0[60]; bf1[60] = bf0[60] + bf0[59]; bf1[61] = bf0[61] + bf0[58]; bf1[62] = bf0[62] + bf0[57]; bf1[63] = bf0[63] + bf0[56]; // stage 6 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = half_btf(cospi[32], bf0[0], cospi[32], bf0[1], cos_bit); bf1[4] = bf0[4] + bf0[5]; bf1[7] = bf0[7] + bf0[6]; bf1[8] = bf0[8]; bf1[9] = half_btf(-cospi[16], bf0[9], cospi[48], bf0[14], cos_bit); bf1[10] = half_btf(-cospi[48], bf0[10], -cospi[16], bf0[13], cos_bit); bf1[11] = bf0[11]; bf1[12] = bf0[12]; bf1[13] = half_btf(cospi[48], bf0[13], -cospi[16], bf0[10], cos_bit); bf1[14] = half_btf(cospi[16], bf0[14], cospi[48], bf0[9], cos_bit); bf1[15] = bf0[15]; bf1[16] = bf0[16] + bf0[19]; bf1[17] = bf0[17] + bf0[18]; bf1[18] = -bf0[18] + bf0[17]; bf1[19] = -bf0[19] + bf0[16]; bf1[20] = -bf0[20] + bf0[23]; bf1[21] = -bf0[21] + bf0[22]; bf1[22] = bf0[22] + bf0[21]; bf1[23] = bf0[23] + bf0[20]; bf1[24] = bf0[24] + bf0[27]; bf1[25] = bf0[25] + bf0[26]; bf1[26] = -bf0[26] + bf0[25]; bf1[27] = -bf0[27] + bf0[24]; bf1[28] = -bf0[28] + bf0[31]; bf1[29] = -bf0[29] + bf0[30]; bf1[30] = bf0[30] + bf0[29]; bf1[31] = bf0[31] + bf0[28]; bf1[32] = bf0[32]; bf1[33] = bf0[33]; bf1[34] = half_btf(-cospi[8], bf0[34], cospi[56], bf0[61], cos_bit); bf1[35] = half_btf(-cospi[8], bf0[35], cospi[56], bf0[60], cos_bit); bf1[36] = half_btf(-cospi[56], bf0[36], -cospi[8], bf0[59], cos_bit); bf1[37] = half_btf(-cospi[56], bf0[37], -cospi[8], bf0[58], cos_bit); bf1[38] = bf0[38]; bf1[39] = bf0[39]; bf1[40] = bf0[40]; bf1[41] = bf0[41]; bf1[42] = half_btf(-cospi[40], bf0[42], cospi[24], bf0[53], cos_bit); bf1[43] = half_btf(-cospi[40], bf0[43], cospi[24], bf0[52], cos_bit); bf1[44] = half_btf(-cospi[24], bf0[44], -cospi[40], bf0[51], cos_bit); bf1[45] = half_btf(-cospi[24], bf0[45], -cospi[40], bf0[50], cos_bit); bf1[46] = bf0[46]; bf1[47] = bf0[47]; bf1[48] = bf0[48]; bf1[49] = bf0[49]; bf1[50] = half_btf(cospi[24], bf0[50], -cospi[40], bf0[45], cos_bit); bf1[51] = half_btf(cospi[24], bf0[51], -cospi[40], bf0[44], cos_bit); bf1[52] = half_btf(cospi[40], bf0[52], cospi[24], bf0[43], cos_bit); bf1[53] = half_btf(cospi[40], bf0[53], cospi[24], bf0[42], cos_bit); bf1[54] = bf0[54]; bf1[55] = bf0[55]; bf1[56] = bf0[56]; bf1[57] = bf0[57]; bf1[58] = half_btf(cospi[56], bf0[58], -cospi[8], bf0[37], cos_bit); bf1[59] = half_btf(cospi[56], bf0[59], -cospi[8], bf0[36], cos_bit); bf1[60] = half_btf(cospi[8], bf0[60], cospi[56], bf0[35], cos_bit); bf1[61] = half_btf(cospi[8], bf0[61], cospi[56], bf0[34], cos_bit); bf1[62] = bf0[62]; bf1[63] = bf0[63]; // stage 7 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[4] = half_btf(cospi[56], bf0[4], cospi[8], bf0[7], cos_bit); bf1[8] = bf0[8] + bf0[9]; bf1[11] = bf0[11] + bf0[10]; bf1[12] = bf0[12] + bf0[13]; bf1[15] = bf0[15] + bf0[14]; bf1[16] = bf0[16]; bf1[17] = half_btf(-cospi[8], bf0[17], cospi[56], bf0[30], cos_bit); bf1[18] = half_btf(-cospi[56], bf0[18], -cospi[8], bf0[29], cos_bit); bf1[19] = bf0[19]; bf1[20] = bf0[20]; bf1[21] = half_btf(-cospi[40], bf0[21], cospi[24], bf0[26], cos_bit); bf1[22] = half_btf(-cospi[24], bf0[22], -cospi[40], bf0[25], cos_bit); bf1[23] = bf0[23]; bf1[24] = bf0[24]; bf1[25] = half_btf(cospi[24], bf0[25], -cospi[40], bf0[22], cos_bit); bf1[26] = half_btf(cospi[40], bf0[26], cospi[24], bf0[21], cos_bit); bf1[27] = bf0[27]; bf1[28] = bf0[28]; bf1[29] = half_btf(cospi[56], bf0[29], -cospi[8], bf0[18], cos_bit); bf1[30] = half_btf(cospi[8], bf0[30], cospi[56], bf0[17], cos_bit); bf1[31] = bf0[31]; bf1[32] = bf0[32] + bf0[35]; bf1[33] = bf0[33] + bf0[34]; bf1[34] = -bf0[34] + bf0[33]; bf1[35] = -bf0[35] + bf0[32]; bf1[36] = -bf0[36] + bf0[39]; bf1[37] = -bf0[37] + bf0[38]; bf1[38] = bf0[38] + bf0[37]; bf1[39] = bf0[39] + bf0[36]; bf1[40] = bf0[40] + bf0[43]; bf1[41] = bf0[41] + bf0[42]; bf1[42] = -bf0[42] + bf0[41]; bf1[43] = -bf0[43] + bf0[40]; bf1[44] = -bf0[44] + bf0[47]; bf1[45] = -bf0[45] + bf0[46]; bf1[46] = bf0[46] + bf0[45]; bf1[47] = bf0[47] + bf0[44]; bf1[48] = bf0[48] + bf0[51]; bf1[49] = bf0[49] + bf0[50]; bf1[50] = -bf0[50] + bf0[49]; bf1[51] = -bf0[51] + bf0[48]; bf1[52] = -bf0[52] + bf0[55]; bf1[53] = -bf0[53] + bf0[54]; bf1[54] = bf0[54] + bf0[53]; bf1[55] = bf0[55] + bf0[52]; bf1[56] = bf0[56] + bf0[59]; bf1[57] = bf0[57] + bf0[58]; bf1[58] = -bf0[58] + bf0[57]; bf1[59] = -bf0[59] + bf0[56]; bf1[60] = -bf0[60] + bf0[63]; bf1[61] = -bf0[61] + bf0[62]; bf1[62] = bf0[62] + bf0[61]; bf1[63] = bf0[63] + bf0[60]; // stage 8 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[4] = bf0[4]; bf1[8] = half_btf(cospi[60], bf0[8], cospi[4], bf0[15], cos_bit); bf1[12] = half_btf(cospi[12], bf0[12], -cospi[52], bf0[11], cos_bit); bf1[16] = bf0[16] + bf0[17]; bf1[19] = bf0[19] + bf0[18]; bf1[20] = bf0[20] + bf0[21]; bf1[23] = bf0[23] + bf0[22]; bf1[24] = bf0[24] + bf0[25]; bf1[27] = bf0[27] + bf0[26]; bf1[28] = bf0[28] + bf0[29]; bf1[31] = bf0[31] + bf0[30]; bf1[32] = bf0[32]; bf1[33] = half_btf(-cospi[4], bf0[33], cospi[60], bf0[62], cos_bit); bf1[34] = half_btf(-cospi[60], bf0[34], -cospi[4], bf0[61], cos_bit); bf1[35] = bf0[35]; bf1[36] = bf0[36]; bf1[37] = half_btf(-cospi[36], bf0[37], cospi[28], bf0[58], cos_bit); bf1[38] = half_btf(-cospi[28], bf0[38], -cospi[36], bf0[57], cos_bit); bf1[39] = bf0[39]; bf1[40] = bf0[40]; bf1[41] = half_btf(-cospi[20], bf0[41], cospi[44], bf0[54], cos_bit); bf1[42] = half_btf(-cospi[44], bf0[42], -cospi[20], bf0[53], cos_bit); bf1[43] = bf0[43]; bf1[44] = bf0[44]; bf1[45] = half_btf(-cospi[52], bf0[45], cospi[12], bf0[50], cos_bit); bf1[46] = half_btf(-cospi[12], bf0[46], -cospi[52], bf0[49], cos_bit); bf1[47] = bf0[47]; bf1[48] = bf0[48]; bf1[49] = half_btf(cospi[12], bf0[49], -cospi[52], bf0[46], cos_bit); bf1[50] = half_btf(cospi[52], bf0[50], cospi[12], bf0[45], cos_bit); bf1[51] = bf0[51]; bf1[52] = bf0[52]; bf1[53] = half_btf(cospi[44], bf0[53], -cospi[20], bf0[42], cos_bit); bf1[54] = half_btf(cospi[20], bf0[54], cospi[44], bf0[41], cos_bit); bf1[55] = bf0[55]; bf1[56] = bf0[56]; bf1[57] = half_btf(cospi[28], bf0[57], -cospi[36], bf0[38], cos_bit); bf1[58] = half_btf(cospi[36], bf0[58], cospi[28], bf0[37], cos_bit); bf1[59] = bf0[59]; bf1[60] = bf0[60]; bf1[61] = half_btf(cospi[60], bf0[61], -cospi[4], bf0[34], cos_bit); bf1[62] = half_btf(cospi[4], bf0[62], cospi[60], bf0[33], cos_bit); bf1[63] = bf0[63]; // stage 9 cospi = cospi_arr(cos_bit); bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[4] = bf0[4]; bf1[8] = bf0[8]; bf1[12] = bf0[12]; bf1[16] = half_btf(cospi[62], bf0[16], cospi[2], bf0[31], cos_bit); bf1[20] = half_btf(cospi[54], bf0[20], cospi[10], bf0[27], cos_bit); bf1[24] = half_btf(cospi[6], bf0[24], -cospi[58], bf0[23], cos_bit); bf1[28] = half_btf(cospi[14], bf0[28], -cospi[50], bf0[19], cos_bit); bf1[32] = bf0[32] + bf0[33]; bf1[35] = bf0[35] + bf0[34]; bf1[36] = bf0[36] + bf0[37]; bf1[39] = bf0[39] + bf0[38]; bf1[40] = bf0[40] + bf0[41]; bf1[43] = bf0[43] + bf0[42]; bf1[44] = bf0[44] + bf0[45]; bf1[47] = bf0[47] + bf0[46]; bf1[48] = bf0[48] + bf0[49]; bf1[51] = bf0[51] + bf0[50]; bf1[52] = bf0[52] + bf0[53]; bf1[55] = bf0[55] + bf0[54]; bf1[56] = bf0[56] + bf0[57]; bf1[59] = bf0[59] + bf0[58]; bf1[60] = bf0[60] + bf0[61]; bf1[63] = bf0[63] + bf0[62]; // stage 10 cospi = cospi_arr(cos_bit); bf0 = output; bf1 = step; bf1[0] = bf0[0]; bf1[4] = bf0[4]; bf1[8] = bf0[8]; bf1[12] = bf0[12]; bf1[16] = bf0[16]; bf1[20] = bf0[20]; bf1[24] = bf0[24]; bf1[28] = bf0[28]; bf1[32] = half_btf(cospi[63], bf0[32], cospi[1], bf0[63], cos_bit); bf1[36] = half_btf(cospi[55], bf0[36], cospi[9], bf0[59], cos_bit); bf1[40] = half_btf(cospi[59], bf0[40], cospi[5], bf0[55], cos_bit); bf1[44] = half_btf(cospi[51], bf0[44], cospi[13], bf0[51], cos_bit); bf1[48] = half_btf(cospi[3], bf0[48], -cospi[61], bf0[47], cos_bit); bf1[52] = half_btf(cospi[11], bf0[52], -cospi[53], bf0[43], cos_bit); bf1[56] = half_btf(cospi[7], bf0[56], -cospi[57], bf0[39], cos_bit); bf1[60] = half_btf(cospi[15], bf0[60], -cospi[49], bf0[35], cos_bit); // stage 11 bf0 = step; bf1 = output; bf1[0] = bf0[0]; bf1[1] = bf0[32]; bf1[2] = bf0[16]; bf1[3] = bf0[48]; bf1[4] = bf0[8]; bf1[5] = bf0[40]; bf1[6] = bf0[24]; bf1[7] = bf0[56]; bf1[8] = bf0[4]; bf1[9] = bf0[36]; bf1[10] = bf0[20]; bf1[11] = bf0[52]; bf1[12] = bf0[12]; bf1[13] = bf0[44]; bf1[14] = bf0[28]; bf1[15] = bf0[60]; } void av1_fidentity64_N4_c(const int32_t *input, int32_t *output, int8_t cos_bit, const int8_t *stage_range) { (void)stage_range; (void)cos_bit; for (int32_t i = 0; i < 16; ++i) output[i] = round_shift((int64_t)input[i] * 4 * new_sqrt2, new_sqrt2_bits); assert(stage_range[0] + new_sqrt2_bits <= 32); } static INLINE TxfmFunc fwd_txfm_type_to_func_N4(TxfmType txfmtype) { switch (txfmtype) { case TXFM_TYPE_DCT4: return svt_av1_fdct4_new_N4; case TXFM_TYPE_DCT8: return svt_av1_fdct8_new_N4; case TXFM_TYPE_DCT16: return svt_av1_fdct16_new_N4; case TXFM_TYPE_DCT32: return svt_av1_fdct32_new_N4; case TXFM_TYPE_DCT64: return svt_av1_fdct64_new_N4; case TXFM_TYPE_ADST4: return svt_av1_fadst4_new_N4; case TXFM_TYPE_ADST8: return svt_av1_fadst8_new_N4; case TXFM_TYPE_ADST16: return svt_av1_fadst16_new_N4; case TXFM_TYPE_ADST32: return av1_fadst32_new; case TXFM_TYPE_IDENTITY4: return svt_av1_fidentity4_N4_c; case TXFM_TYPE_IDENTITY8: return svt_av1_fidentity8_N4_c; case TXFM_TYPE_IDENTITY16: return svt_av1_fidentity16_N4_c; case TXFM_TYPE_IDENTITY32: return svt_av1_fidentity32_N4_c; case TXFM_TYPE_IDENTITY64: return av1_fidentity64_N4_c; default: assert(0); return NULL; } } static INLINE void av1_tranform_two_d_core_N4_c(int16_t *input, uint32_t input_stride, int32_t *output, const Txfm2dFlipCfg *cfg, int32_t *buf, uint8_t bit_depth) { int32_t c, r; // Note when assigning txfm_size_col, we use the txfm_size from the // row configuration and vice versa. This is intentionally done to // accurately perform rectangular transforms. When the transform is // rectangular, the number of columns will be the same as the // txfm_size stored in the row cfg struct. It will make no difference // for square transforms. const int32_t txfm_size_col = tx_size_wide[cfg->tx_size]; const int32_t txfm_size_row = tx_size_high[cfg->tx_size]; // Take the shift from the larger dimension in the rectangular case. const int8_t *shift = cfg->shift; const int32_t rect_type = get_rect_tx_log_ratio(txfm_size_col, txfm_size_row); int8_t stage_range_col[MAX_TXFM_STAGE_NUM]; int8_t stage_range_row[MAX_TXFM_STAGE_NUM]; assert(cfg->stage_num_col <= MAX_TXFM_STAGE_NUM); assert(cfg->stage_num_row <= MAX_TXFM_STAGE_NUM); svt_av1_gen_fwd_stage_range(stage_range_col, stage_range_row, cfg, bit_depth); const int8_t cos_bit_col = cfg->cos_bit_col; const int8_t cos_bit_row = cfg->cos_bit_row; const TxfmFunc txfm_func_col = fwd_txfm_type_to_func_N4(cfg->txfm_type_col); const TxfmFunc txfm_func_row = fwd_txfm_type_to_func_N4(cfg->txfm_type_row); ASSERT(txfm_func_col != NULL); ASSERT(txfm_func_row != NULL); // use output buffer as temp buffer int32_t *temp_in = output; int32_t *temp_out = output + txfm_size_row; // Columns for (c = 0; c < txfm_size_col; ++c) { if (cfg->ud_flip == 0) for (r = 0; r < txfm_size_row; ++r) temp_in[r] = input[r * input_stride + c]; else { for (r = 0; r < txfm_size_row; ++r) // flip upside down temp_in[r] = input[(txfm_size_row - r - 1) * input_stride + c]; } svt_av1_round_shift_array_c( temp_in, txfm_size_row, -shift[0]); // NM svt_av1_round_shift_array_c txfm_func_col(temp_in, temp_out, cos_bit_col, stage_range_col); svt_av1_round_shift_array_c( temp_out, txfm_size_row / 4, -shift[1]); // NM svt_av1_round_shift_array_c if (cfg->lr_flip == 0) { for (r = 0; r < txfm_size_row; ++r) buf[r * txfm_size_col + c] = temp_out[r]; } else { for (r = 0; r < txfm_size_row; ++r) // flip from left to right buf[r * txfm_size_col + (txfm_size_col - c - 1)] = temp_out[r]; } } // Rows for (r = 0; r < txfm_size_row / 4; ++r) { txfm_func_row( buf + r * txfm_size_col, output + r * txfm_size_col, cos_bit_row, stage_range_row); svt_av1_round_shift_array_c(output + r * txfm_size_col, txfm_size_col / 4, -shift[2]); if (abs(rect_type) == 1) { // Multiply everything by Sqrt2 if the transform is rectangular and the // size difference is a factor of 2. for (c = 0; c < txfm_size_col / 4; ++c) { output[r * txfm_size_col + c] = round_shift( (int64_t)output[r * txfm_size_col + c] * new_sqrt2, new_sqrt2_bits); } } } for (int i = 0; i < (txfm_size_col * txfm_size_row); i++) if (i % txfm_size_col >= (txfm_size_col >> 2) || i / txfm_size_col >= (txfm_size_row >> 2)) output[i] = 0; } void av1_transform_two_d_64x64_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[64 * 64]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_64X64, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void av1_transform_two_d_32x32_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 32]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_32X32, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void av1_transform_two_d_16x16_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X16, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void av1_transform_two_d_8x8_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 8]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_8X8, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void av1_transform_two_d_4x4_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[4 * 4]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_4X4, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_64x32_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[64 * 32]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_64X32, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_32x64_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 64]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_32X64, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_64x16_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[64 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_64X16, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x64_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 64]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X64, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_32x16_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_32X16, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x32_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 32]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X32, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x8_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 8]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X8, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_8x16_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_8X16, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_32x8_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[32 * 8]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_32X8, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_8x32_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 32]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_8X32, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_16x4_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[16 * 4]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_16X4, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_4x16_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[4 * 16]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_4X16, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_8x4_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[8 * 4]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_8X4, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); } void svt_av1_fwd_txfm2d_4x8_N4_c(int16_t *input, int32_t *output, uint32_t input_stride, TxType transform_type, uint8_t bit_depth) { int32_t intermediate_transform_buffer[4 * 8]; Txfm2dFlipCfg cfg; av1_transform_config(transform_type, TX_4X8, &cfg); av1_tranform_two_d_core_N4_c( input, input_stride, output, &cfg, intermediate_transform_buffer, bit_depth); }
utf-8
1
BSD-3-Clause-Clear
2016-2021 Alliance for Open Media 2018-2021 Intel Corporation 2020 Tencent Corporation 2019 Netflix, Inc.
cataclysm-dda-0.F-3/src/event_subscriber.h
#ifndef CATA_SRC_EVENT_SUBSCRIBER_H #define CATA_SRC_EVENT_SUBSCRIBER_H namespace cata { class event; } // namespace cata class event_bus; class event_subscriber { public: event_subscriber() = default; event_subscriber( const event_subscriber & ) = delete; event_subscriber &operator=( const event_subscriber & ) = delete; virtual ~event_subscriber(); virtual void notify( const cata::event & ) = 0; private: friend class event_bus; void on_subscribe( event_bus * ); void on_unsubscribe( event_bus * ); event_bus *subscribed_to = nullptr; }; #endif // CATA_SRC_EVENT_SUBSCRIBER_H
utf-8
1
CC-BY-SA-3.0
Kevin Granade <kevin.granade@gmail.com> BevapDin <tho_ki@gmx.de> Angela Graves <rivet.the.zombie@gmail.com> Coolthulhu <Coolthulhu@gmail.com> Christian Buskirk <i2amroy@gmail.com> KA101 <cstrayer@rocketmail.com> Whales <fivedozewhales@gmail.com> and many other contributors
freeorion-0.4.10.2/server/ServerWrapper.cpp
#include "ServerWrapper.h" #include "ServerApp.h" #include "UniverseGenerator.h" #include "../universe/Condition.h" #include "../universe/ScriptingContext.h" #include "../universe/Species.h" #include "../universe/Special.h" #include "../universe/System.h" #include "../universe/Planet.h" #include "../universe/Building.h" #include "../universe/BuildingType.h" #include "../universe/Fleet.h" #include "../universe/FleetPlan.h" #include "../universe/Ship.h" #include "../universe/ShipDesign.h" #include "../universe/Field.h" #include "../universe/FieldType.h" #include "../universe/Tech.h" #include "../universe/Pathfinder.h" #include "../universe/Universe.h" #include "../universe/UnlockableItem.h" #include "../universe/Enums.h" #include "../universe/ValueRef.h" #include "../util/Directories.h" #include "../util/Logger.h" #include "../util/Random.h" #include "../util/i18n.h" #include "../util/OptionsDB.h" #include "../util/SitRepEntry.h" #include "../Empire/Empire.h" #include "../Empire/EmpireManager.h" #include "../python/SetWrapper.h" #include "../python/CommonWrappers.h" #include <vector> #include <map> #include <string> #include <utility> #include <boost/python.hpp> #include <boost/python/list.hpp> #include <boost/python/tuple.hpp> #include <boost/python/extract.hpp> #include <boost/python/stl_iterator.hpp> #include <boost/date_time/posix_time/time_formatters.hpp> #ifdef FREEORION_MACOSX #include <sys/param.h> #endif using boost::python::class_; using boost::python::def; using boost::python::init; using boost::python::no_init; using boost::noncopyable; using boost::python::return_value_policy; using boost::python::copy_const_reference; using boost::python::reference_existing_object; using boost::python::return_by_value; using boost::python::return_internal_reference; using boost::python::object; using boost::python::import; using boost::python::exec; using boost::python::dict; using boost::python::list; using boost::python::tuple; using boost::python::make_tuple; using boost::python::extract; using boost::python::len; using boost::python::long_; FO_COMMON_API extern const int INVALID_DESIGN_ID; // Helper stuff (classes, functions etc.) exposed to the // server side Python scripts namespace { // Functions that return various important constants int AllEmpires() { return ALL_EMPIRES; } int InvalidObjectID() { return INVALID_OBJECT_ID; } float LargeMeterValue() { return Meter::LARGE_VALUE; } double InvalidPosition() { return UniverseObject::INVALID_POSITION; } // Wrapper for GetResourceDir object GetResourceDirWrapper() { return object(PathToString(GetResourceDir())); } // Wrapper for getting empire objects list GetAllEmpires() { list empire_list; for (const auto& entry : Empires()) empire_list.append(entry.second->EmpireID()); return empire_list; } // Wrappers for generating sitrep messages void GenerateSitRep(int empire_id, const std::string& template_string, const dict& py_params, const std::string& icon) { int sitrep_turn = CurrentTurn() + 1; std::vector<std::pair<std::string, std::string>> params; if (py_params) { for (int i = 0; i < len(py_params); i++) { std::string k = extract<std::string>(py_params.keys()[i]); std::string v = extract<std::string>(py_params.values()[i]); params.push_back({k, v}); } } if (empire_id == ALL_EMPIRES) { for (const auto& entry : Empires()) { entry.second->AddSitRepEntry(CreateSitRep(template_string, sitrep_turn, icon, params)); } } else { Empire* empire = GetEmpire(empire_id); if (!empire) { ErrorLogger() << "GenerateSitRep: couldn't get empire with ID " << empire_id; return; } empire->AddSitRepEntry(CreateSitRep(template_string, sitrep_turn, icon, params)); } } void GenerateSitRep1(int empire_id, const std::string& template_string, const std::string& icon) { GenerateSitRep(empire_id, template_string, dict(), icon); } // Wrappers for Species / SpeciesManager class (member) functions object SpeciesPreferredFocus(const std::string& species_name) { const Species* species = GetSpecies(species_name); if (!species) { ErrorLogger() << "SpeciesPreferredFocus: couldn't get species " << species_name; return object(""); } return object(species->PreferredFocus()); } PlanetEnvironment SpeciesGetPlanetEnvironment(const std::string& species_name, PlanetType planet_type) { const Species* species = GetSpecies(species_name); if (!species) { ErrorLogger() << "SpeciesGetPlanetEnvironment: couldn't get species " << species_name; return INVALID_PLANET_ENVIRONMENT; } return species->GetPlanetEnvironment(planet_type); } void SpeciesAddHomeworld(const std::string& species_name, int homeworld_id) { Species* species = SpeciesManager::GetSpeciesManager().GetSpecies(species_name); if (!species) { ErrorLogger() << "SpeciesAddHomeworld: couldn't get species " << species_name; return; } species->AddHomeworld(homeworld_id); } void SpeciesRemoveHomeworld(const std::string& species_name, int homeworld_id) { Species* species = SpeciesManager::GetSpeciesManager().GetSpecies(species_name); if (!species) { ErrorLogger() << "SpeciesAddHomeworld: couldn't get species " << species_name; return; } species->RemoveHomeworld(homeworld_id); } bool SpeciesCanColonize(const std::string& species_name) { Species* species = SpeciesManager::GetSpeciesManager().GetSpecies(species_name); if (!species) { ErrorLogger() << "SpeciesCanColonize: couldn't get species " << species_name; return false; } return species->CanColonize(); } list GetAllSpecies() { list species_list; for (const auto& entry : GetSpeciesManager()) { species_list.append(object(entry.first)); } return species_list; } list GetPlayableSpecies() { list species_list; SpeciesManager& species_manager = GetSpeciesManager(); for (auto it = species_manager.playable_begin(); it != species_manager.playable_end(); ++it) { species_list.append(object(it->first)); } return species_list; } list GetNativeSpecies() { list species_list; SpeciesManager& species_manager = GetSpeciesManager(); for (auto it = species_manager.native_begin(); it != species_manager.native_end(); ++it) { species_list.append(object(it->first)); } return species_list; } //Checks the condition against many objects at once. //Checking many systems is more efficient because for example monster fleet plans //typically uses WithinStarLaneJumps to exclude placement near empires. list FilterIDsWithCondition(const Condition::Condition* cond, const list &obj_ids) { list permitted_ids; Condition::ObjectSet objs; boost::python::stl_input_iterator<int> end; for (boost::python::stl_input_iterator<int> id(obj_ids); id != end; ++id) { if (auto obj = Objects().get(*id)) objs.push_back(obj); else ErrorLogger() << "FilterIDsWithCondition:: Passed an invalid universe object id " << *id; } if (objs.empty()) { ErrorLogger() << "FilterIDsWithCondition:: Couldn't get any valid objects"; return permitted_ids; } Condition::ObjectSet permitted_objs; // get location condition and evaluate it with the specified universe object // if no location condition has been defined, all objects matches if (cond && cond->SourceInvariant()) cond->Eval(ScriptingContext(), permitted_objs, objs); else permitted_objs = std::move(objs); for (auto &obj : permitted_objs) { permitted_ids.append(obj->ID()); } return permitted_ids; } // Wrappers for Specials / SpecialManager functions double SpecialSpawnRate(const std::string special_name) { const Special* special = GetSpecial(special_name); if (!special) { ErrorLogger() << "SpecialSpawnRate: couldn't get special " << special_name; return 0.0; } return special->SpawnRate(); } int SpecialSpawnLimit(const std::string special_name) { const Special* special = GetSpecial(special_name); if (!special) { ErrorLogger() << "SpecialSpawnLimit: couldn't get special " << special_name; return 0; } return special->SpawnLimit(); } list SpecialLocations(const std::string special_name, const list& object_ids) { // get special and check if it exists const Special* special = GetSpecial(special_name); if (!special) { ErrorLogger() << "SpecialLocation: couldn't get special " << special_name; return list(); } return FilterIDsWithCondition(special->Location(), object_ids); } bool SpecialHasLocation(const std::string special_name) { // get special and check if it exists const Special* special = GetSpecial(special_name); if (!special) { ErrorLogger() << "SpecialHasLocation: couldn't get special " << special_name; return false; } return special->Location(); } list GetAllSpecials() { list py_specials; for (const auto& special_name : SpecialNames()) { py_specials.append(object(special_name)); } return py_specials; } // Wrappers for Empire class member functions void EmpireSetName(int empire_id, const std::string& name) { Empire* empire = GetEmpire(empire_id); if (!empire) { ErrorLogger() << "EmpireSetName: couldn't get empire with ID " << empire_id; return; } empire->SetName(name); } bool EmpireSetHomeworld(int empire_id, int planet_id, const std::string& species_name) { Empire* empire = GetEmpire(empire_id); if (!empire) { ErrorLogger() << "EmpireSetHomeworld: couldn't get empire with ID " << empire_id; return false; } return SetEmpireHomeworld(empire, planet_id, species_name); } void EmpireUnlockItem(int empire_id, UnlockableItemType item_type, const std::string& item_name) { Empire* empire = GetEmpire(empire_id); if (!empire) { ErrorLogger() << "EmpireUnlockItem: couldn't get empire with ID " << empire_id; return; } UnlockableItem item = UnlockableItem(item_type, item_name); empire->UnlockItem(item); } void EmpireAddShipDesign(int empire_id, const std::string& design_name) { Universe& universe = GetUniverse(); Empire* empire = GetEmpire(empire_id); if (!empire) { ErrorLogger() << "EmpireAddShipDesign: couldn't get empire with ID " << empire_id; return; } // check if a ship design with ID ship_design_id has been added to the universe const ShipDesign* ship_design = universe.GetGenericShipDesign(design_name); if (!ship_design) { ErrorLogger() << "EmpireAddShipDesign: no ship design with name " << design_name << " has been added to the universe"; return; } universe.SetEmpireKnowledgeOfShipDesign(ship_design->ID(), empire_id); empire->AddShipDesign(ship_design->ID()); } // Wrapper for preunlocked items list LoadUnlockableItemList() { list py_items; auto& items = GetUniverse().InitiallyUnlockedItems(); for (const auto& item : items) { py_items.append(object(item)); } return py_items; } // Wrapper for starting buildings list LoadStartingBuildings() { list py_items; auto& buildings = GetUniverse().InitiallyUnlockedBuildings(); for (auto building : buildings) { if (GetBuildingType(building.name)) py_items.append(object(building)); else ErrorLogger() << "The item " << building.name << " in the starting building list is not a building."; } return py_items; } // Wrappers for ship designs and premade ship designs bool ShipDesignCreate(const std::string& name, const std::string& description, const std::string& hull, const list& py_parts, const std::string& icon, const std::string& model, bool monster) { Universe& universe = GetUniverse(); // Check for empty name if (name.empty()) { ErrorLogger() << "CreateShipDesign: tried to create ship design without a name"; return false; } // check if a ship design with the same name has already been added to the universe if (universe.GetGenericShipDesign(name)) { ErrorLogger() << "CreateShipDesign: a ship design with the name " << name << " has already been added to the universe"; return false; } // copy parts list from Python list to C++ vector std::vector<std::string> parts; for (int i = 0; i < len(py_parts); i++) { parts.push_back(extract<std::string>(py_parts[i])); } // Create the design and add it to the universe ShipDesign* design; try { design = new ShipDesign(std::invalid_argument(""), name, description, BEFORE_FIRST_TURN, ALL_EMPIRES, hull, parts, icon, model, true, monster); } catch (const std::invalid_argument&) { ErrorLogger() << "CreateShipDesign: invalid ship design"; return false; } if (!universe.InsertShipDesign(design)) { ErrorLogger() << "CreateShipDesign: couldn't insert ship design into universe"; delete design; return false; } return true; } list ShipDesignGetPremadeList() { list py_ship_designs; for (const auto& design : GetPredefinedShipDesignManager().GetOrderedShipDesigns()) { py_ship_designs.append(object(design->Name(false))); } return list(py_ship_designs); } list ShipDesignGetMonsterList() { list py_monster_designs; const auto& manager = GetPredefinedShipDesignManager(); for (const auto& monster : manager.GetOrderedMonsterDesigns()) { py_monster_designs.append(object(monster->Name(false))); } return list(py_monster_designs); } // Wrappers for starting fleet plans class FleetPlanWrapper { public: // name ctors FleetPlanWrapper(FleetPlan* fleet_plan) : m_fleet_plan(std::make_shared<FleetPlan>(*fleet_plan)) {} FleetPlanWrapper(const std::string& fleet_name, const list& py_designs) { std::vector<std::string> designs; for (int i = 0; i < len(py_designs); i++) { designs.push_back(extract<std::string>(py_designs[i])); } m_fleet_plan = std::make_shared<FleetPlan>(fleet_name, designs, false); } // name accessors object Name() { return object(m_fleet_plan->Name()); } list ShipDesigns() { list py_designs; for (const auto& design_name : m_fleet_plan->ShipDesigns()) { py_designs.append(object(design_name)); } return list(py_designs); } const FleetPlan& GetFleetPlan() { return *m_fleet_plan; } private: // Use shared_ptr insead of unique_ptr because boost::python requires a deleter std::shared_ptr<FleetPlan> m_fleet_plan; }; list LoadFleetPlanList() { list py_fleet_plans; auto&& fleet_plans = GetUniverse().InitiallyUnlockedFleetPlans(); for (FleetPlan* fleet_plan : fleet_plans) { py_fleet_plans.append(FleetPlanWrapper(fleet_plan)); } return py_fleet_plans; } // Wrappers for starting monster fleet plans class MonsterFleetPlanWrapper { public: // name ctors MonsterFleetPlanWrapper(MonsterFleetPlan* monster_fleet_plan) : m_monster_fleet_plan(std::make_shared<MonsterFleetPlan>(*monster_fleet_plan)) {} MonsterFleetPlanWrapper(const std::string& fleet_name, const list& py_designs, double spawn_rate, int spawn_limit) { std::vector<std::string> designs; for (int i = 0; i < len(py_designs); i++) { designs.push_back(extract<std::string>(py_designs[i])); } m_monster_fleet_plan = std::make_shared<MonsterFleetPlan>(fleet_name, designs, spawn_rate, spawn_limit, nullptr, false); } // name accessors object Name() { return object(m_monster_fleet_plan->Name()); } list ShipDesigns() { list py_designs; for (const auto& design_name : m_monster_fleet_plan->ShipDesigns()) { py_designs.append(object(design_name)); } return list(py_designs); } double SpawnRate() { return m_monster_fleet_plan->SpawnRate(); } int SpawnLimit() { return m_monster_fleet_plan->SpawnLimit(); } list Locations(list systems) { return FilterIDsWithCondition(m_monster_fleet_plan->Location(), systems); } const MonsterFleetPlan& GetMonsterFleetPlan() { return *m_monster_fleet_plan; } private: // Use shared_ptr insead of unique_ptr because boost::python requires a deleter std::shared_ptr<MonsterFleetPlan> m_monster_fleet_plan; }; list LoadMonsterFleetPlanList() { list py_monster_fleet_plans; auto&& monster_fleet_plans = GetUniverse().MonsterFleetPlans(); for (auto* fleet_plan : monster_fleet_plans) { py_monster_fleet_plans.append(MonsterFleetPlanWrapper(fleet_plan)); } return py_monster_fleet_plans; } // Wrappers for the various universe object classes member funtions // This should provide a more safe and consistent set of server side // functions to scripters. All wrapper functions work with object ids, so // handling with object references and passing them between the languages is // avoided. // // Wrappers for common UniverseObject class member funtions object GetName(int object_id) { auto obj = Objects().get(object_id); if (!obj) { ErrorLogger() << "GetName: Couldn't get object with ID " << object_id; return object(""); } return object(obj->Name()); } void SetName(int object_id, const std::string& name) { auto obj = Objects().get(object_id); if (!obj) { ErrorLogger() << "RenameUniverseObject: Couldn't get object with ID " << object_id; return; } obj->Rename(name); } double GetX(int object_id) { auto obj = Objects().get(object_id); if (!obj) { ErrorLogger() << "GetX: Couldn't get object with ID " << object_id; return UniverseObject::INVALID_POSITION; } return obj->X(); } double GetY(int object_id) { auto obj = Objects().get(object_id); if (!obj) { ErrorLogger() << "GetY: Couldn't get object with ID " << object_id; return UniverseObject::INVALID_POSITION; } return obj->Y(); } tuple GetPos(int object_id) { auto obj = Objects().get(object_id); if (!obj) { ErrorLogger() << "GetPos: Couldn't get object with ID " << object_id; return make_tuple(UniverseObject::INVALID_POSITION, UniverseObject::INVALID_POSITION); } return make_tuple(obj->X(), obj->Y()); } int GetOwner(int object_id) { auto obj = Objects().get(object_id); if (!obj) { ErrorLogger() << "GetOwner: Couldn't get object with ID " << object_id; return ALL_EMPIRES; } return obj->Owner(); } void AddSpecial(int object_id, const std::string special_name) { // get the universe object and check if it exists auto obj = Objects().get(object_id); if (!obj) { ErrorLogger() << "AddSpecial: Couldn't get object with ID " << object_id; return; } // check if the special exists const Special* special = GetSpecial(special_name); if (!special) { ErrorLogger() << "AddSpecial: couldn't get special " << special_name; return; } float capacity = special->InitialCapacity(object_id); obj->AddSpecial(special_name, capacity); } void RemoveSpecial(int object_id, const std::string special_name) { // get the universe object and check if it exists auto obj = Objects().get(object_id); if (!obj) { ErrorLogger() << "RemoveSpecial: Couldn't get object with ID " << object_id; return; } // check if the special exists if (!GetSpecial(special_name)) { ErrorLogger() << "RemoveSpecial: couldn't get special " << special_name; return; } obj->RemoveSpecial(special_name); } // Wrappers for Universe class double GetUniverseWidth() { return GetUniverse().UniverseWidth(); } void SetUniverseWidth(double width) { GetUniverse().SetUniverseWidth(width); } double LinearDistance(int system1_id, int system2_id) { return GetPathfinder()->LinearDistance(system1_id, system2_id); } int JumpDistanceBetweenSystems(int system1_id, int system2_id) { return GetPathfinder()->JumpDistanceBetweenSystems(system1_id, system2_id); } list GetAllObjects() { list py_all_objects; for (const auto& object : Objects().all()) { py_all_objects.append(object->ID()); } return py_all_objects; } list GetSystems() { list py_systems; for (const auto& system : Objects().all<System>()) { py_systems.append(system->ID()); } return py_systems; } int CreateSystem(StarType star_type, const std::string& star_name, double x, double y) { // Check if star type is set to valid value if ((star_type == INVALID_STAR_TYPE) || (star_type == NUM_STAR_TYPES)) { ErrorLogger() << "CreateSystem : Can't create a system with a star of type " << star_type; return INVALID_OBJECT_ID; } // Create system and insert it into the object map auto system = GetUniverse().InsertNew<System>(star_type, star_name, x, y); if (!system) { ErrorLogger() << "CreateSystem : Attempt to insert system into the object map failed"; return INVALID_OBJECT_ID; } return system->SystemID(); } int CreatePlanet(PlanetSize size, PlanetType planet_type, int system_id, int orbit, const std::string& name) { auto system = Objects().get<System>(system_id); // Perform some validity checks // Check if system with id system_id exists if (!system) { ErrorLogger() << "CreatePlanet : Couldn't get system with ID " << system_id; return INVALID_OBJECT_ID; } // Check if orbit number is within allowed range if ((orbit < 0) || (orbit >= system->Orbits())) { ErrorLogger() << "CreatePlanet : There is no orbit " << orbit << " in system " << system_id; return INVALID_OBJECT_ID; } // Check if desired orbit is still empty if (system->OrbitOccupied(orbit)) { ErrorLogger() << "CreatePlanet : Orbit " << orbit << " of system " << system_id << " already occupied"; return INVALID_OBJECT_ID; } // Check if planet size is set to valid value if ((size < SZ_TINY) || (size > SZ_GASGIANT)) { ErrorLogger() << "CreatePlanet : Can't create a planet of size " << size; return INVALID_OBJECT_ID; } // Check if planet type is set to valid value if ((planet_type < PT_SWAMP) || (planet_type > PT_GASGIANT)) { ErrorLogger() << "CreatePlanet : Can't create a planet of type " << planet_type; return INVALID_OBJECT_ID; } // Check if planet type and size match // if type is gas giant, size must be too, same goes for asteroids if (((planet_type == PT_GASGIANT) && (size != SZ_GASGIANT)) || ((planet_type == PT_ASTEROIDS) && (size != SZ_ASTEROIDS))) { ErrorLogger() << "CreatePlanet : Planet of type " << planet_type << " can't have size " << size; return INVALID_OBJECT_ID; } // Create planet and insert it into the object map auto planet = GetUniverse().InsertNew<Planet>(planet_type, size); if (!planet) { ErrorLogger() << "CreateSystem : Attempt to insert planet into the object map failed"; return INVALID_OBJECT_ID; } // Add planet to system map system->Insert(std::shared_ptr<UniverseObject>(planet), orbit); // If a name has been specified, set planet name if (!(name.empty())) planet->Rename(name); return planet->ID(); } int CreateBuilding(const std::string& building_type, int planet_id, int empire_id) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "CreateBuilding: couldn't get planet with ID " << planet_id; return INVALID_OBJECT_ID; } auto system = Objects().get<System>(planet->SystemID()); if (!system) { ErrorLogger() << "CreateBuilding: couldn't get system for planet"; return INVALID_OBJECT_ID; } const Empire* empire = GetEmpire(empire_id); if (!empire) { ErrorLogger() << "CreateBuilding: couldn't get empire with ID " << empire_id; return INVALID_OBJECT_ID; } auto building = GetUniverse().InsertNew<Building>(empire_id, building_type, empire_id); if (!building) { ErrorLogger() << "CreateBuilding: couldn't create building"; return INVALID_OBJECT_ID; } system->Insert(building); planet->AddBuilding(building->ID()); building->SetPlanetID(planet_id); return building->ID(); } int CreateFleet(const std::string& name, int system_id, int empire_id, bool aggressive = false) { // Get system and check if it exists auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "CreateFleet: couldn't get system with ID " << system_id; return INVALID_OBJECT_ID; } // Create new fleet at the position of the specified system auto fleet = GetUniverse().InsertNew<Fleet>(name, system->X(), system->Y(), empire_id); if (!fleet) { ErrorLogger() << "CreateFleet: couldn't create new fleet"; return INVALID_OBJECT_ID; } // Insert fleet into specified system system->Insert(fleet); // check if we got a fleet name... if (name.empty()) { // ...no name has been specified, so we have to generate one using the new fleet id fleet->Rename(UserString("OBJ_FLEET") + " " + std::to_string(fleet->ID())); } fleet->SetAggressive(aggressive); // return fleet ID return fleet->ID(); } int CreateShip(const std::string& name, const std::string& design_name, const std::string& species, int fleet_id) { Universe& universe = GetUniverse(); // check if we got a species name, if yes, check if species exists if (!species.empty() && !GetSpecies(species)) { ErrorLogger() << "CreateShip: invalid species specified"; return INVALID_OBJECT_ID; } // get ship design and check if it exists const ShipDesign* ship_design = universe.GetGenericShipDesign(design_name); if (!ship_design) { ErrorLogger() << "CreateShip: couldn't get ship design " << design_name; return INVALID_OBJECT_ID; } // get fleet and check if it exists auto fleet = Objects().get<Fleet>(fleet_id); if (!fleet) { ErrorLogger() << "CreateShip: couldn't get fleet with ID " << fleet_id; return INVALID_OBJECT_ID; } auto system = Objects().get<System>(fleet->SystemID()); if (!system) { ErrorLogger() << "CreateShip: couldn't get system for fleet"; return INVALID_OBJECT_ID; } // get owner empire of specified fleet int empire_id = fleet->Owner(); // if we got the id of an actual empire, get the empire object and check if it exists Empire* empire = nullptr; if (empire_id != ALL_EMPIRES) { empire = GetEmpire(empire_id); if (!empire) { ErrorLogger() << "CreateShip: couldn't get empire with ID " << empire_id; return INVALID_OBJECT_ID; } } // create new ship auto ship = universe.InsertNew<Ship>(empire_id, ship_design->ID(), species, empire_id); if (!ship) { ErrorLogger() << "CreateShip: couldn't create new ship"; return INVALID_OBJECT_ID; } system->Insert(ship); // set ship name // check if we got a ship name... if (name.empty()) { // ...no name has been specified, so we have to generate one // check if the owner empire we got earlier is actually an empire... if (empire) { // ...yes, so construct a name using the empires NewShipName member function ship->Rename(empire->NewShipName()); } else { // ...no, so construct a name using the new ships id ship->Rename(UserString("OBJ_SHIP") + " " + std::to_string(ship->ID())); } } else { // ...yes, name has been specified, so use it ship->Rename(name); } // add ship to fleet, this also moves the ship to the // fleets location and inserts it into the system fleet->AddShips({ship->ID()}); ship->SetFleetID(fleet->ID()); // set the meters of the ship to max values ship->ResetTargetMaxUnpairedMeters(); ship->ResetPairedActiveMeters(); ship->SetShipMetersToMax(); ship->BackPropagateMeters(); //return the new ships id return ship->ID(); } int CreateMonsterFleet(int system_id) { return CreateFleet(UserString("MONSTERS"), system_id, ALL_EMPIRES, true); } int CreateMonster(const std::string& design_name, int fleet_id) { return CreateShip(NewMonsterName(), design_name, "", fleet_id); } std::shared_ptr<Field> CreateFieldImpl(const std::string& field_type_name, double x, double y, double size) { // check if a field type with the specified field type name exists and get the field type const FieldType* field_type = GetFieldType(field_type_name); if (!field_type) { ErrorLogger() << "CreateFieldImpl: couldn't get field type with name: " << field_type_name; return nullptr; } // check if the specified size is within sane limits, and reset its value if not if (size < 1.0) { ErrorLogger() << "CreateFieldImpl given very small / negative size: " << size << ", resetting to 1.0"; size = 1.0; } if (size > 10000.0) { ErrorLogger() << "CreateFieldImpl given very large size: " << size << ", so resetting to 10000.0"; size = 10000.0; } // create the new field auto field = GetUniverse().InsertNew<Field>(field_type->Name(), x, y, size); if (!field) { ErrorLogger() << "CreateFieldImpl: couldn't create field"; return nullptr; } // get the localized version of the field type name and set that as the fields name field->Rename(UserString(field_type->Name())); return field; } int CreateField(const std::string& field_type_name, double x, double y, double size) { auto field = CreateFieldImpl(field_type_name, x, y, size); if (field) return field->ID(); else return INVALID_OBJECT_ID; } int CreateFieldInSystem(const std::string& field_type_name, double size, int system_id) { // check if system exists and get system auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "CreateFieldInSystem: couldn't get system with ID" << system_id; return INVALID_OBJECT_ID; } // create the field with the coordinates of the system auto field = CreateFieldImpl(field_type_name, system->X(), system->Y(), size); if (!field) return INVALID_OBJECT_ID; system->Insert(field); // insert the field into the system return field->ID(); } // Return a list of system ids of universe objects with @p obj_ids. list ObjectsGetSystems(const list& obj_ids) { list py_systems; boost::python::stl_input_iterator<int> end; for (boost::python::stl_input_iterator<int> id(obj_ids); id != end; ++id) { if (auto obj = Objects().get(*id)) { py_systems.append(obj->SystemID()); } else { ErrorLogger() << "Passed an invalid universe object id " << *id; py_systems.append(INVALID_OBJECT_ID); } } return py_systems; } // Return all systems within \p jumps of \p sys_ids list SystemsWithinJumps(size_t jumps, const list& sys_ids) { list py_systems; boost::python::stl_input_iterator<int> end; std::vector<int> systems; for (boost::python::stl_input_iterator<int> id(sys_ids); id != end; ++id) { systems.push_back(*id); } auto systems_in_vicinity = GetPathfinder()->WithinJumps(jumps, systems); for (auto system_id : systems_in_vicinity) { py_systems.append(system_id); } return py_systems; } // Wrappers for System class member functions StarType SystemGetStarType(int system_id) { auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "SystemGetStarType: couldn't get system with ID " << system_id; return INVALID_STAR_TYPE; } return system->GetStarType(); } void SystemSetStarType(int system_id, StarType star_type) { // Check if star type is set to valid value if ((star_type == INVALID_STAR_TYPE) || (star_type == NUM_STAR_TYPES)) { ErrorLogger() << "SystemSetStarType : Can't create a system with a star of type " << star_type; return; } auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "SystemSetStarType : Couldn't get system with ID " << system_id; return; } system->SetStarType(star_type); } int SystemGetNumOrbits(int system_id) { auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "SystemGetNumOrbits : Couldn't get system with ID " << system_id; return 0; } return system->Orbits(); } list SystemFreeOrbits(int system_id) { list py_orbits; auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "SystemFreeOrbits : Couldn't get system with ID " << system_id; return py_orbits; } for (int orbit_idx : system->FreeOrbits()) { py_orbits.append(orbit_idx); } return py_orbits; } bool SystemOrbitOccupied(int system_id, int orbit) { auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "SystemOrbitOccupied : Couldn't get system with ID " << system_id; return 0; } return system->OrbitOccupied(orbit); } int SystemOrbitOfPlanet(int system_id, int planet_id) { auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "SystemOrbitOfPlanet : Couldn't get system with ID " << system_id; return 0; } return system->OrbitOfPlanet(planet_id); } list SystemGetPlanets(int system_id) { list py_planets; auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "SystemGetPlanets : Couldn't get system with ID " << system_id; return py_planets; } for (int planet_id : system->PlanetIDs()) { py_planets.append(planet_id); } return py_planets; } list SystemGetFleets(int system_id) { list py_fleets; auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "SystemGetFleets : Couldn't get system with ID " << system_id; return py_fleets; } for (int fleet_id : system->FleetIDs()) { py_fleets.append(fleet_id); } return py_fleets; } list SystemGetStarlanes(int system_id) { list py_starlanes; // get source system auto system = Objects().get<System>(system_id); if (!system) { ErrorLogger() << "SystemGetStarlanes : Couldn't get system with ID " << system_id; return py_starlanes; } // get list of systems the source system has starlanes to // we actually get a map of ids and a bool indicating if the entry is a starlane (false) or wormhole (true) // iterate over the map we got, only copy starlanes to the python list object we are going to return for (const auto& lane : system->StarlanesWormholes()) { // if the bool value is false, we have a starlane // in this case copy the destination system id to our starlane list if (!(lane.second)) { py_starlanes.append(lane.first); } } return py_starlanes; } void SystemAddStarlane(int from_sys_id, int to_sys_id) { // get source and destination system, check that both exist auto from_sys = Objects().get<System>(from_sys_id); if (!from_sys) { ErrorLogger() << "SystemAddStarlane : Couldn't find system with ID " << from_sys_id; return; } auto to_sys = Objects().get<System>(to_sys_id); if (!to_sys) { ErrorLogger() << "SystemAddStarlane : Couldn't find system with ID " << to_sys_id; return; } // add the starlane on both ends from_sys->AddStarlane(to_sys_id); to_sys->AddStarlane(from_sys_id); } void SystemRemoveStarlane(int from_sys_id, int to_sys_id) { // get source and destination system, check that both exist auto from_sys = Objects().get<System>(from_sys_id); if (!from_sys) { ErrorLogger() << "SystemRemoveStarlane : Couldn't find system with ID " << from_sys_id; return; } auto to_sys = Objects().get<System>(to_sys_id); if (!to_sys) { ErrorLogger() << "SystemRemoveStarlane : Couldn't find system with ID " << to_sys_id; return; } // remove the starlane from both ends from_sys->RemoveStarlane(to_sys_id); to_sys->RemoveStarlane(from_sys_id); } // Wrapper for Planet class member functions PlanetType PlanetGetType(int planet_id) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetGetType: Couldn't get planet with ID " << planet_id; return INVALID_PLANET_TYPE; } return planet->Type(); } void PlanetSetType(int planet_id, PlanetType planet_type) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetSetType: Couldn't get planet with ID " << planet_id; return; } planet->SetType(planet_type); if (planet_type == PT_ASTEROIDS) planet->SetSize(SZ_ASTEROIDS); else if (planet_type == PT_GASGIANT) planet->SetSize(SZ_GASGIANT); else if (planet->Size() == SZ_ASTEROIDS) planet->SetSize(SZ_TINY); else if (planet->Size() == SZ_GASGIANT) planet->SetSize(SZ_HUGE); } PlanetSize PlanetGetSize(int planet_id) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetGetSize: Couldn't get planet with ID " << planet_id; return INVALID_PLANET_SIZE; } return planet->Size(); } void PlanetSetSize(int planet_id, PlanetSize planet_size) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetSetSize: Couldn't get planet with ID " << planet_id; return; } planet->SetSize(planet_size); if (planet_size == SZ_ASTEROIDS) planet->SetType(PT_ASTEROIDS); else if (planet_size == SZ_GASGIANT) planet->SetType(PT_GASGIANT); else if ((planet->Type() == PT_ASTEROIDS) || (planet->Type() == PT_GASGIANT)) planet->SetType(PT_BARREN); } object PlanetGetSpecies(int planet_id) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetGetSpecies: Couldn't get planet with ID " << planet_id; return object(""); } return object(planet->SpeciesName()); } void PlanetSetSpecies(int planet_id, const std::string& species_name) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetSetSpecies: Couldn't get planet with ID " << planet_id; return; } planet->SetSpecies(species_name); } object PlanetGetFocus(int planet_id) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetGetFocus: Couldn't get planet with ID " << planet_id; return object(""); } return object(planet->Focus()); } void PlanetSetFocus(int planet_id, const std::string& focus) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetSetSpecies: Couldn't get planet with ID " << planet_id; return; } planet->SetFocus(focus); } list PlanetAvailableFoci(int planet_id) { list py_foci; auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetAvailableFoci: Couldn't get planet with ID " << planet_id; return py_foci; } for (const std::string& focus : planet->AvailableFoci()) { py_foci.append(object(focus)); } return py_foci; } bool PlanetMakeOutpost(int planet_id, int empire_id) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetMakeOutpost: couldn't get planet with ID:" << planet_id; return false; } if (!GetEmpire(empire_id)) { ErrorLogger() << "PlanetMakeOutpost: couldn't get empire with ID " << empire_id; return false; } return planet->Colonize(empire_id, "", 0.0); } bool PlanetMakeColony(int planet_id, int empire_id, const std::string& species, double population) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetMakeColony: couldn't get planet with ID:" << planet_id; return false; } if (!GetEmpire(empire_id)) { ErrorLogger() << "PlanetMakeColony: couldn't get empire with ID " << empire_id; return false; } if (!GetSpecies(species)) { ErrorLogger() << "PlanetMakeColony: couldn't get species with name: " << species; return false; } if (population < 0.0) population = 0.0; return planet->Colonize(empire_id, species, population); } object PlanetCardinalSuffix(int planet_id) { auto planet = Objects().get<Planet>(planet_id); if (!planet) { ErrorLogger() << "PlanetCardinalSuffix: couldn't get planet with ID:" << planet_id; return object(UserString("ERROR")); } return object(planet->CardinalSuffix()); } } namespace FreeOrionPython { void WrapServer() { class_<PlayerSetupData>("PlayerSetupData") .def_readwrite("player_name", &PlayerSetupData::m_player_name) .def_readwrite("empire_name", &PlayerSetupData::m_empire_name) .def_readonly("empire_color", &PlayerSetupData::m_empire_color) .def_readwrite("starting_species", &PlayerSetupData::m_starting_species_name) .def_readwrite("starting_team", &PlayerSetupData::m_starting_team); class_<FleetPlanWrapper>("FleetPlan", init<const std::string&, const list&>()) .def("name", &FleetPlanWrapper::Name) .def("ship_designs", &FleetPlanWrapper::ShipDesigns); class_<MonsterFleetPlanWrapper>("MonsterFleetPlan", init<const std::string&, const list&, double, int>()) .def("name", &MonsterFleetPlanWrapper::Name) .def("ship_designs", &MonsterFleetPlanWrapper::ShipDesigns) .def("spawn_rate", &MonsterFleetPlanWrapper::SpawnRate) .def("spawn_limit", &MonsterFleetPlanWrapper::SpawnLimit) .def("locations", &MonsterFleetPlanWrapper::Locations); def("get_universe", GetUniverse, return_value_policy<reference_existing_object>()); def("get_all_empires", GetAllEmpires); def("get_empire", GetEmpire, return_value_policy<reference_existing_object>()); def("user_string", make_function(&UserString, return_value_policy<copy_const_reference>())); def("roman_number", RomanNumber); def("get_resource_dir", GetResourceDirWrapper); def("all_empires", AllEmpires); def("invalid_object", InvalidObjectID); def("large_meter_value", LargeMeterValue); def("invalid_position", InvalidPosition); def("get_galaxy_setup_data", GetGalaxySetupData, return_value_policy<reference_existing_object>()); def("current_turn", CurrentTurn); def("generate_sitrep", GenerateSitRep); def("generate_sitrep", GenerateSitRep1); def("generate_starlanes", GenerateStarlanes); def("species_preferred_focus", SpeciesPreferredFocus); def("species_get_planet_environment", SpeciesGetPlanetEnvironment); def("species_add_homeworld", SpeciesAddHomeworld); def("species_remove_homeworld", SpeciesRemoveHomeworld); def("species_can_colonize", SpeciesCanColonize); def("get_all_species", GetAllSpecies); def("get_playable_species", GetPlayableSpecies); def("get_native_species", GetNativeSpecies); def("special_spawn_rate", SpecialSpawnRate); def("special_spawn_limit", SpecialSpawnLimit); def("special_locations", SpecialLocations); def("special_has_location", SpecialHasLocation); def("get_all_specials", GetAllSpecials); def("empire_set_name", EmpireSetName); def("empire_set_homeworld", EmpireSetHomeworld); def("empire_unlock_item", EmpireUnlockItem); def("empire_add_ship_design", EmpireAddShipDesign); def("design_create", ShipDesignCreate); def("design_get_premade_list", ShipDesignGetPremadeList); def("design_get_monster_list", ShipDesignGetMonsterList); def("load_unlockable_item_list", LoadUnlockableItemList); def("load_starting_buildings", LoadStartingBuildings); def("load_fleet_plan_list", LoadFleetPlanList); def("load_monster_fleet_plan_list", LoadMonsterFleetPlanList); def("get_name", GetName); def("set_name", SetName); def("get_x", GetX); def("get_y", GetY); def("get_pos", GetPos); def("get_owner", GetOwner); def("add_special", AddSpecial); def("remove_special", RemoveSpecial); def("get_universe_width", GetUniverseWidth); def("set_universe_width", SetUniverseWidth); def("linear_distance", LinearDistance); def("jump_distance", JumpDistanceBetweenSystems); def("get_all_objects", GetAllObjects); def("get_systems", GetSystems); def("create_system", CreateSystem); def("create_planet", CreatePlanet); def("create_building", CreateBuilding); def("create_fleet", CreateFleet); def("create_ship", CreateShip); def("create_monster_fleet", CreateMonsterFleet); def("create_monster", CreateMonster); def("create_field", CreateField); def("create_field_in_system", CreateFieldInSystem); def("objs_get_systems", ObjectsGetSystems); def("systems_within_jumps_unordered", SystemsWithinJumps, "Return all systems within ''jumps'' of the systems with ids ''sys_ids''"); def("sys_get_star_type", SystemGetStarType); def("sys_set_star_type", SystemSetStarType); def("sys_get_num_orbits", SystemGetNumOrbits); def("sys_free_orbits", SystemFreeOrbits); def("sys_orbit_occupied", SystemOrbitOccupied); def("sys_orbit_of_planet", SystemOrbitOfPlanet); def("sys_get_planets", SystemGetPlanets); def("sys_get_fleets", SystemGetFleets); def("sys_get_starlanes", SystemGetStarlanes); def("sys_add_starlane", SystemAddStarlane); def("sys_remove_starlane", SystemRemoveStarlane); def("planet_get_type", PlanetGetType); def("planet_set_type", PlanetSetType); def("planet_get_size", PlanetGetSize); def("planet_set_size", PlanetSetSize); def("planet_get_species", PlanetGetSpecies); def("planet_set_species", PlanetSetSpecies); def("planet_get_focus", PlanetGetFocus); def("planet_set_focus", PlanetSetFocus); def("planet_available_foci", PlanetAvailableFoci); def("planet_make_outpost", PlanetMakeOutpost); def("planet_make_colony", PlanetMakeColony); def("planet_cardinal_suffix", PlanetCardinalSuffix); } }
utf-8
1
GPL-2
The FreeOrion project
obexpushd-0.11.2/src/x-obex/obex-capability.h
#include <stdio.h> #include <inttypes.h> #if __STDC_VERSION__ >= 199901L #include <stdbool.h> #else #define bool unsigned int #define true 1 #define false 0 #endif struct obex_caps_version { char* version; char* date; }; struct obex_caps_limit { unsigned long size_max; unsigned long namelen_max; }; struct obex_caps_ext { char* name; char** value; }; struct obex_caps_obj { /* type or at least one ext must be defined */ char* type; char** name_ext; unsigned long* size; struct obex_caps_ext** ext; /* NULL terminated list */ }; struct obex_caps_access { char* protocol; char* endpoint; char* target; struct obex_caps_ext** ext; /* NULL terminated list */ }; struct obex_caps_mem { char* type; char* location; unsigned long* free; unsigned long* used; struct obex_caps_limit* file; struct obex_caps_limit* folder; unsigned int flags; #define OBEX_CAPS_MEM_SHARED (1 << 0) #define OBEX_CAPS_MEM_CASESENSE (1 << 1) struct obex_caps_ext** ext; /* NULL terminated list */ }; struct obex_caps_general { char* vendor; char* model; char* serial; char* oem; struct obex_caps_version* sw; struct obex_caps_version* fw; struct obex_caps_version* hw; char lang[2+1]; struct obex_caps_mem** mem; struct obex_caps_ext** ext; }; struct obex_caps_inbox { struct obex_caps_obj** obj; struct obex_caps_ext** ext; }; struct obex_caps_uuid { enum { OBEX_CAPS_UUID_ASCII, OBEX_CAPS_UUID_BINARY, } type; uint8_t data[16]; }; #define OBEX_UUID_FBS \ { 0xF9, 0xEC, 0x7B, 0xC4, 0x95, 0x3C, 0x11, 0xD2, \ 0x98, 0x4E, 0x52, 0x54, 0x00, 0xDC, 0x9E, 0x09 } #define OBEX_UUID_IRMC \ { 'I', 'R', 'M', 'C', '-', 'S', 'Y', 'N', 'C' } struct obex_caps_service { /* name or uuid must be defined */ char* name; struct obex_caps_uuid* uuid; char* version; struct obex_caps_obj** obj; struct obex_caps_access** access; struct obex_caps_ext** ext; }; struct obex_capability { char* charset; struct obex_caps_general general; struct obex_caps_inbox* inbox; struct obex_caps_service* service; }; int obex_capability (FILE* fd, struct obex_capability* caps);
utf-8
1
unknown
unknown
librest-0.8.1/rest/rest-xml-node.c
/* * librest - RESTful web services access * Copyright (c) 2008, 2009, 2011, Intel Corporation. * * Authors: Rob Bradford <rob@linux.intel.com> * Ross Burton <ross@linux.intel.com> * Tomas Frydrych <tf@linux.intel.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "rest-xml-node.h" #define G(x) (gchar *)x static RestXmlNode * rest_xml_node_reverse_siblings (RestXmlNode *current) { RestXmlNode *next; RestXmlNode *prev = NULL; while (current) { next = current->next; current->next = prev; prev = current; current = next; } return prev; } void _rest_xml_node_reverse_children_siblings (RestXmlNode *node) { GList *l, *children; RestXmlNode *new_node; children = g_hash_table_get_values (node->children); for (l = children; l; l = l->next) { new_node = rest_xml_node_reverse_siblings ((RestXmlNode *)l->data); g_hash_table_insert (node->children, new_node->name, new_node); } if (children) g_list_free (children); } /* * _rest_xml_node_prepend: * @cur_node: a sibling #RestXmlNode to prepend the new before * @new_node: new #RestXmlNode to prepend to the siblings list * * Prepends new_node to the list of siblings starting at cur_node. * * Return value: (transfer none): returns new start of the sibling list */ RestXmlNode * _rest_xml_node_prepend (RestXmlNode *cur_node, RestXmlNode *new_node) { g_assert (new_node->next == NULL); new_node->next = cur_node; return new_node; } /* * rest_xml_node_append_end: * @cur_node: a member of the sibling #RestXmlNode list * @new_node: new #RestXmlNode to append to the siblings list * * Appends new_node to end of the list of siblings containing cur_node. */ static void rest_xml_node_append_end (RestXmlNode *cur_node, RestXmlNode *new_node) { RestXmlNode *tmp = cur_node; g_return_if_fail (cur_node); while (tmp->next) tmp = tmp->next; tmp->next = new_node; } GType rest_xml_node_get_type (void) { static GType type = 0; if (G_UNLIKELY (type == 0)) { type = g_boxed_type_register_static ("RestXmlNode", (GBoxedCopyFunc)rest_xml_node_ref, (GBoxedFreeFunc)rest_xml_node_unref); } return type; } /* * _rest_xml_node_new: * * Creates a new instance of #RestXmlNode. * * Return value: (transfer full): newly allocated #RestXmlNode. */ RestXmlNode * _rest_xml_node_new () { RestXmlNode *node; node = g_slice_new0 (RestXmlNode); node->ref_count = 1; node->children = g_hash_table_new (NULL, NULL); node->attrs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); return node; } /** * rest_xml_node_ref: (skip) * @node: a #RestXmlNode * * Increases the reference count of @node. * * Returns: the same @node. */ RestXmlNode * rest_xml_node_ref (RestXmlNode *node) { g_return_val_if_fail (node, NULL); g_return_val_if_fail (node->ref_count > 0, NULL); g_atomic_int_inc (&node->ref_count); return node; } /** * rest_xml_node_unref: (skip) * @node: a #RestXmlNode * * Decreases the reference count of @node. When its reference count drops to 0, * the node is finalized (i.e. its memory is freed). */ void rest_xml_node_unref (RestXmlNode *node) { GList *l; RestXmlNode *next = NULL; g_return_if_fail (node); g_return_if_fail (node->ref_count > 0); /* Try and unref the chain, this is equivalent to being tail recursively * unreffing the next pointer */ while (node && g_atomic_int_dec_and_test (&node->ref_count)) { /* * Save this pointer now since we are going to free the structure it * contains soon. */ next = node->next; l = g_hash_table_get_values (node->children); while (l) { rest_xml_node_unref ((RestXmlNode *)l->data); l = g_list_delete_link (l, l); } g_hash_table_unref (node->children); g_hash_table_unref (node->attrs); g_free (node->content); g_slice_free (RestXmlNode, node); /* * Free the next in the chain by updating node. If we're at the end or * there are no siblings then the next = NULL definition deals with this * case */ node = next; } } G_GNUC_DEPRECATED void rest_xml_node_free (RestXmlNode *node) { rest_xml_node_unref (node); } /** * rest_xml_node_get_attr: * @node: a #RestXmlNode * @attr_name: the name of an attribute * * Get the value of the attribute named @attr_name, or %NULL if it doesn't * exist. * * Returns: the attribute value. This string is owned by #RestXmlNode and should * not be freed. */ const gchar * rest_xml_node_get_attr (RestXmlNode *node, const gchar *attr_name) { return g_hash_table_lookup (node->attrs, attr_name); } /** * rest_xml_node_find: * @start: a #RestXmlNode * @tag: the name of a node * * Searches for the first child node of @start named @tag. * * Returns: the first child node, or %NULL if it doesn't exist. */ RestXmlNode * rest_xml_node_find (RestXmlNode *start, const gchar *tag) { RestXmlNode *node; RestXmlNode *tmp; GQueue stack = G_QUEUE_INIT; GList *children, *l; const char *tag_interned; g_return_val_if_fail (start, NULL); g_return_val_if_fail (start->ref_count > 0, NULL); tag_interned = g_intern_string (tag); g_queue_push_head (&stack, start); while ((node = g_queue_pop_head (&stack)) != NULL) { if ((tmp = g_hash_table_lookup (node->children, tag_interned)) != NULL) { g_queue_clear (&stack); return tmp; } children = g_hash_table_get_values (node->children); for (l = children; l; l = l->next) { g_queue_push_head (&stack, l->data); } g_list_free (children); } g_queue_clear (&stack); return NULL; } /** * rest_xml_node_print: * @node: #RestXmlNode * * Recursively outputs given node and it's children. * * Return value: (transfer full): xml string representing the node. */ char * rest_xml_node_print (RestXmlNode *node) { GHashTableIter iter; gpointer key, value; char *xml = g_strconcat ("<", node->name, NULL); RestXmlNode *n; g_hash_table_iter_init (&iter, node->attrs); while (g_hash_table_iter_next (&iter, &key, &value)) xml = g_strconcat (xml, " ", key, "=\'", value, "\'", NULL); xml = g_strconcat (xml, ">", NULL); g_hash_table_iter_init (&iter, node->children); while (g_hash_table_iter_next (&iter, &key, &value)) { char *child = rest_xml_node_print ((RestXmlNode *) value); xml = g_strconcat (xml, child, NULL); g_free (child); } if (node->content) xml = g_strconcat (xml, node->content, "</", node->name, ">", NULL); else xml = g_strconcat (xml, "</", node->name, ">", NULL); for (n = node->next; n; n = n->next) { char *sibling = rest_xml_node_print (n); xml = g_strconcat (xml, sibling, NULL); g_free (sibling); } return xml; } /** * rest_xml_node_add_child: * @parent: parent #RestXmlNode, or %NULL for the top-level node * @tag: name of the child node * * Adds a new node to the given parent node; to create the top-level node, * parent should be %NULL. * * Return value: (transfer none): the newly added #RestXmlNode; the node object * is owned by, and valid for the life time of, the #RestXmlCreator. */ RestXmlNode * rest_xml_node_add_child (RestXmlNode *parent, const char *tag) { RestXmlNode *node; char *escaped; g_return_val_if_fail (tag && *tag, NULL); escaped = g_markup_escape_text (tag, -1); node = _rest_xml_node_new (); node->name = (char *) g_intern_string (escaped); if (parent) { RestXmlNode *tmp_node; tmp_node = g_hash_table_lookup (parent->children, node->name); if (tmp_node) { rest_xml_node_append_end (tmp_node, node); } else { g_hash_table_insert (parent->children, G(node->name), node); } } g_free (escaped); return node; } /** * rest_xml_node_add_attr: * @node: #RestXmlNode to add attribute to * @attribute: name of the attribute * @value: value to set attribute to * * Adds attribute to the given node. */ void rest_xml_node_add_attr (RestXmlNode *node, const char *attribute, const char *value) { g_return_if_fail (node && attribute && *attribute); g_hash_table_insert (node->attrs, g_markup_escape_text (attribute, -1), g_markup_escape_text (value, -1)); } /** * rest_xml_node_set_content: * @node: #RestXmlNode to set content * @value: the content * * Sets content for the given node. */ void rest_xml_node_set_content (RestXmlNode *node, const char *value) { g_return_if_fail (node && value && *value); g_free (node->content); node->content = g_markup_escape_text (value, -1); }
utf-8
1
LGPL-2.1
2009 Intel Corporation
wpewebkit-2.34.5/Source/WebCore/editing/EditingStyle.h
/* * Copyright (C) 2010 Google Inc. All rights reserved. * Copyright (C) 2013 Apple Inc. 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 Google Inc. 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 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 COPYRIGHT * OWNER 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. */ #pragma once #include "CSSPropertyNames.h" #include "CSSValueKeywords.h" #include "StyleProperties.h" #include "WritingDirection.h" #include <wtf/RefCounted.h> #include <wtf/TriState.h> #include <wtf/text/WTFString.h> namespace WebCore { class CSSStyleDeclaration; class CSSComputedStyleDeclaration; class CSSPrimitiveValue; class CSSValue; class ComputedStyleExtractor; class Document; class Element; class HTMLElement; class MutableStyleProperties; class Node; class Position; class QualifiedName; class RenderStyle; class StyleProperties; class StyledElement; class VisibleSelection; enum class TextDecorationChange { None, Add, Remove }; // FIXME: "Keep" should be "Resolve" instead and resolve all generic font family names. enum class StandardFontFamilySerializationMode : uint8_t { Keep, Strip }; class EditingStyle : public RefCounted<EditingStyle> { public: enum PropertiesToInclude { AllProperties, OnlyEditingInheritableProperties, EditingPropertiesInEffect }; enum ShouldPreserveWritingDirection { PreserveWritingDirection, DoNotPreserveWritingDirection }; enum ShouldExtractMatchingStyle { ExtractMatchingStyle, DoNotExtractMatchingStyle }; static float NoFontDelta; static Ref<EditingStyle> create() { return adoptRef(*new EditingStyle); } static Ref<EditingStyle> create(Node* node, PropertiesToInclude propertiesToInclude = OnlyEditingInheritableProperties) { return adoptRef(*new EditingStyle(node, propertiesToInclude)); } static Ref<EditingStyle> create(const Position& position, PropertiesToInclude propertiesToInclude = OnlyEditingInheritableProperties) { return adoptRef(*new EditingStyle(position, propertiesToInclude)); } static Ref<EditingStyle> create(const StyleProperties* style) { return adoptRef(*new EditingStyle(style)); } static Ref<EditingStyle> create(const CSSStyleDeclaration* style) { return adoptRef(*new EditingStyle(style)); } static Ref<EditingStyle> create(CSSPropertyID propertyID, const String& value) { return adoptRef(*new EditingStyle(propertyID, value)); } static Ref<EditingStyle> create(CSSPropertyID propertyID, CSSValueID value) { return adoptRef(*new EditingStyle(propertyID, value)); } WEBCORE_EXPORT ~EditingStyle(); MutableStyleProperties* style() { return m_mutableStyle.get(); } Ref<MutableStyleProperties> styleWithResolvedTextDecorations() const; std::optional<WritingDirection> textDirection() const; bool isEmpty() const; void setStyle(RefPtr<MutableStyleProperties>&&); void overrideWithStyle(const StyleProperties&); void overrideTypingStyleAt(const EditingStyle&, const Position&); void clear(); Ref<EditingStyle> copy() const; Ref<EditingStyle> extractAndRemoveBlockProperties(); Ref<EditingStyle> extractAndRemoveTextDirection(); void removeBlockProperties(); void removeStyleAddedByNode(Node*); void removeStyleConflictingWithStyleOfNode(Node&); template<typename T> void removeEquivalentProperties(T&); void collapseTextDecorationProperties(); enum ShouldIgnoreTextOnlyProperties { IgnoreTextOnlyProperties, DoNotIgnoreTextOnlyProperties }; TriState triStateOfStyle(EditingStyle*) const; TriState triStateOfStyle(const VisibleSelection&) const; bool conflictsWithInlineStyleOfElement(StyledElement& element) const { return conflictsWithInlineStyleOfElement(element, nullptr, nullptr); } bool conflictsWithInlineStyleOfElement(StyledElement& element, RefPtr<MutableStyleProperties>& newInlineStyle, EditingStyle* extractedStyle) const { return conflictsWithInlineStyleOfElement(element, &newInlineStyle, extractedStyle); } bool conflictsWithImplicitStyleOfElement(HTMLElement&, EditingStyle* extractedStyle = nullptr, ShouldExtractMatchingStyle = DoNotExtractMatchingStyle) const; bool conflictsWithImplicitStyleOfAttributes(HTMLElement&) const; bool extractConflictingImplicitStyleOfAttributes(HTMLElement&, ShouldPreserveWritingDirection, EditingStyle* extractedStyle, Vector<QualifiedName>& conflictingAttributes, ShouldExtractMatchingStyle) const; bool styleIsPresentInComputedStyleOfNode(Node&) const; static bool elementIsStyledSpanOrHTMLEquivalent(const HTMLElement&); void prepareToApplyAt(const Position&, ShouldPreserveWritingDirection = DoNotPreserveWritingDirection); void mergeTypingStyle(Document&); enum CSSPropertyOverrideMode { OverrideValues, DoNotOverrideValues }; void mergeInlineStyleOfElement(StyledElement&, CSSPropertyOverrideMode, PropertiesToInclude = AllProperties); static Ref<EditingStyle> wrappingStyleForSerialization(Node& context, bool shouldAnnotate, StandardFontFamilySerializationMode); void mergeStyleFromRules(StyledElement&); void mergeStyleFromRulesForSerialization(StyledElement&, StandardFontFamilySerializationMode); void removeStyleFromRulesAndContext(StyledElement&, Node* context); void removePropertiesInElementDefaultStyle(Element&); void forceInline(); void addDisplayContents(); bool convertPositionStyle(); bool isFloating(); int legacyFontSize(Document&) const; float fontSizeDelta() const { return m_fontSizeDelta; } bool hasFontSizeDelta() const { return m_fontSizeDelta != NoFontDelta; } bool shouldUseFixedDefaultFontSize() const { return m_shouldUseFixedDefaultFontSize; } void setUnderlineChange(TextDecorationChange change) { m_underlineChange = static_cast<unsigned>(change); } TextDecorationChange underlineChange() const { return static_cast<TextDecorationChange>(m_underlineChange); } void setStrikeThroughChange(TextDecorationChange change) { m_strikeThroughChange = static_cast<unsigned>(change); } TextDecorationChange strikeThroughChange() const { return static_cast<TextDecorationChange>(m_strikeThroughChange); } WEBCORE_EXPORT bool hasStyle(CSSPropertyID, const String& value); WEBCORE_EXPORT static RefPtr<EditingStyle> styleAtSelectionStart(const VisibleSelection&, bool shouldUseBackgroundColorInEffect = false); static WritingDirection textDirectionForSelection(const VisibleSelection&, EditingStyle* typingStyle, bool& hasNestedOrMultipleEmbeddings); Ref<EditingStyle> inverseTransformColorIfNeeded(Element&); private: EditingStyle(); EditingStyle(Node*, PropertiesToInclude); EditingStyle(const Position&, PropertiesToInclude); WEBCORE_EXPORT explicit EditingStyle(const CSSStyleDeclaration*); explicit EditingStyle(const StyleProperties*); EditingStyle(CSSPropertyID, const String& value); EditingStyle(CSSPropertyID, CSSValueID); void init(Node*, PropertiesToInclude); void removeTextFillAndStrokeColorsIfNeeded(const RenderStyle*); void setProperty(CSSPropertyID, const String& value, bool important = false); void extractFontSizeDelta(); template<typename T> TriState triStateOfStyle(T& styleToCompare, ShouldIgnoreTextOnlyProperties) const; bool conflictsWithInlineStyleOfElement(StyledElement&, RefPtr<MutableStyleProperties>* newInlineStyle, EditingStyle* extractedStyle) const; void mergeInlineAndImplicitStyleOfElement(StyledElement&, CSSPropertyOverrideMode, PropertiesToInclude, StandardFontFamilySerializationMode); void mergeStyle(const StyleProperties*, CSSPropertyOverrideMode); RefPtr<MutableStyleProperties> m_mutableStyle; unsigned m_shouldUseFixedDefaultFontSize : 1; unsigned m_underlineChange : 2; unsigned m_strikeThroughChange : 2; float m_fontSizeDelta = NoFontDelta; friend class HTMLElementEquivalent; friend class HTMLAttributeEquivalent; friend class HTMLTextDecorationEquivalent; }; class StyleChange { public: StyleChange() { } StyleChange(EditingStyle*, const Position&); const StyleProperties* cssStyle() const { return m_cssStyle.get(); } bool applyBold() const { return m_applyBold; } bool applyItalic() const { return m_applyItalic; } bool applyUnderline() const { return m_applyUnderline; } bool applyLineThrough() const { return m_applyLineThrough; } bool applySubscript() const { return m_applySubscript; } bool applySuperscript() const { return m_applySuperscript; } bool applyFontColor() const { return m_applyFontColor.length() > 0; } bool applyFontFace() const { return m_applyFontFace.length() > 0; } bool applyFontSize() const { return m_applyFontSize.length() > 0; } String fontColor() { return m_applyFontColor; } String fontFace() { return m_applyFontFace; } String fontSize() { return m_applyFontSize; } bool operator==(const StyleChange&); bool operator!=(const StyleChange& other) { return !(*this == other); } private: void extractTextStyles(Document&, MutableStyleProperties&, bool shouldUseFixedFontDefaultSize); RefPtr<MutableStyleProperties> m_cssStyle; bool m_applyBold = false; bool m_applyItalic = false; bool m_applyUnderline = false; bool m_applyLineThrough = false; bool m_applySubscript = false; bool m_applySuperscript = false; String m_applyFontColor; String m_applyFontFace; String m_applyFontSize; }; } // namespace WebCore
utf-8
1
BSD-2-clause
1999 Antti Koivisto <koivisto@kde.org> 1999-2000 Lars Knoll <knoll@kde.org> 1999-2001 Harri Porten <porten@kde.org> 2001 Dirk Mueller <mueller@kde.org> 2002-2013 Vivek Thampi 2003-2021 Apple Inc 2004-2006 Rob Buis <buis@kde.org> 2004-2008 Nikolas Zimmermann <zimmermann@kde.org> 2005 Frerich Raabe <raabe@kde.org> 2005 Maksim Orlovich <maksim@kde.org> 2005, 2007-2013, 2015, 2017-2021 Google Inc 2005, 2008-2013 Nokia 2005-2006 Alexey Proskuryakov 2005-2006 Kimmo Kinnunen <kimmo.t.kinnunen@nokia.com> 2005-2008 Eric Seidel <eric@webkit.org> 2006 Alexander Kellett <lypanov@kde.org> 2006 Graham Dennis <graham.dennis@gmail.com> 2006 Michael Emmel mike.emmel@gmail.com 2006 Samuel Weinig <sam.weinig@gmail.com> 2006-2007 Alexey Proskuryakov <ap@nypop.com> 2006-2007 Alexey Proskuryakov <ap@webkit.org> 2007 Henry Mason <hmason@mac.com> 2007 Holger Hans Peter Freyther <zecke@selfish.org> 2007 Justin Haygood <jhaygood@reaktix.com> 2007 Samuel Weinig <sam@webkit.org> 2007-2008 Alp Toker <alp@atoker.com> 2007-2009 Torch Mobile Inc 2008 Alex Mathews <possessedpenguinbob@gmail.com> 2008 Collin Jackson <collinj@webkit.org> 2008 Dirk Schulze <vbs85@gmx.de> 2008 Kelvin W Sherlock <ksherlock@gmail.com> 2008 Nuanti Ltd 2008, 2010 The Android Open Source Project 2008, 2010-2011 Julien Chaffraix <jchaffraix@webkit.org> 2008, 2014 Collabora Ltd 2008-2009 Dirk Schulze <krit@webkit.org> 2009 Antonio Gomes <tonikitoo@webkit.org> 2009 Jeff Schiller <codedread@gmail.com> 2009 Joseph Pecoraro 2009-2010 Alex Milowski <alex@milowski.com> 2009-2010 Holger Hans Peter Freyther 2009-2011 Brent Fulgham <bfulgham@webkit.org> 2009-2015 University of Szeged 2009-2021 Igalia S.L. 2010 Andras Becsi <abecsi@inf.u-szeged.hu>, University of Szeged 2010 Mozilla Corporation 2010 Peter Varga <pvarga@inf.u-szeged.hu>, University of Szeged 2010 Renata Hodovan <hodovan@inf.u-szeged.hu> 2010 Sencha Inc 2010 Torch Mobile (Beijing) Co 2010 Zoltan Herczeg <zherczeg@webkit.org> 2010, 2012 MIPS Technologies Inc 2010, 2012-2013 Company 100 Inc 2010, 2012-2014 Patrick Gansterer <paroga@paroga.com> 2010-2011 Adam Barth 2010-2011 Zoltan Herczeg 2010-2012 Research In Motion Limited 2010-2013 Motorola Mobility 2011 Adam Barth <abarth@webkit.org> 2011 Andreas Kling <kling@webkit.org> 2011 Benjamin Poulain <benjamin@webkit.org> 2011 Daniel Bates <dbates@intudata.com> 2011 Felician Marton 2011 Gabor Loki <loki@webkit.org> 2011 Peter Varga <pvarga@webkit.org>, University of Szeged 2011 ProFUSION embedded systems 2011 Renata Hodovan <reni@webkit.org> 2011, 2014-2017 The Chromium Authors 2011-2012, 2014-2015 Ericsson AB 2011-2013 Intel Corporation 2011-2013 Samsung Electronics 2011-2014 Adobe Systems Inc 2012 David Barton <dbarton@mathscribe.com> 2012 Gabor Rapcsanyi 2012 Gabor Rapcsanyi <rgabor@inf.u-szeged.hu>, University of Szeged 2012 Intel Inc 2012 Koji Ishii <kojiishi@gmail.com> 2012 Mathias Bynens <mathias@qiwi.be> 2012 Rik Cabanier <cabanier@adobe.com> 2012 Sony Network Entertainment 2012 Victor Carbune <victor@rosedu.org> 2012 Zan Dobersek <zandobersek@gmail.com> 2012, 2016 SoftAtHome 2012-2013 ChangSeok Oh <shivamidow@gmail.com> 2012-2013 Digia Plc 2012-2013 Michael Pruett <michael@68k.org> 2012-2015 University of Washington 2012-2016 Yann Collet 2013 Adenilson Cavalcanti <cavalcantii@gmail.com> 2013 Andrew Bortz 2013 The MathJax Consortium 2013 Xidorn Quan <quanxunzhen@gmail.com> 2013-2014 Cable Television Labs Inc 2014 Antoine Quint 2014 Dhi Aurrahman <diorahman@rockybars.com> 2014 Gurpreet Kaur <k.gurpreet@samsung.com> 2014 Raspberry Pi Foundation 2014 Saam Barati. <saambarati1@gmail.com> 2014-2015 Frederic Wang <fred.wang@free.fr> 2014-2015 Saam Barati <saambarati1@gmail.com> 2014-2018 Yusuke Suzuki <utatane.tea@gmail.com> 2015 Dominic Szablewski <dominic@phoboslab.org> 2015 Electronic Arts Inc 2015 Jordan Harband 2015 Tobias Reiss <tobi+webkit@basecode.de> 2015, 2018 Andy VanWagoner <andy@vanwagoner.family> 2015-2016 Sukolsak Sakshuwong <sukolsak@gmail.com> 2015-2017 Canon Inc 2015-2020 Devin Rousso <webkit@devinrousso.com> 2016 Caitlin Potter <caitp@igalia.com> 2016 Konstantin Tokavev <annulen@yandex.ru> 2016 Yusuke Suzuki <yusuke.suzuki@sslab.ics.keio.ac.jp> 2016-2018 Akamai Technologies Inc 2016-2019 Oleksandr Skachkov <gskachkov@gmail.com> 2016-2021 Metrological Group B.V 2016-2021 Sony Interactive Entertainment 2017 Caio Lima <ticaiolima@gmail.com> 2017 Endless Mobile Inc 2017 Oleksandr Skachkov <gskackhov@gmail.com> 2018 Google LLC 2018 Yusuke Suzuki <yusukesuzuki@slowstart.org> 2018 mce sys Ltd 2019 Carlos Eduardo Ramalho <cadubentzen@gmail.com> 2019 the V8 project authors 2019-2021 Alexey Shvayka <shvaikalesh@gmail.com> 2020 Cloudinary Inc 2020 Darryl Pogue <darryl@dpogue.ca> 2020 Jan-Michael Brummer <jan.brummer@tabos.org> 2020 WikiMedia Foundation. All Rights Reserve 2021 Tyler Wilcock <twilco.o@protonmail.com>
libgrokj2k-9.5.0/src/include/tclap/Arg.h
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: Arg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno . * Copyright (c) 2017 Google Inc. * All rights reserved. * * See the file COPYING in the top directory of this distribution for * more information. * * 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. * *****************************************************************************/ #ifndef TCLAP_ARG_H #define TCLAP_ARG_H #ifdef HAVE_TCLAP_CONFIG_H #include <tclap/TCLAPConfig.h> #endif #include <tclap/ArgException.h> #include <tclap/ArgTraits.h> #include <tclap/CmdLineInterface.h> #include <tclap/StandardTraits.h> #include <tclap/Visitor.h> #include <tclap/sstream.h> #include <cstdio> #include <iomanip> #include <iostream> #include <list> #include <string> #include <vector> namespace TCLAP { /** * A virtual base class that defines the essential data for all arguments. * This class, or one of its existing children, must be subclassed to do * anything. */ class Arg { private: /** * Prevent accidental copying. */ Arg(const Arg &rhs); /** * Prevent accidental copying. */ Arg &operator=(const Arg &rhs); /** * The delimiter that separates an argument flag/name from the * value. */ static char &delimiterRef() { static char delim = ' '; return delim; } protected: /** * The single char flag used to identify the argument. * This value (preceded by a dash {-}), can be used to identify * an argument on the command line. The _flag can be blank, * in fact this is how unlabeled args work. Unlabeled args must * override appropriate functions to get correct handling. Note * that the _flag does NOT include the dash as part of the flag. */ std::string _flag; /** * A single word namd identifying the argument. * This value (preceded by two dashed {--}) can also be used * to identify an argument on the command line. Note that the * _name does NOT include the two dashes as part of the _name. The * _name cannot be blank. */ std::string _name; /** * Description of the argument. */ std::string _description; /** * Indicating whether the argument is required. */ const bool _required; /** * Label to be used in usage description. Normally set to * "required", but can be changed when necessary. */ std::string _requireLabel; /** * Indicates whether a value is required for the argument. * Note that the value may be required but the argument/value * combination may not be, as specified by _required. */ bool _valueRequired; /** * Indicates whether the argument has been set. * Indicates that a value on the command line has matched the * name/flag of this argument and the values have been set accordingly. */ bool _alreadySet; /** Indicates the value specified to set this flag (like -a or --all). */ std::string _setBy; /** * A pointer to a visitor object. * The visitor allows special handling to occur as soon as the * argument is matched. This defaults to NULL and should not * be used unless absolutely necessary. */ Visitor *_visitor; /** * Whether this argument can be ignored, if desired. */ bool _ignoreable; bool _acceptsMultipleValues; /** * Indicates if the argument is visible in the help output (e.g., * when specifying --help). */ bool _visibleInHelp; /** * Performs the special handling described by the Visitor. */ void _checkWithVisitor() const; /** * Primary constructor. YOU (yes you) should NEVER construct an Arg * directly, this is a base class that is extended by various children * that are meant to be used. Use SwitchArg, ValueArg, MultiArg, * UnlabeledValueArg, or UnlabeledMultiArg instead. * * \param flag - The flag identifying the argument. * \param name - The name identifying the argument. * \param desc - The description of the argument, used in the usage. * \param req - Whether the argument is required. * \param valreq - Whether the a value is required for the argument. * \param v - The visitor checked by the argument. Defaults to NULL. */ Arg(const std::string &flag, const std::string &name, const std::string &desc, bool req, bool valreq, Visitor *v = NULL); public: /** * Destructor. */ virtual ~Arg(); /** * Adds this to the specified list of Args. * \param argList - The list to add this to. */ virtual void addToList(std::list<Arg *> &argList) const; /** * The delimiter that separates an argument flag/name from the * value. */ static char delimiter() { return delimiterRef(); } /** * The char used as a place holder when SwitchArgs are combined. * Currently set to the bell char (ASCII 7). */ static char blankChar() { return '\a'; } /** * The char that indicates the beginning of a flag. Defaults to '-', but * clients can define TCLAP_FLAGSTARTCHAR to override. */ #ifndef TCLAP_FLAGSTARTCHAR #define TCLAP_FLAGSTARTCHAR '-' #endif static char flagStartChar() { return TCLAP_FLAGSTARTCHAR; } /** * The sting that indicates the beginning of a flag. Defaults to "-", but * clients can define TCLAP_FLAGSTARTSTRING to override. Should be the same * as TCLAP_FLAGSTARTCHAR. */ #ifndef TCLAP_FLAGSTARTSTRING #define TCLAP_FLAGSTARTSTRING "-" #endif static const std::string flagStartString() { return TCLAP_FLAGSTARTSTRING; } /** * The sting that indicates the beginning of a name. Defaults to "--", but * clients can define TCLAP_NAMESTARTSTRING to override. */ #ifndef TCLAP_NAMESTARTSTRING #define TCLAP_NAMESTARTSTRING "--" #endif static const std::string nameStartString() { return TCLAP_NAMESTARTSTRING; } /** * The name used to identify the ignore rest argument. */ static const std::string ignoreNameString() { return "ignore_rest"; } /** * Sets the delimiter for all arguments. * \param c - The character that delimits flags/names from values. */ static void setDelimiter(char c) { delimiterRef() = c; } /** * Pure virtual method meant to handle the parsing and value assignment * of the string on the command line. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. What is * passed in from main. */ virtual bool processArg(size_t *i, std::vector<std::string> &args) = 0; /** * Operator ==. * Equality operator. Must be virtual to handle unlabeled args. * \param a - The Arg to be compared to this. */ virtual bool operator==(const Arg &a) const; /** * Returns the argument flag. */ const std::string &getFlag() const; /** * Returns the argument name. */ const std::string &getName() const; /** * Returns the argument description. */ std::string getDescription() const { return getDescription(_required); } /** * Returns the argument description. * * @param required if the argument should be treated as * required when described. */ std::string getDescription(bool required) const { return (required ? "(" + _requireLabel + ") " : "") + _description; } /** * Indicates whether the argument is required. */ virtual bool isRequired() const; /** * Indicates whether a value must be specified for argument. */ bool isValueRequired() const; /** * Indicates whether the argument has already been set. Only true * if the arg has been matched on the command line. */ bool isSet() const; /** * Returns the value specified to set this flag (like -a or --all). */ const std::string &setBy() const { return _setBy; } /** * Indicates whether the argument can be ignored, if desired. */ bool isIgnoreable() const; /** * A method that tests whether a string matches this argument. * This is generally called by the processArg() method. This * method could be re-implemented by a child to change how * arguments are specified on the command line. * \param s - The string to be compared to the flag/name to determine * whether the arg matches. */ virtual bool argMatches(const std::string &s) const; /** * Returns a simple string representation of the argument. * Primarily for debugging. */ virtual std::string toString() const; /** * Returns a short ID for the usage. * \param valueId - The value used in the id. */ virtual std::string shortID(const std::string &valueId = "val") const; /** * Returns a long ID for the usage. * \param valueId - The value used in the id. */ virtual std::string longID(const std::string &valueId = "val") const; /** * Trims a value off of the flag. * \param flag - The string from which the flag and value will be * trimmed. Contains the flag once the value has been trimmed. * \param value - Where the value trimmed from the string will * be stored. */ virtual void trimFlag(std::string &flag, std::string &value) const; /** * Checks whether a given string has blank chars, indicating that * it is a combined SwitchArg. If so, return true, otherwise return * false. * \param s - string to be checked. */ bool _hasBlanks(const std::string &s) const; /** * Used for MultiArgs to determine whether args can still be * set. */ virtual bool allowMore(); /** * Use by output classes to determine whether an Arg accepts * multiple values. */ virtual bool acceptsMultipleValues(); /** * Clears the Arg object and allows it to be reused by new * command lines. */ virtual void reset(); /** * Hide this argument from the help output (e.g., when * specifying the --help flag or on error. */ virtual void hideFromHelp(bool hide = true) { _visibleInHelp = !hide; } /** * Returns true if this Arg is visible in the help output. */ virtual bool visibleInHelp() const { return _visibleInHelp; } virtual bool hasLabel() const { return true; } }; /** * Typedef of an Arg list iterator. */ typedef std::list<Arg *>::const_iterator ArgListIterator; /** * Typedef of an Arg vector iterator. */ typedef std::vector<Arg *>::const_iterator ArgVectorIterator; /** * Typedef of a Visitor list iterator. */ typedef std::list<Visitor *>::const_iterator VisitorListIterator; /* * Extract a value of type T from it's string representation contained * in strVal. The ValueLike parameter used to select the correct * specialization of ExtractValue depending on the value traits of T. * ValueLike traits use operator>> to assign the value from strVal. */ template <typename T> void ExtractValue(T &destVal, const std::string &strVal, ValueLike vl) { static_cast<void>(vl); // Avoid warning about unused vl istringstream is(strVal.c_str()); int valuesRead = 0; while (is.good()) { if (is.peek() != EOF) #ifdef TCLAP_SETBASE_ZERO is >> std::setbase(0) >> destVal; #else is >> destVal; #endif else break; valuesRead++; } if (is.fail()) throw( ArgParseException("Couldn't read argument value " "from string '" + strVal + "'")); if (valuesRead > 1) throw( ArgParseException("More than one valid value parsed from " "string '" + strVal + "'")); } /* * Extract a value of type T from it's string representation contained * in strVal. The ValueLike parameter used to select the correct * specialization of ExtractValue depending on the value traits of T. * StringLike uses assignment (operator=) to assign from strVal. */ template <typename T> void ExtractValue(T &destVal, const std::string &strVal, StringLike sl) { static_cast<void>(sl); // Avoid warning about unused sl SetString(destVal, strVal); } ////////////////////////////////////////////////////////////////////// // BEGIN Arg.cpp ////////////////////////////////////////////////////////////////////// inline Arg::Arg(const std::string &flag, const std::string &name, const std::string &desc, bool req, bool valreq, Visitor *v) : _flag(flag), _name(name), _description(desc), _required(req), _requireLabel("required"), _valueRequired(valreq), _alreadySet(false), _setBy(), _visitor(v), _ignoreable(true), _acceptsMultipleValues(false), _visibleInHelp(true) { if (_flag.length() > 1) throw(SpecificationException( "Argument flag can only be one character long", toString())); if (_name != ignoreNameString() && (_flag == Arg::flagStartString() || _flag == Arg::nameStartString() || _flag == " ")) throw(SpecificationException( "Argument flag cannot be either '" + Arg::flagStartString() + "' or '" + Arg::nameStartString() + "' or a space.", toString())); if ((_name.substr(0, Arg::flagStartString().length()) == Arg::flagStartString()) || (_name.substr(0, Arg::nameStartString().length()) == Arg::nameStartString()) || (_name.find(" ", 0) != std::string::npos)) throw(SpecificationException("Argument name begin with either '" + Arg::flagStartString() + "' or '" + Arg::nameStartString() + "' or space.", toString())); } inline Arg::~Arg() {} inline std::string Arg::shortID(const std::string &valueId) const { std::string id = ""; if (_flag != "") id = Arg::flagStartString() + _flag; else id = Arg::nameStartString() + _name; if (_valueRequired) id += std::string(1, Arg::delimiter()) + valueId; return id; } inline std::string Arg::longID(const std::string &valueId) const { std::string id = ""; if (_flag != "") { id += Arg::flagStartString() + _flag; if (_valueRequired) id += std::string(1, Arg::delimiter()) + valueId; id += ", "; } id += Arg::nameStartString() + _name; if (_valueRequired) id += std::string(1, Arg::delimiter()) + valueId; return id; } inline bool Arg::operator==(const Arg &a) const { if ((_flag != "" && _flag == a._flag) || _name == a._name) return true; else return false; } inline const std::string &Arg::getFlag() const { return _flag; } inline const std::string &Arg::getName() const { return _name; } inline bool Arg::isRequired() const { return _required; } inline bool Arg::isValueRequired() const { return _valueRequired; } inline bool Arg::isSet() const { return _alreadySet; } inline bool Arg::isIgnoreable() const { return _ignoreable; } inline bool Arg::argMatches(const std::string &argFlag) const { if ((argFlag == Arg::flagStartString() + _flag && _flag != "") || argFlag == Arg::nameStartString() + _name) return true; else return false; } inline std::string Arg::toString() const { std::string s = ""; if (_flag != "") s += Arg::flagStartString() + _flag + " "; s += "(" + Arg::nameStartString() + _name + ")"; return s; } inline void Arg::_checkWithVisitor() const { if (_visitor != NULL) _visitor->visit(); } /** * Implementation of trimFlag. */ inline void Arg::trimFlag(std::string &flag, std::string &value) const { size_t stop = 0; for (size_t i = 0; static_cast<unsigned int>(i) < flag.length(); i++) if (flag[i] == Arg::delimiter()) { stop = i; break; } if (stop > 1) { value = flag.substr(stop + 1); flag = flag.substr(0, stop); } } /** * Implementation of _hasBlanks. */ inline bool Arg::_hasBlanks(const std::string &s) const { for (size_t i = 1; static_cast<unsigned int>(i) < s.length(); i++) if (s[i] == Arg::blankChar()) return true; return false; } /** * Overridden by Args that need to added to the end of the list. */ inline void Arg::addToList(std::list<Arg *> &argList) const { argList.push_front(const_cast<Arg *>(this)); } inline bool Arg::allowMore() { return false; } inline bool Arg::acceptsMultipleValues() { return _acceptsMultipleValues; } inline void Arg::reset() { _alreadySet = false; } ////////////////////////////////////////////////////////////////////// // END Arg.cpp ////////////////////////////////////////////////////////////////////// } // namespace TCLAP #endif // TCLAP_ARG_H
utf-8
1
AGPL-3 and BSD-2-clause and Apache-2
2001-2003, David Janssens 2002-2003, Yannick Verschueren 2002-2014, Professor Benoit Macq 2002-2014, Universite catholique de Louvain (UCL), Belgium 2003-2007, Francois-Olivier Devaux 2003-2014, Antonin Descampe 2005, Herve Drolon, FreeImage Team 2006-2007, Parvatha Elangovan 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr> 2011-2012, Centre National d'Etudes Spatiales (CNES), France 2012, CS Systemes d'Information, France 2016-2020, Grok Image Compression Inc.
asl-0.1.7/src/num/aslDataResampling.h
/* * Advanced Simulation Library <http://asl.org.il> * * Copyright 2015 Avtech Scientific <http://avtechscientific.com> * * * This file is part of Advanced Simulation Library (ASL). * * ASL is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, version 3 of the License. * * ASL 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with ASL. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef ASLDATARESAMPLING_H #define ASLDATARESAMPLING_H #include "aslSingleKernelNM.h" #include "math/aslVectors.h" //#include <CL/cl.hpp> // Supply "cl.hpp" with ASL, since it is not present in OpenCL 2.0 // Remove the file after switching to OpenCL 2.1 #include "acl/cl.hpp" namespace acl { class VectorOfElementsData; } namespace asl { class VectorTemplate; template <typename V> class DataWithGhostNodes; typedef DataWithGhostNodes<acl::VectorOfElementsData> DataWithGhostNodesACLData; typedef std::shared_ptr<DataWithGhostNodesACLData> SPDataWithGhostNodesACLData; class AbstractDataWithGhostNodes; typedef std::shared_ptr<AbstractDataWithGhostNodes> SPAbstractDataWithGhostNodes; /// Algorithm for generation of coarsed dataset /** \ingroup NumMethods \todo make and test */ class DataCoarser: public SingleKernelNM { public: typedef SPDataWithGhostNodesACLData Data; private: Data dataIn; Data dataOut; const VectorTemplate* vectorTemplate; virtual void init0(); public: DataCoarser(); DataCoarser(Data dIn); inline Data getDataOut(); }; typedef std::shared_ptr<DataCoarser> SPDataCoarser; /// \ingroup DataUtilities SPDataWithGhostNodesACLData coarseData(SPDataWithGhostNodesACLData d); /// Algorithm for generation of coarsed dataset /** \ingroup NumMethods \todo make and test */ class DataClipper: public SingleKernelNM { public: typedef SPDataWithGhostNodesACLData Data; private: Data dataIn; Data dataOut; AVec<int> a0; AVec<int> aE; virtual void init0(); public: DataClipper(); DataClipper(Data dIn, AVec<int> a0, AVec<int> aE); inline Data getDataOut(); }; typedef std::shared_ptr<DataClipper> SPDataClipper; /// \ingroup DataUtilities inline SPDataWithGhostNodesACLData clipData(SPDataWithGhostNodesACLData d, AVec<int> a0, AVec<int> aE); //----------------------------- Implementation ----------------------- DataCoarser::Data DataCoarser::getDataOut() { return dataOut; } DataClipper::Data DataClipper::getDataOut() { return dataOut; } inline SPDataWithGhostNodesACLData coarseData(SPDataWithGhostNodesACLData d) { DataCoarser dc(d); dc.init(); dc.execute(); return dc.getDataOut(); } inline SPDataWithGhostNodesACLData clipData(SPDataWithGhostNodesACLData d, AVec<int> a0, AVec<int> aE) { asl::DataClipper dcl(d, a0,aE); dcl.init(); dcl.execute(); return dcl.getDataOut(); } } // asl #endif // ASLDATARESAMPLING_H
utf-8
1
AGPL-3
Copyright 2015 Avtech Scientific <http://avtechscientific.com>
widelands-21/src/wui/login_box.cc
/* * Copyright (C) 2002-2020 by the Widelands Development Team * * 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "wui/login_box.h" #include "base/i18n.h" #include "graphic/font_handler.h" #include "network/crypto.h" #include "network/internet_gaming.h" #include "network/internet_gaming_protocol.h" #include "ui_basic/button.h" #include "ui_basic/messagebox.h" #include "wlapplication_options.h" LoginBox::LoginBox(Panel& parent) : Window(&parent, "login_box", 0, 0, 500, 280, _("Online Game Settings")) { center_to_parent(); int32_t margin = 10; ta_nickname = new UI::Textarea(this, margin, margin, 0, 0, _("Nickname:")); ta_password = new UI::Textarea(this, margin, 70, 0, 0, _("Password:")); eb_nickname = new UI::EditBox(this, 150, margin, 330, UI::PanelStyle::kWui); eb_password = new UI::EditBox(this, 150, 70, 330, UI::PanelStyle::kWui); cb_register = new UI::Checkbox(this, Vector2i(margin, 40), _("Log in to a registered account."), "", get_inner_w() - 2 * margin); register_account = new UI::MultilineTextarea( this, margin, 105, 470, 140, UI::PanelStyle::kWui, (boost::format(_("In order to use a registered " "account, you need an account on the Widelands website. " "Please log in at %s and set an online " "gaming password on your profile page.")) % "\n\nhttps://widelands.org/accounts/register/\n\n") .str()); loginbtn = new UI::Button(this, "login", UI::g_fh->fontset()->is_rtl() ? (get_inner_w() / 2 - 200) / 2 : (get_inner_w() / 2 - 200) / 2 + get_inner_w() / 2, get_inner_h() - 20 - margin, 200, 20, UI::ButtonStyle::kWuiPrimary, _("Save")); cancelbtn = new UI::Button(this, "cancel", UI::g_fh->fontset()->is_rtl() ? (get_inner_w() / 2 - 200) / 2 + get_inner_w() / 2 : (get_inner_w() / 2 - 200) / 2, loginbtn->get_y(), 200, 20, UI::ButtonStyle::kWuiSecondary, _("Cancel")); loginbtn->sigclicked.connect([this]() { clicked_ok(); }); cancelbtn->sigclicked.connect([this]() { clicked_back(); }); eb_nickname->changed.connect([this]() { change_playername(); }); cb_register->clickedto.connect([this](bool) { clicked_register(); }); eb_nickname->set_text(get_config_string("nickname", _("nobody"))); cb_register->set_state(get_config_bool("registered", false)); eb_password->set_password(true); if (registered()) { eb_password->set_text(get_config_string("password_sha1", "")); loginbtn->set_enabled(false); } else { eb_password->set_can_focus(false); ta_password->set_style(g_gr->styles().font_style(UI::FontStyle::kDisabled)); } eb_nickname->focus(); eb_nickname->cancel.connect([this]() { clicked_back(); }); eb_password->cancel.connect([this]() { clicked_back(); }); } /// think function of the UI (main loop) void LoginBox::think() { verify_input(); } /** * called, if "login" is pressed. */ void LoginBox::clicked_ok() { if (cb_register->get_state()) { if (check_password()) { set_config_string("nickname", eb_nickname->text()); set_config_bool("registered", true); end_modal<UI::Panel::Returncodes>(UI::Panel::Returncodes::kOk); } } else { set_config_string("nickname", eb_nickname->text()); set_config_bool("registered", false); set_config_string("password_sha1", ""); end_modal<UI::Panel::Returncodes>(UI::Panel::Returncodes::kOk); } } /// Called if "cancel" was pressed void LoginBox::clicked_back() { end_modal<UI::Panel::Returncodes>(UI::Panel::Returncodes::kBack); } /// Called when nickname was changed void LoginBox::change_playername() { cb_register->set_state(false); eb_password->set_can_focus(false); eb_password->set_text(""); } bool LoginBox::handle_key(bool down, SDL_Keysym code) { if (down) { switch (code.sym) { case SDLK_KP_ENTER: case SDLK_RETURN: clicked_ok(); return true; case SDLK_ESCAPE: clicked_back(); return true; default: break; // not handled } } return UI::Panel::handle_key(down, code); } void LoginBox::clicked_register() { if (cb_register->get_state()) { ta_password->set_style(g_gr->styles().font_style(UI::FontStyle::kDisabled)); eb_password->set_can_focus(false); eb_password->set_text(""); } else { ta_password->set_style(g_gr->styles().font_style(UI::FontStyle::kLabel)); eb_password->set_can_focus(true); eb_password->focus(); } } void LoginBox::verify_input() { // Check if all neccessary input fields are valid loginbtn->set_enabled(true); eb_nickname->set_tooltip(""); eb_password->set_tooltip(""); eb_nickname->set_warning(false); if (eb_nickname->text().empty()) { eb_nickname->set_warning(true); eb_nickname->set_tooltip(_("Please enter a nickname!")); loginbtn->set_enabled(false); } else if (!InternetGaming::ref().valid_username(eb_nickname->text())) { eb_nickname->set_warning(true); eb_nickname->set_tooltip(_("Enter a valid nickname. This value may contain only " "English letters, numbers, and @ . + - _ characters.")); loginbtn->set_enabled(false); } if (eb_password->text().empty() && cb_register->get_state()) { eb_password->set_tooltip(_("Please enter your password!")); loginbtn->set_enabled(false); } if (eb_password->has_focus() && eb_password->text() == get_config_string("password_sha1", "")) { eb_password->set_text(""); } if (cb_register->get_state() && eb_password->text() == get_config_string("password_sha1", "")) { loginbtn->set_enabled(false); } } /// Check password against metaserver bool LoginBox::check_password() { // Try to connect to the metaserver const std::string& meta = get_config_string("metaserver", INTERNET_GAMING_METASERVER.c_str()); uint32_t port = get_config_natural("metaserverport", kInternetGamingPort); std::string password = crypto::sha1(eb_password->text()); if (!InternetGaming::ref().check_password(get_nickname(), password, meta, port)) { // something went wrong -> show the error message // idealy it is about the wrong password ChatMessage msg = InternetGaming::ref().get_messages().back(); UI::WLMessageBox wmb(this, _("Error!"), msg.msg, UI::WLMessageBox::MBoxType::kOk); wmb.run<UI::Panel::Returncodes>(); eb_password->set_text(""); eb_password->focus(); return false; } // NOTE: The password is only stored (in memory and on disk) and transmitted (over the network to // the metaserver) as cryptographic hash. This does NOT mean that the password is stored securely // on the local disk. While the password should be secure while transmitted to the metaserver // (no-one can use the transmitted data to log in as the user) this is not the case for local // storage. The stored hash of the password makes it hard to look at the configuration file and // figure out the plaintext password to, e.g., log in on the forum. However, the stored hash can // be copied to another system and used to log in as the user on the metaserver. Further note: // SHA-1 is considered broken and shouldn't be used anymore. But since the passwords on the // server are protected by SHA-1 we have to use it here, too set_config_string("password_sha1", password); InternetGaming::ref().logout(); return true; }
utf-8
1
GPL-2+
2002-2019 by the Widelands Development Team
tupi-0.2+git08/src/framework/tgui/tdualcolorbutton.cpp
/*************************************************************************** * Project TUPI: Magia 2D * * Project Contact: info@maefloresta.com * * Project Website: http://www.maefloresta.com * * Project Leader: Gustav Gonzalez <info@maefloresta.com> * * * * Developers: * * 2010: * * Gustavo Gonzalez / xtingray * * * * KTooN's versions: * * * * 2006: * * David Cuadrado * * Jorge Cuadrado * * 2003: * * Fernado Roldan * * Simena Dinas * * * * Copyright (C) 2010 Gustav Gonzalez - http://www.maefloresta.com * * License: * * 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. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "tdualcolorbutton.h" #include "tcolorarrow.xpm" #include "tcolorreset.xpm" struct TDualColorButton::Private { QPixmap arrowBitmap; QPixmap resetPixmap; QBrush fgBrush; QBrush bgBrush; ColorSpace currentSpace; }; TDualColorButton::TDualColorButton(QWidget *parent) : QWidget(parent), k(new Private) { k->arrowBitmap = QPixmap((const char **)dcolorarrow_bits); k->resetPixmap = QPixmap((const char **)dcolorreset_xpm); k->fgBrush = QBrush(Qt::black, Qt::SolidPattern); k->bgBrush = QBrush(QColor(0, 0, 0, 0), Qt::SolidPattern); k->currentSpace = Foreground; if (sizeHint().isValid()) setMinimumSize(sizeHint()); } TDualColorButton::TDualColorButton(const QBrush &fgColor, const QBrush &bgColor, QWidget *parent) : QWidget(parent), k(new Private) { k->arrowBitmap = QPixmap((const char **)dcolorarrow_bits); k->resetPixmap = QPixmap((const char **)dcolorreset_xpm); k->fgBrush = fgColor; k->bgBrush = bgColor; k->currentSpace = Foreground; if (sizeHint().isValid()) setMinimumSize(sizeHint()); } TDualColorButton::~TDualColorButton() { } QBrush TDualColorButton::foreground() const { return k->fgBrush; } QBrush TDualColorButton::background() const { return k->bgBrush; } TDualColorButton::ColorSpace TDualColorButton::current() const { return k->currentSpace; } QBrush TDualColorButton::currentColor() const { return (k->currentSpace == Background ? k->bgBrush : k->fgBrush); } QSize TDualColorButton::sizeHint() const { return QSize(34, 34); } void TDualColorButton::setForeground(const QBrush &c) { k->fgBrush = c; update(); // emit fgChanged(k->fgBrush.color()); } void TDualColorButton::setBackground(const QBrush &c) { k->bgBrush = c; update(); // emit bgChanged(k->bgBrush.color()); } void TDualColorButton::setCurrentColor(const QBrush &c) { if (k->currentSpace == Background) k->bgBrush = c; else k->fgBrush = c; update(); } void TDualColorButton::setCurrent(ColorSpace s) { k->currentSpace = s; update(); } void TDualColorButton::metrics(QRect &fgRect, QRect &bgRect) { fgRect = QRect(0, 0, width()-14, height()-14); bgRect = QRect(14, 14, width()-14, height()-14); } void TDualColorButton::paintEvent(QPaintEvent *) { QPalette pal = palette(); QPainter painter(this); QRect fgRect, bgRect; metrics(fgRect, bgRect); QBrush defBrush = pal.color(QPalette::Button); QBrush bgAdjusted = k->bgBrush; QBrush fgAdjusted = k->fgBrush; qDrawShadeRect(&painter, bgRect, pal, k->currentSpace == Background, 2, 0, isEnabled() ? &bgAdjusted: &defBrush); qDrawShadeRect(&painter, fgRect, pal, k->currentSpace == Foreground, 2, 0, isEnabled() ? &fgAdjusted : &defBrush); painter.setPen(QPen(palette().shadow().color())); painter.drawPixmap(fgRect.right() + 2, 0, k->arrowBitmap); painter.drawPixmap(0, fgRect.bottom() + 2, k->resetPixmap); } void TDualColorButton::mousePressEvent(QMouseEvent *event) { QPoint mPos = event->pos(); QRect fgRect, bgRect; metrics(fgRect, bgRect); if (fgRect.contains(mPos)) { k->currentSpace = Foreground; // tFatal() << "TDualColorButton::mousePressEvent() - emitting foreground signal!"; emit selectionChanged(Foreground); } else if (bgRect.contains(mPos)) { k->currentSpace = Background; // tFatal() << "TDualColorButton::mousePressEvent() - emitting background signal!"; emit selectionChanged(Background); } else if (event->pos().x() > fgRect.width()) { // We handle the swap and reset controls as soon as the mouse is // is pressed and ignore further events on this click (mosfet). QBrush tmpBrush = k->fgBrush; k->fgBrush = k->bgBrush; k->bgBrush = tmpBrush; emit switchColors(); // emit fgChanged(k->fgBrush); // emit bgChanged(k->bgBrush); } else if (event->pos().x() < bgRect.x()) { k->fgBrush.setColor(Qt::black); k->bgBrush.setColor(QColor(0,0,0,0)); emit resetColors(); // emit fgChanged(k->fgBrush); // emit bgChanged(k->bgBrush); } update(); }
utf-8
1
GPL-2+
2010-2016 Gustav Gonzalez <info@maefloresta.com> 2006 David Cuadrado 2006 Jorge Cuadrado 2003 Fernado Roldan 2012 Mae Floresta 2003 Simena Dinas
elastix-5.0.1/Components/Optimizers/QuasiNewtonLBFGS/itkQuasiNewtonLBFGSOptimizer.cxx
/*========================================================================= * * Copyright UMC Utrecht and contributors * * 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.txt * * 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. * *=========================================================================*/ #ifndef __itkQuasiNewtonLBFGSOptimizer_cxx #define __itkQuasiNewtonLBFGSOptimizer_cxx #include "itkQuasiNewtonLBFGSOptimizer.h" #include "itkArray.h" #include "vnl/vnl_math.h" namespace itk { /** * ******************** Constructor ************************* */ QuasiNewtonLBFGSOptimizer::QuasiNewtonLBFGSOptimizer() { itkDebugMacro( "Constructor" ); this->m_CurrentValue = NumericTraits< MeasureType >::Zero; this->m_CurrentIteration = 0; this->m_StopCondition = Unknown; this->m_Stop = false; this->m_CurrentStepLength = 0.0; this->m_InLineSearch = false; this->m_Point = 0; this->m_PreviousPoint = 0; this->m_Bound = 0; this->m_MaximumNumberOfIterations = 100; this->m_GradientMagnitudeTolerance = 1e-5; this->m_LineSearchOptimizer = 0; this->m_Memory = 5; } // end constructor /** * ******************* StartOptimization ********************* */ void QuasiNewtonLBFGSOptimizer::StartOptimization() { itkDebugMacro( "StartOptimization" ); /** Reset some variables */ this->m_Point = 0; this->m_PreviousPoint = 0; this->m_Bound = 0; this->m_Stop = false; this->m_StopCondition = Unknown; this->m_CurrentIteration = 0; this->m_CurrentStepLength = 0.0; this->m_CurrentValue = NumericTraits< MeasureType >::Zero; /** Get the number of parameters; checks also if a cost function has been set at all. * if not: an exception is thrown */ const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters(); /** Set the current gradient to (0 0 0 ...) */ this->m_CurrentGradient.SetSize( numberOfParameters ); this->m_CurrentGradient.Fill( 0.0 ); /** Resize Rho, Alpha, S and Y. */ this->m_Rho.SetSize( this->GetMemory() ); this->m_S.resize( this->GetMemory() ); this->m_Y.resize( this->GetMemory() ); /** Initialize the scaledCostFunction with the currently set scales */ this->InitializeScales(); /** Set the current position as the scaled initial position */ this->SetCurrentPosition( this->GetInitialPosition() ); if( !this->m_Stop ) { this->ResumeOptimization(); } } // end StartOptimization /** * ******************* ResumeOptimization ********************* */ void QuasiNewtonLBFGSOptimizer::ResumeOptimization() { itkDebugMacro( "ResumeOptimization" ); this->m_Stop = false; this->m_StopCondition = Unknown; this->m_CurrentStepLength = 0.0; ParametersType searchDir; DerivativeType previousGradient; this->InvokeEvent( StartEvent() ); /** Get initial value and derivative */ try { this->GetScaledValueAndDerivative( this->GetScaledCurrentPosition(), this->m_CurrentValue, this->m_CurrentGradient ); } catch( ExceptionObject & err ) { this->m_StopCondition = MetricError; this->StopOptimization(); throw err; } /** Test if the gradient was not zero already by chance */ bool convergence = this->TestConvergence( false ); if( convergence ) { this->StopOptimization(); } /** Start iterating */ while( !this->m_Stop ) { /** Compute the new search direction, using the current gradient */ this->ComputeSearchDirection( this->GetCurrentGradient(), searchDir ); if( this->m_Stop ) { break; } /** Store the current gradient */ previousGradient = this->GetCurrentGradient(); /** Perform a line search along the search direction. On return the * m_CurrentStepLength, m_CurrentScaledPosition, m_CurrentValue, and * m_CurrentGradient are updated. */ this->LineSearch( searchDir, this->m_CurrentStepLength, this->m_ScaledCurrentPosition, this->m_CurrentValue, this->m_CurrentGradient ); if( this->m_Stop ) { break; } /** Store s (in m_S), y (in m_Y), and ys (in m_Rho). These are used to * compute the search direction in the next iterations */ if( this->GetMemory() > 0 ) { ParametersType s; DerivativeType y; s = this->GetCurrentStepLength() * searchDir; y = this->GetCurrentGradient() - previousGradient; this->StoreCurrentPoint( s, y ); s.clear(); y.clear(); } /** Number of valid entries in m_S and m_Y */ if( this->m_Bound < this->GetMemory() ) { this->m_Bound++; } this->InvokeEvent( IterationEvent() ); if( this->m_Stop ) { break; } /** Test if convergence has occurred */ convergence = this->TestConvergence( true ); if( convergence ) { this->StopOptimization(); break; } /** Update the index of m_S and m_Y for the next iteration */ this->m_PreviousPoint = this->m_Point; this->m_Point++; if( this->m_Point >= this->m_Memory ) { this->m_Point = 0; } this->m_CurrentIteration++; } // end while !m_Stop } // end ResumeOptimization /** * *********************** StopOptimization ***************************** */ void QuasiNewtonLBFGSOptimizer::StopOptimization() { itkDebugMacro( "StopOptimization" ); this->m_Stop = true; this->InvokeEvent( EndEvent() ); } // end StopOptimization() /** * ********************* ComputeDiagonalMatrix ******************** */ void QuasiNewtonLBFGSOptimizer::ComputeDiagonalMatrix( DiagonalMatrixType & diag_H0 ) { diag_H0.SetSize( this->GetScaledCostFunction()->GetNumberOfParameters() ); double fill_value = 1.0; if( this->m_Bound > 0 ) { const DerivativeType & y = this->m_Y[ this->m_PreviousPoint ]; const double ys = 1.0 / this->m_Rho[ this->m_PreviousPoint ]; const double yy = y.squared_magnitude(); fill_value = ys / yy; if( fill_value <= 0. ) { this->m_StopCondition = InvalidDiagonalMatrix; this->StopOptimization(); } } diag_H0.Fill( fill_value ); } // end ComputeDiagonalMatrix /** * *********************** ComputeSearchDirection ************************ */ void QuasiNewtonLBFGSOptimizer::ComputeSearchDirection( const DerivativeType & gradient, ParametersType & searchDir ) { itkDebugMacro( "ComputeSearchDirection" ); /** Assumes m_Rho, m_S, and m_Y are up-to-date at m_PreviousPoint */ typedef Array< double > AlphaType; AlphaType alpha( this->GetMemory() ); const unsigned int numberOfParameters = gradient.GetSize(); DiagonalMatrixType H0; this->ComputeDiagonalMatrix( H0 ); searchDir = -gradient; int cp = static_cast< int >( this->m_Point ); for( unsigned int i = 0; i < this->m_Bound; ++i ) { --cp; if( cp == -1 ) { cp = this->GetMemory() - 1; } const double sq = inner_product( this->m_S[ cp ], searchDir ); alpha[ cp ] = this->m_Rho[ cp ] * sq; const double & alpha_cp = alpha[ cp ]; const DerivativeType & y = this->m_Y[ cp ]; for( unsigned int j = 0; j < numberOfParameters; ++j ) { searchDir[ j ] -= alpha_cp * y[ j ]; } } for( unsigned int j = 0; j < numberOfParameters; ++j ) { searchDir[ j ] *= H0[ j ]; } for( unsigned int i = 0; i < this->m_Bound; ++i ) { const double yr = inner_product( this->m_Y[ cp ], searchDir ); const double beta = this->m_Rho[ cp ] * yr; const double alpha_min_beta = alpha[ cp ] - beta; const ParametersType & s = this->m_S[ cp ]; for( unsigned int j = 0; j < numberOfParameters; ++j ) { searchDir[ j ] += alpha_min_beta * s[ j ]; } ++cp; if( static_cast< unsigned int >( cp ) == this->GetMemory() ) { cp = 0; } } /** Normalize if no information about previous steps is available yet */ if( this->m_Bound == 0 ) { searchDir /= gradient.magnitude(); } } // end ComputeSearchDirection /** * ********************* LineSearch ******************************* * * Perform a line search along the search direction. On return the * step, x (new position), f (value at x), and g (derivative at x) * are updated. */ void QuasiNewtonLBFGSOptimizer::LineSearch( const ParametersType searchDir, double & step, ParametersType & x, MeasureType & f, DerivativeType & g ) { itkDebugMacro( "LineSearch" ); LineSearchOptimizerPointer LSO = this->GetModifiableLineSearchOptimizer(); if( LSO.IsNull() ) { this->m_StopCondition = LineSearchError; this->StopOptimization(); itkExceptionMacro( << "No line search optimizer set" ); } LSO->SetCostFunction( this->m_ScaledCostFunction ); LSO->SetLineSearchDirection( searchDir ); LSO->SetInitialPosition( x ); LSO->SetInitialValue( f ); LSO->SetInitialDerivative( g ); this->SetInLineSearch( true ); try { LSO->StartOptimization(); } catch( ExceptionObject & err ) { this->m_StopCondition = LineSearchError; this->StopOptimization(); throw err; } this->SetInLineSearch( false ); step = LSO->GetCurrentStepLength(); x = LSO->GetCurrentPosition(); try { LSO->GetCurrentValueAndDerivative( f, g ); } catch( ExceptionObject & err ) { this->m_StopCondition = MetricError; this->StopOptimization(); throw err; } } // end LineSearch /** * ********************* StoreCurrentPoint ************************ */ void QuasiNewtonLBFGSOptimizer::StoreCurrentPoint( const ParametersType & step, const DerivativeType & grad_dif ) { itkDebugMacro( "StoreCurrentPoint" ); this->m_S[ this->m_Point ] = step; // s this->m_Y[ this->m_Point ] = grad_dif; // y this->m_Rho[ this->m_Point ] = 1.0 / inner_product( step, grad_dif ); // 1/ys } // end StoreCurrentPoint /** * ********************* TestConvergence ************************ */ bool QuasiNewtonLBFGSOptimizer::TestConvergence( bool firstLineSearchDone ) { itkDebugMacro( "TestConvergence" ); /** Check for zero step length */ if( firstLineSearchDone ) { if( this->m_CurrentStepLength < NumericTraits< double >::epsilon() ) { this->m_StopCondition = ZeroStep; return true; } } /** Check if the maximum number of iterations will not be exceeded in the following iteration */ if( ( this->GetCurrentIteration() + 1 ) >= this->GetMaximumNumberOfIterations() ) { this->m_StopCondition = MaximumNumberOfIterations; return true; } /** Check for convergence of gradient magnitude */ const double gnorm = this->GetCurrentGradient().magnitude(); const double xnorm = this->GetScaledCurrentPosition().magnitude(); if( gnorm / std::max( 1.0, xnorm ) <= this->GetGradientMagnitudeTolerance() ) { this->m_StopCondition = GradientMagnitudeTolerance; return true; } return false; } // end TestConvergence } // end namespace itk #endif // #ifndef __itkQuasiNewtonLBFGSOptimizer_cxx
utf-8
1
Apache-2.0
UMC Utrecht and contributors
squid-5.2/src/tests/testStoreSupport.h
/* * Copyright (C) 1996-2021 The Squid Software Foundation and contributors * * Squid software is distributed under GPLv2+ license and includes * contributions from numerous individuals and organizations. * Please see the COPYING and CONTRIBUTORS files for details. */ #ifndef SQUID_TESTSTORESUPPORT_H #define SQUID_TESTSTORESUPPORT_H #include "EventLoop.h" #include "SquidTime.h" /* construct a stock loop with event dispatching, a time service that advances * 1 second a tick */ class StockEventLoop : public EventLoop { public: StockEventLoop(); TimeEngine default_time_engine; }; #endif /* SQUID_TESTSTORESUPPORT_H */
utf-8
1
unknown
unknown
libreoffice-7.3.1~rc1/vcl/inc/salusereventlist.hxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you 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 . */ #ifndef INCLUDED_VCL_INC_SALUSEREVENTLIST_HXX #define INCLUDED_VCL_INC_SALUSEREVENTLIST_HXX #include <sal/config.h> #include <vcl/dllapi.h> #include <osl/mutex.hxx> #include <osl/thread.hxx> #include <list> #include <o3tl/sorted_vector.hxx> class SalFrame; enum class SalEvent; typedef o3tl::sorted_vector< SalFrame* > SalFrameSet; class VCL_PLUGIN_PUBLIC SalUserEventList { public: struct SalUserEvent { SalFrame* m_pFrame; void* m_pData; SalEvent m_nEvent; SalUserEvent( SalFrame* pFrame, void* pData, SalEvent nEvent ) : m_pFrame( pFrame ), m_pData( pData ), m_nEvent( nEvent ) {} bool operator==(const SalUserEvent &aEvent) const { return m_pFrame == aEvent.m_pFrame && m_pData == aEvent.m_pData && m_nEvent== aEvent.m_nEvent; } }; protected: mutable osl::Mutex m_aUserEventsMutex; std::list< SalUserEvent > m_aUserEvents; std::list< SalUserEvent > m_aProcessingUserEvents; bool m_bAllUserEventProcessedSignaled; SalFrameSet m_aFrames; oslThreadIdentifier m_aProcessingThread; virtual void ProcessEvent( SalUserEvent aEvent ) = 0; virtual void TriggerUserEventProcessing() = 0; virtual void TriggerAllUserEventsProcessed() {} public: SalUserEventList(); virtual ~SalUserEventList() COVERITY_NOEXCEPT_FALSE; inline const SalFrameSet& getFrames() const; inline SalFrame* anyFrame() const; void insertFrame( SalFrame* pFrame ); void eraseFrame( SalFrame* pFrame ); inline bool isFrameAlive( const SalFrame* pFrame ) const; void PostEvent( SalFrame* pFrame, void* pData, SalEvent nEvent ); void RemoveEvent( SalFrame* pFrame, void* pData, SalEvent nEvent ); inline bool HasUserEvents() const; bool DispatchUserEvents( bool bHandleAllCurrentEvents ); }; inline SalFrame* SalUserEventList::anyFrame() const { if ( m_aFrames.empty() ) return nullptr; return *m_aFrames.begin(); } inline bool SalUserEventList::isFrameAlive( const SalFrame* pFrame ) const { auto it = m_aFrames.find( const_cast<SalFrame*>( pFrame ) ); return it != m_aFrames.end(); } inline bool SalUserEventList::HasUserEvents() const { osl::MutexGuard aGuard( m_aUserEventsMutex ); return !(m_aUserEvents.empty() && m_aProcessingUserEvents.empty()); } inline void SalUserEventList::PostEvent( SalFrame* pFrame, void* pData, SalEvent nEvent ) { osl::MutexGuard aGuard( m_aUserEventsMutex ); m_aUserEvents.push_back( SalUserEvent( pFrame, pData, nEvent ) ); m_bAllUserEventProcessedSignaled = false; TriggerUserEventProcessing(); } inline const SalFrameSet& SalUserEventList::getFrames() const { return m_aFrames; } #endif // INCLUDED_VCL_INC_SALUSEREVENTLIST_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
utf-8
1
MPL-2.0
Copyright 2000, 2010 Oracle and/or its affiliates. Copyright (c) 2000, 2010 LibreOffice contributors and/or their affiliates.
flightgear-2020.3.6+dfsg/src/FDM/JSBSim/input_output/FGGroundCallback.cpp
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Header: FGGroundCallback.cpp Author: Mathias Froehlich Date started: 05/21/04 ------ Copyright (C) 2004 Mathias Froehlich (Mathias.Froehlich@web.de) ------- This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. HISTORY ------------------------------------------------------------------------------- 05/21/00 MF Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SENTRY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "math/FGLocation.h" #include "FGGroundCallback.h" namespace JSBSim { //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGDefaultGroundCallback::GetAGLevel(double t, const FGLocation& loc, FGLocation& contact, FGColumnVector3& normal, FGColumnVector3& vel, FGColumnVector3& angularVel) const { vel.InitMatrix(); angularVel.InitMatrix(); normal = FGColumnVector3(loc).Normalize(); double loc_radius = loc.GetRadius(); // Get the radius of the given location // (e.g. the CG) double agl = loc_radius - mTerrainLevelRadius; contact = (mTerrainLevelRadius/loc_radius)*FGColumnVector3(loc); return agl; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% } // namespace JSBSim
utf-8
1
GPL-2+
1997-2012 Curtis L. Olson <curt@flightgear.org> 1997-1999 Christian Mayer - Vader@t-online.de 1997 Michele F. America [micheleamerica#geocities:com] 1999-2003 David Megginson, david@megginson.com 1999-2000 Anthony K. Peden (apeden@earthlink.net) 2000,2003,2008 Alexander R. Perry <alex.perry@ieee.org> 2000,2008-2011,2013-2015 James Turner - zakalawe@mac.com 2001-2003,2005,2010 David C Luff - daveluff AT ntlworld.com 2001 Tony Peden (apeden@earthlink.net) 2001 Steve Baker <sbaker@link.com> 2001-2003 Jim Wilson - jimw@kelcomaine.com 2002 Cameron Moore <cameron@unbeatenpath.net> 2003, 2005, 2006, 2008, 2009 Melchior FRANZ - mfranz@aon.at 2002-2005 Erik Hofman <erik@ehofman.com> 2003-2006 David P. Culp (davidculp2@comcast.net) 2003 Alexander Kappes and David Luff 2003 Manuel Bessler and Stephen Lowry 2003 Airservices Australia 2004-2012 Mathias Froehlich - Mathias.Froehlich@web.de 2004-2009 Vivain MEAZZA - vivian.meazza@lineone.net 1998,2004-2007,2009-2011 Durk Talsma 2004 Roy Vegard Ovesen - rvovesen@tiscali.no 2004 Aaron Wilson, Aaron.I.Wilson@nasa.gov 2004 Phillip Merritt, Phillip.M.Merritt@nasa.gov 2005-2006 Jean-Yves Lefort - jylefort@FreeBSD.org 2005 Harald JOHNSEN - hjohnsen@evc.net 2005 Gregor Richards 2005 Oliver Schroeder 2006 Stefan Seifert <nine@detonation.org> 2007,2008 Tim Moore timoore@redhat.com 2007 Csaba Halasz 2008 Nicolas VIVIEN 2008 GARMIN LTD. 2009-2011,2014-2015 Torsten Dreyer - Torsten (at) t3r (dot) de 2009 Patrice Poly p.polypa@gmail.com 2009 Tasuhiro Nishioka, tat <dot> fgmacosx <at> gmail <dot> com 2009 Frederic Bouvier <<fredfgfs01@free.fr> 2010-2013 Thorsten Brehm - brehmt (at) gmail com 2011 Bruce Hellstrom - http://www.celebritycc.com 2011-2012 Adrian Musceac 2012-2013 Thomas Geymayer <tomgey@gmail.com> 2013 Philosopher (Flightgear forums) 2013 Rebecca Palmer 2013 Clement de l'Hamaide - clemaez@hotmail.fr 2013 The FlightGear Community 2015 Stuart Buchanan <stuart_d_buchanan@yahoo.co.uk>
cdtool-2.1.8-release/util.h
#ifndef _UTIL_H #define _UTIL_H #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include "config.h" #include "cdtool.h" /* version string printed with usage message */ #define VERSION_STRING "CDTOOL " PACKAGE_VERSION \ " (c) 1994-2004 Thomas Insel, et al. Licensed under GPL." /* general definitions */ #ifndef TRUE #define TRUE (1==1) #endif #ifndef FALSE #define FALSE (1==0) #endif #define DOCRLF 2 #define DOLF 1 #define DONADA 0 #define BUGFOUND(x) bugfound(x, __FILE__, __FUNCTION__, __LINE__); extern int cdtool_show_crlf; extern int cdtool_show_verbose; extern int cdtool_show_debug; #ifndef HAVE_STRSEP char *strsep(char **stringp, const char *delim); #endif void debugmsg(char *fmt, ...); void errormsg(char *fmt, ...); void verbosemsg(char *fmt, ...); void infomsg(char *fmt, ...); void bugfound(char *message, char *file, char *function, int line); void show_permissions(char *device); void do_crlf(FILE *term); char *device_detect(char *choice); int is_device(char *path, int verbose); int checkmount(char *pszName); char *getprogname(void); char *setprogname(char *name); #endif
utf-8
1
GPL-2
1994 Thomas Insal 1995-1996 Sven Oliver Moll 1997-1998 Wade Hampton, Dan Risacher, Lin Zhe Min, Byron Ellacott, and the original authors 1999 Roland Rosenfeld and Mike Coleman 2000 Peter Samuelson 2001 Richard Kettlewell 2003 Josh Buhl 2004 Max Vozeler
viking-1.10/src/kml.c
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ /* * viking -- GPS Data and Topo Analyzer, Explorer, and Manager * * Copyright (C) 2020, Rob Norris <rw_norris@hotmail.com> * * 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; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "kml.h" #include "viking.h" #include <expat.h> #include "ctype.h" typedef struct { GString *c_cdata; gboolean use_cdata; gchar *name; gchar *desc; gboolean vis; gdouble timestamp; // Waypoints only VikTrwLayer *vtl; VikWaypoint *waypoint; VikTrack *track; VikTrackpoint *trackpoint; GList *tracks; // VikTracks GList *timestamps; // gdoubles GList *hrs; // guints GList *cads; // guints GList *temps; // gdoubles GQueue *gq_start; GQueue *gq_end; XML_Parser parser; } xml_data; static guint unnamed_waypoints = 0; static guint unnamed_tracks = 0; static guint unnamed_routes = 0; // Various helper functions static void parse_tag_reset ( xml_data *xd ) { XML_SetElementHandler ( xd->parser, (XML_StartElementHandler)g_queue_pop_head(xd->gq_start), (XML_EndElementHandler)g_queue_pop_head(xd->gq_end) ); } static void end_leaf_tag ( xml_data *xd ) { g_string_erase ( xd->c_cdata, 0, -1 ); xd->use_cdata = FALSE; XML_SetEndElementHandler ( xd->parser, (XML_EndElementHandler)g_queue_pop_head(xd->gq_end) ); } static void setup_to_read_next_level_tag ( xml_data *xd, gpointer old_start_func, gpointer old_end_func, gpointer new_start_func, gpointer new_end_func ) { if ( g_queue_peek_head(xd->gq_start) != old_start_func ) g_queue_push_head ( xd->gq_start, old_start_func ); if ( g_queue_peek_head(xd->gq_end) != old_end_func ) g_queue_push_head ( xd->gq_end, old_end_func ); XML_SetElementHandler ( xd->parser, (XML_StartElementHandler)new_start_func, (XML_EndElementHandler)new_end_func ); } static const char *get_attr ( const char **attr, const char *key ) { while ( *attr ) { if ( g_strcmp0(*attr,key) == 0 ) return *(attr + 1); attr += 2; } return NULL; } // Start of all the tag processing elements static void name_end ( xml_data *xd, const char *el ) { xd->name = g_strdup ( xd->c_cdata->str ); end_leaf_tag ( xd ); } static void description_end ( xml_data *xd, const char *el ) { xd->desc = g_strdup ( xd->c_cdata->str ); end_leaf_tag ( xd ); } static void visibility_end ( xml_data *xd, const char *el ) { xd->vis = TRUE; if ( g_strcmp0(xd->c_cdata->str, "0") == 0 ) xd->vis = FALSE; end_leaf_tag ( xd ); } // A tag which should only contain cdata (i.e. no further tags) static void setup_to_read_leaf_tag ( xml_data *xd, gpointer old_end_func, gpointer new_end_func ) { // Save old end function if different if ( g_queue_peek_head(xd->gq_end) != old_end_func ) g_queue_push_head ( xd->gq_end, old_end_func ); // Register new end function XML_SetEndElementHandler ( xd->parser, (XML_EndElementHandler)new_end_func ); // Clear buffer and turn on g_string_erase ( xd->c_cdata, 0, -1 ); xd->use_cdata = TRUE; } static void timestamp_when_end ( xml_data *xd, const char *el ) { GTimeVal gtv; if ( g_time_val_from_iso8601(xd->c_cdata->str, &gtv) ) { gdouble d1 = gtv.tv_sec; gdouble d2 = (gdouble)gtv.tv_usec/G_USEC_PER_SEC; xd->timestamp = (d1 < 0) ? d1 - d2 : d1 + d2; } end_leaf_tag ( xd ); } static void timestamp_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "TimeStamp" ) == 0 ) { parse_tag_reset ( xd ); } } static void timestamp_start ( xml_data *xd, const char *el, const char **attr ) { // Ignore 'extrude' and 'altitudeMode' if ( g_strcmp0 ( el, "when" ) == 0 ) { setup_to_read_leaf_tag ( xd, timestamp_end, timestamp_when_end ); } } static void set_vc_to_ll ( xml_data *xd, VikCoord *vc, VikTrwLayer *vtl, gdouble lat, gdouble lon ) { // Remember KML coordinates are the 'lon,lat(,alt)' order struct LatLon c_ll; if ( lat < -90.0 || lat > 90.0 ) { g_warning ( "%s: Invalid latitude value %f at line %ld", G_STRLOC, lat, XML_GetCurrentLineNumber(xd->parser) ); c_ll.lat = 0.0; } else c_ll.lat = lat; if ( lon < -180.0 || lon > 180.0 ) { g_warning ( "%s: Invalid longitude value %f at line %ld", G_STRLOC, lon, XML_GetCurrentLineNumber(xd->parser) ); c_ll.lon = 0.0; } else c_ll.lon = lon; vik_coord_load_from_latlon ( vc, vik_trw_layer_get_coord_mode(vtl), &c_ll ); } static void point_coordinates_end ( xml_data *xd, const char *el ) { if ( xd->waypoint ) { gchar **vals = g_strsplit ( xd->c_cdata->str, ",", -1 ); guint nn = g_strv_length ( vals ); if ( nn < 2 || nn > 3 ) g_warning ( "%s: expected 2 or 3 coordinate parts but got %d at line %ld", G_STRLOC, nn, XML_GetCurrentLineNumber(xd->parser) ); else { // Remember KML coordinates are the 'lon,lat(,alt)' order gdouble lat = g_ascii_strtod ( vals[1], NULL ); gdouble lon = g_ascii_strtod ( vals[0], NULL ); set_vc_to_ll ( xd, &(xd->waypoint->coord), xd->vtl, lat, lon ); if ( nn == 3 ) // ATM altitude is always interpreted to be in absolute mode (to sea level) xd->waypoint->altitude = g_ascii_strtod ( vals[2], NULL ); } g_strfreev ( vals ); } else g_warning ( "%s: no waypoint", G_STRLOC ); end_leaf_tag ( xd ); } static void point_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "Point" ) == 0 ) { if ( xd->waypoint ) { if ( xd->name && strlen(xd->name) > 0 ) { vik_waypoint_set_name ( xd->waypoint, xd->name ); } else { xd->waypoint->hide_name = TRUE; gchar *name = g_strdup_printf ( "WP%04d", unnamed_waypoints++ ); vik_waypoint_set_name ( xd->waypoint, name ); g_free ( name ); } if ( xd->desc ) { vik_waypoint_set_description ( xd->waypoint, xd->desc ); } xd->waypoint->visible = xd->vis; xd->waypoint->timestamp = xd->timestamp; vik_trw_layer_filein_add_waypoint ( xd->vtl, NULL, xd->waypoint ); } parse_tag_reset ( xd ); } } static void point_start ( xml_data *xd, const char *el, const char **attr ) { // Ignore 'extrude' and 'altitudeMode' if ( g_strcmp0 ( el, "coordinates" ) == 0 ) { setup_to_read_leaf_tag ( xd, point_end, point_coordinates_end ); } xd->waypoint = vik_waypoint_new(); } static void linestring_coordinates_end ( xml_data *xd, const char *el ) { if ( xd->track ) { gchar *ptr = xd->c_cdata->str; if ( ptr ) { int len = strlen(ptr); gchar *endptr = ptr + len; gchar *cp; for ( cp = ptr; cp < endptr; cp++ ) if ( !isspace(*cp) ) break; gboolean newseg = TRUE; int val = 0; gdouble values[3]; gchar *vp; for ( vp = cp; cp <= endptr; cp++ ) { if ( *cp == ',' ) { // Get string before this comma gchar *str = g_malloc0 ( cp-vp+1 ); strncpy ( str, vp, cp-vp ); values[val] = g_ascii_strtod ( str, NULL ); g_free ( str ); val++; vp = cp + 1; // +1 for the next one after the comma } else if ( cp == NULL || isspace(*cp) ) { if ( val < 1 || val > 2 ) // Not enough or too many coordinate parts goto end; // Otherwise the value is to end of text block // (should be the last coordinate part) gchar *str = g_malloc0 ( cp-vp+1 ); strncpy ( str, vp, cp-vp ); values[val] = g_ascii_strtod ( str, NULL ); g_free ( str ); VikTrackpoint *tp = vik_trackpoint_new(); // Remember KML coordinates are the 'lon,lat(,alt)' order set_vc_to_ll ( xd, &(tp->coord), xd->vtl, values[1], values[0] ); if ( val == 2 ) // ATM altitude is always interpreted to be in absolute mode (to sea level) tp->altitude = values[2]; if ( newseg ) { tp->newsegment = TRUE; newseg = FALSE; } xd->track->trackpoints = g_list_prepend ( xd->track->trackpoints, tp ); // Consume any extra space to get to the next coordinate part while ( cp != NULL && isspace(*cp) ) cp++; val = 0; vp = cp; } } } } else g_warning ( "%s: no track", G_STRLOC ); end: end_leaf_tag ( xd ); } static void linestring_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "LineString" ) == 0 ) { if ( xd->track ) { if ( xd->name && strlen(xd->name) > 0 ) { vik_track_set_name ( xd->track, xd->name ); } else { gchar *name = g_strdup_printf ( "TRK%04d", unnamed_tracks++ ); vik_track_set_name ( xd->track, name ); g_free ( name ); } if ( xd->desc ) { vik_track_set_description ( xd->track, xd->desc ); } xd->track->trackpoints = g_list_reverse ( xd->track->trackpoints ); xd->track->visible = xd->vis; vik_trw_layer_filein_add_track ( xd->vtl, NULL, xd->track ); } parse_tag_reset ( xd ); } } static void linestring_start ( xml_data *xd, const char *el, const char **attr ) { // ATM ignoring at least 'extrude', 'tessellate' & 'altitudeMode' if ( g_strcmp0 ( el, "coordinates" ) == 0 ) { setup_to_read_leaf_tag ( xd, linestring_end, linestring_coordinates_end ); } } // hardly any different to linestring handling static void linearring_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "LinearRing" ) == 0 ) { if ( xd->track ) { if ( xd->name && strlen(xd->name) > 0 ) { vik_track_set_name ( xd->track, xd->name ); } else { gchar *name = g_strdup_printf ( "TRK%04d", unnamed_tracks++ ); vik_track_set_name ( xd->track, name ); g_free ( name ); } if ( xd->desc ) { vik_track_set_description ( xd->track, xd->desc ); } xd->track->trackpoints = g_list_reverse ( xd->track->trackpoints ); vik_trw_layer_filein_add_track ( xd->vtl, NULL, xd->track ); } parse_tag_reset ( xd ); } } static void linearring_start ( xml_data *xd, const char *el, const char **attr ) { // ATM ignoring at least 'extrude', 'tessellate' & 'altitudeMode' if ( g_strcmp0 ( el, "coordinates" ) == 0 ) { setup_to_read_leaf_tag ( xd, linearring_end, linestring_coordinates_end ); } } static void placemark_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "Placemark" ) == 0 ) { // Reset xd->vis = TRUE; g_free ( xd->name ); xd->name = NULL; g_free ( xd->desc ); xd->desc = NULL; xd->timestamp = NAN; parse_tag_reset ( xd ); } } // For some unknown reason Track coordinates use a ' ' seperator, // whereas linestrings (and points) use a ',' static void track_coordinates_end ( xml_data *xd, const char *el ) { if ( xd->trackpoint && xd->track ) { gchar **vals = g_strsplit ( xd->c_cdata->str, " ", -1 ); guint nn = g_strv_length ( vals ); if ( nn < 2 || nn > 3 ) g_warning ( "%s: expected 2 or 3 coordinate parts but got %d at line %ld", G_STRLOC, nn, XML_GetCurrentLineNumber(xd->parser) ); else { // Remember KML coordinates are the 'lon,lat(,alt)' order gdouble lat = g_ascii_strtod ( vals[1], NULL ); gdouble lon = g_ascii_strtod ( vals[0], NULL ); set_vc_to_ll ( xd, &(xd->trackpoint->coord), xd->vtl, lat, lon ); if ( nn == 3 ) // ATM altitude is always interpreted to be in absolute mode (to sea level) xd->trackpoint->altitude = g_ascii_strtod ( vals[2], NULL ); xd->track->trackpoints = g_list_prepend ( xd->track->trackpoints, xd->trackpoint ); xd->track->visible = xd->vis; xd->vis = TRUE; } g_strfreev ( vals ); } else g_warning ( "%s: no trackpoint", G_STRLOC ); end_leaf_tag ( xd ); } static void track_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "gx:Track" ) == 0 ) { if ( xd->track ) { if ( xd->name && strlen(xd->name) > 0 ) { vik_track_set_name ( xd->track, xd->name ); g_free ( xd->name ); xd->name = NULL; } else { gchar *name = g_strdup_printf ( "TRK%04d", unnamed_tracks++ ); vik_track_set_name ( xd->track, name ); g_free ( name ); } if ( xd->desc ) { vik_track_set_description ( xd->track, xd->desc ); g_free ( xd->desc ); xd->desc = NULL; } xd->track->trackpoints = g_list_reverse ( xd->track->trackpoints ); xd->timestamps = g_list_reverse ( xd->timestamps ); xd->hrs = g_list_reverse ( xd->hrs ); xd->cads = g_list_reverse ( xd->cads ); xd->temps = g_list_reverse ( xd->temps ); gulong num_points = g_list_length ( xd->track->trackpoints ); // Assign times gulong ntimes = g_list_length ( xd->timestamps ); if ( ntimes ) { if ( ntimes == num_points ) { GList *lts = xd->timestamps; for (GList *ltp = xd->track->trackpoints; ltp != NULL; ltp = ltp->next ) { gdouble *dd = (gdouble*)lts->data; VIK_TRACKPOINT(ltp->data)->timestamp = *dd; lts = lts->next; } } else g_warning ( "%s: trackpoint count vs timestamp count differ %ld vs %ld at line %ld", G_STRLOC, num_points, ntimes, XML_GetCurrentLineNumber(xd->parser) ); } g_list_free_full ( xd->timestamps, g_free ); xd->timestamps = NULL; // Assign heart rate gulong nhrs = g_list_length ( xd->hrs ); if ( nhrs ) { if ( nhrs == num_points ) { GList *lts = xd->hrs; for (GList *ltp = xd->track->trackpoints; ltp != NULL; ltp = ltp->next ) { VIK_TRACKPOINT(ltp->data)->heart_rate = GPOINTER_TO_UINT(lts->data); lts = lts->next; } } else g_warning ( "%s: trackpoint count vs heart rate count differ %ld vs %ld at line %ld", G_STRLOC, num_points, nhrs, XML_GetCurrentLineNumber(xd->parser) ); } g_list_free ( xd->hrs ); // NB no data in list has been allocated // Assign cadence gulong ncads = g_list_length ( xd->cads ); if ( ncads ) { if ( ncads == num_points ) { GList *lts = xd->cads; for (GList *ltp = xd->track->trackpoints; ltp != NULL; ltp = ltp->next ) { VIK_TRACKPOINT(ltp->data)->cadence = GPOINTER_TO_UINT(lts->data); lts = lts->next; } } else g_warning ( "%s: trackpoint count vs cadence count differ %ld vs %ld at line %ld", G_STRLOC, num_points, ncads, XML_GetCurrentLineNumber(xd->parser) ); } g_list_free ( xd->cads ); // NB no data in list has been allocated // Assign temps gulong ntemps = g_list_length ( xd->temps ); if ( ntemps ) { if ( ntemps == num_points ) { GList *lts = xd->temps; for (GList *ltp = xd->track->trackpoints; ltp != NULL; ltp = ltp->next ) { gdouble *dd = (gdouble*)lts->data; VIK_TRACKPOINT(ltp->data)->temp = *dd; lts = lts->next; } } else g_warning ( "%s: trackpoint count vs temp count differ %ld vs %ld at line %ld", G_STRLOC, num_points, ntemps, XML_GetCurrentLineNumber(xd->parser) ); } g_list_free_full ( xd->temps, g_free ); xd->temps = NULL; // Set first (and only) segment VikTrackpoint *tpt = vik_track_get_tp_first ( xd->track ); if ( tpt ) tpt->newsegment = TRUE; // Add it or wait if reading multi tracks if ( !xd->tracks ) vik_trw_layer_filein_add_track ( xd->vtl, NULL, xd->track ); } parse_tag_reset ( xd ); } } // Tricky to reuse timestamp_when_end() // Since for tracks the <when></when> should be repeated for each trackpoint // so need to add to a list rather then a singular instance. static void track_when_end ( xml_data *xd, const char *el ) { gdouble *tt = g_malloc0 ( sizeof(gdouble) ); GTimeVal gtv; if ( g_time_val_from_iso8601(xd->c_cdata->str, &gtv) ) { gdouble d1 = gtv.tv_sec; gdouble d2 = (gdouble)gtv.tv_usec/G_USEC_PER_SEC; *tt = (d1 < 0) ? d1 - d2 : d1 + d2; } else { *tt = NAN; } xd->timestamps = g_list_prepend ( xd->timestamps, tt ); end_leaf_tag ( xd ); } static void value_cad_end ( xml_data *xd, const char *el ) { gdouble val = g_ascii_strtod ( xd->c_cdata->str, NULL ); guint ival; if ( isnan(val) ) ival = VIK_TRKPT_CADENCE_NONE; else ival = round ( val ); xd->cads = g_list_prepend ( xd->cads, GUINT_TO_POINTER(ival) ); end_leaf_tag ( xd ); } static void value_hr_end ( xml_data *xd, const char *el ) { gdouble val = g_ascii_strtod ( xd->c_cdata->str, NULL ); guint ival; if ( isnan(val) ) ival = 0; else ival = round ( val ); xd->hrs = g_list_prepend ( xd->hrs, GUINT_TO_POINTER(ival) ); end_leaf_tag ( xd ); } static void value_temp_end ( xml_data *xd, const char *el ) { gdouble *val = g_malloc0 ( sizeof(gdouble) ); *val = g_ascii_strtod ( xd->c_cdata->str, NULL ); xd->temps = g_list_prepend ( xd->temps, val ); end_leaf_tag ( xd ); } static void simplearraydata_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "gx:SimpleArrayData" ) == 0 ) parse_tag_reset ( xd ); } static void simplearraydata_cad_start ( xml_data *xd, const char *el, const char **attr ) { setup_to_read_leaf_tag ( xd, simplearraydata_end, value_cad_end ); } static void simplearraydata_hr_start ( xml_data *xd, const char *el, const char **attr ) { setup_to_read_leaf_tag ( xd, simplearraydata_end, value_hr_end ); } static void simplearraydata_temp_start ( xml_data *xd, const char *el, const char **attr ) { setup_to_read_leaf_tag ( xd, simplearraydata_end, value_temp_end ); } static void schemadata_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "SchemaData" ) == 0 ) parse_tag_reset ( xd ); } static void schemadata_start ( xml_data *xd, const char *el, const char **attr ) { // Looking for cadence or heartrate or temperature if ( g_strcmp0 ( el, "gx:SimpleArrayData" ) == 0 ) { const gchar *name = get_attr ( attr, "name" ); if ( g_strcmp0 ( name, "cadence" ) == 0 ) setup_to_read_next_level_tag ( xd, schemadata_start, schemadata_end, simplearraydata_cad_start, simplearraydata_end ); else if ( g_strcmp0 ( name, "heartrate" ) == 0 ) setup_to_read_next_level_tag ( xd, schemadata_start, schemadata_end, simplearraydata_hr_start, simplearraydata_end ); else if ( g_strcmp0 ( name, "temperature" ) == 0 ) setup_to_read_next_level_tag ( xd, schemadata_start, schemadata_end, simplearraydata_temp_start, simplearraydata_end ); } } static void extendeddata_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "ExtendedData" ) == 0 ) parse_tag_reset ( xd ); } static void extendeddata_start ( xml_data *xd, const char *el, const char **attr ) { if ( g_strcmp0 ( el, "SchemaData" ) == 0 ) setup_to_read_next_level_tag ( xd, extendeddata_start, extendeddata_end, schemadata_start, schemadata_end ); } static void track_start ( xml_data *xd, const char *el, const char **attr ) { // Ignore ''altitudeMode', 'gx:angles', 'Model' // Read values from when + ExtendedData into separate lists // merging into the main trackpoints list once the track end is reached if ( g_strcmp0 ( el, "gx:coord" ) == 0 ) { xd->trackpoint = vik_trackpoint_new(); setup_to_read_leaf_tag ( xd, track_end, track_coordinates_end ); } else if ( g_strcmp0 ( el, "when" ) == 0 ) { setup_to_read_leaf_tag ( xd, track_end, track_when_end ); } else if ( g_strcmp0 ( el, "ExtendedData" ) == 0 ) { setup_to_read_next_level_tag ( xd, track_start, track_end, extendeddata_start, extendeddata_end ); } } static void multitrack_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "gx:MultiTrack" ) == 0 ) { // Join tracks together (but keep segments) parse_tag_reset ( xd ); if ( xd->tracks ) { // Copy first track - so its not freed when the list of tracks are xd->track = vik_track_copy ( VIK_TRACK(xd->tracks->data), TRUE ); guint count = 1; for ( GList *gl = xd->tracks; gl != NULL; gl = gl->next ) { // Don't append the first track to itself if ( count > 1 ) { vik_track_steal_and_append_trackpoints ( xd->track, VIK_TRACK(gl->data) ); } count++; } vik_trw_layer_filein_add_track ( xd->vtl, NULL, xd->track ); xd->track = NULL; g_list_free_full ( xd->tracks, (GDestroyNotify)vik_track_free ); } } } static void multitrack_start ( xml_data *xd, const char *el, const char **attr ) { // Ignore ''altitudeMode', 'gx:interpolate' if ( g_strcmp0 ( el, "gx:Track" ) == 0 ) { setup_to_read_next_level_tag ( xd, multitrack_start, multitrack_end, track_start, track_end ); xd->track = vik_track_new(); xd->tracks = g_list_append ( xd->tracks, xd->track ); } } static void placemark_start ( xml_data *xd, const char *el, const char **attr ) { // NB ignores <MultiGeometry> levels and reads anything found in it anyway if ( g_strcmp0 ( el, "name" ) == 0 ) { setup_to_read_leaf_tag ( xd, placemark_end, name_end ); } else if ( g_strcmp0 ( el, "visibility" ) == 0 ) { setup_to_read_leaf_tag ( xd, placemark_end, visibility_end ); } else if ( g_strcmp0 ( el, "description" ) == 0 ) { setup_to_read_leaf_tag ( xd, placemark_end, description_end ); } else if ( g_strcmp0 ( el, "TimeStamp" ) == 0 ) { setup_to_read_next_level_tag ( xd, placemark_start, placemark_end, timestamp_start, timestamp_end ); } else if ( g_strcmp0 ( el, "Point" ) == 0 ) { setup_to_read_next_level_tag ( xd, placemark_start, placemark_end, point_start, point_end ); } else if ( g_strcmp0 ( el, "LineString" ) == 0 ) { setup_to_read_next_level_tag ( xd, placemark_start, placemark_end, linestring_start, linestring_end ); xd->track = vik_track_new(); xd->track->is_route = TRUE; } else if ( g_strcmp0 ( el, "LinearRing" ) == 0 ) { setup_to_read_next_level_tag ( xd, placemark_start, placemark_end, linearring_start, linearring_end ); xd->track = vik_track_new(); xd->track->is_route = TRUE; } else if ( g_strcmp0 ( el, "gx:Track" ) == 0 ) { setup_to_read_next_level_tag ( xd, placemark_start, placemark_end, track_start, track_end ); xd->track = vik_track_new(); } else if ( g_strcmp0 ( el, "gx:MultiTrack" ) == 0 ) { setup_to_read_next_level_tag ( xd, placemark_start, placemark_end, multitrack_start, multitrack_end ); } } static void top_end ( xml_data *xd, const char *el ) { if ( g_strcmp0 ( el, "kml" ) == 0 ) XML_SetEndElementHandler ( xd->parser, (XML_EndElementHandler)g_queue_pop_head(xd->gq_end) ); } static void top_start ( xml_data *xd, const char *el, const char **attr ) { // NB also finds Placemarks whereever they may be in Document or Folder levels as well if ( g_strcmp0 ( el, "Placemark" ) == 0 ) setup_to_read_next_level_tag ( xd, top_start, top_end, placemark_start, placemark_end ); } static void kml_start ( xml_data *xd, const char *el, const char **attr ) { if ( g_strcmp0 ( el, "kml" ) ) XML_StopParser ( xd->parser, XML_FALSE ); XML_SetStartElementHandler ( xd->parser, (XML_StartElementHandler)top_start ); } static void kml_end ( xml_data *xd, const char *el ) { g_debug ( G_STRLOC ); } static void kml_cdata ( xml_data *xd, const XML_Char *ss, int len ) { if ( xd->use_cdata ) { g_string_append_len ( xd->c_cdata, ss, len ); } } /** * a_kml_read_file: * @FILE: The KML file to open * @VikTrwLayer: The Layer to put the geo data in * * Returns: * TRUE on success */ gboolean a_kml_read_file ( VikTrwLayer *vtl, FILE *ff ) { gchar buffer[4096]; XML_Parser parser = XML_ParserCreate(NULL); enum XML_Status status = XML_STATUS_ERROR; unnamed_waypoints = 1; unnamed_tracks = 1; unnamed_routes = 1; xml_data *xd = g_malloc0 ( sizeof (xml_data) ); // Set default values; xd->c_cdata = g_string_new ( "" ); xd->vis = TRUE; xd->timestamp = NAN; xd->vtl = vtl; xd->gq_start = g_queue_new(); xd->gq_end = g_queue_new(); xd->parser = parser; // Always force V1.1, since we may read in 'extended' data like cadence, etc... vik_trw_layer_set_gpx_version ( vtl, GPX_V1_1 ); // The premise of handling tags is thar for each level down the xml tree, // we use an appropriate handler for that tag // (which knows how to process the data being read in at that point) // And then when the end of the tag is reached, restore the previously active tag handlers g_queue_push_head ( xd->gq_start, kml_start ); g_queue_push_head ( xd->gq_end, kml_end ); XML_SetElementHandler ( parser, (XML_StartElementHandler)kml_start, (XML_EndElementHandler)kml_end ); XML_SetUserData ( parser, xd ); XML_SetCharacterDataHandler ( parser, (XML_CharacterDataHandler)kml_cdata); int done=0, len; while ( !done ) { len = fread ( buffer, 1, sizeof(buffer)-7, ff ); done = feof ( ff ) || !len; status = XML_Parse ( parser, buffer, len, done ); } gboolean ans = (status != XML_STATUS_ERROR); if ( !ans ) { g_warning ( "%s: XML error %s at line %ld", G_STRLOC, XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser) ); } XML_ParserFree ( parser ); g_queue_free ( xd->gq_start ); g_queue_free ( xd->gq_end ); g_string_free ( xd->c_cdata, TRUE ); g_free ( xd ); return ans; }
utf-8
1
unknown
unknown
cctbx-2021.12+ds1/cbflib_adaptbx/detectors/buffer_based_service.cpp
#include <vector> #include <cbflib_adaptbx/detectors/buffer_based_service.h> namespace ide = iotbx::detectors; /* FIXME should add same functions to work for UNSIGNED values */ //Code contributed by Graeme Winter, Diamond Light Source: typedef union { char b[2]; short s; } u_s; typedef union { char b[4]; int i; } u_i; // functions for byte swapping void byte_swap_short(char * b) { char c; c = b[0]; b[0] = b[1]; b[1] = c; return; } void byte_swap_int(char * b) { char c; c = b[0]; b[0] = b[3]; b[3] = c; c = b[1]; b[1] = b[2]; b[2] = c; return; } // helper function: is this machine little endian? CBF files are bool little_endian() { int i = 0x1; char b = ((u_i *) &i)[0].b[0]; if (b == 0) { return false; } else { return true; } } //main functions //In order to return void, calling function would have to allocate extra memory // and then resize after the call...Redesign along these lines if it becomes necessary std::vector<char> ide::buffer_compress(const int* values, const std::size_t& sz) { std::vector<char> packed(0); int current = 0; int delta, i; unsigned int j; bool le = little_endian(); short s; char c; char * b; for (j = 0; j < sz; j++) { delta = values[j] - current; if ((-127 <= delta) && (delta < 128)) { c = (char) delta; packed.push_back(c); current += delta; continue; } packed.push_back(-128); if ((-32767 <= delta) && (delta < 32768)) { s = (short) delta; b = ((u_s *) & s)[0].b; if (!le) { byte_swap_short(b); } packed.push_back(b[0]); packed.push_back(b[1]); current += delta; continue; } s = -32768; b = ((u_s *) & s)[0].b; if (!le) { byte_swap_short(b); } packed.push_back(b[0]); packed.push_back(b[1]); if ((-2147483647 <= delta) && (delta <= 2147483647)) { i = delta; b = ((u_i *) & i)[0].b; if (!le) { byte_swap_int(b); } packed.push_back(b[0]); packed.push_back(b[1]); packed.push_back(b[2]); packed.push_back(b[3]); current += delta; continue; } /* FIXME I should not get here */ //fail silently or throw an exception? } return packed; } void ide::buffer_uncompress(const char* packed, std::size_t packed_sz, int* values) { int current = 0; unsigned int j = 0; short s; char c; int i; bool le = little_endian(); while (j < packed_sz) { c = packed[j]; j += 1; if (c != -128) { current += c; *values=current; values++; continue; } ((u_s *) & s)[0].b[0] = packed[j]; ((u_s *) & s)[0].b[1] = packed[j + 1]; j += 2; if (!le) { byte_swap_short((char *) &s); } if (s != -32768) { current += s; *values=current; values++; continue; } ((u_i *) & i)[0].b[0] = packed[j]; ((u_i *) & i)[0].b[1] = packed[j + 1]; ((u_i *) & i)[0].b[2] = packed[j + 2]; ((u_i *) & i)[0].b[3] = packed[j + 3]; j += 4; if (!le) { byte_swap_int((char *) &i); } current += i; *values=current; values++; } }
utf-8
1
BSD-3-clause
2006-2018 The Regents of the University of California, through Lawrence Berkeley National Laboratory 2005 Jacob N. Smith, Erik Mckee, Texas Agricultural 2005 Jacob N. Smith & Erik McKee 2013 Sunset Lake Software 2013-2015 Diamond Light Source 2005-2009 Jim Idle, Temporal Wave LLC 2013 Diamond Light Source, James Parkhurst & Richard Gildea 2016 STFC Rutherford Appleton Laboratory, UK. 1996 John Wiley & Sons, Inc. 2016 Lawrence Berkeley National Laboratory (LBNL) 2007-2011 Jeffrey J. Headd and Robert Immormino 2005-2009 Jim Idle, Temporal Wave LLC 2010 University of California
scummvm-2.5.1+dfsg/engines/grim/costume/model_component.cpp
/* ResidualVM - A 3D game interpreter * * ResidualVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "engines/grim/debug.h" #include "engines/grim/model.h" #include "engines/grim/resource.h" #include "engines/grim/grim.h" #include "engines/grim/set.h" #include "engines/grim/gfx_base.h" #include "engines/grim/colormap.h" #include "engines/grim/animation.h" #include "engines/grim/costume/model_component.h" #include "engines/grim/costume/main_model_component.h" #include "engines/grim/costume/mesh_component.h" namespace Grim { #define DEFAULT_COLORMAP "item.cmp" ModelComponent::ModelComponent(Component *p, int parentID, const char *filename, Component *prevComponent, tag32 t) : Component(p, parentID, filename, t), _obj(nullptr), _hier(nullptr), _animation(nullptr), _animated(false) { const char *comma = strchr(filename, ','); // Can be called with a comma and a numeric parameter afterward, but // the use for this parameter is currently unknown // Example: At the "scrimshaw parlor" in Rubacava the object // "manny_cafe.3do,1" is requested if (comma) { _name = Common::String(filename, comma); warning("Comma in model components not supported: %s", filename); } _prevComp = prevComponent; } ModelComponent::~ModelComponent() { if (_hier && _hier->_parent) { _hier->_parent->removeChild(_hier); } delete _obj; delete _animation; } void ModelComponent::init() { if (_prevComp && _prevComp->isComponentType('M','M','D','L')) { _previousCmap = _prevComp->getCMap(); } // Skip loading if it was initialized // by the sharing MainModelComponent // constructor before if (!_obj) { CMapPtr cm = getCMap(); // Get the default colormap if we haven't found // a valid colormap if (!cm && g_grim->getCurrSet()) cm = g_grim->getCurrSet()->getCMap(); if (!cm) { Debug::warning(Debug::Costumes, "No colormap specified for %s, using %s", _name.c_str(), DEFAULT_COLORMAP); cm = g_resourceloader->getColormap(DEFAULT_COLORMAP); } // If we're the child of a mesh component, put our nodes in the // parent object's tree. if (_parent) { MeshComponent *mc = static_cast<MeshComponent *>(_parent); _obj = g_resourceloader->loadModel(_name, cm, mc->getModel()); _hier = _obj->getHierarchy(); mc->getNode()->addChild(_hier); } else { _obj = g_resourceloader->loadModel(_name, cm); _hier = _obj->getHierarchy(); Debug::warning(Debug::Costumes, "Parent of model %s wasn't a mesh", _name.c_str()); } // Use parent availablity to decide whether to default the // component to being visible if (_parent) setKey(0); else setKey(1); } if (!_animation) { _animation = new AnimManager(); } } void ModelComponent::setKey(int val) { _visible = (val != 0); _hier->_hierVisible = _visible; } void ModelComponent::reset() { _visible = false; _hier->_hierVisible = _visible; } AnimManager *ModelComponent::getAnimManager() const { return _animation; } int ModelComponent::update(uint time) { // First reset the current animation. for (int i = 0; i < getNumNodes(); i++) { _hier[i]._animPos = _hier[i]._pos; _hier[i]._animRot = _hier[i]._rot; } _animated = false; return 0; } void ModelComponent::animate() { if (_animated) { return; } _animation->animate(_hier, getNumNodes()); _animated = true; } void ModelComponent::resetColormap() { CMap *cm; cm = getCMap(); if (_obj && cm) _obj->reload(cm); } void ModelComponent::restoreState(SaveGame *state) { _hier->_hierVisible = _visible; } int ModelComponent::getNumNodes() { return _obj->getNumNodes(); } void ModelComponent::translateObject(ModelNode *node, bool reset) { if (node->_parent) translateObject(node->_parent, reset); if (reset) { node->translateViewpointFinish(); } else { node->translateViewpointStart(); node->translateViewpoint(); } } void ModelComponent::translateObject(bool res) { ModelNode *node = _hier->_parent; if (node) { translateObject(node, res); } } void ModelComponent::draw() { // If the object was drawn by being a component // of it's parent then don't draw it if (_parent && _parent->isVisible()) return; // Need to translate object to be in accordance // with the setup of the parent translateObject(false); _hier->draw(); // Need to un-translate when done translateObject(true); } void ModelComponent::getBoundingBox(int *x1, int *y1, int *x2, int *y2) { // If the object was drawn by being a component // of it's parent then don't draw it if (_parent && _parent->isVisible()) return; // Need to translate object to be in accordance // with the setup of the parent translateObject(false); _hier->getBoundingBox(x1, y1, x2, y2); // Need to un-translate when done translateObject(true); } } // end of namespace Grim
utf-8
1
GPL-2+
2001-2021 The ScummVM Project The ScummVM Team 2002-2011 The DOSBox Team 1994-1998 Revolution Software Ltd. 2001-2004 Andrea Mazzoleni 2003-2005 Andreas 'Sprawl' Karlsso 2002-2008 Jurgen 'SumthinWicked' Braam 2003-2014 Lars 'AnotherGuest' Persso 2013-2020 Fedor Strizhniou 1990-2012 Neil Dodwell 1995-1997 Presto Studios, Inc. and others listed in COPYRIGHT file
libimobiledevice-1.3.0/tools/ideviceimagemounter.c
/* * ideviceimagemounter.c * Mount developer/debug disk images on the device * * Copyright (C) 2010 Nikias Bassen <nikias@gmx.li> * * 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 */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #define TOOL_NAME "ideviceimagemounter" #include <stdlib.h> #define _GNU_SOURCE 1 #define __USE_GNU 1 #include <stdio.h> #include <string.h> #include <getopt.h> #include <errno.h> #include <libgen.h> #include <time.h> #include <sys/time.h> #include <inttypes.h> #ifndef WIN32 #include <signal.h> #endif #include <libimobiledevice/libimobiledevice.h> #include <libimobiledevice/lockdown.h> #include <libimobiledevice/afc.h> #include <libimobiledevice/notification_proxy.h> #include <libimobiledevice/mobile_image_mounter.h> #include <asprintf.h> #include "common/utils.h" static int list_mode = 0; static int use_network = 0; static int xml_mode = 0; static const char *udid = NULL; static const char *imagetype = NULL; static const char PKG_PATH[] = "PublicStaging"; static const char PATH_PREFIX[] = "/private/var/mobile/Media"; typedef enum { DISK_IMAGE_UPLOAD_TYPE_AFC, DISK_IMAGE_UPLOAD_TYPE_UPLOAD_IMAGE } disk_image_upload_type_t; static void print_usage(int argc, char **argv) { char *name = NULL; name = strrchr(argv[0], '/'); printf("Usage: %s [OPTIONS] IMAGE_FILE IMAGE_SIGNATURE_FILE\n", (name ? name + 1: argv[0])); printf("\n"); printf("Mounts the specified disk image on the device.\n"); printf("\n"); printf("OPTIONS:\n"); printf(" -u, --udid UDID\ttarget specific device by UDID\n"); printf(" -n, --network\t\tconnect to network device\n"); printf(" -l, --list\t\tList mount information\n"); printf(" -t, --imagetype\tImage type to use, default is 'Developer'\n"); printf(" -x, --xml\t\tUse XML output\n"); printf(" -d, --debug\t\tenable communication debugging\n"); printf(" -h, --help\t\tprints usage information\n"); printf(" -v, --version\t\tprints version information\n"); printf("\n"); printf("Homepage: <" PACKAGE_URL ">\n"); printf("Bug Reports: <" PACKAGE_BUGREPORT ">\n"); } static void parse_opts(int argc, char **argv) { static struct option longopts[] = { { "help", no_argument, NULL, 'h' }, { "udid", required_argument, NULL, 'u' }, { "network", no_argument, NULL, 'n' }, { "list", no_argument, NULL, 'l' }, { "imagetype", required_argument, NULL, 't' }, { "xml", no_argument, NULL, 'x' }, { "debug", no_argument, NULL, 'd' }, { "version", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; int c; while (1) { c = getopt_long(argc, argv, "hu:lt:xdnv", longopts, NULL); if (c == -1) { break; } switch (c) { case 'h': print_usage(argc, argv); exit(0); case 'u': if (!*optarg) { fprintf(stderr, "ERROR: UDID must not be empty!\n"); print_usage(argc, argv); exit(2); } udid = optarg; break; case 'n': use_network = 1; break; case 'l': list_mode = 1; break; case 't': imagetype = optarg; break; case 'x': xml_mode = 1; break; case 'd': idevice_set_debug_level(1); break; case 'v': printf("%s %s\n", TOOL_NAME, PACKAGE_VERSION); exit(0); default: print_usage(argc, argv); exit(2); } } } static void print_xml(plist_t node) { char *xml = NULL; uint32_t len = 0; plist_to_xml(node, &xml, &len); if (xml) puts(xml); } static ssize_t mim_upload_cb(void* buf, size_t size, void* userdata) { return fread(buf, 1, size, (FILE*)userdata); } int main(int argc, char **argv) { idevice_t device = NULL; lockdownd_client_t lckd = NULL; lockdownd_error_t ldret = LOCKDOWN_E_UNKNOWN_ERROR; mobile_image_mounter_client_t mim = NULL; afc_client_t afc = NULL; lockdownd_service_descriptor_t service = NULL; int res = -1; char *image_path = NULL; size_t image_size = 0; char *image_sig_path = NULL; #ifndef WIN32 signal(SIGPIPE, SIG_IGN); #endif parse_opts(argc, argv); argc -= optind; argv += optind; if (!list_mode) { if (argc < 1) { printf("ERROR: No IMAGE_FILE has been given!\n"); return -1; } image_path = strdup(argv[0]); if (argc >= 2) { image_sig_path = strdup(argv[1]); } else { if (asprintf(&image_sig_path, "%s.signature", image_path) < 0) { printf("Out of memory?!\n"); return -1; } } } if (IDEVICE_E_SUCCESS != idevice_new_with_options(&device, udid, (use_network) ? IDEVICE_LOOKUP_NETWORK : IDEVICE_LOOKUP_USBMUX)) { if (udid) { printf("No device found with udid %s.\n", udid); } else { printf("No device found.\n"); } return -1; } if (LOCKDOWN_E_SUCCESS != (ldret = lockdownd_client_new_with_handshake(device, &lckd, TOOL_NAME))) { printf("ERROR: Could not connect to lockdown, error code %d.\n", ldret); goto leave; } plist_t pver = NULL; char *product_version = NULL; lockdownd_get_value(lckd, NULL, "ProductVersion", &pver); if (pver && plist_get_node_type(pver) == PLIST_STRING) { plist_get_string_val(pver, &product_version); } disk_image_upload_type_t disk_image_upload_type = DISK_IMAGE_UPLOAD_TYPE_AFC; int product_version_major = 0; int product_version_minor = 0; if (product_version) { if (sscanf(product_version, "%d.%d.%*d", &product_version_major, &product_version_minor) == 2) { if (product_version_major >= 7) disk_image_upload_type = DISK_IMAGE_UPLOAD_TYPE_UPLOAD_IMAGE; } } lockdownd_start_service(lckd, "com.apple.mobile.mobile_image_mounter", &service); if (!service || service->port == 0) { printf("ERROR: Could not start mobile_image_mounter service!\n"); goto leave; } if (mobile_image_mounter_new(device, service, &mim) != MOBILE_IMAGE_MOUNTER_E_SUCCESS) { printf("ERROR: Could not connect to mobile_image_mounter!\n"); goto leave; } if (service) { lockdownd_service_descriptor_free(service); service = NULL; } if (!list_mode) { struct stat fst; if (disk_image_upload_type == DISK_IMAGE_UPLOAD_TYPE_AFC) { if ((lockdownd_start_service(lckd, "com.apple.afc", &service) != LOCKDOWN_E_SUCCESS) || !service || !service->port) { fprintf(stderr, "Could not start com.apple.afc!\n"); goto leave; } if (afc_client_new(device, service, &afc) != AFC_E_SUCCESS) { fprintf(stderr, "Could not connect to AFC!\n"); goto leave; } if (service) { lockdownd_service_descriptor_free(service); service = NULL; } } if (stat(image_path, &fst) != 0) { fprintf(stderr, "ERROR: stat: %s: %s\n", image_path, strerror(errno)); goto leave; } image_size = fst.st_size; if (stat(image_sig_path, &fst) != 0) { fprintf(stderr, "ERROR: stat: %s: %s\n", image_sig_path, strerror(errno)); goto leave; } } lockdownd_client_free(lckd); lckd = NULL; mobile_image_mounter_error_t err = MOBILE_IMAGE_MOUNTER_E_UNKNOWN_ERROR; plist_t result = NULL; if (list_mode) { /* list mounts mode */ if (!imagetype) { imagetype = "Developer"; } err = mobile_image_mounter_lookup_image(mim, imagetype, &result); if (err == MOBILE_IMAGE_MOUNTER_E_SUCCESS) { res = 0; if (xml_mode) { print_xml(result); } else { plist_print_to_stream(result, stdout); } } else { printf("Error: lookup_image returned %d\n", err); } } else { char sig[8192]; size_t sig_length = 0; FILE *f = fopen(image_sig_path, "rb"); if (!f) { fprintf(stderr, "Error opening signature file '%s': %s\n", image_sig_path, strerror(errno)); goto leave; } sig_length = fread(sig, 1, sizeof(sig), f); fclose(f); if (sig_length == 0) { fprintf(stderr, "Could not read signature from file '%s'\n", image_sig_path); goto leave; } f = fopen(image_path, "rb"); if (!f) { fprintf(stderr, "Error opening image file '%s': %s\n", image_path, strerror(errno)); goto leave; } char *targetname = NULL; if (asprintf(&targetname, "%s/%s", PKG_PATH, "staging.dimage") < 0) { fprintf(stderr, "Out of memory!?\n"); goto leave; } char *mountname = NULL; if (asprintf(&mountname, "%s/%s", PATH_PREFIX, targetname) < 0) { fprintf(stderr, "Out of memory!?\n"); goto leave; } if (!imagetype) { imagetype = "Developer"; } switch(disk_image_upload_type) { case DISK_IMAGE_UPLOAD_TYPE_UPLOAD_IMAGE: printf("Uploading %s\n", image_path); err = mobile_image_mounter_upload_image(mim, imagetype, image_size, sig, sig_length, mim_upload_cb, f); break; case DISK_IMAGE_UPLOAD_TYPE_AFC: default: printf("Uploading %s --> afc:///%s\n", image_path, targetname); char **strs = NULL; if (afc_get_file_info(afc, PKG_PATH, &strs) != AFC_E_SUCCESS) { if (afc_make_directory(afc, PKG_PATH) != AFC_E_SUCCESS) { fprintf(stderr, "WARNING: Could not create directory '%s' on device!\n", PKG_PATH); } } if (strs) { int i = 0; while (strs[i]) { free(strs[i]); i++; } free(strs); } uint64_t af = 0; if ((afc_file_open(afc, targetname, AFC_FOPEN_WRONLY, &af) != AFC_E_SUCCESS) || !af) { fclose(f); fprintf(stderr, "afc_file_open on '%s' failed!\n", targetname); goto leave; } char buf[8192]; size_t amount = 0; do { amount = fread(buf, 1, sizeof(buf), f); if (amount > 0) { uint32_t written, total = 0; while (total < amount) { written = 0; if (afc_file_write(afc, af, buf + total, amount - total, &written) != AFC_E_SUCCESS) { fprintf(stderr, "AFC Write error!\n"); break; } total += written; } if (total != amount) { fprintf(stderr, "Error: wrote only %d of %d\n", total, (unsigned int)amount); afc_file_close(afc, af); fclose(f); goto leave; } } } while (amount > 0); afc_file_close(afc, af); break; } fclose(f); if (err != MOBILE_IMAGE_MOUNTER_E_SUCCESS) { if (err == MOBILE_IMAGE_MOUNTER_E_DEVICE_LOCKED) { printf("ERROR: Device is locked, can't mount. Unlock device and try again.\n"); } else { printf("ERROR: Unknown error occurred, can't mount.\n"); } goto error_out; } printf("done.\n"); printf("Mounting...\n"); err = mobile_image_mounter_mount_image(mim, mountname, sig, sig_length, imagetype, &result); if (err == MOBILE_IMAGE_MOUNTER_E_SUCCESS) { if (result) { plist_t node = plist_dict_get_item(result, "Status"); if (node) { char *status = NULL; plist_get_string_val(node, &status); if (status) { if (!strcmp(status, "Complete")) { printf("Done.\n"); res = 0; } else { printf("unexpected status value:\n"); if (xml_mode) { print_xml(result); } else { plist_print_to_stream(result, stdout); } } free(status); } else { printf("unexpected result:\n"); if (xml_mode) { print_xml(result); } else { plist_print_to_stream(result, stdout); } } } node = plist_dict_get_item(result, "Error"); if (node) { char *error = NULL; plist_get_string_val(node, &error); if (error) { printf("Error: %s\n", error); free(error); } else { printf("unexpected result:\n"); if (xml_mode) { print_xml(result); } else { plist_print_to_stream(result, stdout); } } } else { if (xml_mode) { print_xml(result); } else { plist_print_to_stream(result, stdout); } } } } else { printf("Error: mount_image returned %d\n", err); } } if (result) { plist_free(result); } error_out: /* perform hangup command */ mobile_image_mounter_hangup(mim); /* free client */ mobile_image_mounter_free(mim); leave: if (afc) { afc_client_free(afc); } if (lckd) { lockdownd_client_free(lckd); } idevice_free(device); if (image_path) free(image_path); if (image_sig_path) free(image_sig_path); return res; }
utf-8
1
LGPL-2.1+
© 2008-2019 libimobiledevice contributors
qtwebkit-opensource-src-5.212.0~alpha4/Source/JavaScriptCore/API/JSBase.h
/* * Copyright (C) 2006 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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. */ #ifndef JSBase_h #define JSBase_h #ifndef __cplusplus #include <stdbool.h> #endif #ifdef __OBJC__ #import <Foundation/Foundation.h> #endif /* JavaScript engine interface */ /*! @typedef JSContextGroupRef A group that associates JavaScript contexts with one another. Contexts in the same group may share and exchange JavaScript objects. */ typedef const struct OpaqueJSContextGroup* JSContextGroupRef; /*! @typedef JSContextRef A JavaScript execution context. Holds the global object and other execution state. */ typedef const struct OpaqueJSContext* JSContextRef; /*! @typedef JSGlobalContextRef A global JavaScript execution context. A JSGlobalContext is a JSContext. */ typedef struct OpaqueJSContext* JSGlobalContextRef; /*! @typedef JSStringRef A UTF16 character buffer. The fundamental string representation in JavaScript. */ typedef struct OpaqueJSString* JSStringRef; /*! @typedef JSClassRef A JavaScript class. Used with JSObjectMake to construct objects with custom behavior. */ typedef struct OpaqueJSClass* JSClassRef; /*! @typedef JSPropertyNameArrayRef An array of JavaScript property names. */ typedef struct OpaqueJSPropertyNameArray* JSPropertyNameArrayRef; /*! @typedef JSPropertyNameAccumulatorRef An ordered set used to collect the names of a JavaScript object's properties. */ typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef; /* JavaScript data types */ /*! @typedef JSValueRef A JavaScript value. The base type for all JavaScript values, and polymorphic functions on them. */ typedef const struct OpaqueJSValue* JSValueRef; /*! @typedef JSObjectRef A JavaScript object. A JSObject is a JSValue. */ typedef struct OpaqueJSValue* JSObjectRef; /* JavaScript symbol exports */ /* These rules should stay the same as in WebKit2/Shared/API/c/WKBase.h */ #undef JS_EXPORT #if defined(JS_NO_EXPORT) #define JS_EXPORT #elif defined(__GNUC__) && !defined(__CC_ARM) && !defined(__ARMCC__) #define JS_EXPORT __attribute__((visibility("default"))) #elif defined(WIN32) || defined(_WIN32) || defined(_WIN32_WCE) || defined(__CC_ARM) || defined(__ARMCC__) #if defined(BUILDING_JavaScriptCore) || defined(STATICALLY_LINKED_WITH_JavaScriptCore) #define JS_EXPORT __declspec(dllexport) #else #define JS_EXPORT __declspec(dllimport) #endif #else /* !defined(JS_NO_EXPORT) */ #define JS_EXPORT #endif /* defined(JS_NO_EXPORT) */ #ifdef __cplusplus extern "C" { #endif /* Script Evaluation */ /*! @function JSEvaluateScript @abstract Evaluates a string of JavaScript. @param ctx The execution context to use. @param script A JSString containing the script to evaluate. @param thisObject The object to use as "this," or NULL to use the global object as "this." @param sourceURL A JSString containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information. @param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1. @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception. @result The JSValue that results from evaluating script, or NULL if an exception is thrown. */ JS_EXPORT JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception); /*! @function JSCheckScriptSyntax @abstract Checks for syntax errors in a string of JavaScript. @param ctx The execution context to use. @param script A JSString containing the script to check for syntax errors. @param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions. @param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1. @param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception. @result true if the script is syntactically correct, otherwise false. */ JS_EXPORT bool JSCheckScriptSyntax(JSContextRef ctx, JSStringRef script, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception); /*! @function JSGarbageCollect @abstract Performs a JavaScript garbage collection. @param ctx The execution context to use. @discussion JavaScript values that are on the machine stack, in a register, protected by JSValueProtect, set as the global object of an execution context, or reachable from any such value will not be collected. During JavaScript execution, you are not required to call this function; the JavaScript engine will garbage collect as needed. JavaScript values created within a context group are automatically destroyed when the last reference to the context group is released. */ JS_EXPORT void JSGarbageCollect(JSContextRef ctx); #ifdef __cplusplus } #endif /* Enable the Objective-C API for platforms with a modern runtime. */ #if !defined(JSC_OBJC_API_ENABLED) #define JSC_OBJC_API_ENABLED (defined(__clang__) && defined(__APPLE__) && ((defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && !defined(__i386__)) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE))) #endif #endif /* JSBase_h */
utf-8
1
BSD-2-clause
2013, Adenilson Cavalcanti <cavalcantii@gmail.com> 2013, Adobe Systems Incorporated 2006, Alexey Proskuryakov <ap@webkit.org> 2010, Andras Becsi (abecsi@inf.u-szeged.hu), University of Szeged 2011, Andreas Kling <kling@webkit.org> 2013, Andrew Bortz 2008-2009, Anthony Ricaud <rik@webkit.org> 2014, Antoine Quint 2003-2016, Apple Inc 2011, Benjamin Poulain <benjamin@webkit.org> 2011, Brian Grinstead 2015, Canon Inc 2013, Cisco Systems, Inc 2010-2014, Collabora Ltd 2012-2013, Company 100, Inc 2015-2016, Devin Rousso <dcrousso+webkit@gmail.com> 2006, Dirk Mueller <mueller@kde.org> 2015, Electronic Arts, Inc 2011, Gabor Loki <loki@webkit.org> 2006, George Staikos <staikos@kde.org> 2009, Girish Ramakrishnan <girish@forwardbias.in> 2005-2013, Google Inc 2012, Hewlett-Packard Development Company, L.P 2009, Holger Hans Peter Freyther 2011-2016, Igalia S.L 2012-2013, Intel Corporation 2009-2010, Joseph Pecoraro 2010, Juha Savolainen <juha.savolainen@weego.fi> 2007, Justin Haygood <jhaygood@reaktix.com> 2016-2017, Konstantin Tokarev <annulen@yandex.ru> 2011, Kristof Kosztyo <Kosztyo.Kristof@stud.u-szeged.hu> 2013, Matt Holden <jftholden@yahoo.com> 2008, Matt Lilek 2015, Metrological 2010-2011, Motorola Mobility, Inc 2015, Naver Corp 2010, Nikita Vasilyev 2006, Nikolas Zimmermann <zimmermann@kde.org> 2009-2013, Nokia Corporation and/or its subsidiary(-ies) 2010-2014, Patrick Gansterer <paroga@paroga.com> 2012, Raphael Kubo da Costa <rakuco@webkit.org> 2013, Renata Hodovan <reni@inf.u-szeged.hu> 2014-2015, Saam Barati <saambarati1@gmail.com> 2011-2014, Samsung Electronics 2013, Seokju Kwon <seokju.kwon@gmail.com> 2006, Simon Hausmann <hausmann@kde.org> 2015, The Qt Company Ltd 2015, Tobias Reiss <tobi+webkit@basecode.de> 2007-2009, Torch Mobile, Inc. (http://www.torchmobile.com/) 2009-2015, University of Szeged 2013-2015, University of Washington 2015, Yusuke Suzuki <utatane.tea@gmail.com> 2006, Zack Rusin <zack@kde.org> 2011, Zeno Albisser <zeno@webkit.org>
libosl-0.8.0/full/test/threatmate/kfendPredictor.t.cc
#include "osl/threatmate/kfendPredictor.h" #include "osl/csa.h" #include <boost/test/unit_test.hpp> using namespace osl; using namespace osl::threatmate; BOOST_AUTO_TEST_CASE(KfendPredictorTestBeginning) { const NumEffectState state((SimpleState(HIRATE))); const Move move = Move(Square(3,3), PAWN, WHITE); KfendPredictor Kfend; BOOST_CHECK( !Kfend.predict(state, move) ); } BOOST_AUTO_TEST_CASE(KfendPredictorTestAddEffect) { const NumEffectState state(CsaString( "P1-KY * * +TO * +KA-OU-KE-KY\n" "P2-KY * * * +HI-KI * * * \n" "P3 * * -KE * * -FU-FU-FU * \n" "P4 * -FU-FU * * * * -KI-FU\n" "P5-FU * * * +FU * * * * \n" "P6 * * +FU-HI * * * +KI * \n" "P7+FU+FU+KE * -TO-NK+FU * * \n" "P8+OU * +GI * * * * * * \n" "P9+KY * -TO * * * * * * \n" "P+00KI00FU\n" "P-00KA00GI00GI00GI00FU00FU\n" "-\n").initialState()); const Move move = Move(Square(5,2), ROOK, BLACK); KfendPredictor Kfend; BOOST_CHECK( Kfend.predict(state, move) ); } BOOST_AUTO_TEST_CASE(KfendPredictorTestNotAddEffect) { const NumEffectState state(CsaString( "P1+RY-KE-FU * +NK * * -OU-FU\n" "P2 * * -GI * * +KI * * * \n" "P3 * * * * * * * * +GI\n" "P4+FU * * * -KY+GI-KY * +FU\n" "P5 * -FU * * * * * * -KE\n" "P6 * * +FU * * * +KA-UM * \n" "P7 * +FU * * * * -KY+KY-GI\n" "P8 * * * * * -KI * * * \n" "P9-RY+KE+KI * * * * +KI+OU\n" "P+00FU00FU00FU00FU00FU\n" "P-00FU00FU00FU00FU00FU00FU\n" "-\n").initialState()); const Move move = Move(Square(3,6), BISHOP, BLACK); KfendPredictor Kfend; BOOST_CHECK( !Kfend.predict(state, move) ); } BOOST_AUTO_TEST_CASE(KfendPredictorTestCheck) { const NumEffectState state(CsaString( "P1+RY-KE-FU * +NK * * -OU-FU\n" "P2 * * -GI * * +KI * * * \n" "P3 * * * * * * * +KY+GI\n" "P4+FU * * * -UM+GI-KY * +FU\n" "P5 * -FU * * * * * * -KE\n" "P6 * * +FU * * * * * * \n" "P7 * +FU * * * * -KY * -GI\n" "P8 * * * * * -KI * * * \n" "P9-RY+KE+KI * * * * +KI+OU\n" "P+00FU00FU00FU00FU00FU\n" "P-00KA00KY00FU00FU00FU00FU00FU00FU\n" "-\n").initialState()); const Move move = Move(Square(2,3), LANCE, BLACK); KfendPredictor Kfend; BOOST_CHECK( Kfend.predict(state, move) ); } BOOST_AUTO_TEST_CASE(KfendPredictorTestChecked) { const NumEffectState state(CsaString( "P1+RY-KE-FU * +NK * * -OU-FU\n" "P2 * * -GI * * +KI * -FU * \n" "P3 * * * * * * * +KY+GI\n" "P4+FU * * * -UM+GI-KY * +FU\n" "P5 * -FU * * * * * * -KE\n" "P6 * * +FU * * * * * * \n" "P7 * +FU * * * * -KY * -GI\n" "P8 * * * * * -KI * * * \n" "P9-RY+KE+KI * * * * +KI+OU\n" "P+00FU00FU00FU00FU00FU\n" "P-00KA00KY00FU00FU00FU00FU00FU\n" "+\n").initialState()); const Move move = Move(Square(2,2), PAWN, BLACK); KfendPredictor Kfend; BOOST_CHECK( !Kfend.predict(state, move) ); } // ;;; Local Variables: // ;;; mode:c++ // ;;; c-basic-offset:2 // ;;; End:
utf-8
1
BSD
Copyright (C) 2003-2010 Team GPS
lablgtk3-3.1.1+official/src/ml_gtktree.h
/**************************************************************************/ /* Lablgtk */ /* */ /* This program is free software; you can redistribute it */ /* and/or modify it under the terms of the GNU Library General */ /* Public License as published by the Free Software Foundation */ /* version 2, with the exception described in file COPYING which */ /* comes with the library. */ /* */ /* 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 Library General Public License for more details. */ /* */ /* You should have received a copy of the GNU Library General */ /* Public License along with this program; if not, write to the */ /* Free Software Foundation, Inc., 59 Temple Place, Suite 330, */ /* Boston, MA 02111-1307 USA */ /* */ /* */ /**************************************************************************/ #define GtkTreeIter_val(val) ((GtkTreeIter*)MLPointer_val(val)) #define Val_GtkTreeIter(it) (copy_memblock_indirected(it,sizeof(GtkTreeIter))) #define GtkTreeIter_optval(v) Option_val(v, GtkTreeIter_val, NULL) #define GtkTreePath_optval(v) Option_val(v, GtkTreePath_val, NULL) #define GtkTreeModel_optval(v) Option_val(v, GtkTreeModel_val, NULL) #define GtkCellRenderer_optval(v) Option_val(v, GtkCellRenderer_val, NULL) #define GtkTreeViewColumn_optval(v) Option_val(v, GtkTreeViewColumn_val, NULL) gboolean ml_gtk_row_separator_func (GtkTreeModel *model, GtkTreeIter *iter, gpointer data);
utf-8
1
LGPL-2.1 with linking exception
Jacques Garrigue <garrigue@math.nagoya-u.ac.jp> Benjamin Monate <benjamin.monate@free.fr> Olivier Andrieu <oandrieu@nerim.net> Adrien Nader <camaradetux@gmail.com> Jun Furuse <jun.furuse@gmail.com> Maxence Guesdon <maxence.guesdon@inria.fr> Stefano Zacchiroli <zack@cs.unibo.it> Hugo Herbelin <Hugo.Herbelin@inria.fr> Claudio Sacerdoti Coen <claudio.sacerdoticoen@inria.fr> Hubert Fauque <hubert.fauque@wanadoo.fr> Koji Kagawa <kagawa@eng.kagawa-u.ac.jp>
qtwebengine-opensource-src-5.15.8+dfsg/src/3rdparty/chromium/chrome/common/extensions/api/commands/commands_handler.h
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_COMMON_EXTENSIONS_API_COMMANDS_COMMANDS_HANDLER_H_ #define CHROME_COMMON_EXTENSIONS_API_COMMANDS_COMMANDS_HANDLER_H_ #include <memory> #include <string> #include "base/macros.h" #include "chrome/common/extensions/command.h" #include "extensions/common/extension.h" #include "extensions/common/manifest.h" #include "extensions/common/manifest_handler.h" namespace extensions { struct CommandsInfo : public Extension::ManifestData { CommandsInfo(); ~CommandsInfo() override; // Optional list of commands (keyboard shortcuts). // These commands are the commands which the extension wants to use, which are // not necessarily the ones it can use, as it might be inactive (see also // Get*Command[s] in CommandService). std::unique_ptr<Command> browser_action_command; std::unique_ptr<Command> page_action_command; std::unique_ptr<Command> action_command; CommandMap named_commands; static const Command* GetBrowserActionCommand(const Extension* extension); static const Command* GetPageActionCommand(const Extension* extension); static const Command* GetActionCommand(const Extension* extension); static const CommandMap* GetNamedCommands(const Extension* extension); }; // Parses the "commands" manifest key. class CommandsHandler : public ManifestHandler { public: CommandsHandler(); ~CommandsHandler() override; bool Parse(Extension* extension, base::string16* error) override; bool AlwaysParseForType(Manifest::Type type) const override; private: // If the extension defines a browser action, but no command for it, then // we synthesize a generic one, so the user can configure a shortcut for it. // No keyboard shortcut will be assigned to it, until the user selects one. void MaybeSetBrowserActionDefault(const Extension* extension, CommandsInfo* info); base::span<const char* const> Keys() const override; DISALLOW_COPY_AND_ASSIGN(CommandsHandler); }; } // namespace extensions #endif // CHROME_COMMON_EXTENSIONS_API_COMMANDS_COMMANDS_HANDLER_H_
utf-8
1
LGPL-3 or GPL-2
2006-2021 The Chromium Authors 2016-2021 The Qt Company Ltd.
meshlab-2020.09+dfsg1/src/external/u3d/src/RTL/Component/Rendering/CIFXRender.cpp
//*************************************************************************** // // Copyright (c) 2001 - 2006 Intel Corporation // // 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. // //*************************************************************************** // CIFXRender.cpp #include "IFXRenderPCH.h" #include "CIFXRenderServices.h" #include "CIFXRender.h" #define IFXCompareDevice(hr,a,b,func) {if(! (a == b)) { bDirty = TRUE; hr |= func(b); } } //=============================================== // Static object definitions for any of the // IFXRender* helper classes. //=============================================== U32 CIFXRender::AddRef() { return ++m_refCount; } U32 CIFXRender::Release() { if (!(--m_refCount)) { delete this; return 0; } return m_refCount; } IFXRESULT CIFXRender::QueryInterface(IFXREFIID interfaceId, void** ppInterface) { IFXRESULT result = IFX_OK; if (ppInterface) { if (interfaceId == IID_IFXRender) { *(IFXRender**)ppInterface = (IFXRender*) this; } else if (interfaceId == IID_IFXUnknown) { *(IFXUnknown**)ppInterface = (IFXUnknown*) this; } else { *ppInterface = NULL; result = IFX_E_UNSUPPORTED; } if (IFXSUCCESS(result)) AddRef(); } else { result = IFX_E_INVALID_POINTER; } return result; } //========================= // CIFXRender Methods //========================= CIFXRender::CIFXRender() { } CIFXRender::~CIFXRender() { IFXRELEASE(m_pServices); // Release all textures on the device. Textures that are needed // for other sprites will be reloaded. if(m_spDevice.IsValid()) { m_spDevice->DeleteAllTextures(); } } IFXRESULT CIFXRender::Construct() { IFXRESULT rc = IFX_OK; InitData(); return rc; } void CIFXRender::InitData() { m_iInitialized = IFX_E_NOT_INITIALIZED; m_eAAMode = IFX_NONE; m_eDepthStencil = IFX_DEPTH_D16S0; m_uNumHWTexUnits = 1; CIFXRenderServicesPtr rServices; rServices.Create(CID_IFXRenderServices, CID_IFXRenderServices); m_pServices = rServices.GetPointerAR(); m_uDeviceNum = 0; m_rcVisibleWindow.Set(0,0,0,0); m_bVSyncEnabled = FALSE; m_eColorFormat = IFX_BGRA; ClearPerformanceData(); } IFXRESULT CIFXRender::GetCaps(IFXRenderCaps& rCaps) { IFXRESULT rc = IFX_E_NOT_INITIALIZED; if(m_spDevice.IsValid()) { rc = IFX_OK; rCaps = m_RCaps; } return rc; } IFXRESULT CIFXRender::Initialize(U32 uMonitorNum) { IFXRESULT rc = IFX_OK; U32 uNumMonitors = 0; const IFXMonitor* pMons = m_pServices->GetMonitors(uNumMonitors); if(uMonitorNum >= uNumMonitors) { rc = IFX_E_INVALID_RANGE; } IFXRenderDevicePtr rDevice; if(IFXSUCCESS(rc)) { m_uDeviceNum = pMons[uMonitorNum].m_uDeviceNum; rc = m_pServices->GetRenderDevice(m_idRenderDevice, m_uDeviceNum, rDevice); } if(IFXSUCCESS(rc)) { rc = rDevice.QI(m_spDevice, CID_IFXRenderDevice); rDevice = 0; } if(IFXSUCCESS(rc)) { m_uNumHWTexUnits = m_spDevice->GetNumHWTexUnits(); m_spTextures = m_spDevice->GetTextures(); U32 i = 0; for(i = 0; i < IFX_MAX_LIGHTS; i++) { m_pspLights[i] = m_spDevice->GetLight(i); } for(i = 0; i < IFX_MAX_TEXUNITS; i++) { m_pspTexUnits[i] = m_spDevice->GetTexUnit(i); } } if(IFXSUCCESS(rc)) { rc = m_spDevice->GetCaps(m_RCaps); } return rc; } IFXRESULT CIFXRender::GetTransformMatrix(IFXMatrix4x4& rMatrix) { IFXRESULT rc = IFX_OK; if(m_spDevice.IsValid()) { rc = m_spDevice->GetTransformMatrix(rMatrix); } else rc = IFX_E_NOT_INITIALIZED; return rc; } IFXRESULT CIFXRender::GetPerformanceData(IFXenum eData, U32& ruData) { IFXRESULT rc = IFX_OK; switch(eData) { case IFX_NUM_FACES: ruData = m_uNumFacesRendered; break; case IFX_NUM_VERTICES: ruData = m_uNumVerticesRendered; break; case IFX_NUM_MESHES: ruData = m_uNumMeshesRendered; break; case IFX_NUM_RENDER_CALLS: ruData = m_uNumRenderCalls; break; default: rc = IFX_E_INVALID_RANGE; } return rc; } IFXRESULT CIFXRender::ClearPerformanceData() { m_uNumFacesRendered = 0; m_uNumVerticesRendered = 0; m_uNumMeshesRendered = 0; m_uNumRenderCalls = 0; return IFX_OK; } IFXenum CIFXRender::GetColorFormat() { return m_eColorFormat; } IFXRESULT CIFXRender::Enable(IFXenum eParam) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc)) { if ((eParam >= IFX_LIGHT0) && (eParam < (IFX_LIGHT0+IFX_MAX_LIGHTS))) { rc = m_pspLights[eParam - IFX_LIGHT0]->SetEnabled(TRUE); } else if ((eParam >= IFX_TEXUNIT0) && (eParam < (IFX_TEXUNIT0+IFX_MAX_TEXUNITS))) { rc = m_pspTexUnits[eParam - IFX_TEXUNIT0]->SetEnabled(TRUE); } else switch(eParam) { case IFX_LIGHTING: rc = m_spDevice->SetLighting(TRUE); break; case IFX_DEPTH_TEST: rc = m_spDevice->SetDepthTest(TRUE); break; case IFX_DEPTH_WRITE: rc = m_spDevice->SetDepthWrite(TRUE); break; case IFX_CULL: rc = m_spDevice->SetCull(TRUE); break; case IFX_FOG: rc = m_spDevice->SetFogEnabled(TRUE); break; case IFX_FB_BLEND: rc = m_spDevice->SetBlendEnabled(TRUE); break; case IFX_FB_ALPHA_TEST: rc = m_spDevice->SetAlphaTestEnabled(TRUE); break; case IFX_STENCIL: if(m_eDepthStencil == IFX_DEPTH_D24S8) rc = m_spDevice->SetStencilEnabled(TRUE); else rc = m_spDevice->SetStencilEnabled(FALSE); break; case IFX_VSYNC: rc = SetVSyncEnabled(TRUE); break; default: rc = IFX_E_INVALID_RANGE; break; } } return rc; } IFXRESULT CIFXRender::Disable(IFXenum eParam) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc)) { if ((eParam >= IFX_LIGHT0) && (eParam < (IFX_LIGHT0+IFX_MAX_LIGHTS))) { rc = m_pspLights[eParam - IFX_LIGHT0]->SetEnabled(FALSE); } else if ((eParam >= IFX_TEXUNIT0) && (eParam < (IFX_TEXUNIT0+IFX_MAX_TEXUNITS))) { rc = m_pspTexUnits[eParam - IFX_TEXUNIT0]->SetEnabled(FALSE); } else switch(eParam) { case IFX_LIGHTING: rc = m_spDevice->SetLighting(FALSE); break; case IFX_DEPTH_TEST: rc = m_spDevice->SetDepthTest(FALSE); break; case IFX_DEPTH_WRITE: rc = m_spDevice->SetDepthWrite(FALSE); break; case IFX_CULL: rc = m_spDevice->SetCull(FALSE); break; case IFX_FOG: rc = m_spDevice->SetFogEnabled(FALSE); break; case IFX_FB_BLEND: rc = m_spDevice->SetBlendEnabled(FALSE); break; case IFX_FB_ALPHA_TEST: rc = m_spDevice->SetAlphaTestEnabled(FALSE); break; case IFX_STENCIL: rc = m_spDevice->SetStencilEnabled(FALSE); break; case IFX_VSYNC: rc = SetVSyncEnabled(FALSE); break; default: rc = IFX_E_INVALID_RANGE; break; } } return rc; } IFXRESULT CIFXRender::GetEnabled(IFXenum eParam, BOOL& bEnabled) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc)) { if ((eParam >= IFX_LIGHT0) && (eParam < (IFX_LIGHT0+IFX_MAX_LIGHTS))) { bEnabled = m_pspLights[eParam - IFX_LIGHT0]->GetEnabled(); } else if ((eParam >= IFX_TEXUNIT0) && (eParam < (IFX_TEXUNIT0+IFX_MAX_TEXUNITS))) { bEnabled = m_pspTexUnits[eParam - IFX_TEXUNIT0]->GetEnabled(); } else switch(eParam) { case IFX_LIGHTING: bEnabled = m_spDevice->GetLighting(); break; case IFX_DEPTH_TEST: bEnabled = m_spDevice->GetDepthTest(); break; case IFX_DEPTH_WRITE: bEnabled = m_spDevice->GetDepthWrite(); break; case IFX_CULL: bEnabled = m_spDevice->GetCull(); break; case IFX_FOG: bEnabled = FALSE; break; case IFX_FB_BLEND: bEnabled = FALSE; break; case IFX_FB_ALPHA_TEST: bEnabled = FALSE; break; case IFX_STENCIL: bEnabled = FALSE; break; default: rc = IFX_E_INVALID_RANGE; break; } } return rc; } IFXRESULT CIFXRender::Clear(const IFXRenderClear& rClear) { IFXRESULT rc = IFX_OK; BOOL bDepthWrite = m_spDevice->GetDepthWrite(); m_spDevice->SetDepthWrite(TRUE); rc = ClearHW(rClear); m_spDevice->SetDepthWrite(bDepthWrite); return rc; } IFXRESULT CIFXRender::MakeCurrent() { IFXRESULT rc = IFX_OK; if(m_spDevice.IsValid()) { void* pCurr = m_spDevice->GetCurrent(); if(pCurr != this) { m_spDevice->SetCurrent(this); rc = MakeHWCurrent(); m_spDevice->SetWindowSize(m_Window.GetWindowSize()); m_spDevice->SetVisibleWindow(m_rcVisibleWindow); } } return rc; } IFXRESULT CIFXRender::DrawMeshLines(IFXMesh& rMesh) { IFXRESULT rc = IFX_OK; IFXVertexAttributes vaAttribs = rMesh.GetAttributes(); // First we must make sure that all texture units have texture coordinates flowing to // them (if needed). If the texture unit is not doing auto-texcoord-gen, then we // must make sure that either: // // a) The mesh has texture coordinates for every unit that is enabled, or if not: // // b) Redirect any existing texture coordinates into those units that need them, or: // // c) Disable all texture units if there are no tex coords to work with. U32 i; for( i = 0; i < m_uNumHWTexUnits; i++) { if(m_pspTexUnits[i]->GetEnabled()) { U32 uTexCoordSet = 0; if(m_pspTexUnits[i]->GetTextureCoordinateSet() < 0) { uTexCoordSet = i; } else { uTexCoordSet = (U32) m_pspTexUnits[i]->GetTextureCoordinateSet(); } if(vaAttribs.m_uData.m_uNumTexCoordLayers > uTexCoordSet) { m_pspTexUnits[i]->SetTexCoordSet(uTexCoordSet); } else if(vaAttribs.m_uData.m_uNumTexCoordLayers) { m_pspTexUnits[i]->SetTexCoordSet(0); } else { m_pspTexUnits[i]->SetEnabled(FALSE); } } } if (IFXSUCCESS(rc)) { if(m_spDevice.IsValid()) { rc = m_spDevice->DrawMesh(rMesh, m_uNumRenderCalls, /*draw lines*/1); } } return rc; } IFXRESULT CIFXRender::DrawMeshPoints(IFXMesh& rMesh) { IFXRESULT rc = IFX_OK; IFXVertexAttributes vaAttribs = rMesh.GetAttributes(); // First we must make sure that all texture units have texture coordinates flowing to // them (if needed). If the texture unit is not doing auto-texcoord-gen, then we // must make sure that either: // // a) The mesh has texture coordinates for every unit that is enabled, or if not: // // b) Redirect any existing texture coordinates into those units that need them, or: // // c) Disable all texture units if there are no tex coords to work with. U32 i; for( i = 0; i < m_uNumHWTexUnits; i++) { if(m_pspTexUnits[i]->GetEnabled()) { U32 uTexCoordSet = 0; if(m_pspTexUnits[i]->GetTextureCoordinateSet() < 0) { uTexCoordSet = i; } else { uTexCoordSet = (U32) m_pspTexUnits[i]->GetTextureCoordinateSet(); } if(vaAttribs.m_uData.m_uNumTexCoordLayers > uTexCoordSet) { m_pspTexUnits[i]->SetTexCoordSet(uTexCoordSet); } else if(vaAttribs.m_uData.m_uNumTexCoordLayers) { m_pspTexUnits[i]->SetTexCoordSet(0); } else { m_pspTexUnits[i]->SetEnabled(FALSE); } } } if (IFXSUCCESS(rc)) { if(m_spDevice.IsValid()) { rc = m_spDevice->DrawMesh(rMesh, m_uNumRenderCalls, /*draw points*/2); } } return rc; } IFXRESULT CIFXRender::DrawMesh(IFXMesh& rMesh) { IFXRESULT rc = IFX_OK; m_uNumMeshesRendered++; m_uNumFacesRendered += rMesh.GetNumFaces(); m_uNumVerticesRendered += rMesh.GetNumVertices(); IFXVertexAttributes vaAttribs = rMesh.GetAttributes(); // First we must make sure that all texture units have texture coordinates flowing to // them (if needed). If the texture unit is not doing auto-texcoord-gen, then we // must make sure that either: // // a) The mesh has texture coordinates for every unit that is enabled, or if not: // // b) Redirect any existing texture coordinates into those units that need them, or: // // c) Disable all texture units if there are no tex coords to work with. U32 i; for( i = 0; i < m_uNumHWTexUnits; i++) { if(m_pspTexUnits[i]->GetEnabled()) { U32 uTexCoordSet = 0; if(m_pspTexUnits[i]->GetTextureCoordinateSet() < 0) { uTexCoordSet = i; } else { uTexCoordSet = (U32) m_pspTexUnits[i]->GetTextureCoordinateSet(); } if(vaAttribs.m_uData.m_uNumTexCoordLayers > uTexCoordSet) { m_pspTexUnits[i]->SetTexCoordSet(uTexCoordSet); } else if(vaAttribs.m_uData.m_uNumTexCoordLayers) { m_pspTexUnits[i]->SetTexCoordSet(0); } else { m_pspTexUnits[i]->SetEnabled(FALSE); } } } if (IFXSUCCESS(rc)) { if(m_spDevice.IsValid()) { rc = m_spDevice->DrawMesh(rMesh, m_uNumRenderCalls, 0 /*draw faces*/); } } return rc; } IFXRESULT CIFXRender::SetBlend(IFXRenderBlend& rBlend) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc) && m_spDevice.IsValid()) { rc = m_spDevice->SetBlend(rBlend); } return rc; } IFXRESULT CIFXRender::SetFog(IFXRenderFog& rFog) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc) && m_spDevice.IsValid()) { rc = m_spDevice->SetFog(rFog); } return rc; } IFXRESULT CIFXRender::SetLight(IFXenum eLight, IFXRenderLight& rLight) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc)) { if ((eLight >= IFX_LIGHT0) && (eLight < (IFX_LIGHT0+IFX_MAX_LIGHTS))) { if(m_pspLights && m_pspLights[eLight - IFX_LIGHT0].IsValid()) { rc = m_pspLights[eLight - IFX_LIGHT0]->SetLight(rLight); } } else { rc = IFX_E_INVALID_RANGE; } } return rc; } IFXRESULT CIFXRender::SetMaterial(IFXRenderMaterial& rMat) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc) && m_spDevice.IsValid()) { rc = m_spDevice->SetMaterial(rMat); } return rc; } IFXRESULT CIFXRender::SetStencil(IFXRenderStencil& rStencil) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc) && m_spDevice.IsValid()) { rc = m_spDevice->SetStencil(rStencil); } return rc; } IFXRESULT CIFXRender::SetTexture(IFXTextureObject& rTexture) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc)) { U32 uTexId = rTexture.GetId(); IFXUnknownPtr rUnk; CIFXDeviceTexturePtr rTex; if(IFXSUCCESS(m_spTextures->GetData(uTexId, rUnk))) { rc = rUnk.QI(rTex, CID_IFXDeviceTexture); } else { rc = CreateTexture(rTex); if(IFXSUCCESS(rc)) { rc = rTex.QI(rUnk, IID_IFXUnknown); } if(IFXSUCCESS(rc)) { rc = m_spTextures->AddData(uTexId, rUnk); } } if(IFXSUCCESS(rc)) { rc = rTex->SetTexture(rTexture); } } return rc; } IFXRESULT CIFXRender::SetTextureUnit(IFXenum eTexUnit, IFXRenderTexUnit& rTexUnit) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc)) { if ((eTexUnit >= IFX_TEXUNIT0) && (eTexUnit < (IFX_TEXUNIT0+IFX_MAX_TEXUNITS))) { if(m_pspTexUnits && m_pspTexUnits[eTexUnit - IFX_TEXUNIT0].IsValid()) { rc = m_pspTexUnits[eTexUnit - IFX_TEXUNIT0]->SetTexUnit(rTexUnit); } } else { rc = IFX_E_INVALID_RANGE; } } return rc; } IFXRESULT CIFXRender::SetConstantColor(const IFXVector4& vColor) { IFXRESULT rc = IFX_OK; if(m_spDevice.IsValid()) { rc = m_spDevice->SetConstantColor(vColor); } return rc; } IFXRESULT CIFXRender::SetView(IFXRenderView& rView) { IFXRESULT rc = m_iInitialized; if(IFXSUCCESS(rc) && m_spDevice.IsValid()) { rc = m_spDevice->SetView(rView); } return rc; } IFXRESULT CIFXRender::SetWindow(IFXRenderWindow& rWindow) { IFXRESULT rc = m_iInitialized; BOOL bDirty = FALSE; if( IFXSUCCESS(rc) ) { IFXenum eMode = GetCompatibleAAMode(rWindow.GetAntiAliasingMode(), rWindow.GetAntiAliasingEnabled()); IFXCompareDevice(rc, m_eAAMode, eMode, SetHWAntiAliasingMode); eMode = GetCompatibleDepthMode(m_pServices->GetDepthBufferFormat()); IFXCompareDevice(rc, m_eDepthStencil, eMode, SetHWDepthStencilFormat); /* IFXCompareDevice(rc, m_Window.GetDTS(), rWindow.GetDTS(), SetHWDTS); IFXCompareDevice(rc, m_Window.GetTransparent(), rWindow.GetTransparent(), SetHWTransparent); IFXCompareDevice(rc, m_Window.GetWindowSize(), rWindow.GetWindowSize(), SetHWWindowSize); IFXCompareDevice(rc, m_Window.GetWindowPtr(), rWindow.GetWindowPtr(), SetHWWindowPtr);*/ bDirty = m_Window.SetDirtyWindow(rWindow); } if(IFXSUCCESS(rc)) { rc = SetHWWindow(bDirty); if(IFXSUCCESS(rc)) { rc |= m_spDevice->SetWindowSize(rWindow.GetWindowSize()); rc |= m_spDevice->SetVisibleWindow(m_rcVisibleWindow); } } return rc; } IFXRESULT CIFXRender::GetWindow(IFXRenderWindow& rWindow) { rWindow = m_Window; return IFX_OK; } IFXRESULT CIFXRender::SetHWAntiAliasingMode(IFXenum eAAMode) { m_eAAMode = eAAMode; return IFX_OK; } IFXRESULT CIFXRender::SetHWDepthStencilFormat(IFXenum eDepthStencil) { m_eDepthStencil = eDepthStencil; return IFX_OK; } IFXRESULT CIFXRender::SetHWDTS(BOOL bDTS) { m_Window.SetDTS(bDTS); return IFX_OK; } IFXRESULT CIFXRender::SetHWTransparent(BOOL bTransparent) { m_Window.SetTransparent(bTransparent); return IFX_OK; } IFXRESULT CIFXRender::SetHWWindowSize(const IFXRect& rcWindow) { m_Window.SetWindowSize(rcWindow); return IFX_OK; } IFXRESULT CIFXRender::SetHWWindowPtr(void* pvWindow) { m_Window.SetWindowPtr(pvWindow); return IFX_OK; } IFXRESULT CIFXRender::SetHWDeviceNum(U32 uDeviceNum) { m_uDeviceNum = uDeviceNum; return IFX_OK; } void CIFXRender::CalcVisibleWindow() { // Calculate the visible portion of the window m_rcVisibleWindow = m_Window.GetWindowSize(); if(m_rcVisibleWindow.m_X < m_rcBackBuffer.m_X) { I32 iRight = m_rcVisibleWindow.Right(); m_rcVisibleWindow.m_X = m_rcBackBuffer.m_X; m_rcVisibleWindow.SetRight(iRight); } if(m_rcVisibleWindow.m_Y < m_rcBackBuffer.m_Y) { I32 iBottom = m_rcVisibleWindow.Bottom(); m_rcVisibleWindow.m_Y = m_rcBackBuffer.m_Y; m_rcVisibleWindow.SetBottom(iBottom); } if(m_rcVisibleWindow.Right() > m_rcBackBuffer.Right()) { m_rcVisibleWindow.SetRight(m_rcBackBuffer.Right()); } if(m_rcVisibleWindow.Bottom() > m_rcBackBuffer.Bottom()) { m_rcVisibleWindow.SetBottom(m_rcBackBuffer.Bottom()); } } IFXRESULT CIFXRender::SizeBackBuffer(const IFXRect& rcMonitor) { IFXRESULT rc = IFX_OK; const IFXRect& rcWindow = m_Window.GetWindowSize(); if(m_rcBackBuffer.m_X < rcWindow.m_X) { U32 uRight = m_rcBackBuffer.Right(); m_rcBackBuffer.m_X = rcWindow.m_X; m_rcBackBuffer.SetRight(uRight); } if(m_rcBackBuffer.Right() > rcWindow.Right()) { m_rcBackBuffer.SetRight(rcWindow.Right()); } if(m_rcBackBuffer.m_Y < rcWindow.m_Y) { U32 uBottom = m_rcBackBuffer.Bottom(); m_rcBackBuffer.m_Y = rcWindow.m_Y; m_rcBackBuffer.SetBottom(uBottom); } if(m_rcBackBuffer.Bottom() > rcWindow.Bottom()) { m_rcBackBuffer.SetBottom(rcWindow.Bottom()); } if(m_rcBackBuffer.m_X < rcMonitor.m_X) { U32 uRight = m_rcBackBuffer.Right(); m_rcBackBuffer.m_X = rcMonitor.m_X; m_rcBackBuffer.SetRight(uRight); } if(m_rcBackBuffer.Right() > rcMonitor.Right()) { m_rcBackBuffer.SetRight(rcMonitor.Right()); } if(m_rcBackBuffer.m_Y < rcMonitor.m_Y) { U32 uBottom = m_rcBackBuffer.Bottom(); m_rcBackBuffer.m_Y = rcMonitor.m_Y; m_rcBackBuffer.SetBottom(uBottom); } if(m_rcBackBuffer.Bottom() > rcMonitor.Bottom()) { m_rcBackBuffer.SetBottom(rcMonitor.Bottom()); } if(m_rcBackBuffer.m_Width <= 0 || m_rcBackBuffer.m_Height <= 0) { rc = IFX_E_INVALID_RANGE; } return rc; } IFXRESULT CIFXRender::SetViewMatrix(const IFXMatrix4x4& mViewMatrix) { IFXRESULT rc = IFX_OK; if(IFXSUCCESS(rc) && m_spDevice.IsValid()) { rc = m_spDevice->SetViewMatrix(mViewMatrix); } return rc; } const IFXMatrix4x4& CIFXRender::GetViewMatrix() { return m_spDevice->GetViewMatrix(); } IFXRESULT CIFXRender::SetWorldMatrix(const IFXMatrix4x4& mWorldMatrix) { IFXRESULT rc = IFX_OK; if(IFXSUCCESS(rc) && m_spDevice.IsValid()) { rc = m_spDevice->SetWorldMatrix(mWorldMatrix); } return rc; } IFXRESULT CIFXRender::SetCullMode(IFXenum eCullMode) { IFXRESULT rc = IFX_OK; rc = m_spDevice->SetCullMode(eCullMode); return rc; } IFXRESULT CIFXRender::SetLineOffset(U32 uOffset) { IFXRESULT rc = IFX_OK; rc = m_spDevice->SetLineOffset(uOffset); return rc; } IFXRESULT CIFXRender::GetGlobalAmbient(IFXVector4& vColor) { vColor = m_spDevice->GetGlobalAmbient(); return IFX_OK; } IFXRESULT CIFXRender::SetGlobalAmbient(const IFXVector4& vColor) { return m_spDevice->SetGlobalAmbient(vColor); } IFXRESULT CIFXRender::SetVSyncEnabled(BOOL bVSyncEnabled) { m_bVSyncEnabled = bVSyncEnabled; return IFX_OK; } IFXRESULT CIFXRender::SetDepthMode(IFXenum eDepthMode) { IFXRESULT rc = IFX_OK; if(m_spDevice.IsValid()) { rc = m_spDevice->SetDepthCompare(eDepthMode); } return rc; } IFXRESULT CIFXRender::DeleteTexture(U32 uTexId) { IFXRESULT rc = IFX_OK; if(m_spDevice.IsValid()) { rc = m_spDevice->DeleteTexture(uTexId); } return rc; } IFXenum CIFXRender::GetCompatibleAAMode(IFXenum eAAMode, IFXenum eAAEnabled) { switch(eAAEnabled) { case IFX_AA_DEFAULT: if(m_pServices->GetDefaultAAEnalbed()) return GetCompatibleAAMode(eAAMode, IFX_AA_ENABLED); else return IFX_NONE; break; case IFX_AA_DISABLED: return IFX_NONE; break; } switch(eAAMode) { case IFX_AA_DEFAULT: eAAMode = GetCompatibleAAMode(m_pServices->GetDefaultAAMode(), eAAEnabled); break; case IFX_AA_4X_SW: if(!m_RCaps.m_bAA4XSW) eAAMode = IFX_NONE; break; case IFX_AA_4X: if(!m_RCaps.m_bAA4X) eAAMode = GetCompatibleAAMode(IFX_AA_3X, eAAEnabled); break; case IFX_AA_3X: if(!m_RCaps.m_bAA3X) eAAMode = GetCompatibleAAMode(IFX_AA_2X, eAAEnabled); break; case IFX_AA_2X: if(!m_RCaps.m_bAA2X) eAAMode = IFX_NONE; break; } return eAAMode; } IFXenum CIFXRender::GetCompatibleDepthMode(IFXenum eDepthMode) { switch(eDepthMode) { case IFX_DEPTH_D16S0: if(!m_RCaps.m_b16BitDepth) eDepthMode = IFX_NONE; break; case IFX_DEPTH_D32S0: if(!m_RCaps.m_b24BitDepth) eDepthMode = GetCompatibleDepthMode(IFX_DEPTH_D16S0); break; case IFX_DEPTH_D24S8: if(!m_RCaps.m_b8BitStencil) eDepthMode = GetCompatibleDepthMode(IFX_DEPTH_D32S0); break; default: eDepthMode = IFX_DEPTH_D16S0; break; } return eDepthMode; } IFXRESULT CIFXRender::CopyImageData(U8* pSrc, U8* pDst, U32 uSrcPitch, U32 uDstPitch, U32 uWidth, U32 uHeight, U32 uBpp, BOOL bFlip) { //IFXRESULT rc = IFX_OK; if(bFlip) { U32 y; for( y = 0; y < uHeight; y++) { memcpy(pDst+((uHeight-1-y)*uDstPitch), pSrc+(y*uSrcPitch), uBpp*uWidth); } } else { U32 y; for( y = 0; y < uHeight; y++) { memcpy(pDst+(y*uDstPitch), pSrc+(y*uSrcPitch), uBpp*uWidth); } } return IFX_OK; }
utf-8
1
GPL-2+
2005-2020, Visual Computing Lab, ISTI - Italian National Research Council
magic-8.3.105+ds.1/wiring/wiring.h
/* * wiring.h -- * * Contains definitions for things that are exported by the * wiring module. * * ********************************************************************* * * Copyright (C) 1985, 1990 Regents of the University of California. * * * Permission to use, copy, modify, and distribute this * * * software and its documentation for any purpose and without * * * fee is hereby granted, provided that the above copyright * * * notice appear in all copies. The University of California * * * makes no representations about the suitability of this * * * software for any purpose. It is provided "as is" without * * * express or implied warranty. Export of this software outside * * * of the United States of America may require an export license. * * ********************************************************************* * * rcsid $Header$ */ #ifndef _WIRING_H #define _WIRING_H #include "utils/magic.h" #include "database/database.h" /* Table that defines the shape of contacts and the layers that they * connect. This definition allows some layers to extend around the * contact, to support technologies where the contact pads are different * sizes for the different layers that the contact connects. */ typedef struct _Contact *ContactPtr; typedef struct _Contact { TileType con_type; /* Type of material that forms core of * contact. */ int con_size; /* Minimum size of this contact (size of * minimum con_type area). */ TileType con_layer1; /* First of two layers that the contact * really isn't a contact. */ int con_surround1; /* How much additional material of type * con_layer1 must be painted around the * edge of the contact. */ int con_extend1; /* How much additional material of type * con_layer1 must extend beyond the * contact in the orientation of the route. */ TileType con_layer2; /* Same information for second layer that * the contact connects. */ int con_surround2; int con_extend2; ContactPtr con_next; /* Pointer to next contact record */ } Contact; extern Contact *WireContacts; /* Points to all the contacts that are * defined. */ /* Types defining the current state of the wiring tool */ extern TileType WireType; /* Type of material currently selected * for wiring. */ extern int WireWidth; /* Thickness of material to use for wiring. */ /* Procedures for placing wires: */ extern void WirePickType(); extern void WireAddLeg(); extern void WireAddContact(); extern void WireShowLeg(); extern int WireGetWidth(); extern TileType WireGetType(); /* Legal values for the "direction" parameter to WireAddLeg: */ #define WIRE_CHOOSE 0 #define WIRE_HORIZONTAL 1 #define WIRE_VERTICAL 2 /* Procedures for reading the technology file: */ extern void WireTechInit(); extern bool WireTechLine(); extern void WireTechFinal(); extern void WireTechScale(); /* Initialization: */ extern void WireInit(); #endif /* _WIRING_H */
utf-8
1
BSD-style
2010-2017 Tim Edwards (Johns Hopkins APL) 2010 Mike Godfrey (Stanford, Pixeldevices) 2010 Wes Hansford (MOSIS) 2010 Rajit Manohar (Cornell) 2010 Mika Nyström (Caltech) 2010 Philippe Pouliquen (Johns Hopkins University) 2010 Stefanos Sidiropolous (Aeluros) 2010 Jeff Solomon (Stanford) 2010 Jeff Sondeen (USC) 2010 Holger Vogt (Fraunhofer-Institut IMS, Duisburg, Germany) 2017 Chuan Chen
apr-1.7.0/misc/win32/charset.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "apr.h" #include "apr_strings.h" #include "apr_portable.h" APR_DECLARE(const char*) apr_os_default_encoding (apr_pool_t *pool) { return apr_psprintf(pool, "CP%u", (unsigned) GetACP()); } APR_DECLARE(const char*) apr_os_locale_encoding (apr_pool_t *pool) { #ifdef _UNICODE int i; #endif #if defined(_WIN32_WCE) LCID locale = GetUserDefaultLCID(); #else LCID locale = GetThreadLocale(); #endif int len = GetLocaleInfo(locale, LOCALE_IDEFAULTANSICODEPAGE, NULL, 0); char *cp = apr_palloc(pool, (len * sizeof(TCHAR)) + 2); if (0 < GetLocaleInfo(locale, LOCALE_IDEFAULTANSICODEPAGE, (TCHAR*) (cp + 2), len)) { /* Fix up the returned number to make a valid codepage name of the form "CPnnnn". */ cp[0] = 'C'; cp[1] = 'P'; #ifdef _UNICODE for(i = 0; i < len; i++) { cp[i + 2] = (char) ((TCHAR*) (cp + 2))[i]; } #endif return cp; } return apr_os_default_encoding(pool); }
utf-8
1
unknown
unknown
wine-development-6.0+repack/dlls/mcicda/mcicda.c
/* * MCI driver for audio CD (MCICDA) * * Copyright 1994 Martin Ayotte * Copyright 1998-99 Eric Pouech * Copyright 2000 Andreas Mohr * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA */ #include <stdarg.h> #include <stdio.h> #include <string.h> #define WIN32_NO_STATUS #include "windef.h" #include "winbase.h" #include "wingdi.h" #include "winuser.h" #include "wownt32.h" #include "mmddk.h" #include "winioctl.h" #include "ntddcdrm.h" #include "winternl.h" #include "wine/debug.h" #include "dsound.h" WINE_DEFAULT_DEBUG_CHANNEL(mcicda); #define CDFRAMES_PERSEC 75 #define CDFRAMES_PERMIN (CDFRAMES_PERSEC * 60) #define FRAME_OF_ADDR(a) ((a)[1] * CDFRAMES_PERMIN + (a)[2] * CDFRAMES_PERSEC + (a)[3]) #define FRAME_OF_TOC(toc, idx) FRAME_OF_ADDR((toc).TrackData[idx - (toc).FirstTrack].Address) /* Defined by red-book standard; do not change! */ #define RAW_SECTOR_SIZE (2352) /* Must be >= RAW_SECTOR_SIZE */ #define CDDA_FRAG_SIZE (32768) /* Must be >= 2 */ #define CDDA_FRAG_COUNT (3) typedef struct { UINT wDevID; int nUseCount; /* Incremented for each shared open */ BOOL fShareable; /* TRUE if first open was shareable */ MCIDEVICEID wNotifyDeviceID; /* MCI device ID with a pending notification */ HANDLE hCallback; /* Callback handle for pending notification */ DWORD dwTimeFormat; HANDLE handle; /* The following are used for digital playback only */ HANDLE hThread; HANDLE stopEvent; DWORD start, end; IDirectSound *dsObj; IDirectSoundBuffer *dsBuf; CRITICAL_SECTION cs; } WINE_MCICDAUDIO; /*-----------------------------------------------------------------------*/ typedef HRESULT(WINAPI*LPDIRECTSOUNDCREATE)(LPCGUID,LPDIRECTSOUND*,LPUNKNOWN); static LPDIRECTSOUNDCREATE pDirectSoundCreate; static BOOL device_io(HANDLE dev, DWORD code, void *inbuffer, DWORD insize, void *outbuffer, DWORD outsize, DWORD *retsize, OVERLAPPED *overlapped) { const char *str; BOOL ret = DeviceIoControl(dev, code, inbuffer, insize, outbuffer, outsize, retsize, overlapped); #define XX(x) case (x): str = #x; break switch (code) { XX(IOCTL_CDROM_RAW_READ); XX(IOCTL_CDROM_READ_TOC); XX(IOCTL_CDROM_READ_Q_CHANNEL); XX(IOCTL_CDROM_SEEK_AUDIO_MSF); XX(IOCTL_CDROM_PLAY_AUDIO_MSF); XX(IOCTL_CDROM_STOP_AUDIO); XX(IOCTL_CDROM_PAUSE_AUDIO); XX(IOCTL_CDROM_RESUME_AUDIO); XX(IOCTL_STORAGE_EJECT_MEDIA); XX(IOCTL_STORAGE_LOAD_MEDIA); default: str = wine_dbg_sprintf("UNKNOWN (0x%x)", code); }; #undef XX TRACE("Device %p, Code %s -> Return %d, Bytes %u\n", dev, str, ret, *retsize); return ret; } static DWORD CALLBACK MCICDA_playLoop(void *ptr) { WINE_MCICDAUDIO *wmcda = (WINE_MCICDAUDIO*)ptr; DWORD lastPos, curPos, endPos, br; void *cdData; DWORD lockLen, fragLen; DSBCAPS caps; RAW_READ_INFO rdInfo; HRESULT hr = DS_OK; memset(&caps, 0, sizeof(caps)); caps.dwSize = sizeof(caps); hr = IDirectSoundBuffer_GetCaps(wmcda->dsBuf, &caps); fragLen = caps.dwBufferBytes/CDDA_FRAG_COUNT; curPos = lastPos = 0; endPos = ~0u; while (SUCCEEDED(hr) && endPos != lastPos && WaitForSingleObject(wmcda->stopEvent, 0) != WAIT_OBJECT_0) { hr = IDirectSoundBuffer_GetCurrentPosition(wmcda->dsBuf, &curPos, NULL); if ((curPos-lastPos+caps.dwBufferBytes)%caps.dwBufferBytes < fragLen) { Sleep(1); continue; } EnterCriticalSection(&wmcda->cs); rdInfo.DiskOffset.QuadPart = wmcda->start<<11; rdInfo.SectorCount = min(fragLen/RAW_SECTOR_SIZE, wmcda->end-wmcda->start); rdInfo.TrackMode = CDDA; hr = IDirectSoundBuffer_Lock(wmcda->dsBuf, lastPos, fragLen, &cdData, &lockLen, NULL, NULL, 0); if (hr == DSERR_BUFFERLOST) { if(FAILED(IDirectSoundBuffer_Restore(wmcda->dsBuf)) || FAILED(IDirectSoundBuffer_Play(wmcda->dsBuf, 0, 0, DSBPLAY_LOOPING))) { LeaveCriticalSection(&wmcda->cs); break; } hr = IDirectSoundBuffer_Lock(wmcda->dsBuf, lastPos, fragLen, &cdData, &lockLen, NULL, NULL, 0); } if (SUCCEEDED(hr)) { if (rdInfo.SectorCount > 0) { if (!device_io(wmcda->handle, IOCTL_CDROM_RAW_READ, &rdInfo, sizeof(rdInfo), cdData, lockLen, &br, NULL)) WARN("CD read failed at sector %d: 0x%x\n", wmcda->start, GetLastError()); } if (rdInfo.SectorCount*RAW_SECTOR_SIZE < lockLen) { if(endPos == ~0u) endPos = lastPos; memset((BYTE*)cdData + rdInfo.SectorCount*RAW_SECTOR_SIZE, 0, lockLen - rdInfo.SectorCount*RAW_SECTOR_SIZE); } hr = IDirectSoundBuffer_Unlock(wmcda->dsBuf, cdData, lockLen, NULL, 0); } lastPos += fragLen; lastPos %= caps.dwBufferBytes; wmcda->start += rdInfo.SectorCount; LeaveCriticalSection(&wmcda->cs); } IDirectSoundBuffer_Stop(wmcda->dsBuf); SetEvent(wmcda->stopEvent); /* A design bug in native: the independent CD player called by the * MCI has no means to signal end of playing, therefore the MCI * notification is left hanging. MCI_NOTIFY_SUPERSEDED will be * signaled by the next command that has MCI_NOTIFY set (or * MCI_NOTIFY_ABORTED for MCI_PLAY). */ return 0; } /************************************************************************** * MCICDA_drvOpen [internal] */ static DWORD MCICDA_drvOpen(LPCWSTR str, LPMCI_OPEN_DRIVER_PARMSW modp) { static HMODULE dsHandle; WINE_MCICDAUDIO* wmcda; if (!modp) return 0xFFFFFFFF; /* FIXME: MCIERR_CANNOT_LOAD_DRIVER if there's no drive of type CD-ROM */ wmcda = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WINE_MCICDAUDIO)); if (!wmcda) return 0; if (!dsHandle) { dsHandle = LoadLibraryA("dsound.dll"); if(dsHandle) pDirectSoundCreate = (LPDIRECTSOUNDCREATE)GetProcAddress(dsHandle, "DirectSoundCreate"); } wmcda->wDevID = modp->wDeviceID; mciSetDriverData(wmcda->wDevID, (DWORD_PTR)wmcda); modp->wCustomCommandTable = MCI_NO_COMMAND_TABLE; modp->wType = MCI_DEVTYPE_CD_AUDIO; InitializeCriticalSection(&wmcda->cs); wmcda->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": WINE_MCICDAUDIO.cs"); return modp->wDeviceID; } /************************************************************************** * MCICDA_drvClose [internal] */ static DWORD MCICDA_drvClose(DWORD dwDevID) { WINE_MCICDAUDIO* wmcda = (WINE_MCICDAUDIO*)mciGetDriverData(dwDevID); if (wmcda) { wmcda->cs.DebugInfo->Spare[0] = 0; DeleteCriticalSection(&wmcda->cs); HeapFree(GetProcessHeap(), 0, wmcda); mciSetDriverData(dwDevID, 0); } return (dwDevID == 0xFFFFFFFF) ? 1 : 0; } /************************************************************************** * MCICDA_GetOpenDrv [internal] */ static WINE_MCICDAUDIO* MCICDA_GetOpenDrv(UINT wDevID) { WINE_MCICDAUDIO* wmcda = (WINE_MCICDAUDIO*)mciGetDriverData(wDevID); if (wmcda == NULL || wmcda->nUseCount == 0) { WARN("Invalid wDevID=%u\n", wDevID); return 0; } return wmcda; } /************************************************************************** * MCICDA_mciNotify [internal] * * Notifications in MCI work like a 1-element queue. * Each new notification request supersedes the previous one. */ static void MCICDA_Notify(DWORD_PTR hWndCallBack, WINE_MCICDAUDIO* wmcda, UINT wStatus) { MCIDEVICEID wDevID = wmcda->wNotifyDeviceID; HANDLE old = InterlockedExchangePointer(&wmcda->hCallback, NULL); if (old) mciDriverNotify(old, wDevID, MCI_NOTIFY_SUPERSEDED); mciDriverNotify(HWND_32(LOWORD(hWndCallBack)), wDevID, wStatus); } /************************************************************************** * MCICDA_ReadTOC [internal] */ static BOOL MCICDA_ReadTOC(WINE_MCICDAUDIO* wmcda, CDROM_TOC *toc, DWORD *br) { if (!device_io(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0, toc, sizeof(*toc), br, NULL)) { WARN("error reading TOC !\n"); return FALSE; } return TRUE; } /************************************************************************** * MCICDA_GetStatus [internal] */ static DWORD MCICDA_GetStatus(WINE_MCICDAUDIO* wmcda) { CDROM_SUB_Q_DATA_FORMAT fmt; SUB_Q_CHANNEL_DATA data; DWORD br; DWORD mode = MCI_MODE_NOT_READY; fmt.Format = IOCTL_CDROM_CURRENT_POSITION; if(wmcda->hThread != 0) { DWORD status; HRESULT hr; hr = IDirectSoundBuffer_GetStatus(wmcda->dsBuf, &status); if(SUCCEEDED(hr)) { if(!(status&DSBSTATUS_PLAYING)) { if(WaitForSingleObject(wmcda->stopEvent, 0) == WAIT_OBJECT_0) mode = MCI_MODE_STOP; else mode = MCI_MODE_PAUSE; } else mode = MCI_MODE_PLAY; } } else if (!device_io(wmcda->handle, IOCTL_CDROM_READ_Q_CHANNEL, &fmt, sizeof(fmt), &data, sizeof(data), &br, NULL)) { if (GetLastError() == ERROR_NOT_READY) mode = MCI_MODE_OPEN; } else { switch (data.CurrentPosition.Header.AudioStatus) { case AUDIO_STATUS_IN_PROGRESS: mode = MCI_MODE_PLAY; break; case AUDIO_STATUS_PAUSED: mode = MCI_MODE_PAUSE; break; case AUDIO_STATUS_NO_STATUS: case AUDIO_STATUS_PLAY_COMPLETE: mode = MCI_MODE_STOP; break; case AUDIO_STATUS_PLAY_ERROR: case AUDIO_STATUS_NOT_SUPPORTED: default: break; } } return mode; } /************************************************************************** * MCICDA_GetError [internal] */ static int MCICDA_GetError(WINE_MCICDAUDIO* wmcda) { switch (GetLastError()) { case ERROR_NOT_READY: return MCIERR_DEVICE_NOT_READY; case ERROR_NOT_SUPPORTED: case ERROR_IO_DEVICE: return MCIERR_HARDWARE; default: FIXME("Unknown mode %u\n", GetLastError()); } return MCIERR_DRIVER_INTERNAL; } /************************************************************************** * MCICDA_CalcFrame [internal] */ static DWORD MCICDA_CalcFrame(WINE_MCICDAUDIO* wmcda, DWORD dwTime) { DWORD dwFrame = 0; UINT wTrack; CDROM_TOC toc; DWORD br; BYTE* addr; TRACE("(%p, %08X, %u);\n", wmcda, wmcda->dwTimeFormat, dwTime); switch (wmcda->dwTimeFormat) { case MCI_FORMAT_MILLISECONDS: dwFrame = ((dwTime - 1) * CDFRAMES_PERSEC + 500) / 1000; TRACE("MILLISECONDS %u\n", dwFrame); break; case MCI_FORMAT_MSF: TRACE("MSF %02u:%02u:%02u\n", MCI_MSF_MINUTE(dwTime), MCI_MSF_SECOND(dwTime), MCI_MSF_FRAME(dwTime)); dwFrame += CDFRAMES_PERMIN * MCI_MSF_MINUTE(dwTime); dwFrame += CDFRAMES_PERSEC * MCI_MSF_SECOND(dwTime); dwFrame += MCI_MSF_FRAME(dwTime); break; case MCI_FORMAT_TMSF: default: /* unknown format ! force TMSF ! ... */ wTrack = MCI_TMSF_TRACK(dwTime); if (!device_io(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0, &toc, sizeof(toc), &br, NULL)) return 0; if (wTrack < toc.FirstTrack || wTrack > toc.LastTrack) return 0; TRACE("MSF %02u-%02u:%02u:%02u\n", MCI_TMSF_TRACK(dwTime), MCI_TMSF_MINUTE(dwTime), MCI_TMSF_SECOND(dwTime), MCI_TMSF_FRAME(dwTime)); addr = toc.TrackData[wTrack - toc.FirstTrack].Address; TRACE("TMSF trackpos[%u]=%d:%d:%d\n", wTrack, addr[1], addr[2], addr[3]); dwFrame = CDFRAMES_PERMIN * (addr[1] + MCI_TMSF_MINUTE(dwTime)) + CDFRAMES_PERSEC * (addr[2] + MCI_TMSF_SECOND(dwTime)) + addr[3] + MCI_TMSF_FRAME(dwTime); break; } return dwFrame; } /************************************************************************** * MCICDA_CalcTime [internal] */ static DWORD MCICDA_CalcTime(WINE_MCICDAUDIO* wmcda, DWORD tf, DWORD dwFrame, LPDWORD lpRet) { DWORD dwTime = 0; UINT wTrack; UINT wMinutes; UINT wSeconds; UINT wFrames; CDROM_TOC toc; DWORD br; TRACE("(%p, %08X, %u);\n", wmcda, tf, dwFrame); switch (tf) { case MCI_FORMAT_MILLISECONDS: dwTime = (dwFrame * 1000) / CDFRAMES_PERSEC + 1; TRACE("MILLISECONDS %u\n", dwTime); *lpRet = 0; break; case MCI_FORMAT_MSF: wMinutes = dwFrame / CDFRAMES_PERMIN; wSeconds = (dwFrame - CDFRAMES_PERMIN * wMinutes) / CDFRAMES_PERSEC; wFrames = dwFrame - CDFRAMES_PERMIN * wMinutes - CDFRAMES_PERSEC * wSeconds; dwTime = MCI_MAKE_MSF(wMinutes, wSeconds, wFrames); TRACE("MSF %02u:%02u:%02u -> dwTime=%u\n", wMinutes, wSeconds, wFrames, dwTime); *lpRet = MCI_COLONIZED3_RETURN; break; case MCI_FORMAT_TMSF: default: /* unknown format ! force TMSF ! ... */ if (!device_io(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0, &toc, sizeof(toc), &br, NULL)) return 0; if (dwFrame < FRAME_OF_TOC(toc, toc.FirstTrack) || dwFrame > FRAME_OF_TOC(toc, toc.LastTrack + 1)) { ERR("Out of range value %u [%u,%u]\n", dwFrame, FRAME_OF_TOC(toc, toc.FirstTrack), FRAME_OF_TOC(toc, toc.LastTrack + 1)); *lpRet = 0; return 0; } for (wTrack = toc.FirstTrack; wTrack <= toc.LastTrack; wTrack++) { if (FRAME_OF_TOC(toc, wTrack) > dwFrame) break; } wTrack--; dwFrame -= FRAME_OF_TOC(toc, wTrack); wMinutes = dwFrame / CDFRAMES_PERMIN; wSeconds = (dwFrame - CDFRAMES_PERMIN * wMinutes) / CDFRAMES_PERSEC; wFrames = dwFrame - CDFRAMES_PERMIN * wMinutes - CDFRAMES_PERSEC * wSeconds; dwTime = MCI_MAKE_TMSF(wTrack, wMinutes, wSeconds, wFrames); TRACE("%02u-%02u:%02u:%02u\n", wTrack, wMinutes, wSeconds, wFrames); *lpRet = MCI_COLONIZED4_RETURN; break; } return dwTime; } static DWORD MCICDA_Stop(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms); /************************************************************************** * MCICDA_Open [internal] */ static DWORD MCICDA_Open(UINT wDevID, DWORD dwFlags, LPMCI_OPEN_PARMSW lpOpenParms) { MCIDEVICEID dwDeviceID; DWORD ret; WINE_MCICDAUDIO* wmcda = (WINE_MCICDAUDIO*)mciGetDriverData(wDevID); WCHAR root[7], drive = 0; TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpOpenParms); if (lpOpenParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; dwDeviceID = lpOpenParms->wDeviceID; if (wmcda->nUseCount > 0) { /* The driver is already open on this channel */ /* If the driver was opened shareable before and this open specifies */ /* shareable then increment the use count */ if (wmcda->fShareable && (dwFlags & MCI_OPEN_SHAREABLE)) ++wmcda->nUseCount; else return MCIERR_MUST_USE_SHAREABLE; } else { wmcda->nUseCount = 1; wmcda->fShareable = dwFlags & MCI_OPEN_SHAREABLE; } if (dwFlags & MCI_OPEN_ELEMENT) { if (dwFlags & MCI_OPEN_ELEMENT_ID) { WARN("MCI_OPEN_ELEMENT_ID %p! Abort\n", lpOpenParms->lpstrElementName); ret = MCIERR_FLAGS_NOT_COMPATIBLE; goto the_error; } TRACE("MCI_OPEN_ELEMENT element name: %s\n", debugstr_w(lpOpenParms->lpstrElementName)); /* Only the first letter counts since w2k * Win9x-NT accept only d: and w98SE accepts d:\foobar as well. * Play d:\Track03.cda plays from the first track, not #3. */ if (!isalpha(lpOpenParms->lpstrElementName[0])) { ret = MCIERR_INVALID_FILE; goto the_error; } drive = toupper(lpOpenParms->lpstrElementName[0]); root[0] = drive; root[1] = ':'; root[2] = '\\'; root[3] = '\0'; if (GetDriveTypeW(root) != DRIVE_CDROM) { ret = MCIERR_INVALID_FILE; goto the_error; } } else { root[0] = 'A'; root[1] = ':'; root[2] = '\\'; root[3] = '\0'; for ( ; root[0] <= 'Z'; root[0]++) { if (GetDriveTypeW(root) == DRIVE_CDROM) { drive = root[0]; break; } } if (!drive) { ret = MCIERR_CANNOT_LOAD_DRIVER; /* drvOpen should return this */ goto the_error; } } wmcda->wNotifyDeviceID = dwDeviceID; wmcda->dwTimeFormat = MCI_FORMAT_MSF; /* now, open the handle */ root[0] = root[1] = '\\'; root[2] = '.'; root[3] = '\\'; root[4] = drive; root[5] = ':'; root[6] = '\0'; wmcda->handle = CreateFileW(root, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0); if (wmcda->handle == INVALID_HANDLE_VALUE) { ret = MCIERR_MUST_USE_SHAREABLE; goto the_error; } if (dwFlags & MCI_NOTIFY) { mciDriverNotify(HWND_32(LOWORD(lpOpenParms->dwCallback)), dwDeviceID, MCI_NOTIFY_SUCCESSFUL); } return 0; the_error: --wmcda->nUseCount; return ret; } /************************************************************************** * MCICDA_Close [internal] */ static DWORD MCICDA_Close(UINT wDevID, DWORD dwParam, LPMCI_GENERIC_PARMS lpParms) { WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); TRACE("(%04X, %08X, %p);\n", wDevID, dwParam, lpParms); if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; MCICDA_Stop(wDevID, MCI_WAIT, NULL); if (--wmcda->nUseCount == 0) { CloseHandle(wmcda->handle); } if ((dwParam & MCI_NOTIFY) && lpParms) MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL); return 0; } /************************************************************************** * MCICDA_GetDevCaps [internal] */ static DWORD MCICDA_GetDevCaps(UINT wDevID, DWORD dwFlags, LPMCI_GETDEVCAPS_PARMS lpParms) { WINE_MCICDAUDIO* wmcda = (WINE_MCICDAUDIO*)mciGetDriverData(wDevID); DWORD ret = 0; TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms); if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; if (dwFlags & MCI_GETDEVCAPS_ITEM) { TRACE("MCI_GETDEVCAPS_ITEM dwItem=%08X;\n", lpParms->dwItem); switch (lpParms->dwItem) { case MCI_GETDEVCAPS_CAN_RECORD: lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE); ret = MCI_RESOURCE_RETURNED; break; case MCI_GETDEVCAPS_HAS_AUDIO: lpParms->dwReturn = MAKEMCIRESOURCE(TRUE, MCI_TRUE); ret = MCI_RESOURCE_RETURNED; break; case MCI_GETDEVCAPS_HAS_VIDEO: lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE); ret = MCI_RESOURCE_RETURNED; break; case MCI_GETDEVCAPS_DEVICE_TYPE: lpParms->dwReturn = MAKEMCIRESOURCE(MCI_DEVTYPE_CD_AUDIO, MCI_DEVTYPE_CD_AUDIO); ret = MCI_RESOURCE_RETURNED; break; case MCI_GETDEVCAPS_USES_FILES: lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE); ret = MCI_RESOURCE_RETURNED; break; case MCI_GETDEVCAPS_COMPOUND_DEVICE: lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE); ret = MCI_RESOURCE_RETURNED; break; case MCI_GETDEVCAPS_CAN_EJECT: lpParms->dwReturn = MAKEMCIRESOURCE(TRUE, MCI_TRUE); ret = MCI_RESOURCE_RETURNED; break; case MCI_GETDEVCAPS_CAN_PLAY: lpParms->dwReturn = MAKEMCIRESOURCE(TRUE, MCI_TRUE); ret = MCI_RESOURCE_RETURNED; break; case MCI_GETDEVCAPS_CAN_SAVE: lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE); ret = MCI_RESOURCE_RETURNED; break; default: WARN("Unsupported %x devCaps item\n", lpParms->dwItem); return MCIERR_UNSUPPORTED_FUNCTION; } } else { TRACE("No GetDevCaps-Item !\n"); return MCIERR_MISSING_PARAMETER; } TRACE("lpParms->dwReturn=%08X;\n", lpParms->dwReturn); if (dwFlags & MCI_NOTIFY) { MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL); } return ret; } static DWORD CDROM_Audio_GetSerial(CDROM_TOC* toc) { DWORD serial = 0; int i; WORD wMagic; DWORD dwStart, dwEnd; /* * wMagic collects the wFrames from track 1 * dwStart, dwEnd collect the beginning and end of the disc respectively, in * frames. * There it is collected for correcting the serial when there are less than * 3 tracks. */ wMagic = toc->TrackData[0].Address[3]; dwStart = FRAME_OF_TOC(*toc, toc->FirstTrack); for (i = 0; i <= toc->LastTrack - toc->FirstTrack; i++) { serial += (toc->TrackData[i].Address[1] << 16) | (toc->TrackData[i].Address[2] << 8) | toc->TrackData[i].Address[3]; } dwEnd = FRAME_OF_TOC(*toc, toc->LastTrack + 1); if (toc->LastTrack - toc->FirstTrack + 1 < 3) serial += wMagic + (dwEnd - dwStart); return serial; } /************************************************************************** * MCICDA_Info [internal] */ static DWORD MCICDA_Info(UINT wDevID, DWORD dwFlags, LPMCI_INFO_PARMSW lpParms) { LPCWSTR str = NULL; WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); DWORD ret = 0; WCHAR buffer[16]; TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms); if (lpParms == NULL || lpParms->lpstrReturn == NULL) return MCIERR_NULL_PARAMETER_BLOCK; if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; TRACE("buf=%p, len=%u\n", lpParms->lpstrReturn, lpParms->dwRetSize); if (dwFlags & MCI_INFO_PRODUCT) { str = L"Wine's audio CD"; } else if (dwFlags & MCI_INFO_MEDIA_UPC) { ret = MCIERR_NO_IDENTITY; } else if (dwFlags & MCI_INFO_MEDIA_IDENTITY) { DWORD res = 0; CDROM_TOC toc; DWORD br; if (!device_io(wmcda->handle, IOCTL_CDROM_READ_TOC, NULL, 0, &toc, sizeof(toc), &br, NULL)) { return MCICDA_GetError(wmcda); } res = CDROM_Audio_GetSerial(&toc); swprintf(buffer, ARRAY_SIZE(buffer), L"%lu", res); str = buffer; } else { WARN("Don't know this info command (%u)\n", dwFlags); ret = MCIERR_MISSING_PARAMETER; } if (!ret) { TRACE("=> %s\n", debugstr_w(str)); if (lpParms->dwRetSize) { /* FIXME? Since NT, mciwave, mciseq and mcicda set dwRetSize * to the number of characters written, excluding \0. */ lstrcpynW(lpParms->lpstrReturn, str, lpParms->dwRetSize); } else ret = MCIERR_PARAM_OVERFLOW; } if (MMSYSERR_NOERROR==ret && (dwFlags & MCI_NOTIFY)) MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL); return ret; } /************************************************************************** * MCICDA_Status [internal] */ static DWORD MCICDA_Status(UINT wDevID, DWORD dwFlags, LPMCI_STATUS_PARMS lpParms) { WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); DWORD ret = 0; CDROM_SUB_Q_DATA_FORMAT fmt; SUB_Q_CHANNEL_DATA data; CDROM_TOC toc; DWORD br; TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms); if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; if (dwFlags & MCI_STATUS_ITEM) { TRACE("dwItem = %x\n", lpParms->dwItem); switch (lpParms->dwItem) { case MCI_STATUS_CURRENT_TRACK: fmt.Format = IOCTL_CDROM_CURRENT_POSITION; if (!device_io(wmcda->handle, IOCTL_CDROM_READ_Q_CHANNEL, &fmt, sizeof(fmt), &data, sizeof(data), &br, NULL)) { return MCICDA_GetError(wmcda); /* alt. data.CurrentPosition.TrackNumber = 1; -- what native yields */ } lpParms->dwReturn = data.CurrentPosition.TrackNumber; TRACE("CURRENT_TRACK=%lu\n", lpParms->dwReturn); break; case MCI_STATUS_LENGTH: if (!MCICDA_ReadTOC(wmcda, &toc, &br)) return MCICDA_GetError(wmcda); if (dwFlags & MCI_TRACK) { TRACE("MCI_TRACK #%u LENGTH=??? !\n", lpParms->dwTrack); if (lpParms->dwTrack < toc.FirstTrack || lpParms->dwTrack > toc.LastTrack) return MCIERR_OUTOFRANGE; lpParms->dwReturn = FRAME_OF_TOC(toc, lpParms->dwTrack + 1) - FRAME_OF_TOC(toc, lpParms->dwTrack); /* Windows returns one frame less than the total track length for the last track on the CD. See CDDB HOWTO. Verified on Win95OSR2. */ if (lpParms->dwTrack == toc.LastTrack) lpParms->dwReturn--; } else { /* Sum of the lengths of all of the tracks. Inherits the 'off by one frame' behavior from the length of the last track. See above comment. */ lpParms->dwReturn = FRAME_OF_TOC(toc, toc.LastTrack + 1) - FRAME_OF_TOC(toc, toc.FirstTrack) - 1; } lpParms->dwReturn = MCICDA_CalcTime(wmcda, (wmcda->dwTimeFormat == MCI_FORMAT_TMSF) ? MCI_FORMAT_MSF : wmcda->dwTimeFormat, lpParms->dwReturn, &ret); TRACE("LENGTH=%lu\n", lpParms->dwReturn); break; case MCI_STATUS_MODE: lpParms->dwReturn = MCICDA_GetStatus(wmcda); TRACE("MCI_STATUS_MODE=%08lX\n", lpParms->dwReturn); lpParms->dwReturn = MAKEMCIRESOURCE(lpParms->dwReturn, lpParms->dwReturn); ret = MCI_RESOURCE_RETURNED; break; case MCI_STATUS_MEDIA_PRESENT: lpParms->dwReturn = (MCICDA_GetStatus(wmcda) == MCI_MODE_OPEN) ? MAKEMCIRESOURCE(FALSE, MCI_FALSE) : MAKEMCIRESOURCE(TRUE, MCI_TRUE); TRACE("MCI_STATUS_MEDIA_PRESENT =%c!\n", LOWORD(lpParms->dwReturn) ? 'Y' : 'N'); ret = MCI_RESOURCE_RETURNED; break; case MCI_STATUS_NUMBER_OF_TRACKS: if (!MCICDA_ReadTOC(wmcda, &toc, &br)) return MCICDA_GetError(wmcda); lpParms->dwReturn = toc.LastTrack - toc.FirstTrack + 1; TRACE("MCI_STATUS_NUMBER_OF_TRACKS = %lu\n", lpParms->dwReturn); if (lpParms->dwReturn == (WORD)-1) return MCICDA_GetError(wmcda); break; case MCI_STATUS_POSITION: switch (dwFlags & (MCI_STATUS_START | MCI_TRACK)) { case MCI_STATUS_START: if (!MCICDA_ReadTOC(wmcda, &toc, &br)) return MCICDA_GetError(wmcda); lpParms->dwReturn = FRAME_OF_TOC(toc, toc.FirstTrack); TRACE("get MCI_STATUS_START !\n"); break; case MCI_TRACK: if (!MCICDA_ReadTOC(wmcda, &toc, &br)) return MCICDA_GetError(wmcda); if (lpParms->dwTrack < toc.FirstTrack || lpParms->dwTrack > toc.LastTrack) return MCIERR_OUTOFRANGE; lpParms->dwReturn = FRAME_OF_TOC(toc, lpParms->dwTrack); TRACE("get MCI_TRACK #%u !\n", lpParms->dwTrack); break; case 0: fmt.Format = IOCTL_CDROM_CURRENT_POSITION; if (!device_io(wmcda->handle, IOCTL_CDROM_READ_Q_CHANNEL, &fmt, sizeof(fmt), &data, sizeof(data), &br, NULL)) { return MCICDA_GetError(wmcda); } lpParms->dwReturn = FRAME_OF_ADDR(data.CurrentPosition.AbsoluteAddress); break; default: return MCIERR_FLAGS_NOT_COMPATIBLE; } lpParms->dwReturn = MCICDA_CalcTime(wmcda, wmcda->dwTimeFormat, lpParms->dwReturn, &ret); TRACE("MCI_STATUS_POSITION=%08lX\n", lpParms->dwReturn); break; case MCI_STATUS_READY: TRACE("MCI_STATUS_READY !\n"); switch (MCICDA_GetStatus(wmcda)) { case MCI_MODE_NOT_READY: case MCI_MODE_OPEN: lpParms->dwReturn = MAKEMCIRESOURCE(FALSE, MCI_FALSE); break; default: lpParms->dwReturn = MAKEMCIRESOURCE(TRUE, MCI_TRUE); break; } TRACE("MCI_STATUS_READY=%u!\n", LOWORD(lpParms->dwReturn)); ret = MCI_RESOURCE_RETURNED; break; case MCI_STATUS_TIME_FORMAT: lpParms->dwReturn = MAKEMCIRESOURCE(wmcda->dwTimeFormat, MCI_FORMAT_RETURN_BASE + wmcda->dwTimeFormat); TRACE("MCI_STATUS_TIME_FORMAT=%08x!\n", LOWORD(lpParms->dwReturn)); ret = MCI_RESOURCE_RETURNED; break; case 4001: /* FIXME: for bogus FullCD */ case MCI_CDA_STATUS_TYPE_TRACK: if (!(dwFlags & MCI_TRACK)) ret = MCIERR_MISSING_PARAMETER; else { if (!MCICDA_ReadTOC(wmcda, &toc, &br)) return MCICDA_GetError(wmcda); if (lpParms->dwTrack < toc.FirstTrack || lpParms->dwTrack > toc.LastTrack) ret = MCIERR_OUTOFRANGE; else lpParms->dwReturn = (toc.TrackData[lpParms->dwTrack - toc.FirstTrack].Control & 0x04) ? MCI_CDA_TRACK_OTHER : MCI_CDA_TRACK_AUDIO; /* FIXME: MAKEMCIRESOURCE "audio" | "other", localised */ } TRACE("MCI_CDA_STATUS_TYPE_TRACK[%d]=%ld\n", lpParms->dwTrack, lpParms->dwReturn); break; default: FIXME("unknown command %08X !\n", lpParms->dwItem); return MCIERR_UNSUPPORTED_FUNCTION; } } else return MCIERR_MISSING_PARAMETER; if ((dwFlags & MCI_NOTIFY) && HRESULT_CODE(ret)==0) MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL); return ret; } /************************************************************************** * MCICDA_SkipDataTracks [internal] */ static DWORD MCICDA_SkipDataTracks(WINE_MCICDAUDIO* wmcda,DWORD *frame) { int i; DWORD br; CDROM_TOC toc; if (!MCICDA_ReadTOC(wmcda, &toc, &br)) return MCICDA_GetError(wmcda); if (*frame < FRAME_OF_TOC(toc,toc.FirstTrack) || *frame >= FRAME_OF_TOC(toc,toc.LastTrack+1)) /* lead-out */ return MCIERR_OUTOFRANGE; for(i=toc.LastTrack+1;i>toc.FirstTrack;i--) if ( FRAME_OF_TOC(toc, i) <= *frame ) break; /* i points to last track whose start address is not greater than frame. * Now skip non-audio tracks */ for(;i<=toc.LastTrack;i++) if ( ! (toc.TrackData[i-toc.FirstTrack].Control & 4) ) break; /* The frame will be an address in the next audio track or * address of lead-out. */ if ( FRAME_OF_TOC(toc, i) > *frame ) *frame = FRAME_OF_TOC(toc, i); /* Lead-out is an invalid seek position (on Linux as well). */ if (*frame == FRAME_OF_TOC(toc,toc.LastTrack+1)) (*frame)--; return 0; } /************************************************************************** * MCICDA_Play [internal] */ static DWORD MCICDA_Play(UINT wDevID, DWORD dwFlags, LPMCI_PLAY_PARMS lpParms) { WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); DWORD ret = 0, start, end; HANDLE oldcb; DWORD br; CDROM_PLAY_AUDIO_MSF play; CDROM_SUB_Q_DATA_FORMAT fmt; SUB_Q_CHANNEL_DATA data; CDROM_TOC toc; TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms); if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; if (!MCICDA_ReadTOC(wmcda, &toc, &br)) return MCICDA_GetError(wmcda); if (dwFlags & MCI_FROM) { start = MCICDA_CalcFrame(wmcda, lpParms->dwFrom); if ( (ret=MCICDA_SkipDataTracks(wmcda, &start)) ) return ret; TRACE("MCI_FROM=%08X -> %u\n", lpParms->dwFrom, start); } else { fmt.Format = IOCTL_CDROM_CURRENT_POSITION; if (!device_io(wmcda->handle, IOCTL_CDROM_READ_Q_CHANNEL, &fmt, sizeof(fmt), &data, sizeof(data), &br, NULL)) { return MCICDA_GetError(wmcda); } start = FRAME_OF_ADDR(data.CurrentPosition.AbsoluteAddress); if ( (ret=MCICDA_SkipDataTracks(wmcda, &start)) ) return ret; } if (dwFlags & MCI_TO) { end = MCICDA_CalcFrame(wmcda, lpParms->dwTo); if ( (ret=MCICDA_SkipDataTracks(wmcda, &end)) ) return ret; TRACE("MCI_TO=%08X -> %u\n", lpParms->dwTo, end); } else { end = FRAME_OF_TOC(toc, toc.LastTrack + 1) - 1; } if (end < start) return MCIERR_OUTOFRANGE; TRACE("Playing from %u to %u\n", start, end); oldcb = InterlockedExchangePointer(&wmcda->hCallback, (dwFlags & MCI_NOTIFY) ? HWND_32(LOWORD(lpParms->dwCallback)) : NULL); if (oldcb) mciDriverNotify(oldcb, wmcda->wNotifyDeviceID, MCI_NOTIFY_ABORTED); if (start == end || start == FRAME_OF_TOC(toc,toc.LastTrack+1)-1) { if (dwFlags & MCI_NOTIFY) { oldcb = InterlockedExchangePointer(&wmcda->hCallback, NULL); if (oldcb) mciDriverNotify(oldcb, wDevID, MCI_NOTIFY_SUCCESSFUL); } return MMSYSERR_NOERROR; } if (wmcda->hThread != 0) { SetEvent(wmcda->stopEvent); WaitForSingleObject(wmcda->hThread, INFINITE); CloseHandle(wmcda->hThread); wmcda->hThread = 0; CloseHandle(wmcda->stopEvent); wmcda->stopEvent = 0; IDirectSoundBuffer_Stop(wmcda->dsBuf); IDirectSoundBuffer_Release(wmcda->dsBuf); wmcda->dsBuf = NULL; IDirectSound_Release(wmcda->dsObj); wmcda->dsObj = NULL; } if (pDirectSoundCreate) { WAVEFORMATEX format; DSBUFFERDESC desc; DWORD lockLen; void *cdData; HRESULT hr; hr = pDirectSoundCreate(NULL, &wmcda->dsObj, NULL); if (SUCCEEDED(hr)) { IDirectSound_SetCooperativeLevel(wmcda->dsObj, GetDesktopWindow(), DSSCL_PRIORITY); /* The "raw" frame is relative to the start of the first track */ wmcda->start = start - FRAME_OF_TOC(toc, toc.FirstTrack); wmcda->end = end - FRAME_OF_TOC(toc, toc.FirstTrack); memset(&format, 0, sizeof(format)); format.wFormatTag = WAVE_FORMAT_PCM; format.nChannels = 2; format.nSamplesPerSec = 44100; format.wBitsPerSample = 16; format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8; format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign; format.cbSize = 0; memset(&desc, 0, sizeof(desc)); desc.dwSize = sizeof(desc); desc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS; desc.dwBufferBytes = (CDDA_FRAG_SIZE - (CDDA_FRAG_SIZE%RAW_SECTOR_SIZE)) * CDDA_FRAG_COUNT; desc.lpwfxFormat = &format; hr = IDirectSound_CreateSoundBuffer(wmcda->dsObj, &desc, &wmcda->dsBuf, NULL); } if (SUCCEEDED(hr)) { hr = IDirectSoundBuffer_Lock(wmcda->dsBuf, 0, 0, &cdData, &lockLen, NULL, NULL, DSBLOCK_ENTIREBUFFER); } if (SUCCEEDED(hr)) { RAW_READ_INFO rdInfo; int readok; rdInfo.DiskOffset.QuadPart = wmcda->start<<11; rdInfo.SectorCount = min(desc.dwBufferBytes/RAW_SECTOR_SIZE, wmcda->end-wmcda->start); rdInfo.TrackMode = CDDA; readok = device_io(wmcda->handle, IOCTL_CDROM_RAW_READ, &rdInfo, sizeof(rdInfo), cdData, lockLen, &br, NULL); IDirectSoundBuffer_Unlock(wmcda->dsBuf, cdData, lockLen, NULL, 0); if (readok) { wmcda->start += rdInfo.SectorCount; wmcda->stopEvent = CreateEventA(NULL, TRUE, FALSE, NULL); } if (wmcda->stopEvent != 0) wmcda->hThread = CreateThread(NULL, 0, MCICDA_playLoop, wmcda, 0, &br); if (wmcda->hThread != 0) { hr = IDirectSoundBuffer_Play(wmcda->dsBuf, 0, 0, DSBPLAY_LOOPING); if (SUCCEEDED(hr)) { /* FIXME: implement MCI_WAIT and send notification only in that case */ if (0) { oldcb = InterlockedExchangePointer(&wmcda->hCallback, NULL); if (oldcb) mciDriverNotify(oldcb, wmcda->wNotifyDeviceID, FAILED(hr) ? MCI_NOTIFY_FAILURE : MCI_NOTIFY_SUCCESSFUL); } return ret; } SetEvent(wmcda->stopEvent); WaitForSingleObject(wmcda->hThread, INFINITE); CloseHandle(wmcda->hThread); wmcda->hThread = 0; } } if (wmcda->stopEvent != 0) { CloseHandle(wmcda->stopEvent); wmcda->stopEvent = 0; } if (wmcda->dsBuf) { IDirectSoundBuffer_Release(wmcda->dsBuf); wmcda->dsBuf = NULL; } if (wmcda->dsObj) { IDirectSound_Release(wmcda->dsObj); wmcda->dsObj = NULL; } } play.StartingM = start / CDFRAMES_PERMIN; play.StartingS = (start / CDFRAMES_PERSEC) % 60; play.StartingF = start % CDFRAMES_PERSEC; play.EndingM = end / CDFRAMES_PERMIN; play.EndingS = (end / CDFRAMES_PERSEC) % 60; play.EndingF = end % CDFRAMES_PERSEC; if (!device_io(wmcda->handle, IOCTL_CDROM_PLAY_AUDIO_MSF, &play, sizeof(play), NULL, 0, &br, NULL)) { wmcda->hCallback = NULL; ret = MCIERR_HARDWARE; } /* The independent CD player has no means to signal MCI_NOTIFY when it's done. * Native sends a notification with MCI_WAIT only. */ return ret; } /************************************************************************** * MCICDA_Stop [internal] */ static DWORD MCICDA_Stop(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms) { WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); HANDLE oldcb; DWORD br; TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms); if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; oldcb = InterlockedExchangePointer(&wmcda->hCallback, NULL); if (oldcb) mciDriverNotify(oldcb, wmcda->wNotifyDeviceID, MCI_NOTIFY_ABORTED); if (wmcda->hThread != 0) { SetEvent(wmcda->stopEvent); WaitForSingleObject(wmcda->hThread, INFINITE); CloseHandle(wmcda->hThread); wmcda->hThread = 0; CloseHandle(wmcda->stopEvent); wmcda->stopEvent = 0; IDirectSoundBuffer_Release(wmcda->dsBuf); wmcda->dsBuf = NULL; IDirectSound_Release(wmcda->dsObj); wmcda->dsObj = NULL; } else if (!device_io(wmcda->handle, IOCTL_CDROM_STOP_AUDIO, NULL, 0, NULL, 0, &br, NULL)) return MCIERR_HARDWARE; if ((dwFlags & MCI_NOTIFY) && lpParms) MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL); return 0; } /************************************************************************** * MCICDA_Pause [internal] */ static DWORD MCICDA_Pause(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms) { WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); HANDLE oldcb; DWORD br; TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms); if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; oldcb = InterlockedExchangePointer(&wmcda->hCallback, NULL); if (oldcb) mciDriverNotify(oldcb, wmcda->wNotifyDeviceID, MCI_NOTIFY_ABORTED); if (wmcda->hThread != 0) { /* Don't bother calling stop if the playLoop thread has already stopped */ if(WaitForSingleObject(wmcda->stopEvent, 0) != WAIT_OBJECT_0 && FAILED(IDirectSoundBuffer_Stop(wmcda->dsBuf))) return MCIERR_HARDWARE; } else if (!device_io(wmcda->handle, IOCTL_CDROM_PAUSE_AUDIO, NULL, 0, NULL, 0, &br, NULL)) return MCIERR_HARDWARE; if ((dwFlags & MCI_NOTIFY) && lpParms) MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL); return 0; } /************************************************************************** * MCICDA_Resume [internal] */ static DWORD MCICDA_Resume(UINT wDevID, DWORD dwFlags, LPMCI_GENERIC_PARMS lpParms) { WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); DWORD br; TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms); if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; if (wmcda->hThread != 0) { /* Don't restart if the playLoop thread has already stopped */ if(WaitForSingleObject(wmcda->stopEvent, 0) != WAIT_OBJECT_0 && FAILED(IDirectSoundBuffer_Play(wmcda->dsBuf, 0, 0, DSBPLAY_LOOPING))) return MCIERR_HARDWARE; } else if (!device_io(wmcda->handle, IOCTL_CDROM_RESUME_AUDIO, NULL, 0, NULL, 0, &br, NULL)) return MCIERR_HARDWARE; if ((dwFlags & MCI_NOTIFY) && lpParms) MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL); return 0; } /************************************************************************** * MCICDA_Seek [internal] */ static DWORD MCICDA_Seek(UINT wDevID, DWORD dwFlags, LPMCI_SEEK_PARMS lpParms) { DWORD at; WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); CDROM_SEEK_AUDIO_MSF seek; DWORD br, position, ret; CDROM_TOC toc; TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms); if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; position = dwFlags & (MCI_SEEK_TO_START|MCI_SEEK_TO_END|MCI_TO); if (!position) return MCIERR_MISSING_PARAMETER; if (position&(position-1)) return MCIERR_FLAGS_NOT_COMPATIBLE; /* Stop sends MCI_NOTIFY_ABORTED when needed. * Tests show that native first sends ABORTED and reads the TOC, * then only checks the position flags, then stops and seeks. */ MCICDA_Stop(wDevID, MCI_WAIT, 0); if (!MCICDA_ReadTOC(wmcda, &toc, &br)) return MCICDA_GetError(wmcda); switch (position) { case MCI_SEEK_TO_START: TRACE("Seeking to start\n"); at = FRAME_OF_TOC(toc,toc.FirstTrack); if ( (ret=MCICDA_SkipDataTracks(wmcda, &at)) ) return ret; break; case MCI_SEEK_TO_END: TRACE("Seeking to end\n"); /* End is prior to lead-out * yet Win9X seeks to even one frame less than that. */ at = FRAME_OF_TOC(toc, toc.LastTrack + 1) - 1; if ( (ret=MCICDA_SkipDataTracks(wmcda, &at)) ) return ret; break; case MCI_TO: TRACE("Seeking to %u\n", lpParms->dwTo); at = MCICDA_CalcFrame(wmcda, lpParms->dwTo); if ( (ret=MCICDA_SkipDataTracks(wmcda, &at)) ) return ret; break; default: return MCIERR_FLAGS_NOT_COMPATIBLE; } { seek.M = at / CDFRAMES_PERMIN; seek.S = (at / CDFRAMES_PERSEC) % 60; seek.F = at % CDFRAMES_PERSEC; if (!device_io(wmcda->handle, IOCTL_CDROM_SEEK_AUDIO_MSF, &seek, sizeof(seek), NULL, 0, &br, NULL)) return MCIERR_HARDWARE; } if (dwFlags & MCI_NOTIFY) MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL); return 0; } /************************************************************************** * MCICDA_SetDoor [internal] */ static DWORD MCICDA_SetDoor(UINT wDevID, BOOL open) { WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); DWORD br; TRACE("(%04x, %s) !\n", wDevID, (open) ? "OPEN" : "CLOSE"); if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; if (!device_io(wmcda->handle, (open) ? IOCTL_STORAGE_EJECT_MEDIA : IOCTL_STORAGE_LOAD_MEDIA, NULL, 0, NULL, 0, &br, NULL)) return MCIERR_HARDWARE; return 0; } /************************************************************************** * MCICDA_Set [internal] */ static DWORD MCICDA_Set(UINT wDevID, DWORD dwFlags, LPMCI_SET_PARMS lpParms) { WINE_MCICDAUDIO* wmcda = MCICDA_GetOpenDrv(wDevID); TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms); if (wmcda == NULL) return MCIERR_INVALID_DEVICE_ID; if (dwFlags & MCI_SET_DOOR_OPEN) { MCICDA_SetDoor(wDevID, TRUE); } if (dwFlags & MCI_SET_DOOR_CLOSED) { MCICDA_SetDoor(wDevID, FALSE); } /* only functions which require valid lpParms below this line ! */ if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; /* TRACE("dwTimeFormat=%08lX\n", lpParms->dwTimeFormat); */ if (dwFlags & MCI_SET_TIME_FORMAT) { switch (lpParms->dwTimeFormat) { case MCI_FORMAT_MILLISECONDS: TRACE("MCI_FORMAT_MILLISECONDS !\n"); break; case MCI_FORMAT_MSF: TRACE("MCI_FORMAT_MSF !\n"); break; case MCI_FORMAT_TMSF: TRACE("MCI_FORMAT_TMSF !\n"); break; default: return MCIERR_BAD_TIME_FORMAT; } wmcda->dwTimeFormat = lpParms->dwTimeFormat; } if (dwFlags & MCI_SET_AUDIO) /* one xp machine ignored it */ TRACE("SET_AUDIO %X %x\n", dwFlags, lpParms->dwAudio); if (dwFlags & MCI_NOTIFY) MCICDA_Notify(lpParms->dwCallback, wmcda, MCI_NOTIFY_SUCCESSFUL); return 0; } /************************************************************************** * DriverProc (MCICDA.@) */ LRESULT CALLBACK MCICDA_DriverProc(DWORD_PTR dwDevID, HDRVR hDriv, UINT wMsg, LPARAM dwParam1, LPARAM dwParam2) { switch(wMsg) { case DRV_LOAD: return 1; case DRV_FREE: return 1; case DRV_OPEN: return MCICDA_drvOpen((LPCWSTR)dwParam1, (LPMCI_OPEN_DRIVER_PARMSW)dwParam2); case DRV_CLOSE: return MCICDA_drvClose(dwDevID); case DRV_ENABLE: return 1; case DRV_DISABLE: return 1; case DRV_QUERYCONFIGURE: return 1; case DRV_CONFIGURE: MessageBoxA(0, "MCI audio CD driver !", "Wine Driver", MB_OK); return 1; case DRV_INSTALL: return DRVCNF_RESTART; case DRV_REMOVE: return DRVCNF_RESTART; } if (dwDevID == 0xFFFFFFFF) return MCIERR_UNSUPPORTED_FUNCTION; switch (wMsg) { case MCI_OPEN_DRIVER: return MCICDA_Open(dwDevID, dwParam1, (LPMCI_OPEN_PARMSW)dwParam2); case MCI_CLOSE_DRIVER: return MCICDA_Close(dwDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2); case MCI_GETDEVCAPS: return MCICDA_GetDevCaps(dwDevID, dwParam1, (LPMCI_GETDEVCAPS_PARMS)dwParam2); case MCI_INFO: return MCICDA_Info(dwDevID, dwParam1, (LPMCI_INFO_PARMSW)dwParam2); case MCI_STATUS: return MCICDA_Status(dwDevID, dwParam1, (LPMCI_STATUS_PARMS)dwParam2); case MCI_SET: return MCICDA_Set(dwDevID, dwParam1, (LPMCI_SET_PARMS)dwParam2); case MCI_PLAY: return MCICDA_Play(dwDevID, dwParam1, (LPMCI_PLAY_PARMS)dwParam2); case MCI_STOP: return MCICDA_Stop(dwDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2); case MCI_PAUSE: return MCICDA_Pause(dwDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2); case MCI_RESUME: return MCICDA_Resume(dwDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2); case MCI_SEEK: return MCICDA_Seek(dwDevID, dwParam1, (LPMCI_SEEK_PARMS)dwParam2); /* commands that should report an error as they are not supported in * the native version */ case MCI_RECORD: case MCI_LOAD: case MCI_SAVE: return MCIERR_UNSUPPORTED_FUNCTION; case MCI_BREAK: case MCI_FREEZE: case MCI_PUT: case MCI_REALIZE: case MCI_UNFREEZE: case MCI_UPDATE: case MCI_WHERE: case MCI_STEP: case MCI_SPIN: case MCI_ESCAPE: case MCI_COPY: case MCI_CUT: case MCI_DELETE: case MCI_PASTE: case MCI_WINDOW: TRACE("Unsupported command [0x%x]\n", wMsg); break; case MCI_OPEN: case MCI_CLOSE: ERR("Shouldn't receive a MCI_OPEN or CLOSE message\n"); break; default: TRACE("Sending msg [0x%x] to default driver proc\n", wMsg); return DefDriverProc(dwDevID, hDriv, wMsg, dwParam1, dwParam2); } return MCIERR_UNRECOGNIZED_COMMAND; } /*-----------------------------------------------------------------------*/
utf-8
1
LGPL-2.1+
Copyright (c) 1993-2020 Wine project authors (see AUTHORS file)
boost1.74-1.74.0/libs/compute/perf/perf_cart_to_polar.cpp
//---------------------------------------------------------------------------// // Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #define _USE_MATH_DEFINES #include <algorithm> #include <iostream> #include <vector> #include <boost/compute/system.hpp> #include <boost/compute/algorithm/copy.hpp> #include <boost/compute/algorithm/copy_n.hpp> #include <boost/compute/algorithm/transform.hpp> #include <boost/compute/container/vector.hpp> #include "perf.hpp" namespace compute = boost::compute; using compute::float2_; float rand_float() { return (float(rand()) / float(RAND_MAX)) * 1000.f; } void serial_cartesian_to_polar(const float *input, size_t n, float *output) { for(size_t i = 0; i < n; i++){ float x = input[i*2+0]; float y = input[i*2+1]; float magnitude = std::sqrt(x*x + y*y); float angle = std::atan2(y, x) * 180.f / M_PI; output[i*2+0] = magnitude; output[i*2+1] = angle; } } void serial_polar_to_cartesian(const float *input, size_t n, float *output) { for(size_t i = 0; i < n; i++){ float magnitude = input[i*2+0]; float angle = input[i*2+1]; float x = magnitude * cos(angle); float y = magnitude * sin(angle); output[i*2+0] = x; output[i*2+1] = y; } } // converts from cartesian coordinates (x, y) to polar coordinates (magnitude, angle) BOOST_COMPUTE_FUNCTION(float2_, cartesian_to_polar, (float2_ p), { float x = p.x; float y = p.y; float magnitude = sqrt(x*x + y*y); float angle = atan2(y, x) * 180.f / M_PI; return (float2)(magnitude, angle); }); // converts from polar coordinates (magnitude, angle) to cartesian coordinates (x, y) BOOST_COMPUTE_FUNCTION(float2_, polar_to_cartesian, (float2_ p), { float magnitude = p.x; float angle = p.y; float x = magnitude * cos(angle); float y = magnitude * sin(angle); return (float2)(x, y) }); int main(int argc, char *argv[]) { perf_parse_args(argc, argv); std::cout << "size: " << PERF_N << std::endl; // setup context and queue for the default device compute::device device = compute::system::default_device(); compute::context context(device); compute::command_queue queue(context, device); std::cout << "device: " << device.name() << std::endl; // create vector of random numbers on the host std::vector<float> host_vector(PERF_N*2); std::generate(host_vector.begin(), host_vector.end(), rand_float); // create vector on the device and copy the data compute::vector<float2_> device_vector(PERF_N, context); compute::copy_n( reinterpret_cast<float2_ *>(&host_vector[0]), PERF_N, device_vector.begin(), queue ); perf_timer t; for(size_t trial = 0; trial < PERF_TRIALS; trial++){ t.start(); compute::transform( device_vector.begin(), device_vector.end(), device_vector.begin(), cartesian_to_polar, queue ); queue.finish(); t.stop(); } std::cout << "time: " << t.min_time() / 1e6 << " ms" << std::endl; // perform saxpy on host t.clear(); for(size_t trial = 0; trial < PERF_TRIALS; trial++){ t.start(); serial_cartesian_to_polar(&host_vector[0], PERF_N, &host_vector[0]); t.stop(); } std::cout << "host time: " << t.min_time() / 1e6 << " ms" << std::endl; std::vector<float> device_data(PERF_N*2); compute::copy( device_vector.begin(), device_vector.end(), reinterpret_cast<float2_ *>(&device_data[0]), queue ); for(size_t i = 0; i < PERF_N; i++){ float host_value = host_vector[i]; float device_value = device_data[i]; if(std::abs(device_value - host_value) > 1e-3){ std::cout << "ERROR: " << "value at " << i << " " << "device_value (" << device_value << ") " << "!= " << "host_value (" << host_value << ")" << std::endl; return -1; } } return 0; }
utf-8
1
BSL-1.0
Boost project contributors
chromium-98.0.4758.102/chrome/browser/ash/policy/external_data/device_local_account_external_data_manager.cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/policy/external_data/device_local_account_external_data_manager.h" #include <memory> #include "base/task/sequenced_task_runner.h" #include "chrome/browser/ash/policy/external_data/device_local_account_external_data_service.h" #include "components/policy/core/common/cloud/cloud_external_data_store.h" #include "components/policy/core/common/cloud/resource_cache.h" #include "components/policy/policy_constants.h" namespace policy { DeviceLocalAccountExternalDataManager::DeviceLocalAccountExternalDataManager( const std::string& account_id, const GetChromePolicyDetailsCallback& get_policy_details, scoped_refptr<base::SequencedTaskRunner> backend_task_runner, ResourceCache* resource_cache) : CloudExternalDataManagerBase(get_policy_details, backend_task_runner) { SetExternalDataStore(std::make_unique<CloudExternalDataStore>( account_id, backend_task_runner, resource_cache)); } DeviceLocalAccountExternalDataManager:: ~DeviceLocalAccountExternalDataManager() { SetExternalDataStore(nullptr); } void DeviceLocalAccountExternalDataManager::OnPolicyStoreLoaded() { CloudExternalDataManagerBase::OnPolicyStoreLoaded(); // Proactively try to download and cache all external data referenced by // policies. FetchAll(); } } // namespace policy
utf-8
1
BSD-3-clause
The Chromium Authors. All rights reserved.