repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
filebench
filebench-master/filebench.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #ifndef _FB_FILEBENCH_H #define _FB_FILEBENCH_H #include "config.h" #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/param.h> #include <sys/resource.h> #include <pthread.h> #include <signal.h> #ifndef HAVE_SYSV_SEM #include <semaphore.h> #endif #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/times.h> #ifdef HAVE_STDINT_H #include <stdint.h> #endif /* We use __STDC__ to determine how to handle functions with variable number of arguments in filbench_log function */ #ifdef __STDC__ #include <stdarg.h> #define __V(x) x #ifndef __P #define __P(x) x #endif #else #include <varargs.h> #define __V(x) (va_alist) va_dcl #define __P(x) () #define const #endif #ifdef HAVE_AIO #include <aio.h> #endif #include <dirent.h> /* Defining our internal types */ typedef uint64_t fbint_t; #ifndef HAVE_BOOLEAN_T typedef enum { B_FALSE, B_TRUE } boolean_t; #endif #define TRUE 1 #define FALSE 0 #ifndef HAVE_U_LONGLONG_T typedef unsigned long long u_longlong_t; #endif #ifndef HAVE_UINT_T typedef unsigned int uint_t; #endif #ifndef MIN /* not defined on OpenSolaris */ #define MIN(a,b) (((a)<(b))?(a):(b)) #endif /* change 64-postfixed defininition to the regular: on FreeBSD all these function are already 64bit */ #ifndef HAVE_OFF64_T #define off64_t off_t #endif #ifndef HAVE_STAT64 /* this will replace both: struct stat64 and function stat64 */ #define stat64 stat #endif #ifndef HAVE_AIO_ERROR64 #define aio_error64 aio_error #endif #ifndef HAVE_AIO_WRITE64 #define aio_write64 aio_write #define aiocb64 aiocb #endif #ifndef HAVE_AIO_RETURN64 #define aio_return64 aio_return #endif #ifndef HAVE_OPEN64 #define open64 open #endif #ifndef HAVE_MMAP64 #define mmap64 mmap #endif #ifndef HAVE_FSTAT64 #define fstat64 fstat #endif #ifndef HAVE_LSEEK64 #define lseek64 lseek #endif #ifndef HAVE_PWRITE64 #define pwrite64 pwrite #endif #ifndef HAVE_PREAD64 #define pread64 pread #endif #include "flag.h" #include "vars.h" #include "fb_cvar.h" #include "fb_avl.h" #include "stats.h" #include "procflow.h" #include "misc.h" #include "fsplug.h" #include "fileset.h" #include "threadflow.h" #include "flowop.h" #include "fb_random.h" #include "ipc.h" extern pid_t my_pid; /* this process' process id */ extern procflow_t *my_procflow; /* if slave process, procflow pointer */ extern int errno; extern char *execname; void filebench_log __V((int level, const char *fmt, ...)); void filebench_shutdown(int error); void filebench_plugin_funcvecinit(void); #define FILEBENCH_RANDMAX64 UINT64_MAX #define FILEBENCH_RANDMAX32 UINT32_MAX #if defined(_LP64) || (__WORDSIZE == 64) #define fb_random fb_random64 #define FILEBENCH_RANDMAX FILEBENCH_RANDMAX64 #else #define fb_random fb_random32 #define FILEBENCH_RANDMAX FILEBENCH_RANDMAX32 #endif #ifndef HAVE_SIGIGNORE /* No sigignore on FreeBSD */ static inline int sigignore(int sig) { struct sigaction sa; bzero(&sa, sizeof(sa)); sa.sa_handler = SIG_IGN; return (sigaction(sig, &sa, NULL)); } #endif #define KB (1024LL) #define MB (KB * KB) #define GB (KB * MB) #define KB_FLOAT ((double)1024.0) #define MB_FLOAT (KB_FLOAT * KB_FLOAT) #define GB_FLOAT (KB_FLOAT * MB_FLOAT) #define MMAP_SIZE (1024UL * 1024UL * 1024UL) #define FILEBENCH_VERSION VERSION #define FILEBENCH_PROMPT "filebench> " #define MAX_LINE_LEN 1024 #define MAX_CMD_HIST 128 #define SHUTDOWN_WAIT_SECONDS 3 /* time to wait for proc / thrd to quit */ #define FILEBENCH_DONE 1 #define FILEBENCH_OK 0 #define FILEBENCH_ERROR -1 #define FILEBENCH_NORSC -2 #endif /* _FB_FILEBENCH_H */
4,589
22.782383
74
h
filebench
filebench-master/fileset.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_FILESET_H #define _FB_FILESET_H #include "filebench.h" #define FILE_ALLOC_BLOCK (off64_t)(1024 * 1024) #define FSE_MAXTID 16384 #define FSE_MAXPATHLEN 16 #define FSE_TYPE_FILE 0x00 #define FSE_TYPE_DIR 0x01 #define FSE_TYPE_LEAFDIR 0x02 #define FSE_TYPE_MASK 0x03 #define FSE_FREE 0x04 #define FSE_EXISTS 0x08 #define FSE_BUSY 0x10 #define FSE_REUSING 0x20 #define FSE_THRD_WAITNG 0x40 typedef struct filesetentry { struct filesetentry *fse_next; /* master list of entries */ struct filesetentry *fse_parent; /* link to directory */ avl_node_t fse_link; /* links in avl btree, prot. */ /* by fs_pick_lock */ uint_t fse_index; /* file order number */ struct filesetentry *fse_nextoftype; /* List of specific fse */ struct fileset *fse_fileset; /* Parent fileset */ char *fse_path; int fse_depth; off64_t fse_size; int fse_open_cnt; /* protected by fs_pick_lock */ int fse_flags; /* protected by fs_pick_lock */ } filesetentry_t; #define FSE_OFFSETOF(f) ((size_t)(&(((filesetentry_t *)0)->f))) /* type of fileset entry to obtain */ #define FILESET_PICKFILE 0x00 /* Pick a file from the set */ #define FILESET_PICKDIR 0x01 /* Pick a directory */ #define FILESET_PICKLEAFDIR 0x02 /* Pick a leaf directory */ #define FILESET_PICKMASK 0x03 /* Pick type mask */ /* other pick flags */ #define FILESET_PICKUNIQUE 0x04 /* Pick a unique file or leafdir from the */ /* fileset until empty */ #define FILESET_PICKEXISTS 0x10 /* Pick an existing file */ #define FILESET_PICKNOEXIST 0x20 /* Pick a file that doesn't exist */ #define FILESET_PICKBYINDEX 0x40 /* use supplied index number to select file */ #define FILESET_PICKFREE FILESET_PICKUNIQUE /* fileset attributes */ #define FILESET_IS_RAW_DEV 0x01 /* fileset is a raw device */ #define FILESET_IS_FILE 0x02 /* Fileset is emulating a single file */ typedef struct fileset { struct fileset *fs_next; /* Next in list */ avd_t fs_name; /* Name */ avd_t fs_path; /* Pathname prefix in fileset */ avd_t fs_entries; /* Number of entries attr */ /* (possibly random) */ fbint_t fs_constentries; /* Constant version of enties attr */ avd_t fs_leafdirs; /* Number of leaf directories attr */ /* (possibly random) */ fbint_t fs_constleafdirs; /* Constant version of leafdirs */ /* attr */ avd_t fs_preallocpercent; /* Prealloc size */ int fs_attrs; /* Attributes */ avd_t fs_dirwidth; /* Explicit or mean for distribution */ avd_t fs_dirdepthrv; /* random variable for dir depth */ avd_t fs_size; /* Explicit or mean for distribution */ avd_t fs_dirgamma; /* Dirdepth Gamma distribution */ /* (* 1000) defaults to 1500, set */ /* to 0 for explicit depth */ avd_t fs_create; /* Attr */ avd_t fs_paralloc; /* Attr */ avd_t fs_reuse; /* Attr */ avd_t fs_readonly; /* Attr */ avd_t fs_writeonly; /* Attr */ avd_t fs_trust_tree; /* Attr */ double fs_meandepth; /* Computed mean depth */ double fs_meanwidth; /* Specified mean dir width */ int fs_realfiles; /* Actual files */ int fs_realleafdirs; /* Actual explicit leaf directories */ off64_t fs_bytes; /* Total space consumed by files */ int64_t fs_idle_files; /* number of files NOT busy */ pthread_cond_t fs_idle_files_cv; /* idle files condition variable */ int64_t fs_idle_dirs; /* number of dirs NOT busy */ pthread_cond_t fs_idle_dirs_cv; /* idle dirs condition variable */ int64_t fs_idle_leafdirs; /* number of dirs NOT busy */ pthread_cond_t fs_idle_leafdirs_cv; /* idle dirs condition variable */ pthread_mutex_t fs_pick_lock; /* per fileset "pick" function lock */ pthread_cond_t fs_thrd_wait_cv; /* per fileset file busy wait cv */ avl_tree_t fs_free_files; /* btree of free files */ avl_tree_t fs_exist_files; /* btree of files on device */ avl_tree_t fs_noex_files; /* btree of files NOT on device */ avl_tree_t fs_dirs; /* btree of internal dirs */ avl_tree_t fs_free_leaf_dirs; /* btree of free leaf dirs */ avl_tree_t fs_exist_leaf_dirs; /* btree of leaf dirs on device */ avl_tree_t fs_noex_leaf_dirs; /* btree of leaf dirs NOT */ /* currently on device */ filesetentry_t *fs_filelist; /* List of files */ uint_t fs_file_exrotor[FSE_MAXTID]; /* next file to */ /* select */ uint_t fs_file_nerotor; /* next non existent file */ /* to select for createfile */ filesetentry_t *fs_dirlist; /* List of directories */ uint_t fs_dirrotor; /* index of next directory to select */ filesetentry_t *fs_leafdirlist; /* List of leaf directories */ uint_t fs_leafdir_exrotor; /* Ptr to next existing leaf */ /* directory to select */ uint_t fs_leafdir_nerotor; /* Ptr to next non-existing */ int *fs_filehistop; /* Ptr to access histogram */ pthread_mutex_t fs_histo_lock; /* lock for incr of histo */ } fileset_t; int fileset_createsets(); void fileset_delete_all_filesets(void); int fileset_openfile(fb_fdesc_t *fd, fileset_t *fileset, filesetentry_t *entry, int flag, int mode, int attrs); fileset_t *fileset_define(avd_t name, avd_t path); fileset_t *fileset_find(char *name); filesetentry_t *fileset_pick(fileset_t *fileset, int flags, int tid, int index); char *fileset_resolvepath(filesetentry_t *entry); int fileset_iter(int (*cmd)(fileset_t *fileset, int first)); int fileset_print(fileset_t *fileset, int first); void fileset_unbusy(filesetentry_t *entry, int update_exist, int new_exist_val, int open_cnt_incr); int fileset_dump_histo(fileset_t *fileset, int first); void fileset_attach_all_histos(void); #endif /* _FB_FILESET_H */
6,504
38.907975
79
h
filebench
filebench-master/flowop.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_FLOWOP_H #define _FB_FLOWOP_H #include "filebench.h" typedef struct flowop { char fo_name[128]; /* Name */ int fo_instance; /* Instance number */ struct flowop *fo_next; /* Next in global list */ struct flowop *fo_exec_next; /* Next in thread's or compfo's list */ struct flowop *fo_resultnext; /* List of flowops in result */ struct flowop *fo_comp_fops; /* List of flowops in composite fo */ var_t *fo_lvar_list; /* List of composite local vars */ struct threadflow *fo_thread; /* Backpointer to thread */ int (*fo_func)(); /* Method */ int (*fo_init)(); /* Init Method */ void (*fo_destruct)(); /* Destructor Method */ int fo_type; /* Type */ int fo_attrs; /* Flow op attribute */ avd_t fo_filename; /* file/fileset name */ fileset_t *fo_fileset; /* Fileset for op */ int fo_fdnumber; /* User specified file descriptor */ int fo_srcfdnumber; /* User specified src file descriptor */ fbint_t fo_constvalue; /* constant version of fo_value */ fbint_t fo_constwss; /* constant version of fo_wss */ avd_t fo_iosize; /* Size of operation */ avd_t fo_wss; /* Flow op working set size */ char fo_targetname[128]; /* Target, for wakeup etc... */ struct flowop *fo_targets; /* List of targets matching name */ struct flowop *fo_targetnext; /* List of targets matching name */ avd_t fo_iters; /* Number of iterations of op */ avd_t fo_value; /* Attr */ avd_t fo_sequential; /* Attr */ avd_t fo_random; /* Attr */ avd_t fo_stride; /* Attr */ avd_t fo_backwards; /* Attr */ avd_t fo_dsync; /* Attr */ avd_t fo_blocking; /* Attr */ avd_t fo_directio; /* Attr */ avd_t fo_rotatefd; /* Attr */ avd_t fo_fileindex; /* Attr */ avd_t fo_noreadahead; /* Attr */ struct flowstats fo_stats; /* Flow statistics */ pthread_cond_t fo_cv; /* Block/wakeup cv */ pthread_mutex_t fo_lock; /* Mutex around flowop */ void *fo_private; /* Flowop private scratch pad area */ char *fo_buf; /* Per-flowop buffer */ uint64_t fo_buf_size; /* current size of buffer */ #ifdef HAVE_SYSV_SEM int fo_semid_lw; /* sem id */ int fo_semid_hw; /* sem id for highwater block */ #else sem_t fo_sem; /* sem_t for posix semaphores */ #endif /* HAVE_SYSV_SEM */ avd_t fo_highwater; /* value of highwater paramter */ void *fo_idp; /* id, for sems etc */ hrtime_t fo_timestamp; /* for ratecontrol, etc... */ int fo_initted; /* Set to one if initialized */ int64_t fo_tputbucket; /* Throughput bucket, for limiter */ uint64_t fo_tputlast; /* Throughput count, for delta's */ } flowop_t; /* Flow Op Attrs */ #define FLOW_ATTR_SEQUENTIAL 0x1 #define FLOW_ATTR_RANDOM 0x2 #define FLOW_ATTR_STRIDE 0x4 #define FLOW_ATTR_BACKWARDS 0x8 #define FLOW_ATTR_DSYNC 0x10 #define FLOW_ATTR_BLOCKING 0x20 #define FLOW_ATTR_DIRECTIO 0x40 #define FLOW_ATTR_READ 0x80 #define FLOW_ATTR_WRITE 0x100 #define FLOW_ATTR_FADV_RANDOM 0x200 /* Flowop Instance Numbers */ /* Worker flowops have instance numbers > 0 */ #define FLOW_DEFINITION 0 /* Prototype definition of flowop from library */ #define FLOW_INNER_DEF -1 /* Constructed proto flowops within composite */ #define FLOW_MASTER -2 /* Master flowop based on flowop declaration */ /* supplied within a thread definition */ /* Flowop type definitions */ #define FLOW_TYPES 6 #define FLOW_TYPE_GLOBAL 0 /* Rolled up statistics */ #define FLOW_TYPE_IO 1 /* Op is an I/O, reflected in iops and lat */ #define FLOW_TYPE_AIO 2 /* Op is an async I/O, reflected in iops */ #define FLOW_TYPE_SYNC 3 /* Op is a sync event */ #define FLOW_TYPE_COMPOSITE 4 /* Op is a composite flowop */ #define FLOW_TYPE_OTHER 5 /* Op is a something else */ typedef struct flowop_proto { int fl_type; int fl_attrs; char *fl_name; int (*fl_init)(); int (*fl_func)(); void (*fl_destruct)(); } flowop_proto_t; extern struct flowstats controlstats; extern pthread_mutex_t controlstats_lock; flowop_t *flowop_define(threadflow_t *, char *name, flowop_t *inherit, flowop_t **flowoplist_hdp, int instance, int type); flowop_t *flowop_find(char *name); flowop_t *flowop_find_one(char *name, int instance); flowop_t *flowop_find_from_list(char *name, flowop_t *list); int flowop_init_generic(flowop_t *flowop); void flowop_destruct_generic(flowop_t *flowop); void flowop_add_from_proto(flowop_proto_t *list, int nops); int flowoplib_iosetup(threadflow_t *threadflow, flowop_t *flowop, fbint_t *wssp, caddr_t *iobufp, fb_fdesc_t **filedescp, fbint_t iosize); void flowoplib_flowinit(void); void flowop_delete_all(flowop_t **threadlist); void flowop_endop(threadflow_t *threadflow, flowop_t *flowop, int64_t bytes); void flowop_beginop(threadflow_t *threadflow, flowop_t *flowop); void flowop_destruct_all_flows(threadflow_t *threadflow); flowop_t *flowop_new_composite_define(char *name); void flowop_printall(void); void flowop_init(int ismaster); /* Local file system specific */ void fb_lfs_funcvecinit(); void fb_lfs_newflowops(); #endif /* _FB_FLOWOP_H */
5,901
37.077419
77
h
filebench
filebench-master/fsplug.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * */ #ifndef _FB_FSPLUG_H #define _FB_FSPLUG_H #include "filebench.h" /* * Type of file system client plug-in desired. */ typedef enum fb_plugin_type { LOCAL_FS_PLUG = 0, NFS3_PLUG, NFS4_PLUG, CIFS_PLUG } fb_plugin_type_t; /* universal file descriptor for both local and nfs file systems */ typedef union fb_fdesc { int fd_num; /* OS file descriptor number */ void *fd_ptr; /* Pointer to nfs information block */ } fb_fdesc_t; typedef struct aiolist aiol_t; /* Functions vector for file system plug-ins */ typedef struct fsplug_func_s { char fs_name[16]; int (*fsp_freemem)(fb_fdesc_t *, off64_t); int (*fsp_open)(fb_fdesc_t *, char *, int, int); int (*fsp_pread)(fb_fdesc_t *, caddr_t, fbint_t, off64_t); int (*fsp_read)(fb_fdesc_t *, caddr_t, fbint_t); int (*fsp_pwrite)(fb_fdesc_t *, caddr_t, fbint_t, off64_t); int (*fsp_write)(fb_fdesc_t *, caddr_t, fbint_t); int (*fsp_lseek)(fb_fdesc_t *, off64_t, int); int (*fsp_ftrunc)(fb_fdesc_t *, off64_t); int (*fsp_rename)(const char *, const char *); int (*fsp_close)(fb_fdesc_t *); int (*fsp_link)(const char *, const char *); int (*fsp_symlink)(const char *, const char *); int (*fsp_unlink)(char *); ssize_t (*fsp_readlink)(const char *, char *, size_t); int (*fsp_mkdir)(char *, int); int (*fsp_rmdir)(char *); DIR *(*fsp_opendir)(char *); struct dirent *(*fsp_readdir)(DIR *); int (*fsp_closedir)(DIR *); int (*fsp_fsync)(fb_fdesc_t *); int (*fsp_stat)(char *, struct stat64 *); int (*fsp_fstat)(fb_fdesc_t *, struct stat64 *); int (*fsp_access)(const char *, int); void (*fsp_recur_rm)(char *); } fsplug_func_t; extern fsplug_func_t *fs_functions_vec; /* Macros for calling functions */ #define FB_FREEMEM(fd, sz) \ (*fs_functions_vec->fsp_freemem)(fd, sz) #define FB_OPEN(fd, path, flags, perms) \ (*fs_functions_vec->fsp_open)(fd, path, flags, perms) #define FB_PREAD(fdesc, iobuf, iosize, offset) \ (*fs_functions_vec->fsp_pread)(fdesc, iobuf, iosize, offset) #define FB_READ(fdesc, iobuf, iosize) \ (*fs_functions_vec->fsp_read)(fdesc, iobuf, iosize) #define FB_PWRITE(fdesc, iobuf, iosize, offset) \ (*fs_functions_vec->fsp_pwrite)(fdesc, iobuf, iosize, offset) #define FB_WRITE(fdesc, iobuf, iosize) \ (*fs_functions_vec->fsp_write)(fdesc, iobuf, iosize) #define FB_LSEEK(fdesc, amnt, whence) \ (*fs_functions_vec->fsp_lseek)(fdesc, amnt, whence) #define FB_CLOSE(fdesc) \ (*fs_functions_vec->fsp_close)(fdesc) #define FB_UNLINK(path) \ (*fs_functions_vec->fsp_unlink)(path) #define FB_MKDIR(path, perm) \ (*fs_functions_vec->fsp_mkdir)(path, perm) #define FB_RMDIR(path) \ (*fs_functions_vec->fsp_rmdir)(path) #define FB_OPENDIR(path) \ (*fs_functions_vec->fsp_opendir)(path) #define FB_READDIR(dir) \ (*fs_functions_vec->fsp_readdir)(dir) #define FB_CLOSEDIR(dir) \ (*fs_functions_vec->fsp_closedir)(dir) #define FB_FSYNC(fdesc) \ (*fs_functions_vec->fsp_fsync)(fdesc) #define FB_RECUR_RM(path) \ (*fs_functions_vec->fsp_recur_rm)(path) #define FB_STAT(path, statp) \ (*fs_functions_vec->fsp_stat)(path, statp) #define FB_FSTAT(fdesc, statp) \ (*fs_functions_vec->fsp_fstat)(fdesc, statp) #define FB_FTRUNC(fdesc, size) \ (*fs_functions_vec->fsp_ftrunc)(fdesc, size) #define FB_LINK(existing, new) \ (*fs_functions_vec->fsp_link)(existing, new) #define FB_SYMLINK(name1, name2) \ (*fs_functions_vec->fsp_symlink)(name1, name2) #endif /* _FB_FSPLUG_H */
4,327
28.442177
70
h
filebench
filebench-master/gamma_dist.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include <stdlib.h> #include <math.h> /* * This is valid for 0 < a <= 1 * * From Knuth Volume 2, 3rd edition, pages 586 - 587. */ static double gamma_dist_knuth_algG(double a, double (*src)(unsigned short *), unsigned short *xi) { double p, U, V, X, q; p = M_E/(a + M_E); G2: /* get a random number U */ U = (*src)(xi); do { /* get a random number V */ V = (*src)(xi); } while (V == 0); if (U < p) { X = pow(V, 1/a); /* q = e^(-X) */ q = exp(-X); } else { X = 1 - log(V); q = pow(X, a-1); } /* * X now has density g, and q = f(X)/cg(X) */ /* get a random number U */ U = (*src)(xi); if (U >= q) goto G2; return (X); } /* * This is valid for a > 1 * * From Knuth Volume 2, 3rd edition, page 134. */ static double gamma_dist_knuth_algA(double a, double (*src)(unsigned short *), unsigned short *xi) { double U, Y, X, V; A1: /* get a random number U */ U = (*src)(xi); Y = tan(M_PI*U); X = (sqrt((2*a) - 1) * Y) + a - 1; if (X <= 0) goto A1; /* get a random number V */ V = (*src)(xi); if (V > ((1 + (Y*Y)) * exp((a-1) * log(X/(a-1)) - sqrt(2*a -1) * Y))) goto A1; return (X); } /* * fetch a uniformly distributed random number using the drand48 generator */ /* ARGSUSED */ static double default_src(unsigned short *xi) { return (drand48()); } /* * Sample the gamma distributed random variable with gamma 'a' and * result mulitplier 'b', which is usually mean/gamma. Uses the default * drand48 random number generator as input */ double gamma_dist_knuth(double a, double b) { if (a <= 1.0) return (b * gamma_dist_knuth_algG(a, default_src, NULL)); else return (b * gamma_dist_knuth_algA(a, default_src, NULL)); } /* * Sample the gamma distributed random variable with gamma 'a' and * multiplier 'b', which is mean / gamma adjusted for the specified * minimum value. The suppled random number source function is * used to optain the uniformly distributed random numbers. */ double gamma_dist_knuth_src(double a, double b, double (*src)(unsigned short *), unsigned short *xi) { if (a <= 1.0) return (b * gamma_dist_knuth_algG(a, src, xi)); else return (b * gamma_dist_knuth_algA(a, src, xi)); }
3,163
21.125874
74
c
filebench
filebench-master/gamma_dist.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_GAMMA_DIST_H #define _FB_GAMMA_DIST_H #pragma ident "%Z%%M% %I% %E% SMI" #include "filebench.h" double gamma_dist_knuth(double a, double b); double gamma_dist_knuth_src(double a, double b, double (*src)(unsigned short *), unsigned short *xi); #endif /* _FB_GAMMA_DIST_H */
1,220
31.131579
70
h
filebench
filebench-master/ipc.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_IPC_H #define _FB_IPC_H #include "filebench.h" /* Mutex Priority Inheritance and Robustness flags */ #define IPC_MUTEX_NORMAL 0x0 #define IPC_MUTEX_PRIORITY 0x1 #define IPC_MUTEX_ROBUST 0x2 #define IPC_MUTEX_PRI_ROB 0x3 #define IPC_NUM_MUTEX_ATTRS 4 #define FILEBENCH_NSEMS 128 #define FILEBENCH_ABORT_ERROR 1 #define FILEBENCH_ABORT_DONE 2 #define FILEBENCH_ABORT_RSRC 3 #define FILEBENCH_ABORT_FINI 4 /* run modes */ #define FILEBENCH_MODE_TIMEOUT 0x0 #define FILEBENCH_MODE_Q1STDONE 0x1 #define FILEBENCH_MODE_QALLDONE 0x2 /* misc. modes */ #define FILEBENCH_MODE_NOUSAGE 0x01 /* * Types of IPC shared memory pools we have. * ipc_malloc() gets the type as an argument and * allocates a slot from the appropriate pool. * */ #define FILEBENCH_FILESET 0 #define FILEBENCH_FILESETENTRY 1 #define FILEBENCH_PROCFLOW 2 #define FILEBENCH_THREADFLOW 3 #define FILEBENCH_FLOWOP 4 #define FILEBENCH_VARIABLE 5 #define FILEBENCH_AVD 6 #define FILEBENCH_RANDDIST 7 #define FILEBENCH_CVAR 8 #define FILEBENCH_CVAR_LIB_INFO 9 #define FILEBENCH_MAXTYPE (FILEBENCH_CVAR_LIB_INFO + 1) /* * The values below are selected by intuition: these limits * seem to be reasonable for medium-scale workloads. If * one needs more processes, threads, flowops, etc., one * has to increase these values */ #define FILEBENCH_NFILESETS (16) #define FILEBENCH_NFILESETENTRIES (1024 * 1024) #define FILEBENCH_NPROCFLOWS (1024) #define FILEBENCH_NTHREADFLOWS (1024) /* 16 flowops per threadflow seems reasonable */ #define FILEBENCH_NFLOWOPS (16 * 1024) /* variables are not the only one that are specified explicitly in the .f file. Some special variables are used within FB itself. So, let's put this value to some save large value */ #define FILEBENCH_NVARIABLES (1024) #define FILEBENCH_NAVDS (4096) #define FILEBENCH_NRANDDISTS (16) #define FILEBENCH_NCVARS (16) #define FILEBENCH_NCVAR_LIB_INFO (32) #define FILEBENCH_MAXBITMAP FILEBENCH_NFILESETENTRIES /* these below are not regular pools and are allocated separately from ipc_malloc() */ #define FILEBENCH_FILESETPATHMEMORY (FILEBENCH_NFILESETENTRIES * FSE_MAXPATHLEN) #define FILEBENCH_STRINGMEMORY (FILEBENCH_NVARIABLES * 128) #define FILEBENCH_CVAR_HEAPSIZE (FILEBENCH_NCVARS * 4096) typedef struct filebench_shm { /* * All fields down to shm_marker are set to zero during * filebench initialization in ipc_init() function. */ /* * Global lists and locks for main Filebench objects: * filesets, procflows, threaflows, and flowops. */ fileset_t *shm_filesetlist; pthread_mutex_t shm_fileset_lock; procflow_t *shm_procflowlist; pthread_mutex_t shm_procflow_lock; /* threadflow_t *shm_threadflowlist; (this one is per procflow) */ pthread_mutex_t shm_threadflow_lock; flowop_t *shm_flowoplist; pthread_mutex_t shm_flowop_lock; /* * parallel file allocation control. Restricts number of spawned * allocation threads and allows waiting for allocation to finish. */ pthread_cond_t shm_fsparalloc_cv; /* cv to wait for alloc threads */ int shm_fsparalloc_count; /* active alloc thread count */ pthread_mutex_t shm_fsparalloc_lock; /* lock to protect count */ /* * Procflow and process state */ int shm_procs_running; /* count of running processes */ pthread_mutex_t shm_procs_running_lock; /* protects shm_procs_running */ int shm_f_abort; /* stop the run NOW! */ pthread_rwlock_t shm_run_lock; /* used as barrier to sync run */ flag_t shm_procflows_defined_flag; /* indicates that process creator thread has defined all the procflows */ /* * flowop state */ pthread_rwlock_t shm_flowop_find_lock; /* prevents flowop_find() */ /* during initial flowop creation */ /* * Variable lits. */ var_t *shm_var_list; /* normal variables */ var_t *shm_var_loc_list; /* variables local to composite flowops */ /* List of randdist instances (randdist for every random variable) */ randdist_t *shm_rand_list; cvar_t *shm_cvar_list; /* custom variables */ cvar_library_info_t *shm_cvar_lib_info_list; /* * log and statistics dumping controls and state */ int shm_debug_level; int shm_bequiet; /* pause run while collecting stats */ int shm_dump_fd; /* dump file descriptor */ char shm_dump_filename[MAXPATHLEN]; /* * Event generator state */ int shm_eventgen_enabled; /* event gen in operation */ avd_t shm_eventgen_hz; /* number of events per sec. */ uint64_t shm_eventgen_q; /* count of unclaimed events */ pthread_mutex_t shm_eventgen_lock; /* lock protecting count */ pthread_cond_t shm_eventgen_cv; /* cv to wait on for more events */ /* * System 5 semaphore state */ key_t shm_semkey; int shm_sys_semid; char shm_semids[FILEBENCH_NSEMS]; /* * Misc. pointers and state */ char shm_fscriptname[1024]; int shm_id; int shm_rmode; /* run mode settings */ int shm_mmode; /* misc. mode settings */ int shm_1st_err; pthread_mutex_t shm_msg_lock; pthread_mutexattr_t shm_mutexattr[IPC_NUM_MUTEX_ATTRS]; char *shm_string_ptr; char *shm_path_ptr; hrtime_t shm_epoch; hrtime_t shm_starttime; int shm_utid; int lathist_enabled; int shm_cvar_heapsize; /* * Shared memory allocation control */ pthread_mutex_t shm_ism_lock; size_t shm_required; size_t shm_allocated; caddr_t shm_addr; char *shm_ptr; /* * Type of plug-in file system client to use. Defaults to * local file system, which is type "0". */ fb_plugin_type_t shm_filesys_type; /* * IPC shared memory pools allocation/deallocation control: * - bitmap (if fact, bit is an integer here) * - last allocated index * - lock for the operations on the pool */ int shm_bitmap[FILEBENCH_MAXTYPE][FILEBENCH_MAXBITMAP]; int shm_lastbitmapindex[FILEBENCH_MAXTYPE]; pthread_mutex_t shm_malloc_lock; /* * end of pre-zeroed data. We do not bzero pools, because * otherwise we will touch every page in the pools and * consequently use a lot of physical memory, while * in fact, we might not need so much memory later. */ int shm_marker[0]; /* * IPC shared memory pools. Allocated to users * when ipc_malloc() is called. Not zeroed, but * ipc_malloc() will bzero each allocated slot. */ fileset_t shm_fileset[FILEBENCH_NFILESETS]; filesetentry_t shm_filesetentry[FILEBENCH_NFILESETENTRIES]; procflow_t shm_procflow[FILEBENCH_NPROCFLOWS]; threadflow_t shm_threadflow[FILEBENCH_NTHREADFLOWS]; flowop_t shm_flowop[FILEBENCH_NFLOWOPS]; var_t shm_var[FILEBENCH_NVARIABLES]; struct avd shm_avd_ptrs[FILEBENCH_NAVDS]; randdist_t shm_randdist[FILEBENCH_NRANDDISTS]; cvar_t shm_cvar[FILEBENCH_NCVARS]; cvar_library_info_t shm_cvar_lib_info[FILEBENCH_NCVAR_LIB_INFO]; /* these below are not regular pools and are allocated separately from ipc_malloc() */ char shm_strings[FILEBENCH_STRINGMEMORY]; char shm_filesetpaths[FILEBENCH_FILESETPATHMEMORY]; char shm_cvar_heap[FILEBENCH_CVAR_HEAPSIZE]; } filebench_shm_t; extern char shmpath[128]; extern void ipc_init(void); extern int ipc_attach(void *shmaddr, char *shmpath); void *ipc_malloc(int type); void ipc_free(int type, char *addr); pthread_mutexattr_t *ipc_mutexattr(int); pthread_condattr_t *ipc_condattr(void); int ipc_semidalloc(void); void ipc_semidfree(int semid); char *ipc_stralloc(const char *string); char *ipc_pathalloc(char *string); void *ipc_cvar_heapalloc(size_t size); void ipc_cvar_heapfree(void *ptr); int ipc_mutex_lock(pthread_mutex_t *mutex); int ipc_mutex_unlock(pthread_mutex_t *mutex); void ipc_seminit(void); char *ipc_ismmalloc(size_t size); int ipc_ismcreate(size_t size); void ipc_ismdelete(void); void ipc_fini(void); extern filebench_shm_t *filebench_shm; #endif /* _FB_IPC_H */
8,677
30.215827
87
h
filebench
filebench-master/misc.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <stdio.h> #include <fcntl.h> #include <limits.h> #include <time.h> #include <libgen.h> #include <unistd.h> #include <strings.h> #include <sys/time.h> #include "filebench.h" #include "ipc.h" #include "eventgen.h" #include "utils.h" #include "fsplug.h" #include "fbtime.h" /* File System functions vector */ fsplug_func_t *fs_functions_vec; extern int lex_lineno; /* * Writes a message consisting of information formated by * "fmt" to the log file, dump file or stdout. The supplied * "level" argument determines which file to write to and * what other actions to take. * The level LOG_DUMP writes to the "dump" file, * and will open it on the first invocation. Other levels * print to the stdout device, with the amount of information * dependent on the error level and the current error level * setting in filebench_shm->shm_debug_level. */ void filebench_log __V((int level, const char *fmt, ...)) { va_list args; hrtime_t now = 0; char line[131072]; char buf[131072]; /* we want to be able to use filebench_log() eveing before filebench_shm is initialized. In this case, all logs have FATAL level. */ if (!filebench_shm) level = LOG_FATAL; if (level == LOG_FATAL) goto fatal; /* open dumpfile if not already open and writing to it */ if ((level == LOG_DUMP) && (*filebench_shm->shm_dump_filename == 0)) return; if ((level == LOG_DUMP) && (filebench_shm->shm_dump_fd < 0)) { filebench_shm->shm_dump_fd = open(filebench_shm->shm_dump_filename, O_RDWR | O_CREAT | O_TRUNC, 0666); } if ((level == LOG_DUMP) && (filebench_shm->shm_dump_fd < 0)) { (void) snprintf(line, sizeof (line), "Open logfile failed: %s", strerror(errno)); level = LOG_ERROR; } /* Quit if this is a LOG_ERROR messages and they are disabled */ if ((filebench_shm->shm_1st_err) && (level == LOG_ERROR)) return; if (level == LOG_ERROR1) { if (filebench_shm->shm_1st_err) return; /* A LOG_ERROR1 temporarily disables LOG_ERROR messages */ filebench_shm->shm_1st_err = 1; level = LOG_ERROR; } /* Only log greater or equal than debug setting */ if ((level != LOG_DUMP) && (level > filebench_shm->shm_debug_level)) return; now = gethrtime(); fatal: #ifdef __STDC__ va_start(args, fmt); #else char *fmt; va_start(args); fmt = va_arg(args, char *); #endif (void) vsprintf(line, fmt, args); va_end(args); if (level == LOG_FATAL) { (void) fprintf(stderr, "%s\n", line); return; } /* Serialize messages to log */ (void) ipc_mutex_lock(&filebench_shm->shm_msg_lock); if (level == LOG_DUMP) { if (filebench_shm->shm_dump_fd != -1) { (void) snprintf(buf, sizeof (buf), "%s\n", line); /* We ignore the return value of write() */ if (write(filebench_shm->shm_dump_fd, buf, strlen(buf))); (void) fsync(filebench_shm->shm_dump_fd); (void) ipc_mutex_unlock(&filebench_shm->shm_msg_lock); return; } } else if (filebench_shm->shm_debug_level > LOG_INFO) { if (level < LOG_INFO) (void) fprintf(stderr, "%5d: ", (int)my_pid); else (void) fprintf(stdout, "%5d: ", (int)my_pid); } if (level < LOG_INFO) { (void) fprintf(stderr, "%4.3f: %s", (now - filebench_shm->shm_epoch) / SEC2NS_FLOAT, line); if (my_procflow == NULL) (void) fprintf(stderr, " around line %d", lex_lineno); (void) fprintf(stderr, "\n"); (void) fflush(stderr); } else { (void) fprintf(stdout, "%4.3f: %s", (now - filebench_shm->shm_epoch) / SEC2NS_FLOAT, line); (void) fprintf(stdout, "\n"); (void) fflush(stdout); } (void) ipc_mutex_unlock(&filebench_shm->shm_msg_lock); } /* * Stops the run and exits filebench. If filebench is * currently running a workload, calls procflow_shutdown() * to stop the run. Also closes and deletes shared memory. */ void filebench_shutdown(int error) { if (error) { filebench_log(LOG_DEBUG_IMPL, "Shutdown on error %d", error); (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); if (filebench_shm->shm_f_abort == FILEBENCH_ABORT_FINI) { (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); return; } filebench_shm->shm_f_abort = FILEBENCH_ABORT_ERROR; (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); } else { filebench_log(LOG_DEBUG_IMPL, "Shutdown"); } procflow_shutdown(); (void) unlink("/tmp/filebench_shm"); ipc_ismdelete(); exit(error); }
5,319
25.206897
70
c
filebench
filebench-master/misc.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_MISC_H #define _FB_MISC_H #pragma ident "%Z%%M% %I% %E% SMI" #define LOG_ERROR 0 /* a major error */ #define LOG_ERROR1 1 /* also major error, but turn off error reporting */ /* for now */ #define LOG_INFO 2 /* some useful information. Default is to print */ #define LOG_VERBOSE 3 /* four more levels of detailed information */ #define LOG_DEBUG_SCRIPT 4 #define LOG_DEBUG_IMPL 6 #define LOG_DEBUG_NEVER 10 #define LOG_FATAL 999 /* really bad error, shut down */ #define LOG_DUMP 1001 #endif /* _FB_MISC_H */
1,454
32.837209
73
h
filebench
filebench-master/multi_client_sync.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include "filebench.h" #include "multi_client_sync.h" #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #define MCS_NAMELENGTH 128 #define MCS_MSGLENGTH (MCS_NAMELENGTH * 8) static int mc_sync_sock_id; static char this_client_name[MCS_NAMELENGTH]; /* * Open a socket to the master synchronization host */ int mc_sync_open_sock(char *master_name, int master_port, char *my_name) { struct sockaddr_in client_in; struct sockaddr_in master_in; struct hostent *master_info; //int error_num; //char buffer[MCS_MSGLENGTH]; (void) strncpy(this_client_name, my_name, MCS_NAMELENGTH); if ((mc_sync_sock_id = socket(PF_INET, SOCK_STREAM, 0)) == -1) { filebench_log(LOG_ERROR, "could not create a client socket"); return (FILEBENCH_ERROR); } client_in.sin_family = AF_INET; client_in.sin_port = INADDR_ANY; client_in.sin_addr.s_addr = INADDR_ANY; if (bind(mc_sync_sock_id, (struct sockaddr *)&client_in, sizeof (client_in)) == -1) { filebench_log(LOG_ERROR, "could not bind to client socket"); return (FILEBENCH_ERROR); } master_info = gethostbyname(master_name); /* if (gethostbyname_r(master_name, &master_info, buffer, MCS_MSGLENGTH, &error_num) == NULL) { filebench_log(LOG_ERROR, "could not locate sync master"); return (FILEBENCH_ERROR); } */ master_in.sin_family = AF_INET; master_in.sin_port = htons((uint16_t)master_port); (void) memcpy(&master_in.sin_addr.s_addr, *(master_info->h_addr_list), sizeof (master_in.sin_addr.s_addr)); if (connect(mc_sync_sock_id, (struct sockaddr *)&master_in, sizeof (master_in)) == -1) { filebench_log(LOG_ERROR, "connection refused to sync master, error %d", errno); return (FILEBENCH_ERROR); } return (FILEBENCH_OK); } /* * Send a synchronization message and wait for a reply */ int mc_sync_synchronize(int sync_point) { char msg[MCS_MSGLENGTH]; int amnt; (void) snprintf(msg, MCS_MSGLENGTH, "cmd=SYNC,id=xyzzy,name=%s,sample=%d\n", this_client_name, sync_point); (void) send(mc_sync_sock_id, msg, strlen(msg), 0); amnt = 0; msg[0] = 0; while (strchr(msg, '\n') == NULL) amnt += recv(mc_sync_sock_id, msg, sizeof (msg), 0); filebench_log(LOG_INFO, "sync point %d succeeded!\n", sync_point); return (FILEBENCH_OK); }
3,217
26.741379
71
c
filebench
filebench-master/multi_client_sync.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _MULTI_CLIENT_SYNC_H #define _MULTI_CLIENT_SYNC_H #include <sys/types.h> #if defined(HAVE_SYS_SOCKET_H) #include <sys/socket.h> #endif int mc_sync_open_sock(char *master_name, int master_port, char *client_name); int mc_sync_synchronize(int synch_point); #endif /* _MULTI_CLIENT_SYNC_H */
1,227
31.315789
77
h
filebench
filebench-master/parsertypes.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_PARSERTYPES_H #define _FB_PARSERTYPES_H #include "filebench.h" #define DOFILE_FALSE 0 #define DOFILE_TRUE 1 #define FSE_SYSTEM 1 typedef struct list { struct list *list_next; avd_t list_string; avd_t list_integer; } list_t; typedef struct attr { int attr_name; struct attr *attr_next; avd_t attr_avd; void *attr_obj; } attr_t; typedef struct cmd { void (*cmd)(struct cmd *); char *cmd_name; char *cmd_tgt1; char *cmd_tgt2; char *cmd_tgt3; char *thread_name; int cmd_subtype; uint64_t cmd_qty; int64_t cmd_qty1; struct cmd *cmd_list; struct cmd *cmd_next; attr_t *cmd_attr_list; list_t *cmd_param_list; list_t *cmd_param_list2; } cmd_t; typedef union { int64_t i; unsigned char b; char *s; } fs_u; typedef struct pidlist { struct pidlist *pl_next; int pl_fd; pid_t pl_pid; } pidlist_t; typedef void (*cmdfunc)(cmd_t *); int yy_switchfileparent(FILE *file); int yy_switchfilescript(FILE *file); #endif /* _FB_PARSERTYPES_H */
1,922
21.892857
70
h
filebench
filebench-master/procflow.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include <signal.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/wait.h> #include "filebench.h" #include "procflow.h" #include "flowop.h" #include "ipc.h" #include "eventgen.h" /* pid and procflow pointer for this process */ pid_t my_pid; procflow_t *my_procflow = NULL; static procflow_t *procflow_define_common(procflow_t **list, char *name, procflow_t *inherit, int instance); static void procflow_sleep(procflow_t *procflow, int wait_cnt); /* * Procflows are filebench entities which manage processes. Each * worker procflow spawns a separate filebench process, with attributes * inherited from a FLOW_MASTER procflow created during f model language * parsing. This section contains routines to define, create, control, * and delete procflows. * * Each process defined in the f model creates a FLOW_MASTER * procflow which encapsulates the defined attributes, and threads of * the f process, including the number of instances to create. At * runtime, a worker procflow instance with an associated filebench * process is created, which runs until told to quite by the original * filebench process or is specifically deleted. */ /* * This routine forks a child process and uses either system() or exec() to * start up a new instance of filebench, passing it the procflow name, instance * number and shared memory region address. */ static int procflow_createproc(procflow_t *procflow) { pid_t pid = 0; char instance[128]; char shmaddr[128]; char procname[128]; (void) snprintf(instance, sizeof (instance), "%d", procflow->pf_instance); (void) snprintf(procname, sizeof (procname), "%s", procflow->pf_name); (void) snprintf(shmaddr, sizeof (shmaddr), "%p", filebench_shm); filebench_log(LOG_DEBUG_IMPL, "creating process %s", procflow->pf_name); procflow->pf_running = 0; #ifdef HAVE_FORK1 if ((pid = fork1()) < 0) { filebench_log(LOG_ERROR, "procflow_createproc fork failed: %s", strerror(errno)); return (-1); } #else if ((pid = fork()) < 0) { filebench_log(LOG_ERROR, "procflow_createproc fork failed: %s", strerror(errno)); return (-1); } #endif /* HAVE_FORK1 */ /* if child, start up new copy of filebench */ if (pid == 0) { #ifdef USE_SYSTEM char syscmd[1024]; #endif (void) sigignore(SIGINT); filebench_log(LOG_DEBUG_SCRIPT, "Starting %s-%d", procflow->pf_name, procflow->pf_instance); /* Child */ #ifdef USE_SYSTEM (void) snprintf(syscmd, sizeof (syscmd), "%s -a %s -i %s -s %s", execname, procname, instance, shmaddr); if (system(syscmd) < 0) { filebench_log(LOG_ERROR, "procflow exec proc failed: %s", strerror(errno)); filebench_shutdown(1); } #else if (execlp(execname, procname, "-a", procname, "-i", instance, "-s", shmaddr, "-m", shmpath, NULL) < 0) { filebench_log(LOG_ERROR, "procflow exec proc failed: %s", strerror(errno)); filebench_shutdown(1); } #endif exit(1); } else { /* if parent, save pid and return */ procflow->pf_pid = pid; } filebench_log(LOG_DEBUG_IMPL, "procflow_createproc created pid %d", pid); return (0); } /* * Iterates over all defined (MASTER) procflows, allocates procflow instances, * creates worker monitor processes that correspond to these instances * and waits until monitors define all threadflows. There is now guarantee * after this function that all threads are running, but there is a guarantee * that all threadflow instances are defined and are in corresponding lists. */ static int procflow_create_all_procs(void) { procflow_t *procflow; int ret = 0; procflow = filebench_shm->shm_procflowlist; while (procflow) { int instances; int i; instances = (int)avd_get_int(procflow->pf_instances); filebench_log(LOG_INFO, "Starting %d %s instances", instances, procflow->pf_name); /* Create instances of procflow */ for (i = 0; (i < instances) && (ret == 0); i++) { procflow_t *newproc; /* Define procflows and add them to the list */ newproc = procflow_define_common(&filebench_shm->shm_procflowlist, procflow->pf_name, procflow, i + 1); /* * We clear pf_threads_defined_flag in the procflow * structure before starting a worker monitor * process. Each worker monitor process will set this flag * later as soon as it defines _all_ threadflows (and puts them * into the corresponding list). Than this thread will wait * on this flag to make sure that all threadflows were defined. */ if (!newproc) { ret = -1; } else { clear_flag(&newproc->pf_threads_defined_flag); ret = procflow_createproc(newproc); } } if (ret) break; procflow = procflow->pf_next; } /* Wait here for all monitor threads to define threadflows */ procflow = filebench_shm->shm_procflowlist; while (procflow) { if (procflow->pf_instance && (procflow->pf_instance == FLOW_MASTER)) { procflow = procflow->pf_next; continue; } wait_flag(&procflow->pf_threads_defined_flag); procflow = procflow->pf_next; } return (ret); } /* * Find a procflow of name "name" and instance "instance" on the * master procflow list, filebench_shm->shm_procflowlist. Locks the list * and scans through it searching for a procflow with matching * name and instance number. If found returns a pointer to the * procflow, otherwise returns NULL. */ static procflow_t * procflow_find(char *name, int instance) { procflow_t *procflow; (void)ipc_mutex_lock(&filebench_shm->shm_procflow_lock); procflow = filebench_shm->shm_procflowlist; while (procflow) { if ((strcmp(name, procflow->pf_name) == 0) && (instance == procflow->pf_instance)) { (void)ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); return (procflow); } procflow = procflow->pf_next; } (void)ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); return (NULL); } /* * Used to start up threads on a child process, when filebench is * compiled to support multiple processes. Uses the name string * and instance number passed to the child to find the previously * created procflow entity. Then uses nice() to reduce the * process' priority by at least 10. A call is then made to * threadflow_init() which creates and runs the process' threads * and flowops to completion. When threadflow_init() returns, * a call to exit() terminates the child process. */ int procflow_exec(char *name, int instance) { procflow_t *procflow; int proc_nice; #ifdef HAVE_SETRLIMIT struct rlimit rlp; #endif int ret; if ((procflow = procflow_find(name, instance)) == NULL) { filebench_log(LOG_FATAL, "procflow_exec could not find %s-%d", name, instance); return (-1); } /* set the slave process' procflow pointer */ my_procflow = procflow; /* set its pid from value stored by main() */ procflow->pf_pid = my_pid; filebench_log(LOG_DEBUG_IMPL, "Started up %s pid %d", procflow->pf_name, my_pid); filebench_log(LOG_DEBUG_IMPL, "nice = %llx", procflow->pf_nice); proc_nice = avd_get_int(procflow->pf_nice); if (proc_nice) filebench_log(LOG_DEBUG_IMPL, "Setting pri of %s-%d to %d", name, instance, nice(proc_nice)); procflow->pf_running = 1; #ifdef HAVE_SETRLIMIT /* Get resource limits */ (void) getrlimit(RLIMIT_NOFILE, &rlp); filebench_log(LOG_DEBUG_SCRIPT, "%d file descriptors", rlp.rlim_cur); #endif if ((ret = threadflow_init(procflow)) != FILEBENCH_OK) { if (ret < 0) { filebench_log(LOG_ERROR, "Failed to start threads for %s pid %d", procflow->pf_name, my_pid); } } else { filebench_log(LOG_DEBUG_IMPL, "procflow_createproc exiting..."); } (void) ipc_mutex_lock(&filebench_shm->shm_procs_running_lock); filebench_shm->shm_procs_running --; (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); procflow->pf_running = 0; return (ret); } /* * A special thread from which worker (child) processes are created, and which * then waits for worker processes to die. If they die unexpectedly, * then report an error and terminate the run. */ static void * procflow_createnwait(void *unused) { /* XXX: do not disregard potential error return!!! */ procflow_create_all_procs(); /* * After procflow_create_all_procs returns, we can be sure * that all procflows and threadflows were defined and put into * the corresponding lists. So, we can allow main thread to * continue. It will iterate over the procflow/threadflow lists * to ensure that all processes and threads have been started. */ set_flag(&filebench_shm->shm_procflows_defined_flag); /* CONSTCOND */ while (1) { /* wait for any child process to exit */ #ifdef HAVE_WAITID siginfo_t status; if (waitid(P_ALL, 0, &status, WEXITED) != 0) #else /* HAVE_WAITID */ int status; if (waitpid(-1, &status, 0) < 0) #endif pthread_exit(0); (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); /* if normal shutdown in progress, just quit */ if (filebench_shm->shm_f_abort) { (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); pthread_exit(0); } /* if nothing running, exit */ if (filebench_shm->shm_procs_running == 0) { filebench_shm->shm_f_abort = FILEBENCH_ABORT_RSRC; (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); pthread_exit(0); } (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); #ifdef HAVE_WAITID if (status.si_code == CLD_EXITED) { /* A process called exit(); check returned status */ if (status.si_status != 0) { filebench_log(LOG_ERROR, "Unexpected Process termination; exiting", status.si_status); filebench_shutdown(1); } } else { /* A process quit because of some fatal error */ filebench_log(LOG_ERROR, "Unexpected Process termination Code %d, Errno %d", status.si_code, status.si_errno); filebench_shutdown(1); } #else /* HAVE_WAITID */ /* child did not exit, but got a signal, so just continue waiting */ if (WIFSTOPPED(status)) continue; #ifdef WIFCONTINUED /* some versions (NetBSD before version 8.0) do not support WIFCONTINUED */ if (WIFCONTINUED(status)) continue; #endif if (WIFEXITED(status)) { /* A process called exit(); check returned status */ if (WEXITSTATUS(status) != 0) { filebench_log(LOG_ERROR, "Unexpected Process termination; exiting", WEXITSTATUS(status)); filebench_shutdown(1); } } else { /* A process quit because of some fatal error */ filebench_log(LOG_ERROR, "Unexpected Process termination Code %d", WTERMSIG(status)); filebench_shutdown(1); } #endif } /* NOTREACHED */ return (NULL); } /* * Cancel all threads within a processes, as well as the process itself. * Called by ^c or by sig_kill */ /* ARGSUSED */ static void procflow_cancel(int arg1) { filebench_log(LOG_DEBUG_IMPL, "Process signal handler on pid %", my_procflow->pf_pid); procflow_sleep(my_procflow, SHUTDOWN_WAIT_SECONDS); threadflow_delete_all(&my_procflow->pf_threads); /* quit the main procflow thread and hence the process */ exit(0); } /* * Creates a process creator thread and waits until * it defines all the procflows (and threadflows in turn). */ static int procflow_init(void) { procflow_t *procflow; pthread_t tid; int ret = 0; procflow = filebench_shm->shm_procflowlist; if (!procflow) { filebench_log(LOG_ERROR, "Workload has no processes"); return (FILEBENCH_ERROR); } filebench_log(LOG_DEBUG_IMPL, "procflow_init %s, %llu", procflow->pf_name, (u_longlong_t)avd_get_int(procflow->pf_instances)); /* * This (main) process clears the shm_procflows_defined_flag here. * Later, procflow creator thread will set this flag only after all procflows * and threadflows are defined and put into the corresponding lists. */ clear_flag(&filebench_shm->shm_procflows_defined_flag); ret = pthread_create(&tid, NULL, procflow_createnwait, NULL); if (ret) return ret; (void) signal(SIGUSR1, procflow_cancel); /* * Wait for the process creator thread to define * all procflows (and threadflows in turn). */ wait_flag(&filebench_shm->shm_procflows_defined_flag); return (ret); } /* * Waits for child processes to finish and returns their exit status. Used by * procflow_delete() to wait for a deleted process to exit. */ static void procflow_wait(pid_t pid) { pid_t wpid; int stat; (void) waitpid(pid, &stat, 0); while ((wpid = waitpid(getpid() * -1, &stat, WNOHANG)) > 0) filebench_log(LOG_DEBUG_IMPL, "Waited for pid %d", (int)wpid); } /* * Common routine to sleep for wait_cnt seconds or for pf_running to * go false. Checks once a second to see if pf_running has gone false. */ static void procflow_sleep(procflow_t *procflow, int wait_cnt) { while (procflow->pf_running & wait_cnt) { (void) sleep(1); wait_cnt--; } } /* * Deletes the designated procflow. Finally it frees the * procflow entity. filebench_shm->shm_procflow_lock must be held on entry. * * If the designated procflow is not found on the list it returns -1 and * the procflow is not deleted. Otherwise it returns 0. */ static int procflow_cleanup(procflow_t *procflow) { procflow_t *entry; filebench_log(LOG_DEBUG_SCRIPT, "Deleted proc: (%s-%d) pid %d", procflow->pf_name, procflow->pf_instance, procflow->pf_pid); procflow->pf_running = 0; /* remove entry from proclist */ entry = filebench_shm->shm_procflowlist; /* unlink procflow entity from proclist */ if (entry == procflow) { /* at head of list */ filebench_shm->shm_procflowlist = procflow->pf_next; } else { /* search list for procflow */ while (entry && entry->pf_next != procflow) entry = entry->pf_next; /* if entity found, unlink it */ if (entry == NULL) return (-1); else entry->pf_next = procflow->pf_next; } /* free up the procflow entity */ ipc_free(FILEBENCH_PROCFLOW, (char *)procflow); return (0); } /* * Waits till all threadflows are started, or a timeout occurs. * Checks through the list of procflows, waiting up to 30 * seconds for each one to set its pf_running flag to 1. If not * set after 30 seconds, continues on to the next procflow * anyway after logging the fact. Once pf_running is set * to 1 for a given procflow or the timeout is reached, * threadflow_allstarted() is called to start the threads. * Returns 0 (OK), unless filebench_shm->shm_f_abort is signaled, * in which case it returns -1. */ static int procflow_allstarted() { procflow_t *procflow = filebench_shm->shm_procflowlist; int running_procs = 0; int ret = 0; (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); (void) sleep(1); while (procflow) { int waits; if (procflow->pf_instance && (procflow->pf_instance == FLOW_MASTER)) { procflow = procflow->pf_next; continue; } waits = 10; while (waits && procflow->pf_running == 0) { (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); if (filebench_shm->shm_f_abort == 1) return (-1); if (waits < 3) filebench_log(LOG_INFO, "Waiting for process %s-%d %d", procflow->pf_name, procflow->pf_instance, procflow->pf_pid); (void) sleep(3); waits--; (void) ipc_mutex_lock( &filebench_shm->shm_procflow_lock); } if (waits == 0) filebench_log(LOG_INFO, "Failed to start process %s-%d", procflow->pf_name, procflow->pf_instance); running_procs++; threadflow_allstarted(procflow->pf_pid, procflow->pf_threads); procflow = procflow->pf_next; } (void) ipc_mutex_lock(&filebench_shm->shm_procs_running_lock); filebench_shm->shm_procs_running = running_procs; (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); return (ret); } /* * Sets the f_abort flag and clears the running count to stop * all the flowop execution threads from running. Iterates * through the procflow list and deletes all procflows except * for the FLOW_MASTER procflow. Resets the f_abort flag when * finished. * */ void procflow_shutdown(void) { procflow_t *procflow, *next_procflow; int wait_cnt = SHUTDOWN_WAIT_SECONDS; (void) ipc_mutex_lock(&filebench_shm->shm_procs_running_lock); if (filebench_shm->shm_procs_running <= 0) { /* No processes running, so no need to do anything */ (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); return; } (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); if (filebench_shm->shm_f_abort == FILEBENCH_ABORT_FINI) { (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); return; } procflow = filebench_shm->shm_procflowlist; if (filebench_shm->shm_f_abort == FILEBENCH_OK) filebench_shm->shm_f_abort = FILEBENCH_ABORT_DONE; while (procflow) { if (procflow->pf_instance && (procflow->pf_instance == FLOW_MASTER)) { procflow = procflow->pf_next; continue; } filebench_log(LOG_DEBUG_IMPL, "Deleting process %s-%d %d", procflow->pf_name, procflow->pf_instance, procflow->pf_pid); next_procflow = procflow->pf_next; /* * Signalling the process with SIGUSR1 will result in it * gracefully shutting down and exiting */ procflow_sleep(procflow, wait_cnt); if (procflow->pf_running) { pid_t pid; pid = procflow->pf_pid; #ifdef HAVE_SIGSEND (void) sigsend(P_PID, pid, SIGUSR1); #else (void) kill(pid, SIGUSR1); #endif procflow_wait(pid); } (void) procflow_cleanup(procflow); procflow = next_procflow; if (wait_cnt > 0) wait_cnt--; } filebench_shm->shm_f_abort = FILEBENCH_ABORT_FINI; (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); /* indicate all processes are stopped, even if some are "stuck" */ (void) ipc_mutex_lock(&filebench_shm->shm_procs_running_lock); filebench_shm->shm_procs_running = 0; (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); } /* * Create an in-memory process object. Allocates a procflow * entity, initialized from the "inherit" procflow if supplied. * The name and instance number are set from the supplied name * and instance number and the procflow is added to the head of * the master procflow list. Returns pointer to the allocated * procflow, or NULL if a name isn't supplied or the procflow * entity cannot be allocated. * * The calling routine must hold the filebench_shm->shm_procflow_lock. */ static procflow_t * procflow_define_common(procflow_t **list, char *name, procflow_t *inherit, int instance) { procflow_t *procflow; if (name == NULL) return (NULL); procflow = (procflow_t *)ipc_malloc(FILEBENCH_PROCFLOW); if (procflow == NULL) return (NULL); if (inherit) (void) memcpy(procflow, inherit, sizeof (procflow_t)); else (void) memset(procflow, 0, sizeof (procflow_t)); procflow->pf_instance = instance; (void) strcpy(procflow->pf_name, name); filebench_log(LOG_DEBUG_IMPL, "defining process %s-%d", name, instance); /* Add procflow to list, lock is being held already */ if (*list == NULL) { *list = procflow; procflow->pf_next = NULL; } else { procflow->pf_next = *list; *list = procflow; } filebench_log(LOG_DEBUG_IMPL, "process %s-%d proclist %zx", name, instance, filebench_shm->shm_procflowlist); return (procflow); } /* * Create an in-memory process object as described by the syntax. * Acquires the filebench_shm->shm_procflow_lock and calls * procflow_define_common() to create and initialize a * FLOW_MASTER procflow entity from the optional "inherit" * procflow with the given name and configured for "instances" * number of worker procflows. Currently only called from * parser_proc_define(). */ procflow_t * procflow_define(char *name, avd_t instances) { procflow_t *procflow; (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); procflow = procflow_define_common(&filebench_shm->shm_procflowlist, name, NULL, FLOW_MASTER); procflow->pf_instances = instances; (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); return (procflow); } /* * Creates and starts all defined procflow processes. The call to * procflow_init() results in creation of the requested number of * process instances for each previously defined procflow. The * child processes exec() a new instance of filebench, passing it * the instance number and address of the shared memory region. * The child processes will then create their threads and flowops. * The routine then unlocks the run_lock to allow all the processes' * threads to start and waits for all of them to begin execution. * Finally, it records the start time and resets the event generation * system. */ void proc_create() { filebench_shm->shm_1st_err = 0; filebench_shm->shm_f_abort = FILEBENCH_OK; (void) pthread_rwlock_rdlock(&filebench_shm->shm_run_lock); if (procflow_init() != 0) { filebench_log(LOG_ERROR, "Failed to create processes\n"); filebench_shutdown(1); } /* Wait for all threads to start */ if (procflow_allstarted() != 0) { filebench_log(LOG_ERROR, "Could not start run"); return; } /* * Make sure we create the shared memory before we wake up worker * processes, which will alloc memory from this shm. */ if (filebench_shm->shm_required && (ipc_ismcreate(filebench_shm->shm_required) < 0)) { filebench_log(LOG_ERROR, "Could not allocate shared memory"); return; } /* Release the read lock, allowing threads to start */ (void) pthread_rwlock_unlock(&filebench_shm->shm_run_lock); filebench_shm->shm_starttime = gethrtime(); eventgen_reset(); } /* * Shuts down all processes and their associated threads. When finished * it deletes interprocess shared memory and resets the event generator. * It does not exit the filebench program though. */ void proc_shutdown() { filebench_log(LOG_INFO, "Shutting down processes"); procflow_shutdown(); if (filebench_shm->shm_required) ipc_ismdelete(); eventgen_reset(); }
23,056
26.38361
95
c
filebench
filebench-master/procflow.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_PROCFLOW_H #define _FB_PROCFLOW_H #pragma ident "%Z%%M% %I% %E% SMI" #include "filebench.h" typedef struct procflow { char pf_name[128]; int pf_instance; avd_t pf_instances; int pf_running; flag_t pf_threads_defined_flag; struct procflow *pf_next; pid_t pf_pid; pthread_t pf_tid; struct threadflow *pf_threads; int pf_attrs; avd_t pf_nice; } procflow_t; procflow_t *procflow_define(char *name, avd_t instances); void proc_create(void); void procflow_shutdown(void); void proc_shutdown(void); int procflow_exec(char *name, int instance); #endif /* _FB_PROCFLOW_H */
1,536
27.462963
70
h
filebench
filebench-master/stats.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <stdarg.h> #include <limits.h> #include "filebench.h" #include "flowop.h" #include "vars.h" #include "stats.h" #include "fbtime.h" /* * A set of routines for collecting and dumping various filebench * run statistics. */ /* Global statistics */ static struct flowstats *globalstats = NULL; /* * Add a flowstat b to a, leave sum in a. */ static void stats_add(struct flowstats *a, struct flowstats *b) { int i; a->fs_count += b->fs_count; a->fs_rcount += b->fs_rcount; a->fs_wcount += b->fs_wcount; a->fs_bytes += b->fs_bytes; a->fs_rbytes += b->fs_rbytes; a->fs_wbytes += b->fs_wbytes; a->fs_total_lat += b->fs_total_lat; if (b->fs_maxlat > a->fs_maxlat) a->fs_maxlat = b->fs_maxlat; if (b->fs_minlat < a->fs_minlat) a->fs_minlat = b->fs_minlat; for (i = 0; i < OSPROF_BUCKET_NUMBER; i++) a->fs_distribution[i] += b->fs_distribution[i]; } /* * Takes a "snapshot" of the global statistics. Actually, it calculates * them from the local statistics maintained by each flowop. * First the routine pauses filebench, then rolls the statistics for * each flowop into its associated FLOW_MASTER flowop. * Next all the FLOW_MASTER flowops' statistics are written * to the log file followed by the global totals. Then filebench * operation is allowed to resume. */ void stats_snap(void) { struct flowstats *iostat = &globalstats[FLOW_TYPE_IO]; struct flowstats *aiostat = &globalstats[FLOW_TYPE_AIO]; hrtime_t orig_starttime; flowop_t *flowop; char *str; double total_time_sec; if (!globalstats) { filebench_log(LOG_ERROR, "'stats snap' called before 'stats clear'"); return; } /* don't print out if run ended in error */ if (filebench_shm->shm_f_abort == FILEBENCH_ABORT_ERROR) { filebench_log(LOG_ERROR, "NO VALID RESULTS! Filebench run terminated prematurely"); return; } /* Freeze statistics during update */ filebench_shm->shm_bequiet = 1; /* We want to have blank global statistics each * time we start the summation process, but the * statistics collection start time must remain * unchanged (it's a snapshot compared to the original * start time). */ orig_starttime = globalstats->fs_stime; (void) memset(globalstats, 0, FLOW_TYPES * sizeof(struct flowstats)); globalstats->fs_stime = orig_starttime; globalstats->fs_etime = gethrtime(); total_time_sec = (globalstats->fs_etime - globalstats->fs_stime) / SEC2NS_FLOAT; filebench_log(LOG_DEBUG_SCRIPT, "Stats period = %.0f sec", total_time_sec); /* Similarly we blank the master flowop statistics */ flowop = filebench_shm->shm_flowoplist; while (flowop) { if (flowop->fo_instance == FLOW_MASTER) { (void) memset(&flowop->fo_stats, 0, sizeof(struct flowstats)); flowop->fo_stats.fs_minlat = ULLONG_MAX; } flowop = flowop->fo_next; } /* Roll up per-flowop statistics in globalstats and master flowops */ flowop = filebench_shm->shm_flowoplist; while (flowop) { flowop_t *flowop_master; if (flowop->fo_instance <= FLOW_DEFINITION) { flowop = flowop->fo_next; continue; } /* Roll up per-flowop into global stats */ stats_add(&globalstats[flowop->fo_type], &flowop->fo_stats); stats_add(&globalstats[FLOW_TYPE_GLOBAL], &flowop->fo_stats); flowop_master = flowop_find_one(flowop->fo_name, FLOW_MASTER); if (flowop_master) { /* Roll up per-flowop stats into master */ stats_add(&flowop_master->fo_stats, &flowop->fo_stats); } else { filebench_log(LOG_DEBUG_NEVER, "flowop_stats could not find %s", flowop->fo_name); } filebench_log(LOG_DEBUG_SCRIPT, "flowop %-20s-%4d - %5d ops %5.1lf ops/sec %5.1lfmb/s " "%8.3fms/op", flowop->fo_name, flowop->fo_instance, flowop->fo_stats.fs_count, flowop->fo_stats.fs_count / total_time_sec, (flowop->fo_stats.fs_bytes / MB_FLOAT) / total_time_sec, flowop->fo_stats.fs_count ? flowop->fo_stats.fs_total_lat / (flowop->fo_stats.fs_count * SEC2MS_FLOAT) : 0); flowop = flowop->fo_next; } flowop = filebench_shm->shm_flowoplist; str = malloc(1048576); *str = '\0'; (void) strcpy(str, "Per-Operation Breakdown\n"); while (flowop) { char line[1024]; char histogram[1024]; char hist_reading[20]; int i = 0; if (flowop->fo_instance != FLOW_MASTER) { flowop = flowop->fo_next; continue; } (void) snprintf(line, sizeof(line), "%-20s %dops %8.0lfops/s " "%5.1lfmb/s %8.3fms/op", flowop->fo_name, flowop->fo_stats.fs_count, flowop->fo_stats.fs_count / total_time_sec, (flowop->fo_stats.fs_bytes / MB_FLOAT) / total_time_sec, flowop->fo_stats.fs_count ? flowop->fo_stats.fs_total_lat / (flowop->fo_stats.fs_count * SEC2MS_FLOAT) : 0); (void) strcat(str, line); (void) snprintf(line, sizeof(line)," [%.3fms - %5.3fms]", flowop->fo_stats.fs_minlat / SEC2MS_FLOAT, flowop->fo_stats.fs_maxlat / SEC2MS_FLOAT); (void) strcat(str, line); if (filebench_shm->lathist_enabled) { (void) sprintf(histogram, "\t[ "); for (i = 0; i < OSPROF_BUCKET_NUMBER; i++) { (void) sprintf(hist_reading, "%lu ", flowop->fo_stats.fs_distribution[i]); (void) strcat(histogram, hist_reading); } (void) strcat(histogram, "]\n"); (void) strcat(str, histogram); } else (void) strcat(str, "\n"); flowop = flowop->fo_next; } /* removing last \n */ str[strlen(str) - 1] = '\0'; filebench_log(LOG_INFO, "%s", str); free(str); filebench_log(LOG_INFO, "IO Summary: %5d ops %5.3lf ops/s %0.0lf/%0.0lf rd/wr " "%5.1lfmb/s %5.3fms/op", iostat->fs_count + aiostat->fs_count, (iostat->fs_count + aiostat->fs_count) / total_time_sec, (iostat->fs_rcount + aiostat->fs_rcount) / total_time_sec, (iostat->fs_wcount + aiostat->fs_wcount) / total_time_sec, ((iostat->fs_bytes + aiostat->fs_bytes) / MB_FLOAT) / total_time_sec, (iostat->fs_count + aiostat->fs_count) ? (iostat->fs_total_lat + aiostat->fs_total_lat) / ((iostat->fs_count + aiostat->fs_count) * SEC2MS_FLOAT) : 0); filebench_shm->shm_bequiet = 0; } /* * Clears all the statistics variables (fo_stats) for every defined flowop. * It also creates a global flowstat table if one doesn't already exist and * clears it. */ void stats_clear(void) { flowop_t *flowop; if (globalstats == NULL) globalstats = malloc(FLOW_TYPES * sizeof (struct flowstats)); (void) memset(globalstats, 0, FLOW_TYPES * sizeof (struct flowstats)); flowop = filebench_shm->shm_flowoplist; while (flowop) { filebench_log(LOG_DEBUG_IMPL, "Clearing stats for %s-%d", flowop->fo_name, flowop->fo_instance); (void) memset(&flowop->fo_stats, 0, sizeof (struct flowstats)); flowop = flowop->fo_next; } (void) memset(globalstats, 0, sizeof(struct flowstats)); globalstats->fs_stime = gethrtime(); }
7,813
28.048327
75
c
filebench
filebench-master/stats.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_STATS_H #define _FB_STATS_H #include "filebench.h" #include "fbtime.h" void stats_clear(void); void stats_snap(void); #define OSPROF_BUCKET_NUMBER 64 struct flowstats { /* Eight fields below are updated per each flowop and * added up in globalstats and master flowop at stats_snap() */ int fs_count; /* Number of ops */ uint64_t fs_rcount; /* Number of read ops */ uint64_t fs_wcount; /* Number of write ops */ uint64_t fs_bytes; /* Number of bytes read/written */ uint64_t fs_rbytes; /* Number of bytes read */ uint64_t fs_wbytes; /* Number of bytes written */ unsigned long fs_distribution[OSPROF_BUCKET_NUMBER]; /* Used for OSprof */ hrtime_t fs_total_lat; unsigned long long fs_maxlat; /* max flowop latency (nanoseconds) */ unsigned long long fs_minlat; /* min flowop latency (nanoseconds) */ /* These two fields are used only in globalstats variable * to note the total time of statistics collection: from * stats_clear() to stats_snap() */ hrtime_t fs_stime; hrtime_t fs_etime; }; #define IS_FLOW_IOP(x) (x->fo_stats.fs_rcount + x->fo_stats.fs_wcount) #define STAT_IOPS(x) ((x->fs_rcount) + (x->fs_wcount)) #define IS_FLOW_ACTIVE(x) (x->fo_stats.fs_count) #define STAT_CPUTIME(x) (x->fs_cpu_op) #define STAT_OHEADTIME(x) (x->fs_cpu_ohead) #endif /* _FB_STATS_H */
2,242
32.477612
75
h
filebench
filebench-master/threadflow.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include "config.h" #include <pthread.h> #include <signal.h> #include "filebench.h" #include "threadflow.h" #include "flowop.h" #include "ipc.h" static threadflow_t *threadflow_define_common(procflow_t *procflow, char *name, threadflow_t *inherit, int instance); /* * Threadflows are filebench entities which manage operating system * threads. Each worker threadflow spawns a separate filebench thread, * with attributes inherited from a FLOW_MASTER threadflow created during * f model language parsing. This section contains routines to define, * create, control, and delete threadflows. * * Each thread defined in the f model creates a FLOW_MASTER * threadflow which encapsulates the defined attributes and flowops of * the f language thread, including the number of instances to create. * At runtime, a worker threadflow instance with an associated filebench * thread is created, which runs until told to quit or is specifically * deleted. */ /* * Creates a thread for the supplied threadflow. If interprocess * shared memory is desired, then increments the amount of shared * memory needed by the amount specified in the threadflow's * tf_memsize parameter. The thread starts in routine * flowop_start() with a poineter to the threadflow supplied * as the argument. */ static int threadflow_createthread(threadflow_t *threadflow) { fbint_t memsize; memsize = avd_get_int(threadflow->tf_memsize); threadflow->tf_constmemsize = memsize; int ret; filebench_log(LOG_DEBUG_SCRIPT, "Creating thread %s, memory = %ld", threadflow->tf_name, memsize); if (threadflow->tf_attrs & THREADFLOW_USEISM) filebench_shm->shm_required += memsize; ret = pthread_create(&threadflow->tf_tid, NULL, (void *(*)(void*))flowop_start, threadflow); if (ret != 0) { filebench_log(LOG_ERROR, "thread create failed: %s", strerror(ret)); filebench_shutdown(1); return (FILEBENCH_ERROR); } return (FILEBENCH_OK); } /* * Creates threads for the threadflows associated with a procflow. * The routine iterates through the list of threadflows in the * supplied procflow's pf_threads list. For each threadflow on * the list, it defines tf_instances number of cloned * threadflows, and then calls threadflow_createthread() for * each to create and start the actual operating system thread. * Note that each of the newly defined threadflows will be linked * into the procflows threadflow list, but at the head of the * list, so they will not become part of the supplied set. After * all the threads have been created, threadflow_init enters * a join loop for all the threads in the newly defined * threadflows. Once all the created threads have exited, * threadflow_init will return 0. If errors are encountered, it * will return a non zero value. */ int threadflow_init(procflow_t *procflow) { threadflow_t *threadflow = procflow->pf_threads; int ret = 0; (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); while (threadflow) { threadflow_t *newthread; int instances; int i; instances = avd_get_int(threadflow->tf_instances); filebench_log(LOG_VERBOSE, "Starting %d %s threads", instances, threadflow->tf_name); for (i = 1; i < instances; i++) { /* Create threads */ newthread = threadflow_define_common(procflow, threadflow->tf_name, threadflow, i + 1); if (newthread == NULL) return (-1); ret |= threadflow_createthread(newthread); } newthread = threadflow_define_common(procflow, threadflow->tf_name, threadflow, 1); if (newthread == NULL) return (-1); /* Create each thread */ ret |= threadflow_createthread(newthread); threadflow = threadflow->tf_next; } threadflow = procflow->pf_threads; (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); /* * All threadflows for this process were defined. * Inform process creator thread about that. * When all thread monitors set this flag (in their * corresponding procflow structures), the process creator * thread will set shm_procflows_defined_flag, which * will allow main process to continue. */ set_flag(&procflow->pf_threads_defined_flag); while (threadflow) { /* wait for all threads to finish */ if (threadflow->tf_tid) { void *status; if (pthread_join(threadflow->tf_tid, &status) == 0) ret += *(int *)status; } threadflow = threadflow->tf_next; } procflow->pf_running = 0; return (ret); } /* * Tells the threadflow's thread to stop and optionally signals * its associated process to end the thread. */ static void threadflow_kill(threadflow_t *threadflow) { int wait_cnt = 2; /* Tell thread to finish */ threadflow->tf_abort = 1; /* wait a bit for threadflow to stop */ while (wait_cnt && threadflow->tf_running) { (void) sleep(1); wait_cnt--; } if (threadflow->tf_running) { threadflow->tf_running = FALSE; (void) pthread_kill(threadflow->tf_tid, SIGKILL); } } /* * Deletes the specified threadflow from the specified threadflow * list after first terminating the threadflow's thread, deleting * the threadflow's flowops, and finally freeing the threadflow * entity. It also subtracts the threadflow's shared memory * requirements from the total amount required, shm_required. If * the specified threadflow is found, returns 0, otherwise * returns -1. */ static int threadflow_delete(threadflow_t **threadlist, threadflow_t *threadflow) { threadflow_t *entry = *threadlist; filebench_log(LOG_DEBUG_IMPL, "Deleting thread: (%s-%d)", threadflow->tf_name, threadflow->tf_instance); if (threadflow->tf_attrs & THREADFLOW_USEISM) filebench_shm->shm_required -= threadflow->tf_constmemsize; if (threadflow == *threadlist) { /* First on list */ filebench_log(LOG_DEBUG_IMPL, "Deleted thread: (%s-%d)", threadflow->tf_name, threadflow->tf_instance); threadflow_kill(threadflow); flowop_delete_all(&threadflow->tf_thrd_fops); *threadlist = threadflow->tf_next; (void) pthread_mutex_destroy(&threadflow->tf_lock); ipc_free(FILEBENCH_THREADFLOW, (char *)threadflow); return (0); } while (entry->tf_next) { filebench_log(LOG_DEBUG_IMPL, "Delete thread: (%s-%d) == (%s-%d)", entry->tf_next->tf_name, entry->tf_next->tf_instance, threadflow->tf_name, threadflow->tf_instance); if (threadflow == entry->tf_next) { /* Delete */ filebench_log(LOG_DEBUG_IMPL, "Deleted thread: (%s-%d)", entry->tf_next->tf_name, entry->tf_next->tf_instance); threadflow_kill(entry->tf_next); flowop_delete_all(&entry->tf_next->tf_thrd_fops); (void) pthread_mutex_destroy(&threadflow->tf_lock); ipc_free(FILEBENCH_THREADFLOW, (char *)threadflow); entry->tf_next = entry->tf_next->tf_next; return (0); } entry = entry->tf_next; } return (-1); } /* * Given a pointer to the thread list of a procflow, cycles * through all the threadflows on the list, deleting each one * except the FLOW_MASTER. */ void threadflow_delete_all(threadflow_t **threadlist) { threadflow_t *threadflow; (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); threadflow = *threadlist; filebench_log(LOG_DEBUG_IMPL, "Deleting all threads"); while (threadflow) { if (threadflow->tf_instance && (threadflow->tf_instance == FLOW_MASTER)) { threadflow = threadflow->tf_next; continue; } (void) threadflow_delete(threadlist, threadflow); threadflow = threadflow->tf_next; } (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); } /* * Waits till all threadflows are started, or a timeout occurs. * Checks through the list of threadflows, waiting up to 10 * seconds for each one to set its tf_running flag to 1. If not * set after 10 seconds, continues on to the next threadflow * anyway. */ void threadflow_allstarted(pid_t pid, threadflow_t *threadflow) { (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); while (threadflow) { int waits; if ((threadflow->tf_instance == 0) || (threadflow->tf_instance == FLOW_MASTER)) { threadflow = threadflow->tf_next; continue; } filebench_log(LOG_DEBUG_IMPL, "Checking pid %d thread %s-%d", pid, threadflow->tf_name, threadflow->tf_instance); waits = 10; while (waits && (threadflow->tf_running == 0) && (filebench_shm->shm_f_abort == 0)) { (void) ipc_mutex_unlock( &filebench_shm->shm_threadflow_lock); if (waits < 3) filebench_log(LOG_INFO, "Waiting for pid %d thread %s-%d", pid, threadflow->tf_name, threadflow->tf_instance); (void) sleep(1); (void) ipc_mutex_lock( &filebench_shm->shm_threadflow_lock); waits--; } threadflow = threadflow->tf_next; } (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); } /* * Create an in-memory thread object linked to a parent procflow. * A threadflow entity is allocated from shared memory and * initialized from the "inherit" threadflow if supplied, * otherwise to zeros. The threadflow is assigned a unique * thread id, the supplied instance number, the supplied name * and added to the procflow's pf_thread list. If no name is * supplied or the threadflow can't be allocated, NULL is * returned Otherwise a pointer to the newly allocated threadflow * is returned. * * The filebench_shm->shm_threadflow_lock must be held by the caller. */ static threadflow_t * threadflow_define_common(procflow_t *procflow, char *name, threadflow_t *inherit, int instance) { threadflow_t *threadflow; threadflow_t **threadlistp = &procflow->pf_threads; if (name == NULL) return (NULL); threadflow = (threadflow_t *)ipc_malloc(FILEBENCH_THREADFLOW); if (threadflow == NULL) return (NULL); if (inherit) (void) memcpy(threadflow, inherit, sizeof (threadflow_t)); else (void) memset(threadflow, 0, sizeof (threadflow_t)); threadflow->tf_utid = ++filebench_shm->shm_utid; threadflow->tf_instance = instance; (void) strcpy(threadflow->tf_name, name); threadflow->tf_process = procflow; (void) pthread_mutex_init(&threadflow->tf_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); filebench_log(LOG_DEBUG_IMPL, "Defining thread %s-%d", name, instance); /* Add threadflow to list */ if (*threadlistp == NULL) { *threadlistp = threadflow; threadflow->tf_next = NULL; } else { threadflow->tf_next = *threadlistp; *threadlistp = threadflow; } return threadflow; } /* * Create an in memory FLOW_MASTER thread object as described * by the syntax. Acquire the filebench_shm->shm_threadflow_lock and * call threadflow_define_common() to create a threadflow entity. * Set the number of instances to create at runtime, * tf_instances, to "instances". Return the threadflow pointer * returned by the threadflow_define_common call. */ threadflow_t * threadflow_define(procflow_t *procflow, char *name, threadflow_t *inherit, avd_t instances) { threadflow_t *threadflow; (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); if ((threadflow = threadflow_define_common(procflow, name, inherit, FLOW_MASTER)) == NULL) return (NULL); threadflow->tf_instances = instances; (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); return (threadflow); } /* * Searches the provided threadflow list for the named threadflow. * A pointer to the threadflow is returned, or NULL if threadflow * is not found. */ threadflow_t * threadflow_find(threadflow_t *threadlist, char *name) { threadflow_t *threadflow = threadlist; (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); while (threadflow) { if (strcmp(name, threadflow->tf_name) == 0) { (void) ipc_mutex_unlock( &filebench_shm->shm_threadflow_lock); return (threadflow); } threadflow = threadflow->tf_next; } (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); return (NULL); }
12,856
27.507761
73
c
filebench
filebench-master/threadflow.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_THREADFLOW_H #define _FB_THREADFLOW_H #include "filebench.h" #define AL_READ 1 #define AL_WRITE 2 #ifdef HAVE_AIO typedef struct aiolist { int al_type; struct aiolist *al_next; struct aiolist *al_worknext; struct aiocb64 al_aiocb; } aiolist_t; #endif #define THREADFLOW_MAXFD 128 #define THREADFLOW_USEISM 0x1 typedef struct threadflow { char tf_name[128]; /* Name */ int tf_attrs; /* Attributes */ int tf_instance; /* Instance number */ int tf_running; /* Thread running indicator */ int tf_abort; /* Shutdown thread */ int tf_utid; /* Unique id for thread */ struct procflow *tf_process; /* Back pointer to process */ pthread_t tf_tid; /* Thread id */ pthread_mutex_t tf_lock; /* Mutex around threadflow */ avd_t tf_instances; /* Number of instances for this flow */ struct threadflow *tf_next; /* Next on proc list */ struct flowop *tf_thrd_fops; /* Flowop list */ caddr_t tf_mem; /* Private Memory */ avd_t tf_memsize; /* Private Memory size attribute */ fbint_t tf_constmemsize; /* constant copy of memory size */ fb_fdesc_t tf_fd[THREADFLOW_MAXFD + 1]; /* Thread local fd's */ filesetentry_t *tf_fse[THREADFLOW_MAXFD + 1]; /* Thread local files */ int tf_fdrotor; /* Rotating fd within set */ struct flowstats tf_stats; /* Thread statistics */ hrtime_t tf_stime; /* Start time of current flowop: used to measure the latency of the flowop */ #ifdef HAVE_AIO aiolist_t *tf_aiolist; /* List of async I/Os */ #endif avd_t tf_ioprio; /* ioprio attribute */ } threadflow_t; /* Thread attrs */ #define THREADFLOW_DEFAULTMEM 1024*1024LL; threadflow_t *threadflow_define(procflow_t *, char *name, threadflow_t *inherit, avd_t instances); threadflow_t *threadflow_find(threadflow_t *, char *); int threadflow_init(procflow_t *); void flowop_start(threadflow_t *threadflow); void threadflow_allstarted(pid_t pid, threadflow_t *threadflow); void threadflow_delete_all(threadflow_t **threadlist); #endif /* _FB_THREADFLOW_H */
2,915
32.906977
97
h
filebench
filebench-master/utils.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include <limits.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <errno.h> #ifdef HAVE_STDINT_H #include <stdint.h> #endif #include "filebench.h" #include "utils.h" #include "parsertypes.h" /* * For now, just three routines: one to allocate a string in shared * memory, one to emulate a strlcpy() function and one to emulate a * strlcat() function, both the second and third only used in non * Solaris environments, * */ /* * Allocates space for a new string of the same length as * the supplied string "str". Copies the old string into * the new string and returns a pointer to the new string. * Returns NULL if memory allocation for the new string fails. */ char * fb_stralloc(char *str) { char *newstr; if ((newstr = malloc(strlen(str) + 1)) == NULL) return (NULL); (void) strcpy(newstr, str); return (newstr); } #ifndef HAVE_STRLCPY /* * Implements the strlcpy function when compilied for non Solaris * operating systems. On solaris the strlcpy() function is used * directly. */ size_t fb_strlcpy(char *dst, const char *src, size_t dstsize) { uint_t i; for (i = 0; i < (dstsize - 1); i++) { /* quit if at end of source string */ if (src[i] == '\0') break; dst[i] = src[i]; } /* set end of dst string to \0 */ dst[i] = '\0'; i++; return (i); } #endif /* HAVE_STRLCPY */ #ifndef HAVE_STRLCAT /* * Implements the strlcat function when compilied for non Solaris * operating systems. On solaris the strlcat() function is used * directly. */ size_t fb_strlcat(char *dst, const char *src, size_t dstsize) { uint_t i, j; /* find the end of the current destination string */ for (i = 0; i < (dstsize - 1); i++) { if (dst[i] == '\0') break; } /* append the source string to the destination string */ for (j = 0; i < (dstsize - 1); i++) { if (src[j] == '\0') break; dst[i] = src[j]; j++; } /* set end of dst string to \0 */ dst[i] = '\0'; i++; return (i); } #endif /* HAVE_STRLCAT */ #ifdef HAVE_PROC_SYS_KERNEL_SHMMAX /* * Increase the maximum shared memory segment size till some large value. We do * not restore it to the old value when the Filebench run is over. If we could * not change the value - we continue execution. */ void fb_set_shmmax(void) { FILE *f; int ret; f = fopen("/proc/sys/kernel/shmmax", "r+"); if (!f) { filebench_log(LOG_FATAL, "WARNING: Could not open " "/proc/sys/kernel/shmmax file!\n" "It means that you probably ran Filebench not " "as a root. Filebench will not increase shared\n" "region limits in this case, which can lead " "to the failures on certain workloads."); return; } /* writing new value */ #define SOME_LARGE_SHMAX "268435456" /* 256 MB */ ret = fwrite(SOME_LARGE_SHMAX, sizeof(SOME_LARGE_SHMAX), 1, f); if (ret != 1) filebench_log(LOG_ERROR, "Coud not write to " "/proc/sys/kernel/shmmax file!"); #undef SOME_LARGE_SHMAX fclose(f); return; } #else /* HAVE_PROC_SYS_KERNEL_SHMMAX */ void fb_set_shmmax(void) { return; } #endif /* HAVE_PROC_SYS_KERNEL_SHMMAX */ #ifdef HAVE_SETRLIMIT /* * Increase the limit of opened files. * * We first set the limit to the hardlimit reported by the kernel; this call * will always succeed. Then we try to set the limit to some large number of * files (unfortunately we can't set this ulimit to infinity), this will only * succeed if the process is ran by root. Therefore, we always set the maximum * possible value for the limit for this given process (well, only if hardlimit * is greater then the large number of files defined by us, it is not true). * * Increasing this limit is especially important when we use thread model, * because opened files are accounted per-process, not per-thread. */ void fb_set_rlimit(void) { struct rlimit rlp; (void)getrlimit(RLIMIT_NOFILE, &rlp); rlp.rlim_cur = rlp.rlim_max; (void)setrlimit(RLIMIT_NOFILE, &rlp); #define SOME_LARGE_NUMBER_OF_FILES 50000 rlp.rlim_cur = rlp.rlim_max = SOME_LARGE_NUMBER_OF_FILES; #undef SOME_LARGE_NUMBER_OF_FILES (void)setrlimit(RLIMIT_NOFILE, &rlp); return; } #else /* HAVE_SETRLIMIT */ void fb_set_rlimit(void) { return; } #endif /* HAVE_SETRLIMIT */
5,166
23.722488
80
c
filebench
filebench-master/utils.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_UTILS_H #define _FB_UTILS_H #include "filebench.h" extern char *fb_stralloc(char *str); #ifdef HAVE_STRLCAT #define fb_strlcat strlcat #else extern size_t fb_strlcat(char *dst, const char *src, size_t dstsize); #endif /* HAVE_STRLCAT */ #ifdef HAVE_STRLCPY #define fb_strlcpy strlcpy #else extern size_t fb_strlcpy(char *dst, const char *src, size_t dstsize); #endif /* HAVE_STRLCPY */ extern void fb_set_shmmax(void); void fb_set_rlimit(void); #endif /* _FB_UTILS_H */
1,416
27.34
70
h
filebench
filebench-master/vars.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _VARS_H #define _VARS_H #include "filebench.h" /* Attribute Value Descriptor (AVD) types */ typedef enum avd_type { AVD_INVALID = 0, /* avd is empty */ AVD_VAL_BOOL, /* avd contains a boolean_t */ AVD_VARVAL_BOOL, /* avd points to the boolean_t in a var_t */ AVD_VAL_INT, /* avd contains an uint64_t */ AVD_VARVAL_INT, /* avd points to the uint64_t in a var_t */ AVD_VAL_DBL, /* avd contains a double float */ AVD_VARVAL_DBL, /* avd points to the double in a var_t */ AVD_VAL_STR, /* avd contains a sting (*char) */ AVD_VARVAL_STR, /* avd points to a string in a var_t */ AVD_VARVAL_UNKNOWN, /* avd points to a variable whose type is not * known yet */ AVD_VARVAL_RANDOM, /* avd points to the randdist_t associated */ /* with a random variable type var_t */ AVD_VARVAL_CUSTOM /* avd points to the cvar_t associated */ /* with a custom variable type var_t */ } avd_type_t; /* Attribute Value Descriptor (AVD) */ typedef struct avd { avd_type_t avd_type; union { boolean_t boolval; boolean_t *boolptr; uint64_t intval; uint64_t *intptr; double dblval; double *dblptr; char *strval; char **strptr; struct var *varptr; /* * Used by AVDs that point to * uninitialized variables of * yet unknown type. */ struct randdist *randptr; struct cvar *cvarptr; } avd_val; } *avd_t; #define AVD_IS_RANDOM(vp) ((vp) && ((vp)->avd_type == AVD_VARVAL_RANDOM)) #define AVD_IS_STRING(vp) ((vp) && (((vp)->avd_type == AVD_VAL_STR) || \ ((vp)->avd_type == AVD_VARVAL_STR))) #define AVD_IS_BOOL(vp) ((vp) && (((vp)->avd_type == AVD_VAL_BOOL) || \ ((vp)->avd_type == AVD_VARVAL_BOOL))) #define AVD_IS_INT(vp) ((vp) && (((vp)->avd_type == AVD_VAL_INT) || \ ((vp)->avd_type == AVD_VARVAL_INT))) /* Variable Types */ typedef enum var_type { VAR_INVALID = 0, VAR_BOOL, VAR_INT, VAR_DBL, VAR_STR, VAR_RANDOM, VAR_CUSTOM, VAR_UNKNOWN, } var_type_t; typedef struct var { char *var_name; var_type_t var_type; struct var *var_next; union { boolean_t boolean; uint64_t integer; double dbl; char *string; struct randdist *randptr; struct cvar *cvarptr; } var_val; } var_t; #define VAR_HAS_BOOLEAN(vp) \ ((vp)->var_type == VAR_BOOL) #define VAR_HAS_INTEGER(vp) \ ((vp)->var_type == VAR_INT) #define VAR_HAS_DOUBLE(vp) \ ((vp)->var_type == VAR_DBL) #define VAR_HAS_STRING(vp) \ ((vp)->var_type == VAR_STR) #define VAR_HAS_RANDOM(vp) \ ((vp)->var_type == VAR_RANDOM) #define VAR_HAS_CUSTOM(vp) \ ((vp)->var_type == VAR_CUSTOM) #define VAR_HAS_UNKNOWN(vp) \ ((vp)->var_type == VAR_UNKNOWN) #define VAR_SET_BOOL(vp, val) \ { \ (vp)->var_val.boolean = (val); \ (vp)->var_type = VAR_BOOL;\ } #define VAR_SET_INT(vp, val) \ { \ (vp)->var_val.integer = (val); \ (vp)->var_type = VAR_INT; \ } #define VAR_SET_DBL(vp, val) \ { \ (vp)->var_val.dbl = (val); \ (vp)->var_type = VAR_DBL; \ } #define VAR_SET_STR(vp, val) \ { \ (vp)->var_val.string = (val); \ (vp)->var_type = VAR_STR; \ } #define VAR_SET_RANDOM(vp, val) \ { \ (vp)->var_val.randptr = (val); \ (vp)->var_type = VAR_RANDOM; \ } #define VAR_SET_CUSTOM(vp, val) \ { \ (vp)->var_val.cvarptr = (val); \ (vp)->var_type = VAR_CUSTOM; \ } #define VAR_SET_UNKNOWN(vp) \ { \ (vp)->var_type = VAR_UNKNOWN; \ } avd_t avd_bool_alloc(boolean_t bool); avd_t avd_int_alloc(uint64_t integer); avd_t avd_dbl_alloc(double integer); avd_t avd_str_alloc(char *string); avd_t avd_var_alloc(char *varname); int var_assign_boolean(char *name, boolean_t bool); int var_assign_integer(char *name, uint64_t integer); int var_assign_double(char *name, double dbl); int var_assign_string(char *name, char *string); int var_assign_random(char *name, struct randdist *rndp); int var_assign_custom(char *name, struct cvar *cvar); boolean_t avd_get_bool(avd_t); uint64_t avd_get_int(avd_t); double avd_get_dbl(avd_t); char *avd_get_str(avd_t); /* Local variables related */ void avd_update(avd_t *avdp, var_t *lvar_list); void var_update_comp_lvars(var_t *newlvar, var_t *proto_comp_vars, var_t *mstr_lvars); var_t *var_lvar_alloc_local(char *name); var_t *var_lvar_assign_boolean(char *name, boolean_t); var_t *var_lvar_assign_integer(char *name, uint64_t); var_t *var_lvar_assign_double(char *name, double); var_t *var_lvar_assign_string(char *name, char *string); var_t *var_lvar_assign_var(char *name, char *src_name); /* miscelaneous */ char *var_to_string(char *name); char *var_randvar_to_string(char *name, int param); #endif /* _VARS_H */
5,483
26.837563
73
h
filebench
filebench-master/cvars/cvar-erlang.c
/* * rand-erlang.c * * Custom variable that returns random numbers following the Erlang * distribution. * * Author: Santhosh Kumar Koundinya ([email protected]) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-erlang.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of shape and rate. */ t = find_token(list_head, RER_SHAPE); if (t && t->value) { t->used = 1; handle.shape = atoi(t->value); } else handle.shape = RER_SHAPE_DEFAULT; t = find_token(list_head, RER_RATE); if (t && t->value) { t->used = 1; handle.rate = atof(t->value); } else handle.rate = RER_RATE_DEFAULT; cvar_trace("shape = %d, rate = %lf", handle.shape, handle.rate); /* Validate parameters. */ if (handle.shape < 0) { cvar_log_error("Invalid parameter value: shape = %d. shape is a " "non-zero positive integer", handle.shape); goto out; } if (handle.rate < 0) { cvar_log_error("Invalid parameter value: rate = %lf. rate is a " "non-zero positive rational number", handle.rate); goto out; } t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_trace("NULL cvar_handle"); return -1; } if (!value) { cvar_trace("NULL value"); return -1; } *value = rds_erlang(&h->state, h->shape, h->rate); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%d\n", RER_SHAPE, RER_SHAPE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RER_RATE, RER_RATE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%d%c%s%c%.1f'", RER_SHAPE, DEFAULT_KEY_VALUE_DELIMITER, RER_SHAPE_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RER_RATE, DEFAULT_KEY_VALUE_DELIMITER, RER_RATE_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,537
20.839506
72
c
filebench
filebench-master/cvars/cvar-lognormal.c
/* * rand-lognormal.c * * Custom variable implementation that returns Log-Normally distributed random * numbers. * * Author: Santhosh Kumar Koundinya ([email protected]) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-lognormal.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of shape and scale. */ t = find_token(list_head, RLN_SHAPE); if (t && t->value) { t->used = 1; handle.shape = atof(t->value); } else handle.shape = RLN_SHAPE_DEFAULT; t = find_token(list_head, RLN_SCALE); if (t && t->value) { t->used = 1; handle.scale = atof(t->value); } else handle.scale = RLN_SCALE_DEFAULT; cvar_trace("shape = %lf, scale = %lf", handle.shape, handle.scale); if (handle.shape < 0) { cvar_log_error("Invalid parameter value: shape = %lf. shape is a " "non-zero, positive rational number", handle.shape); goto out; } if (handle.scale < 0) { cvar_log_error("Invalid parameter value: scale = %lf. scale is a " "non-zero, positive rational number", handle.scale); goto out; } t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_trace("NULL cvar_handle"); return -1; } if (!value) { cvar_trace("NULL value"); return -1; } *value = rds_lognormal(&h->state, h->shape, h->scale); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RLN_SHAPE, RLN_SHAPE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RLN_SCALE, RLN_SCALE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f'", RLN_SHAPE, DEFAULT_KEY_VALUE_DELIMITER, RLN_SHAPE_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RLN_SCALE, DEFAULT_KEY_VALUE_DELIMITER, RLN_SCALE_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,556
21.093168
78
c
filebench
filebench-master/cvars/cvar-normal.c
/* * rand-normal.h * * Custom variable that returns random numbers following the Normal * distribution. * * Author: Santhosh Kumar Koundinya ([email protected]) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-normal.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of mean and sigma. */ t = find_token(list_head, RN_MEAN); if (t && t->value) { t->used = 1; handle.mean = atof(t->value); } else handle.mean = RN_MEAN_DEFAULT; t = find_token(list_head, RN_SIGMA); if (t && t->value) { t->used = 1; handle.sigma = atof(t->value); } else handle.sigma = RN_SIGMA_DEFAULT; cvar_trace("mean = %lf, sigma = %lf", handle.mean, handle.sigma); t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_trace("NULL cvar_handle"); return -1; } if (!value) { cvar_trace("NULL value"); return -1; } *value = rds_normal(&h->state, h->mean, h->sigma); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RN_MEAN, RN_MEAN_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RN_SIGMA, RN_SIGMA_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f'", RN_MEAN, DEFAULT_KEY_VALUE_DELIMITER, RN_MEAN_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RN_SIGMA, DEFAULT_KEY_VALUE_DELIMITER, RN_SIGMA_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,183
20.369128
72
c
filebench
filebench-master/cvars/cvar-triangular.c
/* * rand-triangular.c * * Custom variable implementation that returns random numbers following a * Triangular distribution. * * Author: Santhosh Kumar Koundinya ([email protected]) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-triangular.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of lower, upper and mode. */ t = find_token(list_head, RT_LOWER); if (t && t->value) { t->used = 1; handle.lower = atof(t->value); } else handle.lower = RT_LOWER_DEFAULT; t = find_token(list_head, RT_UPPER); if (t && t->value) { t->used = 1; handle.upper = atof(t->value); } else handle.upper = RT_UPPER_DEFAULT; t = find_token(list_head, RT_MODE); if (t && t->value) { t->used = 1; handle.mode = atof(t->value); } else handle.mode = RT_MODE_DEFAULT; cvar_trace("lower = %lf, upper = %lf, mode = %lf", handle.lower, handle.upper, handle.mode); /* Validate parameters. */ if (handle.upper < handle.lower) { cvar_log_error("Invalid parameter values: lower = %lf and upper = %lf. " "upper must be greater than lower", handle.lower, handle.upper); goto out; } if ((handle.mode > handle.upper) || (handle.mode < handle.lower)) { cvar_log_error("Invalid parameter values: lower = %lf, mode = %lf and " "upper = %lf. mode must be between lower and upper", handle.lower, handle.mode, handle.upper); goto out; } /* Check if there are unused tokens. */ t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_log_error("NULL cvar_handle"); return -1; } if (!value) { cvar_log_error("NULL value"); return -1; } *value = rds_triangular(&h->state, h->lower, h->upper, h->mode); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RT_LOWER, RT_LOWER_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RT_UPPER, RT_UPPER_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RT_MODE, RT_MODE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f%c%s%c%.1f'", RT_LOWER, DEFAULT_KEY_VALUE_DELIMITER, RT_LOWER_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RT_UPPER, DEFAULT_KEY_VALUE_DELIMITER, RT_UPPER_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RT_MODE, DEFAULT_KEY_VALUE_DELIMITER, RT_MODE_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
4,154
22.607955
74
c
filebench
filebench-master/cvars/cvar-uniform.c
/* * rand-uniform.c * * Custom variable implementation that returns uniformly distributed random * numbers. * * Author: Santhosh Kumar Koundinya ([email protected]) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-uniform.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the values for lower and upper. */ t = find_token(list_head, RU_LOWER); if (t && t->value) { t->used = 1; handle.lower = atof(t->value); } else handle.lower = RU_LOWER_DEFAULT; t = find_token(list_head, RU_UPPER); if (t && t->value) { t->used = 1; handle.upper = atof(t->value); } else handle.upper = RU_UPPER_DEFAULT; cvar_trace("lower = %lf, upper = %lf", handle.lower, handle.upper); /* Validate parameters. */ if (handle.lower > handle.upper) { cvar_log_error("Invalid parameter values: lower = %lf and upper = %lf. " "upper must be greater than lower", handle.lower, handle.upper); } t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_log_error("NULL cvar_handle"); return -1; } if (!value) { cvar_log_error("NULL value"); return -1; } *value = rds_uniform(&h->state, h->lower, h->upper); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RU_LOWER, RU_LOWER_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RU_UPPER, RU_UPPER_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f'", RU_LOWER, DEFAULT_KEY_VALUE_DELIMITER, RU_LOWER_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RU_UPPER, DEFAULT_KEY_VALUE_DELIMITER, RU_UPPER_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,422
21.227273
75
c
filebench
filebench-master/cvars/cvar-weibull.c
/* * rand-weibull.c * * Custom variable implementation that returns random numbers following the * Weibull distribution. * * Author: Santhosh Kumar Koundinya ([email protected]) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-weibull.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of shape and scale. */ t = find_token(list_head, RW_SHAPE); if (t && t->value) { t->used = 1; handle.shape = atof(t->value); } else handle.shape = RW_SHAPE_DEFAULT; t = find_token(list_head, RW_SCALE); if (t && t->value) { t->used = 1; handle.scale = atof(t->value); } else handle.scale = RW_SCALE_DEFAULT; cvar_trace("shape = %lf, scale = %lf", handle.shape, handle.scale); /* Validate parameters. */ if (handle.shape < 0) { cvar_log_error("Invalid parameter value: shape = %lf. shape is a " "non-zero, positive integer", handle.shape); goto out; } if (handle.scale < 0) { cvar_log_error("Invalid parameter value: scale = %lf. scale is a " "non-zero, positive rational number", handle.scale); goto out; } t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_trace("NULL cvar_handle"); return -1; } if (!value) { cvar_trace("NULL value"); return -1; } *value = rds_weibull(&h->state, h->shape, h->scale); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RW_SHAPE, RW_SHAPE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RW_SCALE, RW_SCALE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f'", RW_SHAPE, DEFAULT_KEY_VALUE_DELIMITER, RW_SHAPE_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RW_SCALE, DEFAULT_KEY_VALUE_DELIMITER, RW_SCALE_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,568
21.030864
75
c
filebench
filebench-master/cvars/cvar.h
/* * cvar.h * * Include file for code implementing custom variables. * * @Author Santhosh Kumar Koundinya ([email protected]) */ #ifndef _CVAR_H #define _CVAR_H /* * Initialize the state of the library supporting the custom variable. * cvar_module_init is the first function to be invoked when a custom variable * module is loaded. * * Implementation: Optional. * * Return 0 on success and a non-zero error code on failure. */ int cvar_module_init(); /* * Allocate a new custom variable handle. A handle is subsequently used to * generate values. Memory required for initializing the handle must be * allocated using argument cvar_malloc only. Libraries can use cvar_free to * clean up memory allocated by cvar_malloc in case construction of the handle * fails. Libraries must not store references to cvar_malloc and cvar_free for * later use. * * Implementation: Mandatory. * * Return a non NULL handle on success and a NULL handle on error. */ void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *ptr)); /* * Re-validate a previously allocated handle. Filebench will always * re-validate handles that were not allocated in the current process before * use in the current process. * * Implementation: Optional. * * Return 0 on success and a non-zero error code on failure to re-validate * existing handle. */ int cvar_revalidate_handle(void *cvar_handle); /* * Called every time a new value of the custom variable is required. * * Implementation: Mandatory. * * Return 0 on success and non zero on error. On success, argument value is * initialized to the next value of the variable whose state is in handle. */ int cvar_next_value(void *cvar_handle, double *value); /* * Called when an existing custom variable has to be destroyed. Use function * cvar_free to free up memory allocated for cvar_handle. * * Implementation: Mandatory. * * Note: cvar_free_handle may not be called at all, i.e., Filebench may choose * to quit without invoking free_handle. */ void cvar_free_handle(void *cvar_handle, void (*cvar_free)(void *ptr)); /* * Invoked before unloading the module. * * Implementation: Optional. * * Note: * 1. cvar_module_exit will never be invoked if cvar_module_init failed. * 2. cvar_module_exit may not be called at all, i.e., Filebench may choose * to quit without invoking cvar_module_exit. */ void cvar_module_exit(); /* * Show usage, including information on the list of parameters supported and the * format of the parameter string. * * Implementation: Optional. * * Return a non-null, formatted string to be displayed on screen. */ const char *cvar_usage(); /* * Show version. * * Implementation: Optional. * * Return a non-null version string. */ const char *cvar_version(); #endif /* _CVAR_H */
2,873
24.891892
80
h
filebench
filebench-master/cvars/cvar_tokens.h
/* * cvar_tokens.h * * Simple utilities to manipulate tokens. * * Author: Santhosh Kumar Koundinya ([email protected]) */ #ifndef _CVAR_TOKENS_H #define _CVAR_TOKENS_H #define DEFAULT_PARAMETER_DELIMITER ';' #define DEFAULT_KEY_VALUE_DELIMITER ':' /* A token holds a key-value pair. */ typedef struct cvar_token { char *key; char *value; int used; /* Non-zero if the token is used */ struct cvar_token *next; } cvar_token_t; /* * Return 0 if tokenization was successful, non-zero otherwise. This function * does not use strtok (or strtok_r) as we need to point out empty keys. */ int tokenize(const char *parameters, const char parameter_delimiter, const char key_value_delimiter, cvar_token_t **list_head); /* * Finds a token with a given key. Returns NULL if the token is not found or if * list_head or key is NULL. */ cvar_token_t *find_token(cvar_token_t *list_head, const char *key); /* * Returns a pointer to the first unused token or NULL if no unused tokens * exist. */ cvar_token_t *unused_tokens(cvar_token_t *list_head); /* * Free up a list of tokens. */ void free_tokens(cvar_token_t *list_head); #endif /* _CVAR_TOKENS_H */
1,178
23.061224
79
h
filebench
filebench-master/cvars/mtwist/mtwist.h
#ifndef MTWIST_H #define MTWIST_H /* * $Id: mtwist.h,v 1.24 2012-12-31 22:22:03-08 geoff Exp $ * * Header file for C/C++ use of the Mersenne-Twist pseudo-RNG. See * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html for full * information. * * Author of this header file: Geoff Kuenning, March 18, 2001. * * IMPORTANT NOTE: this implementation assumes a modern compiler. In * particular, it assumes that the "inline" keyword is available, and * that the "stdint.h" header file is present. * * The variables above are defined in an inverted sense because I * expect that most modern compilers will support these features. By * inverting the sense, this common case will require no special * compiler flags. * * IMPORTANT NOTE: this software requires access to a 32-bit type. * The Mersenne Twist algorithms are not guaranteed to produce correct * results with a 64-bit type. * * The executable part of this software is based on LGPL-ed code by * Takuji Nishimura. The header file is therefore also distributed * under the LGPL: * * 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 Foundation, Inc., 59 * Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Log: mtwist.h,v $ * Revision 1.24 2012-12-31 22:22:03-08 geoff * Fix the out-of-bounds bug in mt_llrand and mt_ldrand that were * overlooked because I assumed they used mts_*. * * Revision 1.23 2013-01-01 01:18:52-08 geoff * Fix a lot of compiler warnings. * * Revision 1.22 2012-12-30 16:24:49-08 geoff * Declare the new versions of the /dev/random and urandom seeding * functions, which now return the seed chosen. * * Revision 1.21 2012-09-23 23:15:40-07 geoff * Fix an array index violation found by valgrind and reported by David * Chapman; under some circumstances statevec[-1] could be accessed and * used in random-number generation. The bug only affects the *_llrand * and *_ldrand functions. * * Revision 1.20 2010-12-10 03:28:18-08 geoff * Add support for GENERATE_CODE_IN_HEADER. Fix the URL for the original * Web page. * * Revision 1.19 2010-06-24 20:53:59+12 geoff * Switch to using types from stdint.h. Get rid of all compilation * options. * * Revision 1.18 2010-06-24 00:29:38-07 geoff * Do a better job of auto-determining MT_MACHINE_BITS. * * Revision 1.17 2007-10-26 00:21:06-07 geoff * Introduce, document, and use the new mt_u32bit_t type so that the code * will compile and run on 64-bit platforms (although it does not * currently use the 64-bit Mersenne Twist algorithm). * * Revision 1.16 2005/11/11 08:21:39 geoff * If possible, try to infer MT_MACHINE_BITS from limits.h. * * Revision 1.15 2003/09/11 23:56:20 geoff * Allow stdio references in C++ files; it turns out that ANSI has * blessed it. Declare the various functions as external even if they're * inlined or being compiled directly (in mtwist.c). Get rid of a #ifdef * that can't ever be true. * * Revision 1.14 2003/09/11 05:50:53 geoff * Don't allow stdio references from C++, since they're not guaranteed to * work on all compilers. Disable inlining using the MT_INLINE keyword * rather than #defining inline, since doing the latter can affect other * files and functions than our own. * * Revision 1.13 2003/07/01 23:29:29 geoff * Refer to streams from the standard library using the correct namespace. * * Revision 1.12 2002/10/30 07:39:54 geoff * Declare the new seeding functions. * * Revision 1.11 2001/06/19 00:41:16 geoff * For consistency with other C++ types, don't put out a newline after * the saved data. * * Revision 1.10 2001/06/18 10:09:24 geoff * Fix some places where I forgot to set one of the result values. Make * the C++ state vector protected so the random-distributions package can * pass it to the C functions. * * Revision 1.9 2001/06/18 05:40:12 geoff * Prefix the compile options with MT_. * * Revision 1.8 2001/06/14 10:26:59 geoff * Invert the sense of the #define flags so that the default is the * normal case (if gcc is normal!). Also default MT_MACHINE_BITS to 32. * * Revision 1.7 2001/06/14 10:10:38 geoff * Move the critical-path PRNG code into the header file so that it can * be inlined. Add saving/loading of state. Add functions to seed based * on /dev/random or the time. Add the function-call operator in the C++ * code. * * Revision 1.6 2001/06/11 10:00:04 geoff * Add declarations of the refresh and /dev/random seeding functions. * Change getstate to return a complete state pointer, since knowing the * position in the state vector is critical to restoring the state. * * Revision 1.5 2001/04/23 08:36:03 geoff * Remember to zero the state pointer when constructing, since otherwise * proper initialization won't happen. * * Revision 1.4 2001/04/14 01:33:32 geoff * Clarify the license * * Revision 1.3 2001/04/14 01:04:54 geoff * Add a C++ class, mt_prng, that makes usage more convenient for C++ * programmers. * * Revision 1.2 2001/04/09 08:45:00 geoff * Fix the name in the #ifndef wrapper, and clean up some outdated comments. * * Revision 1.1 2001/04/07 09:43:41 geoff * Initial revision * */ #include <stdio.h> #ifdef __cplusplus #include <iostream> #endif /* __cplusplus */ #define __STDC_LIMIT_MACROS #include <stdint.h> /* * The following value is a fundamental parameter of the algorithm. * It was found experimentally using methods described in Matsumoto * and Nishimura's paper. It is exceedingly magic; don't change it. */ #define MT_STATE_SIZE 624 /* Size of the MT state vector */ /* * Internal state for an MT RNG. The user can keep multiple mt_state * structures around as a way of generating multiple streams of random * numbers. * * In Matsumoto and Nishimura's original paper, the state vector was * processed in a forward direction. I have reversed the state vector * in this implementation. The reason for the reversal is that it * allows the critical path to use a test against zero instead of a * test against 624 to detect the need to refresh the state. on most * machines, testing against zero is slightly faster. It also means * that a state that has been set to all zeros will be correctly * detected as needing initialization; this means that setting a state * vector to zero (either with memset or by statically allocating it) * will cause the RNG to operate properly. */ typedef struct { uint32_t statevec[MT_STATE_SIZE]; /* Vector holding current state */ int stateptr; /* Next state entry to be used */ int initialized; /* NZ if state was initialized */ } mt_state; #ifdef __cplusplus extern "C" { #endif /* * Functions for manipulating any generator (given a state pointer). */ extern void mts_mark_initialized(mt_state* state); /* Mark a PRNG state as initialized */ extern void mts_seed32(mt_state* state, uint32_t seed); /* Set random seed for any generator */ extern void mts_seed32new(mt_state* state, uint32_t seed); /* Set random seed for any generator */ extern void mts_seedfull(mt_state* state, uint32_t seeds[MT_STATE_SIZE]); /* Set complicated seed for any gen. */ extern uint32_t mts_seed(mt_state* state); /* Choose seed from random input. */ /* ..Prefers /dev/urandom; uses time */ /* ..if /dev/urandom unavailable. */ /* ..Only gives 32 bits of entropy. */ /* ..Returns seed usable with seed32 */ extern uint32_t mts_goodseed(mt_state* state); /* Choose seed from more random */ /* ..input than mts_seed. Prefers */ /* ../dev/random; uses time if that */ /* ..is unavailable. Only gives 32 */ /* ..bits of entropy. */ /* ..Returns seed usable with seed32 */ extern void mts_bestseed(mt_state* state); /* Choose seed from extremely random */ /* ..input (can be *very* slow). */ /* ..Prefers /dev/random and reads */ /* ..the entire state from there. */ /* ..If /dev/random is unavailable, */ /* ..falls back to mt_goodseed(). */ /* ..Not usually worth the cost. */ extern void mts_refresh(mt_state* state); /* Generate 624 more random values */ extern int mts_savestate(FILE* statefile, mt_state* state); /* Save state to a file (ASCII). */ /* ..Returns NZ if succeeded. */ extern int mts_loadstate(FILE* statefile, mt_state* state); /* Load state from a file (ASCII). */ /* ..Returns NZ if succeeded. */ /* * Functions for manipulating the default generator. */ extern void mt_seed32(uint32_t seed); /* Set random seed for default gen. */ extern void mt_seed32new(uint32_t seed); /* Set random seed for default gen. */ extern void mt_seedfull(uint32_t seeds[MT_STATE_SIZE]); /* Set complicated seed for default */ extern uint32_t mt_seed(void); /* Choose seed from random input. */ /* ..Prefers /dev/urandom; uses time */ /* ..if /dev/urandom unavailable. */ /* ..Only gives 32 bits of entropy. */ extern uint32_t mt_goodseed(void); /* Choose seed from more random */ /* ..input than mts_seed. Prefers */ /* ../dev/random; uses time if that */ /* ..is unavailable. Only gives 32 */ /* ..bits of entropy. */ extern void mt_bestseed(void); /* Choose seed from extremely random */ /* ..input (can be *very* slow). */ /* ..Prefers /dev/random and reads */ /* ..the entire state from there. */ /* ..If /dev/random is unavailable, */ /* ..falls back to mt_goodseed(). */ /* ..Not usually worth the cost. */ extern mt_state* mt_getstate(void); /* Get current state of default */ /* ..generator */ extern int mt_savestate(FILE* statefile); /* Save state to a file (ASCII) */ /* ..Returns NZ if succeeded. */ extern int mt_loadstate(FILE* statefile); /* Load state from a file (ASCII) */ /* ..Returns NZ if succeeded. */ #ifdef __cplusplus } #endif /* * Functions for generating random numbers. The actual code of the * functions is given in this file so that it can be declared inline. * For compilers that don't have the inline feature, mtwist.c will * incorporate this file with some clever #defining so that the code * actually gets compiled. In that case, however, "extern" * definitions will be needed here, so we give them. */ #ifdef __cplusplus #endif /* __cplusplus */ extern uint32_t mts_lrand(mt_state* state); /* Generate 32-bit value, any gen. */ #ifdef UINT64_MAX extern uint64_t mts_llrand(mt_state* state); /* Generate 64-bit value, any gen. */ #endif /* UINT64_MAX */ extern double mts_drand(mt_state* state); /* Generate floating value, any gen. */ /* Fast, with only 32-bit precision */ extern double mts_ldrand(mt_state* state); /* Generate floating value, any gen. */ /* Slower, with 64-bit precision */ extern uint32_t mt_lrand(void); /* Generate 32-bit random value */ #ifdef UINT64_MAX extern uint64_t mt_llrand(void); /* Generate 64-bit random value */ #endif /* UINT64_MAX */ extern double mt_drand(void); /* Generate floating value */ /* Fast, with only 32-bit precision */ extern double mt_ldrand(void); /* Generate floating value */ /* Slower, with 64-bit precision */ /* * Tempering parameters. These are perhaps the most magic of all the magic * values in the algorithm. The values are again experimentally determined. * The values generated by the recurrence relation (constants above) are not * equidistributed in 623-space. For some reason, the tempering process * produces that effect. Don't ask me why. Read the paper if you can * understand the math. Or just trust these magic numbers. */ #define MT_TEMPERING_MASK_B 0x9d2c5680 #define MT_TEMPERING_MASK_C 0xefc60000 #define MT_TEMPERING_SHIFT_U(y) \ (y >> 11) #define MT_TEMPERING_SHIFT_S(y) \ (y << 7) #define MT_TEMPERING_SHIFT_T(y) \ (y << 15) #define MT_TEMPERING_SHIFT_L(y) \ (y >> 18) /* * Macros to do the tempering. MT_PRE_TEMPER does all but the last step; * it's useful for situations where the final step can be incorporated * into a return statement. MT_FINAL_TEMPER does that final step (not as * an assignment). MT_TEMPER does the entire process. Note that * MT_PRE_TEMPER and MT_TEMPER both modify their arguments. */ #define MT_PRE_TEMPER(value) \ do \ { \ value ^= MT_TEMPERING_SHIFT_U(value); \ value ^= MT_TEMPERING_SHIFT_S(value) & MT_TEMPERING_MASK_B; \ value ^= MT_TEMPERING_SHIFT_T(value) & MT_TEMPERING_MASK_C; \ } \ while (0) #define MT_FINAL_TEMPER(value) \ ((value) ^ MT_TEMPERING_SHIFT_L(value)) #define MT_TEMPER(value) \ do \ { \ value ^= MT_TEMPERING_SHIFT_U(value); \ value ^= MT_TEMPERING_SHIFT_S(value) & MT_TEMPERING_MASK_B; \ value ^= MT_TEMPERING_SHIFT_T(value) & MT_TEMPERING_MASK_C; \ value ^= MT_TEMPERING_SHIFT_L(value); \ } \ while (0) /* * The Mersenne Twist PRNG makes it default state available as an * external variable. This feature is undocumented, but is useful to * use because it allows us to avoid implementing every randistr function * twice. (In fact, the feature was added to enable randistrs.c to be * written. It would be better to write in C++, where I could control * the access to the state.) */ extern mt_state mt_default_state; /* State of the default generator */ extern double mt_32_to_double; /* Multiplier to convert long to dbl */ extern double mt_64_to_double; /* Mult'r to cvt long long to dbl */ #ifdef __cplusplus /* * C++ interface to the Mersenne Twist PRNG. This class simply * provides a more C++-ish way to access the PRNG. Only state-based * functions are provided. All functions are inlined, both for speed * and so that the same implementation code can be used in C and C++. */ class mt_prng { friend class mt_empirical_distribution; public: /* * Constructors and destructors. The default constructor * leaves initialization (seeding) for later unless pickSeed * is true, in which case the seed is chosen based on either * /dev/urandom (if available) or the system time. The other * constructors accept either a 32-bit seed, or a full * 624-integer seed. */ mt_prng( // Default constructor bool pickSeed = false) // True to get seed from /dev/urandom // ..or time { state.stateptr = 0; state.initialized = 0; if (pickSeed) (void)mts_seed(&state); } mt_prng(uint32_t newseed) // Construct with 32-bit seeding { state.stateptr = 0; state.initialized = 0; mts_seed32(&state, newseed); } mt_prng(uint32_t seeds[MT_STATE_SIZE]) // Construct with full seeding { state.stateptr = 0; state.initialized = 0; mts_seedfull(&state, seeds); } ~mt_prng() { } /* * Copy and assignment are best left defaulted. */ /* * PRNG seeding functions. */ void seed32(uint32_t newseed) // Set 32-bit random seed { mts_seed32(&state, newseed); } void seed32new(uint32_t newseed) // Set 32-bit random seed { mts_seed32new(&state, newseed); } void seedfull(uint32_t seeds[MT_STATE_SIZE]) // Set complicated random seed { mts_seedfull(&state, seeds); } uint32_t seed() // Choose seed from random input { return mts_seed(&state); } uint32_t goodseed() // Choose better seed from random input { return mts_goodseed(&state); } void bestseed() // Choose best seed from random input { mts_bestseed(&state); } friend std::ostream& operator<<(std::ostream& stream, const mt_prng& rng); friend std::istream& operator>>(std::istream& stream, mt_prng& rng); /* * PRNG generation functions */ uint32_t lrand() // Generate 32-bit pseudo-random value { return mts_lrand(&state); } #ifdef UINT64_MAX uint64_t llrand() // Generate 64-bit pseudo-random value { return mts_llrand(&state); } #endif /* UINT64_MAX */ double drand() // Generate fast 32-bit floating value { return mts_drand(&state); } double ldrand() // Generate slow 64-bit floating value { return mts_ldrand(&state); } /* * Following Richard J. Wagner's example, we overload the * function-call operator to return a 64-bit floating value. * That allows the common use of the PRNG to be simplified as * in the following example: * * mt_prng ranno(true); * // ... * coinFlip = ranno() >= 0.5 ? heads : tails; */ double operator()() { return mts_drand(&state); } protected: /* * Protected data */ mt_state state; // Current state of the PRNG }; #endif /* __cplusplus */ #endif /* MTWIST_H */
17,513
34.168675
76
h
filebench
filebench-master/cvars/mtwist/randistrs.h
#ifndef RANDISTRS_H #define RANDISTRS_H /* * $Id: randistrs.h,v 1.8 2013-01-05 01:18:52-08 geoff Exp $ * * Header file for C/C++ use of a generalized package that generates * random numbers in various distributions, using the Mersenne-Twist * pseudo-RNG. See mtwist.h and mtwist.c for documentation on the PRNG. * * Author of this header file: Geoff Kuenning, April 7, 2001. * * All of the functions provided by this package have three variants. * The rd_xxx versions use the default state vector provided by the MT * package. The rds_xxx versions use a state vector provided by the * caller. In general, the rds_xxx versions are preferred for serious * applications, since they allow random numbers used for different * purposes to be drawn from independent, uncorrelated streams. * Finally, the C++ interface provides a class "mt_distribution", * derived from mt_prng, with no-prefix ("xxx") versions of each * function. * * The summary below will describe only the rds_xxx functions. The * rd_xxx functions have identical specifications, except that the * "state" argument is omitted. In all cases, the "state" argument * has type mt_state, and must have been initialized either by calling * one of the Mersenne Twist seeding functions, or by being set to all * zeros. * * The "l" version of each function calls the 64-bit version of the * PRNG instead of the 32-bit version. In general, you shouldn't use * those functions unless your application is *very* sensitive to tiny * variations in the probability distribution. This is especially * true of the uniform and empirical distributions. * * Random-distribution functions: * * rds_iuniform(mt_state* state, long lower, long upper) * (Integer) uniform on the half-open interval [lower, upper). * rds_liuniform(mt_state* state, long long lower, long long upper) * (Integer) uniform on the half-open interval [lower, upper). * Don't use unless you need numbers bigger than a long! * rds_uniform(mt_state* state, double lower, double upper) * (Floating) uniform on the half-open interval [lower, upper). * rds_luniform(mt_state* state, double lower, double upper) * (Floating) uniform on the half-open interval [lower, upper). * Higher precision but slower than rds_uniform. * rds_exponential(mt_state* state, double mean) * Exponential with the given mean. * rds_lexponential(mt_state* state, double mean) * Exponential with the given mean. * Higher precision but slower than rds_exponential. * rds_erlang(mt_state* state, int p, double mean) * p-Erlang with the given mean. * rds_lerlang(mt_state* state, int p, double mean) * p-Erlang with the given mean. * Higher precision but slower than rds_erlang. * rds_weibull(mt_state* state, double shape, double scale) * Weibull with the given shape and scale parameters. * rds_lweibull(mt_state* state, double shape, double scale) * Weibull with the given shape and scale parameters. * Higher precision but slower than rds_weibull. * rds_normal(mt_state* state, double mean, double sigma) * Normal with the given mean and standard deviation. * rds_lnormal(mt_state* state, double mean, double sigma) * Normal with the given mean and standard deviation. * Higher precision but slower than rds_normal. * rds_lognormal(mt_state* state, double shape, double scale) * Lognormal with the given shape and scale parameters. * rds_llognormal(mt_state* state, double shape, double scale) * Lognormal with the given shape and scale parameters. * Higher precision but slower than rds_lognormal. * rds_triangular(mt_state* state, double lower, double upper, double mode) * Triangular on the closed interval (lower, upper) with * the given mode. * rds_ltriangular(mt_state* state, double lower, double upper, double mode) * Triangular on the closed interval (lower, upper) with * the given mode. * Higher precision but slower than rds_triangular. * rds_int_empirical(mt_state* state, rd_empirical_control* control) * Unsigned integer (actually a size_t) in the range [0, n) * with empirically determined probabilities. The * "control" argument is the return value from a previous * call to rd_emprical_setup; see documentation on that * function below for more information. * rds_double_empirical(mt_state* state, rd_empirical_control* control) * Double empirically selected from a list of values * given to rd_empirical_setup (q.v.). * rds_continuous_empirical(mt_state* state, rd_empirical_control* control) * Continuous empirical distribution. See rd_empirical_setup. * rd_iuniform(long lower, long upper) * rd_liuniform(long long lower, long long upper) * As above, using the default MT-PRNG. * rd_uniform(double lower, double upper) * rd_luniform(double lower, double upper) * As above, using the default MT-PRNG. * rd_exponential(double mean) * rd_lexponential(double mean) * As above, using the default MT-PRNG. * rd_erlang(int p, double mean) * rd_lerlang(int p, double mean) * As above, using the default MT-PRNG. * rd_weibull(double shape, double scale) * rd_lweibull(double shape, double scale) * As above, using the default MT-PRNG. * rd_normal(double mean, double sigma) * rd_lnormal(double mean, double sigma) * As above, using the default MT-PRNG. * rd_lognormal(double shape, double scale) * rd_llognormal(double shape, double scale) * As above, using the default MT-PRNG. * rd_triangular(double lower, double upper, double mode) * rd_ltriangular(double lower, double upper, double mode) * As above, using the default MT-PRNG. * rd_empirical_setup(int n_probs, double* probs, double* values) * Set up the control table for an empirical * distribution. Once set up, the returned control table * can be used with multiple independent generators, and * can be used with any of the three empirical * distribution functions; usage can even be intermixed. * In all cases, n_probs is the size of the probs array, * which gives relative weights for different empirically * observed values. The weights do not need to sum to 1; * if they do not, they will be normalized. (In the * following descriptions, normalized weights are assumed * for simplicity.) * For calls to int_empirical, the values array is * ignored. In this case, the return value is in the * range [0, n), where 0 is returned with probability * probs[0], 1 with probability probs[1], etc. * For calls to double_empirical, the value * calculated by int_empirical is used as an index into * the values array, so that values[0] is returned with * probability probs[0], values[1] with probability * probs[1], etc. * For calls to continuous_empirical, the values * array must contain n_probs+1 entries. It is best for * the values array to be sorted into ascending order; * however, this condition is not enforced. The return * value is uniformly distributed between values[0] and * values[1] with probability probs[0], between values[1] * and values[2] with probability probs[1], etc. The * effect will be to generate a piecewise linear * approximation to the empirically observed CDF. * If "values" is NULL, the setup function will * automatically generate an array of uniformly spaced * values in the range [0.0,1.0]. However, if a values * array is provided, n_probs+1 entries must be supplied * EVEN IF only double_empirical will be called. This is * because the setup function will be copying n_probs+1 * values, and there is a (small) possibility of a * segfault if fewer are provided. * rd_empirical_free(rd_empirical_control* control) * Free a structure allocated by rd_empirical_setup. * rd_int_empirical(rd_empirical_control* control) * rd_double_empirical(rd_empirical_control* control) * rd_continuous_empirical(rd_empirical_control* control) * As above, using the default MT-PRNG. * * $Log: randistrs.h,v $ * Revision 1.8 2013-01-05 01:18:52-08 geoff * Fix a lot of compiler warnings. Allow rd_empirical_setup to take * const arguments. * * Revision 1.7 2010-12-10 03:28:19-08 geoff * Support the new empirical_distribution interface. * * Revision 1.6 2010-06-24 20:53:59+12 geoff * Switch to using types from stdint.h. * * Revision 1.5 2008-07-25 16:34:01-07 geoff * Fix notation for intervals in commentary. * * Revision 1.4 2001/06/20 09:07:58 geoff * Fix a place where long long wasn't conditionalized. * * Revision 1.3 2001/06/19 00:41:17 geoff * Add the "l" versions of all functions. * * Revision 1.2 2001/06/18 10:09:24 geoff * Add the iuniform functions. Improve the header comments. Add a C++ * interface. Clean up some stylistic inconsistencies. * * Revision 1.1 2001/04/09 08:39:54 geoff * Initial revision * */ #include "mtwist.h" #ifdef __cplusplus #include <stdexcept> #include <vector> #endif /* * Internal structure used to support O(1) generation of empirical * distributions. */ typedef struct { size_t n; /* Number of probabilities given */ double* cutoff; /* Table of probability cutoffs */ /* ..this is NOT probabilities; see */ /* ..comments in the code */ size_t* remap; /* Table of where to remap to */ double* values; /* Float values to return */ } rd_empirical_control; #ifdef __cplusplus extern "C" { #endif /* * Functions that use a provided state. */ extern int32_t rds_iuniform(mt_state* state, int32_t lower, int32_t upper); /* (Integer) uniform distribution */ #ifdef INT64_MAX extern int64_t rds_liuniform(mt_state* state, int64_t lower, int64_t upper); /* (Integer) uniform distribution */ #endif /* INT64_MAX */ extern double rds_uniform(mt_state* state, double lower, double upper); /* (Floating) uniform distribution */ extern double rds_luniform(mt_state* state, double lower, double upper); /* (Floating) uniform distribution */ extern double rds_exponential(mt_state* state, double mean); /* Exponential distribution */ extern double rds_lexponential(mt_state* state, double mean); /* Exponential distribution */ extern double rds_erlang(mt_state* state, int p, double mean); /* p-Erlang distribution */ extern double rds_lerlang(mt_state* state, int p, double mean); /* p-Erlang distribution */ extern double rds_weibull(mt_state* state, double shape, double scale); /* Weibull distribution */ extern double rds_lweibull(mt_state* state, double shape, double scale); /* Weibull distribution */ extern double rds_normal(mt_state* state, double mean, double sigma); /* Normal distribution */ extern double rds_lnormal(mt_state* state, double mean, double sigma); /* Normal distribution */ extern double rds_lognormal(mt_state* state, double shape, double scale); /* Lognormal distribution */ extern double rds_llognormal(mt_state* state, double shape, double scale); /* Lognormal distribution */ extern double rds_triangular(mt_state* state, double lower, double upper, double mode); /* Triangular distribution */ extern double rds_ltriangular(mt_state* state, double lower, double upper, double mode); /* Triangular distribution */ extern size_t rds_int_empirical(mt_state* state, rd_empirical_control* control); /* Discrete integer empirical distr. */ extern double rds_double_empirical(mt_state* state, rd_empirical_control* control); /* Discrete float empirical distr. */ extern double rds_continuous_empirical(mt_state* state, rd_empirical_control* control); /* Continuous empirical distribution */ /* * Functions that use the default state of the PRNG. */ extern int32_t rd_iuniform(int32_t lower, int32_t upper); /* (Integer) uniform distribution */ #ifdef INT64_MAX extern int64_t rd_liuniform(int64_t lower, int64_t upper); /* (Integer) uniform distribution */ #endif /* INT64_MAX */ extern double rd_uniform(double lower, double upper); /* (Floating) uniform distribution */ extern double rd_luniform(double lower, double upper); /* (Floating) uniform distribution */ extern double rd_exponential(double mean); /* Exponential distribution */ extern double rd_lexponential(double mean); /* Exponential distribution */ extern double rd_erlang(int p, double mean); /* p-Erlang distribution */ extern double rd_lerlang(int p, double mean); /* p-Erlang distribution */ extern double rd_weibull(double shape, double scale); /* Weibull distribution */ extern double rd_lweibull(double shape, double scale); /* Weibull distribution */ extern double rd_normal(double mean, double sigma); /* Normal distribution */ extern double rd_lnormal(double mean, double sigma); /* Normal distribution */ extern double rd_lognormal(double shape, double scale); /* Lognormal distribution */ extern double rd_llognormal(double shape, double scale); /* Lognormal distribution */ extern double rd_triangular(double lower, double upper, double mode); /* Triangular distribution */ extern double rd_ltriangular(double lower, double upper, double mode); /* Triangular distribution */ extern rd_empirical_control* rd_empirical_setup(size_t n_probs, const double* probs, const double* values); /* Set up empirical distribution */ extern void rd_empirical_free(rd_empirical_control* control); /* Free empirical control structure */ extern size_t rd_int_empirical(rd_empirical_control* control); /* Discrete integer empirical distr. */ extern double rd_double_empirical(rd_empirical_control* control); /* Discrete float empirical distr. */ extern double rd_continuous_empirical(rd_empirical_control* control); /* Continuous empirical distribution */ #ifdef __cplusplus } #endif #ifdef __cplusplus /* * C++ interface to the random-distribution generators. This class is * little more than a wrapper for the C functions, but it fits a bit * more nicely with the mt_prng class. */ class mt_distribution : public mt_prng { public: /* * Constructors and destructors. All constructors and * destructors are the same as for mt_prng. */ mt_distribution( // Default constructor bool pickSeed = false) // True to get seed from /dev/urandom // ..or time : mt_prng(pickSeed) { } mt_distribution(uint32_t newseed) // Construct with 32-bit seeding : mt_prng(newseed) { } mt_distribution(uint32_t seeds[MT_STATE_SIZE]) // Construct with full seeding : mt_prng(seeds) { } ~mt_distribution() { } /* * Functions for generating distributions. These simply * invoke the C functions above. */ int32_t iuniform(int32_t lower, int32_t upper) /* Uniform distribution */ { return rds_iuniform(&state, lower, upper); } #ifdef INT64_MAX int64_t liuniform(int64_t lower, int64_t upper) /* Uniform distribution */ { return rds_liuniform(&state, lower, upper); } #endif /* INT64_MAX */ double uniform(double lower, double upper) /* Uniform distribution */ { return rds_uniform(&state, lower, upper); } double luniform(double lower, double upper) /* Uniform distribution */ { return rds_luniform(&state, lower, upper); } double exponential(double mean) /* Exponential distribution */ { return rds_exponential(&state, mean); } double lexponential(double mean) /* Exponential distribution */ { return rds_lexponential(&state, mean); } double erlang(int p, double mean) /* p-Erlang distribution */ { return rds_erlang(&state, p, mean); } double lerlang(int p, double mean) /* p-Erlang distribution */ { return rds_lerlang(&state, p, mean); } double weibull(double shape, double scale) /* Weibull distribution */ { return rds_weibull(&state, shape, scale); } double lweibull(double shape, double scale) /* Weibull distribution */ { return rds_lweibull(&state, shape, scale); } double normal(double mean, double sigma) /* Normal distribution */ { return rds_normal(&state, mean, sigma); } double lnormal(double mean, double sigma) /* Normal distribution */ { return rds_lnormal(&state, mean, sigma); } double lognormal(double shape, double scale) /* Lognormal distribution */ { return rds_lognormal(&state, shape, scale); } double llognormal(double shape, double scale) /* Lognormal distribution */ { return rds_llognormal(&state, shape, scale); } double triangular(double lower, double upper, double mode) /* Triangular distribution */ { return rds_triangular(&state, lower, upper, mode); } double ltriangular(double lower, double upper, double mode) /* Triangular distribution */ { return rds_ltriangular(&state, lower, upper, mode); } }; /* * Class for handing empirical distributions. This is necessary * because of the need to allocate and initialize extra parameters. * * BUG/WARNING: this code will only work on compilers where C * malloc/free can be freely intermixed with C++ new/delete. */ class mt_empirical_distribution { public: mt_empirical_distribution(const std::vector<double>& probs, const std::vector<double>& values) : c(NULL) { if (values.size() != probs.size() + 1) throw std::invalid_argument( "values must be one longer than probs"); c = rd_empirical_setup(probs.size(), &probs.front(), &values.front()); } mt_empirical_distribution(const std::vector<double>& probs) : c(rd_empirical_setup(probs.size(), &probs.front(), NULL)) { } ~mt_empirical_distribution() { rd_empirical_free(c); } size_t int_empirical(mt_prng& rng) /* Discrete integer empirical distr. */ { return rds_int_empirical(&rng.state, c); } double double_empirical(mt_prng& rng) /* Discrete double empirical distr. */ { return rds_double_empirical(&rng.state, c); } double continuous_empirical(mt_prng& rng) /* Continuous empirical distribution */ { return rds_continuous_empirical(&rng.state, c); } private: /* * Copying and assignment are not supported. (Implementing * them would either require reconstructing the * original weights, which is ugly, or doing C-style * allocation, which is equally ugly.) */ mt_empirical_distribution( const mt_empirical_distribution& source); mt_empirical_distribution& operator=( const mt_empirical_distribution& rhs); /* * Private Data. */ rd_empirical_control* c; /* C-style control structure */ }; #endif /* __cplusplus */ #endif /* RANDISTRS_H */
19,046
35.984466
76
h
filebench
filebench-master/cvars/mtwist/rdtest.c
#ifndef lint #ifdef __GNUC__ #define ATTRIBUTE(attrs) __attribute__(attrs) #else #define ATTRIBUTE(attrs) #endif static char Rcs_Id[] ATTRIBUTE((used)) = "$Id: rdtest.c,v 1.11 2013-01-05 01:18:52-08 geoff Exp $"; #endif /* * Test the random-distribution library. Usage: * * rdtest seed how_many distribution [params...] * * where: * * seed is the random seed. If seed is zero, the package's * automatic seed generator is used. * how_many * is how many random numbers to generate. * distribution * is the distribution to draw from (see below). * params are the parameters to the distribution (see below). * * Distributions supported: * * iuniform A uniform distribution of integers on the interval [p1, p2). * uniform A uniform distribution on the interval [p1, p2). * exponential Exponential with mean p1, default 1. * erlang p1-Erlang with mean p2. * weibull Weibull with shape parameter p1 and scale parameter p2. * normal Normal with mean p1 and standard deviation p2. * lognormal Lognormal with scale parameter p1 and shape parameter p2. * triangular Triangular on the interval (p1, p2) with mode at p3. * empirical p1 with probability p2, p3 with probability p4, ..., * p(2n+1) with probability p(2n). Actually, the * "probabilities" are * weights, and do not need to sum to 1. * continuous_empirical * p1 to p3 with probability p2, p3 to p5 with * probability p4, ..., p(2n+1) to p(2n+2) with * probability p(2n). Actually, the "probabilities" are * weights, and do not need to sum to 1. * * $Log: rdtest.c,v $ * Revision 1.11 2013-01-05 01:18:52-08 geoff * Fix a lot of compiler warnings. * * Revision 1.10 2012-12-30 16:24:49-08 geoff * Use gcc attributes to suppress warnings on Rcs_Id. * * Revision 1.9 2010-12-10 03:28:19-08 geoff * Support the new empirical_distribution interface. * * Revision 1.8 2008-07-26 11:34:01+12 geoff * Fix notation for intervals in commentary. * * Revision 1.7 2007/10/26 07:21:06 geoff * Fix the usage message to be correct. * * Revision 1.6 2004/03/30 07:29:43 geoff * Document the program better, and allow the random seed to be * controlled for verification testing. * * Revision 1.5 2003/09/11 05:50:53 geoff * Include string.h to get the declaration of strcmp. * * Revision 1.4 2001/06/18 10:09:24 geoff * Get rid of some warning messages. * * Revision 1.3 2001/04/10 09:11:38 geoff * Add a tiny bit of explanatory commentary. When testing the empirical * distribution, expect the parameters to give individual probabilities, * not running sums. In other words, calculate the running sums for the * user before generating the distribution. * * Revision 1.2 2001/04/09 08:47:19 geoff * Add RCS ID keywords. Give a name to a magic number I missed. * */ #include "randistrs.h" #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char * argv[]); static void usage(void); #define SEED_PARAM 1 /* Offset of seed param in argv */ #define COUNT_PARAM 2 /* Offset of count param in argv */ #define DISTR_PARAM 3 /* Offset of distr param in argv */ #define PARAM_OFFSET 4 /* Offset of params in argv */ int main( int argc, /* Argument count */ char * argv[]) /* Argument vector */ { rd_empirical_control* control = NULL; /* Control if empirical distr. */ size_t how_many; /* How many numbers to generate */ size_t i; /* Loop index */ size_t needed_params = 0; /* Number of params needed by distr */ size_t n_params; /* Number of parameters */ size_t n_probs = 0; /* Number of empirical probabilites */ double * params; /* Parameters of distribution */ double * probs = NULL; /* Probabilities for empirical */ double ran_value = 0.0; /* Value generated by PRNG */ uint32_t seed; /* Seed for PRNG */ double * values = NULL; /* Values for empirical */ if (argc <= PARAM_OFFSET) usage(); seed = atoi (argv[SEED_PARAM]); how_many = atoi (argv[COUNT_PARAM]); n_params = argc - PARAM_OFFSET; params = (double *) malloc (sizeof (double) * n_params); if (params == NULL) { (void) fprintf (stderr, "rdtest: can't malloc params\n"); return 1; } for (i = 0; i < n_params; i++) params[i] = atof (argv[i + PARAM_OFFSET]); if (strcmp (argv[DISTR_PARAM], "iuniform") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "uniform") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "exponential") == 0) needed_params = 1; else if (strcmp (argv[DISTR_PARAM], "erlang") == 0) { if (n_params < 2 || params[0] < 1.0) usage(); needed_params = 2; } else if (strcmp (argv[DISTR_PARAM], "weibull") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "normal") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "lognormal") == 0) needed_params = 2; else if (strcmp (argv[DISTR_PARAM], "triangular") == 0) needed_params = 3; else if (strcmp (argv[DISTR_PARAM], "empirical") == 0) { if (n_params % 2 != 0 || n_params < 4) usage(); n_probs = n_params / 2; probs = (double *) malloc (sizeof (double) * n_probs); values = (double *) malloc (sizeof (double) * (n_probs + 1)); if (probs == NULL || values == NULL) { (void) fprintf (stderr, "rdtest: can't malloc probs/values\n"); return 1; } for (i = 0; i < n_probs; i++) { values[i] = params[i * 2]; probs[i] = params[i * 2 + 1]; if (probs[i] < 0) { (void)fprintf(stderr, "rdtest: negative probability given\n"); exit(2); } } values[n_probs] = 0.0; /* Just for cleanliness */ needed_params = n_params; control = rd_empirical_setup(n_probs, probs, values); } else if (strcmp(argv[DISTR_PARAM], "continuous_empirical") == 0) { if (n_params % 2 == 0 || n_params < 5) usage(); n_probs = (n_params - 1) / 2; probs = (double *) malloc (sizeof (double) * n_probs); values = (double *) malloc (sizeof (double) * (n_probs + 1)); if (probs == NULL || values == NULL) { (void) fprintf (stderr, "rdtest: can't malloc probs/values\n"); return 1; } for (i = 0; i < n_probs; i++) { values[i] = params[i * 2]; probs[i] = params[i * 2 + 1]; if (probs[i] < 0) { (void)fprintf(stderr, "rdtest: negative probability given\n"); exit(2); } } values[n_probs] = params[n_probs * 2]; needed_params = n_params; control = rd_empirical_setup(n_probs, probs, values); } else usage(); if (n_params != needed_params) usage(); /* * Pick a seed */ if (seed == 0) mt_goodseed(); else mt_seed32(seed); for (i = 0; i < how_many; i++) { if (strcmp (argv[DISTR_PARAM], "iuniform") == 0) ran_value = rd_iuniform ((int32_t)params[0], (int32_t)params[1]); else if (strcmp (argv[DISTR_PARAM], "uniform") == 0) ran_value = rd_uniform (params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "exponential") == 0) ran_value = rd_exponential (params[0]); else if (strcmp (argv[DISTR_PARAM], "erlang") == 0) ran_value = rd_erlang ((int) params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "weibull") == 0) ran_value = rd_weibull (params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "normal") == 0) ran_value = rd_normal (params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "lognormal") == 0) ran_value = rd_lognormal (params[0], params[1]); else if (strcmp (argv[DISTR_PARAM], "triangular") == 0) ran_value = rd_triangular (params[0], params[1], params[2]); else if (strcmp (argv[DISTR_PARAM], "empirical") == 0) ran_value = rd_double_empirical (control); else if (strcmp (argv[DISTR_PARAM], "continuous_empirical") == 0) ran_value = rd_continuous_empirical (control); (void) printf ("%f\n", ran_value); } return 0; } static void usage(void) { (void) fprintf (stderr, "Usage: rdtest seed count distribution p0 ...\n"); (void) fprintf (stderr, "Distributions:\n"); (void) fprintf (stderr, "\tiuniform lower upper\n"); (void) fprintf (stderr, "\tuniform lower upper\n"); (void) fprintf (stderr, "\texponential mean\n"); (void) fprintf (stderr, "\terlang p mean\n"); (void) fprintf (stderr, "\tweibull shape scale\n"); (void) fprintf (stderr, "\tnormal mean sigma\n"); (void) fprintf (stderr, "\tlognormal shape scale\n"); (void) fprintf (stderr, "\ttriangular lower upper mode\n"); (void) fprintf (stderr, "\tempirical v0 p0 v1 p1 ... vn-1 pn-1\n"); (void) fprintf (stderr, "\tcontinuous_empirical v0 p0 v1 p1 ... vn-1 pn-1 vn\n"); exit(2); }
8,709
32.371648
78
c
filebench
filebench-master/cvars/test/sanity.c
/* * sanity.c * * Sanity checker for custom libraries. * * Author: Santhosh Kumar Koundinya ([email protected]) */ #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> #include <stdint.h> #include <fb_cvar.h> char *pgmname; void print_usage() { printf("Usage: %s <library name> <parameter string> " "<count>\n", pgmname); printf("Example: %s librand-triangular.so.1 " "'lower:1024;upper:4096;mode:4096'" " 10\n", pgmname); return; } int main(int argc, char *argv[]) { void *cvar_lib; void *cvar_handle; char *libname; char *parameters; int count; int ret; cvar_operations_t cvar_op; double d; /* Set the global program name. */ pgmname = argv[0]; if (argc < 4) { printf("Insufficient parameters.\n"); print_usage(); ret = -1; goto exit; } /* Load the library. */ libname = argv[1]; cvar_lib = dlopen(libname, RTLD_NOW | RTLD_GLOBAL); if (!cvar_lib) { printf("Unable to load library: %s.\n", dlerror()); ret = -2; goto exit; } /* Initialize the function pointers. */ cvar_op.cvar_module_init = dlsym(cvar_lib, FB_CVAR_MODULE_INIT); cvar_op.cvar_alloc_handle = dlsym(cvar_lib, FB_CVAR_ALLOC_HANDLE); if (!cvar_op.cvar_alloc_handle) { printf("Unable to find " FB_CVAR_ALLOC_HANDLE ": %s.\n", dlerror()); ret = -3; goto dlclose; } cvar_op.cvar_revalidate_handle = dlsym(cvar_lib, FB_CVAR_REVALIDATE_HANDLE); if (!cvar_op.cvar_revalidate_handle) { printf("Unable to find " FB_CVAR_ALLOC_HANDLE ": %s.\n", dlerror()); ret = -4; goto dlclose; } cvar_op.cvar_next_value = dlsym(cvar_lib, FB_CVAR_NEXT_VALUE); if (!cvar_op.cvar_next_value) { printf("Unable to find " FB_CVAR_NEXT_VALUE ": %s.\n", dlerror()); ret = -5; goto dlclose; } cvar_op.cvar_free_handle = dlsym(cvar_lib, FB_CVAR_FREE_HANDLE); if (!cvar_op.cvar_free_handle) { printf("Unable to find " FB_CVAR_FREE_HANDLE ": %s.\n", dlerror()); ret = -6; goto dlclose; } cvar_op.cvar_module_exit = dlsym(cvar_lib, FB_CVAR_MODULE_EXIT); cvar_op.cvar_usage = dlsym(cvar_lib, FB_CVAR_USAGE); cvar_op.cvar_version = dlsym(cvar_lib, FB_CVAR_VERSION); if (cvar_op.cvar_module_init) { ret = cvar_op.cvar_module_init(); if (ret) { printf("Custom variable module initialization failed.\n"); goto dlclose; } } if (cvar_op.cvar_version) printf("Variable: %s (%s)\n", libname, cvar_op.cvar_version()); else printf("Variable: %s\n", libname); if (cvar_op.cvar_usage) printf("%s\n", cvar_op.cvar_usage()); /* Allocate a new custom variable handle */ parameters = argv[2]; cvar_handle = cvar_op.cvar_alloc_handle(parameters, malloc, free); if (!cvar_handle) { printf("Custom variable handle allocation failed.\n"); ret = -7; goto cvar_free; } /* Try revalidating the handle. */ ret = cvar_op.cvar_revalidate_handle(cvar_handle); if (ret) { printf("Custom variable handle revalidation failed.\n"); ret = -10; goto cvar_free; } count = atoi(argv[3]); if (count > 0) { while (count > 1) { ret = cvar_op.cvar_next_value(cvar_handle, &d); if (ret) { printf("Unable to get the next value. Error %d.\n" ,ret); ret = -11; goto cvar_free; } printf("%lf,", d); count--; } ret = cvar_op.cvar_next_value(cvar_handle, &d); if (ret) { printf("Unable to get the next value. Error %d.\n" ,ret); ret = -11; goto cvar_free; } printf("%lf.\n", d); } ret = 0; printf("\nAll done.\n"); cvar_free: cvar_op.cvar_free_handle(cvar_handle, free); if (cvar_op.cvar_module_exit) cvar_op.cvar_module_exit(); dlclose: dlclose(cvar_lib); exit: return ret; }
3,594
21.055215
77
c
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/dependencies/nanoflann/KDTreeVectorOfVectorsAdaptor.h
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2011-16 Jose Luis Blanco ([email protected]). * 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 THE AUTHOR ``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 AUTHOR 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 "nanoflann.hpp" #include <vector> // ===== This example shows how to use nanoflann with these types of containers: ======= // typedef std::vector<std::vector<double> > my_vector_of_vectors_t; // typedef std::vector<Eigen::VectorXd> my_vector_of_vectors_t; // This requires #include // <Eigen/Dense> // ===================================================================================== /** A simple vector-of-vectors adaptor for nanoflann, without duplicating the storage. * The i'th vector represents a point in the state space. * * \tparam DIM If set to >0, it specifies a compile-time fixed dimensionality for the points in * the data set, allowing more compiler optimizations. * \tparam num_t The type of the point coordinates (typically, double or float). * \tparam Distance The distance metric to use: nanoflann::metric_L1, nanoflann::metric_L2, * nanoflann::metric_L2_Simple, etc. * \tparam IndexType The type for indices in the KD-tree index (typically, size_t of int) */ template <class VectorOfVectorsType, typename num_t = double, int DIM = -1, class Distance = nanoflann::metric_L2, typename IndexType = size_t> struct KDTreeVectorOfVectorsAdaptor { typedef KDTreeVectorOfVectorsAdaptor<VectorOfVectorsType, num_t, DIM, Distance> self_t; typedef typename Distance::template traits<num_t, self_t>::distance_t metric_t; typedef nanoflann::KDTreeSingleIndexAdaptor<metric_t, self_t, DIM, IndexType> index_t; index_t *index; //! The kd-tree index for the user to call its methods as usual with any other //! FLANN index. /// Constructor: takes a const ref to the vector of vectors object with the data points KDTreeVectorOfVectorsAdaptor(const int dimensionality, const VectorOfVectorsType &mat, const int leaf_max_size = 10) : m_data(mat) { // assert(mat.size()!=0 && mat[0].size()!=0); // const size_t dims = mat[0].size(); // if (DIM>0 && static_cast<int>(dims)!=DIM) // throw std::runtime_error("Data set dimensionality does not match the 'DIM' // template // argument"); // size_t dims = dimensionality; index = new index_t(dimensionality, *this /* adaptor */, nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size)); index->buildIndex(); } ~KDTreeVectorOfVectorsAdaptor() { delete index; } const VectorOfVectorsType &m_data; /** Query for the \a num_closest closest points to a given point (entered as * query_point[0:dim-1]). * Note that this is a short-cut method for index->findNeighbors(). * The user can also call index->... methods as desired. * \note nChecks_IGNORED is ignored but kept for compatibility with the original FLANN interface. */ inline void query(const num_t *query_point, const size_t num_closest, IndexType *out_indices, num_t *out_distances_sq, const int nChecks_IGNORED = 10) const { nanoflann::KNNResultSet<num_t, IndexType> resultSet(num_closest); resultSet.init(out_indices, out_distances_sq); index->findNeighbors(resultSet, query_point, nanoflann::SearchParams()); } /** @name Interface expected by KDTreeSingleIndexAdaptor * @{ */ const self_t &derived() const { return *this; } self_t &derived() { return *this; } // Must return the number of data points inline size_t kdtree_get_point_count() const { return m_data.getPointCount(); } // Returns the distance between the vector "p1[0:size-1]" and the data point with index "idx_p2" // stored in the class: inline num_t kdtree_distance(const num_t *p1, const size_t idx_p2, size_t size) const { num_t s = 0; for (size_t i = 0; i < size; i++) { const num_t d = p1[i] - m_data[idx_p2][i]; s += d * d; } return s; } // Returns the dim'th component of the idx'th point in the class: inline num_t kdtree_get_pt(const size_t idx, int dim) const { return m_data[idx][dim]; } // Optional bounding-box computation: return false to default to a standard bbox computation loop. // Return true if the BBOX was already computed by the class and returned in "bb" so it can be // avoided to redo it again. // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX & /*bb*/) const { return false; } /** @} */ }; // end of KDTreeVectorOfVectorsAdaptor
6,011
45.604651
100
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/dependencies/schroedinger/schroarith.c
#include <string.h> #define SCHRO_ARITH_DEFINE_INLINE #define TRUE 1 #define FALSE 0 #include "schroarith.h" static const uint16_t lut[256] = { //LUT corresponds to window = 16 @ p0=0.5 & 256 @ p=1.0 0, 2, 5, 8, 11, 15, 20, 24, 29, 35, 41, 47, 53, 60, 67, 74, 82, 89, 97, 106, 114, 123, 132, 141, 150, 160, 170, 180, 190, 201, 211, 222, 233, 244, 256, 267, 279, 291, 303, 315, 327, 340, 353, 366, 379, 392, 405, 419, 433, 447, 461, 475, 489, 504, 518, 533, 548, 563, 578, 593, 609, 624, 640, 656, 672, 688, 705, 721, 738, 754, 771, 788, 805, 822, 840, 857, 875, 892, 910, 928, 946, 964, 983, 1001, 1020, 1038, 1057, 1076, 1095, 1114, 1133, 1153, 1172, 1192, 1211, 1231, 1251, 1271, 1291, 1311, 1332, 1352, 1373, 1393, 1414, 1435, 1456, 1477, 1498, 1520, 1541, 1562, 1584, 1606, 1628, 1649, 1671, 1694, 1716, 1738, 1760, 1783, 1806, 1828, 1851, 1874, 1897, 1920, 1935, 1942, 1949, 1955, 1961, 1968, 1974, 1980, 1985, 1991, 1996, 2001, 2006, 2011, 2016, 2021, 2025, 2029, 2033, 2037, 2040, 2044, 2047, 2050, 2053, 2056, 2058, 2061, 2063, 2065, 2066, 2068, 2069, 2070, 2071, 2072, 2072, 2072, 2072, 2072, 2072, 2071, 2070, 2069, 2068, 2066, 2065, 2063, 2060, 2058, 2055, 2052, 2049, 2045, 2042, 2038, 2033, 2029, 2024, 2019, 2013, 2008, 2002, 1996, 1989, 1982, 1975, 1968, 1960, 1952, 1943, 1934, 1925, 1916, 1906, 1896, 1885, 1874, 1863, 1851, 1839, 1827, 1814, 1800, 1786, 1772, 1757, 1742, 1727, 1710, 1694, 1676, 1659, 1640, 1622, 1602, 1582, 1561, 1540, 1518, 1495, 1471, 1447, 1422, 1396, 1369, 1341, 1312, 1282, 1251, 1219, 1186, 1151, 1114, 1077, 1037, 995, 952, 906, 857, 805, 750, 690, 625, 553, 471, 376, 255 }; /* This is a copy of the above lookup-table, with the elements interleaved in a way that decreases the number of operations during decode. */ static const int16_t lut_interleaved[512] = { 255, 0, 376, -2, 471, -5, 553, -8, 625, -11, 690, -15, 750, -20, 805, -24, 857, -29, 906, -35, 952, -41, 995, -47, 1037, -53, 1077, -60, 1114, -67, 1151, -74, 1186, -82, 1219, -89, 1251, -97, 1282, -106, 1312, -114, 1341, -123, 1369, -132, 1396, -141, 1422, -150, 1447, -160, 1471, -170, 1495, -180, 1518, -190, 1540, -201, 1561, -211, 1582, -222, 1602, -233, 1622, -244, 1640, -256, 1659, -267, 1676, -279, 1694, -291, 1710, -303, 1727, -315, 1742, -327, 1757, -340, 1772, -353, 1786, -366, 1800, -379, 1814, -392, 1827, -405, 1839, -419, 1851, -433, 1863, -447, 1874, -461, 1885, -475, 1896, -489, 1906, -504, 1916, -518, 1925, -533, 1934, -548, 1943, -563, 1952, -578, 1960, -593, 1968, -609, 1975, -624, 1982, -640, 1989, -656, 1996, -672, 2002, -688, 2008, -705, 2013, -721, 2019, -738, 2024, -754, 2029, -771, 2033, -788, 2038, -805, 2042, -822, 2045, -840, 2049, -857, 2052, -875, 2055, -892, 2058, -910, 2060, -928, 2063, -946, 2065, -964, 2066, -983, 2068, -1001, 2069, -1020, 2070, -1038, 2071, -1057, 2072, -1076, 2072, -1095, 2072, -1114, 2072, -1133, 2072, -1153, 2072, -1172, 2071, -1192, 2070, -1211, 2069, -1231, 2068, -1251, 2066, -1271, 2065, -1291, 2063, -1311, 2061, -1332, 2058, -1352, 2056, -1373, 2053, -1393, 2050, -1414, 2047, -1435, 2044, -1456, 2040, -1477, 2037, -1498, 2033, -1520, 2029, -1541, 2025, -1562, 2021, -1584, 2016, -1606, 2011, -1628, 2006, -1649, 2001, -1671, 1996, -1694, 1991, -1716, 1985, -1738, 1980, -1760, 1974, -1783, 1968, -1806, 1961, -1828, 1955, -1851, 1949, -1874, 1942, -1897, 1935, -1920, 1920, -1935, 1897, -1942, 1874, -1949, 1851, -1955, 1828, -1961, 1806, -1968, 1783, -1974, 1760, -1980, 1738, -1985, 1716, -1991, 1694, -1996, 1671, -2001, 1649, -2006, 1628, -2011, 1606, -2016, 1584, -2021, 1562, -2025, 1541, -2029, 1520, -2033, 1498, -2037, 1477, -2040, 1456, -2044, 1435, -2047, 1414, -2050, 1393, -2053, 1373, -2056, 1352, -2058, 1332, -2061, 1311, -2063, 1291, -2065, 1271, -2066, 1251, -2068, 1231, -2069, 1211, -2070, 1192, -2071, 1172, -2072, 1153, -2072, 1133, -2072, 1114, -2072, 1095, -2072, 1076, -2072, 1057, -2071, 1038, -2070, 1020, -2069, 1001, -2068, 983, -2066, 964, -2065, 946, -2063, 928, -2060, 910, -2058, 892, -2055, 875, -2052, 857, -2049, 840, -2045, 822, -2042, 805, -2038, 788, -2033, 771, -2029, 754, -2024, 738, -2019, 721, -2013, 705, -2008, 688, -2002, 672, -1996, 656, -1989, 640, -1982, 624, -1975, 609, -1968, 593, -1960, 578, -1952, 563, -1943, 548, -1934, 533, -1925, 518, -1916, 504, -1906, 489, -1896, 475, -1885, 461, -1874, 447, -1863, 433, -1851, 419, -1839, 405, -1827, 392, -1814, 379, -1800, 366, -1786, 353, -1772, 340, -1757, 327, -1742, 315, -1727, 303, -1710, 291, -1694, 279, -1676, 267, -1659, 256, -1640, 244, -1622, 233, -1602, 222, -1582, 211, -1561, 201, -1540, 190, -1518, 180, -1495, 170, -1471, 160, -1447, 150, -1422, 141, -1396, 132, -1369, 123, -1341, 114, -1312, 106, -1282, 97, -1251, 89, -1219, 82, -1186, 74, -1151, 67, -1114, 60, -1077, 53, -1037, 47, -995, 41, -952, 35, -906, 29, -857, 24, -805, 20, -750, 15, -690, 11, -625, 8, -553, 5, -471, 2, -376, 0, -255 }; void schro_arith_decode_init (SchroArith * arith, SchroRdFn read_fn, void * read_fn_priv) { int size; memset (arith, 0, sizeof (SchroArith)); arith->range[0] = 0; arith->range[1] = 0xffff0000; arith->range_size = arith->range[1] - arith->range[0]; arith->code = 0; arith->cntr = 1; arith->read = read_fn; arith->io_priv = read_fn_priv; arith->code = arith->read(arith->io_priv) << 24; arith->code |= arith->read(arith->io_priv) << 16; memcpy (arith->lut, (void *) lut_interleaved, 512 * sizeof (int16_t)); } void schro_arith_encode_init (SchroArith * arith, SchroWrFn write_fn, void * write_fn_priv) { int i; memset (arith, 0, sizeof (SchroArith)); arith->range[0] = 0; arith->range[1] = 0xffff; arith->range_size = arith->range[1] - arith->range[0]; arith->code = 0; arith->first_byte = 1; arith->write = write_fn; arith->io_priv = write_fn_priv; for (i = 0; i < 256; i++) { arith->lut[i] = lut[i]; arith->lut[511 - i] = lut[255 - i]; } } void schro_arith_decode_flush (SchroArith * arith) { // perform an extra renormalisation to match encoding while (arith->range[1] <= 0x40000000) { if (!--arith->cntr) { arith->read(arith->io_priv); arith->cntr = 8; } arith->range[1] <<= 1; } } void schro_arith_flush (SchroArith * arith) { int extra_byte; int i; if (arith->cntr > 0) { extra_byte = TRUE; } else { extra_byte = FALSE; } for (i = 0; i < 16; i++) { if ((arith->range[0] | ((1 << (i + 1)) - 1)) > arith->range[1] - 1) break; } arith->range[0] |= ((1 << i) - 1); //arith->range[0] += arith->range[1] - 1; while (arith->cntr < 8) { arith->range[0] <<= 1; arith->range[0] |= 1; arith->cntr++; } if (arith->range[0] >= (1 << 24)) { arith->output_byte++; if (!arith->first_byte) arith->write(arith->output_byte, arith->io_priv); while (arith->carry) { arith->write(0x00, arith->io_priv); arith->carry--; } } else { if (!arith->first_byte) arith->write(arith->output_byte, arith->io_priv); while (arith->carry) { arith->write(0xff, arith->io_priv); arith->carry--; } } arith->write(arith->range[0] >> 16, arith->io_priv); arith->write(arith->range[0] >> 8, arith->io_priv); if (extra_byte) arith->write(arith->range[0], arith->io_priv); } /* wrappers */ void schro_arith_encode_bit (SchroArith * arith, uint16_t *probability, int value) { _schro_arith_encode_bit (arith, probability, value); } int schro_arith_decode_bit (SchroArith * arith, uint16_t *probability) { return _schro_arith_decode_bit (arith, probability); }
8,374
34.944206
86
c
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/dependencies/schroedinger/schroarith.h
#ifndef _SCHRO_ARITH_H_ #define _SCHRO_ARITH_H_ #define SCHRO_INTERNAL #include <stdint.h> #if __cplusplus extern "C" { #endif typedef uint8_t (*SchroRdFn)(void *); typedef void (*SchroWrFn)(uint8_t byte, void *); typedef struct _SchroArith SchroArith; struct _SchroArith { SchroRdFn read; SchroWrFn write; void * io_priv; uint32_t range[2]; uint32_t code; uint32_t range_size; int cntr; int carry; uint8_t first_byte; uint8_t output_byte; uint16_t lut[512]; }; void schro_arith_decode_init (SchroArith *arith, SchroRdFn read_fn, void * priv); void schro_arith_encode_init (SchroArith *arith, SchroWrFn write_fn, void * priv); void schro_arith_flush (SchroArith *arith); void schro_arith_decode_flush (SchroArith *arith); void schro_arith_encode_bit (SchroArith *arith, uint16_t *probability, int value); int schro_arith_decode_bit (SchroArith *arith, uint16_t *probability); #ifdef SCHRO_ARITH_DEFINE_INLINE static inline int _schro_arith_decode_bit (SchroArith *arith, uint16_t *probability) { unsigned int range_x_prob; unsigned int value; unsigned int lut_index; register unsigned int range = arith->range[1]; register unsigned int code_minus_low = arith->code; while (range <= 0x40000000) { if (!--arith->cntr) { code_minus_low |= arith->read(arith->io_priv) << 8; arith->cntr = 8; } range <<= 1; code_minus_low <<= 1; } range_x_prob = ((range >> 16) * (*probability)) & 0xFFFF0000; lut_index = (*probability)>>7 & ~1; value = (code_minus_low >= range_x_prob); (*probability) += arith->lut[lut_index | value]; if (value) { code_minus_low -= range_x_prob; range -= range_x_prob; } else { range = range_x_prob; } arith->range[1] = range; arith->code = code_minus_low; return value; } static inline void _schro_arith_encode_bit (SchroArith *arith, uint16_t *probability, int value) { unsigned int range; unsigned int probability0; unsigned int range_x_prob; probability0 = (*probability); range = arith->range[1]; range_x_prob = (range * probability0) >> 16; if (value) { arith->range[0] = arith->range[0] + range_x_prob; arith->range[1] -= range_x_prob; (*probability) -= arith->lut[(*probability)>>8]; } else { arith->range[1] = range_x_prob; (*probability) += arith->lut[255-((*probability)>>8)]; } while (arith->range[1] <= 0x4000) { arith->range[0] <<= 1; arith->range[1] <<= 1; arith->cntr++; if (arith->cntr == 8) { if (arith->range[0] < (1<<24) && (arith->range[0] + arith->range[1]) >= (1<<24)) { // NB: carry cannot occur on the first byte since: // - requires initial low=ff80, range=8000 for seq of False // - requires initial low=8000, range=8000 for seq of True // - requires initial low=0001, range=ffff for seq of True arith->carry++; } else { if (arith->range[0] >= (1<<24)) { // NB: output_byte is always valid here since: // - given the initial value of low = 0, range = ffff // - the largest value of low after the first bit=1 is ff00 (p=ff01) // - coding subsequent symbols cannot cause low > 7fff00 // => minimum initial value of low that can trigger this = 2 // (this is not a valid initial condition) // - with range = 8000 (the maximum renormalised range) // - minimum initial value of low to trigger = 8080 arith->output_byte++; while (arith->carry) { arith->write(arith->output_byte, arith->io_priv); arith->output_byte = 0x00; arith->carry--; } } else { while (arith->carry) { arith->write(arith->output_byte, arith->io_priv); arith->output_byte = 0xff; arith->carry--; } } if (!arith->first_byte) arith->write(arith->output_byte, arith->io_priv); else arith->first_byte = 0; arith->output_byte = arith->range[0] >> 16; } arith->range[0] &= 0xffff; arith->cntr = 0; } } } static inline int maxbit (unsigned int x) { #if 0 int i; for(i=0;x;i++){ x >>= 1; } return i; #else int i = 0; if (x == 0) return 0; if (x > 0x00ff) { i += 8; x >>= 8; } if (x > 0x000f) { i += 4; x >>= 4; } if (x > 0x0003) { i += 2; x >>= 2; } if (x > 0x0001) { i += 1; x >>= 1; } if (x > 0x0000) { i += 1; } return i; #endif } #else /* SCHRO_ARITH_DEFINE_INLINE */ int _schro_arith_decode_bit (SchroArith *arith, uint16_t *probability); void _schro_arith_encode_bit (SchroArith *arith, uint16_t *probability, int value) SCHRO_INTERNAL; #endif /* SCHRO_ARITH_DEFINE_INLINE */ #if __cplusplus } // extern "C" #endif #endif
4,857
23.169154
83
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/Attribute.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2019, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <memory> #include "hls.h" #include "PayloadBuffer.h" #include "PCCPointSet.h" #include "entropy.h" namespace pcc { //============================================================================ class AttributeContexts; //============================================================================ class AttributeDecoderIntf { public: virtual ~AttributeDecoderIntf(); virtual void decode( const SequenceParameterSet& sps, const AttributeDescription& desc, const AttributeParameterSet& aps, const AttributeBrickHeader& abh, int geom_num_points_minus1, int minGeomNodeSizeLog2, const char* payload, size_t payloadLen, AttributeContexts& ctxtMem, PCCPointSet3& pointCloud) = 0; // Indicates if the attribute decoder can decode the given aps virtual bool isReusable( const AttributeParameterSet& aps, const AttributeBrickHeader& abh) const = 0; }; //---------------------------------------------------------------------------- std::unique_ptr<AttributeDecoderIntf> makeAttributeDecoder(); //============================================================================ class AttributeEncoderIntf { public: virtual ~AttributeEncoderIntf(); virtual void encode( const SequenceParameterSet& sps, const AttributeDescription& desc, const AttributeParameterSet& attr_aps, AttributeBrickHeader& abh, AttributeContexts& ctxtMem, PCCPointSet3& pointCloud, PayloadBuffer* payload) = 0; // Indicates if the attribute decoder can decode the given aps virtual bool isReusable( const AttributeParameterSet& aps, const AttributeBrickHeader& abh) const = 0; }; //---------------------------------------------------------------------------- std::unique_ptr<AttributeEncoderIntf> makeAttributeEncoder(); //============================================================================ int estimateDist2( const PCCPointSet3& cloud, int samplingPeriod, int searchRange, float percentileEstimate); //============================================================================ } // namespace pcc
3,945
33.313043
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/AttributeCommon.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2019, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <stdint.h> #include <vector> #include "entropy.h" #include "hls.h" #include "PCCTMC3Common.h" namespace pcc { //============================================================================ class AttributeContexts { public: void reset(); protected: AdaptiveBitModel ctxRunLen[5]; AdaptiveBitModel ctxCoeffGtN[2][7]; AdaptiveBitModel ctxCoeffRemPrefix[2][3]; AdaptiveBitModel ctxCoeffRemSuffix[2][3]; }; //---------------------------------------------------------------------------- inline void AttributeContexts::reset() { this->~AttributeContexts(); new (this) AttributeContexts; } //============================================================================ struct AttributeLods { // Indicates if the generated LoDs are compatible with the provided aps bool isReusable( const AttributeParameterSet& aps, const AttributeBrickHeader& abh) const; bool empty() const { return numPointsInLod.empty(); }; void generate( const AttributeParameterSet& aps, const AttributeBrickHeader& abh, int geom_num_points_minus1, int minGeomNodeSizeLog2, const PCCPointSet3& cloud); std::vector<PCCPredictor> predictors; std::vector<uint32_t> numPointsInLod; std::vector<uint32_t> indexes; private: // This is the aps that was used to generate the LoDs. It is used to check // if the generated LoDs are reusable. AttributeParameterSet _aps; // This is the abh that was used to generate the LoDs. It is used to check // if the generated LoDs are reusable. AttributeBrickHeader _abh; }; //============================================================================ bool predModeEligibleColor( const AttributeDescription& desc, const AttributeParameterSet& aps, const PCCPointSet3& pointCloud, const std::vector<uint32_t>& indexes, const PCCPredictor& predictor); bool predModeEligibleRefl( const AttributeDescription& desc, const AttributeParameterSet& aps, const PCCPointSet3& pointCloud, const std::vector<uint32_t>& indexes, const PCCPredictor& predictor); //============================================================================ } // namespace pcc
3,993
32.847458
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/AttributeDecoder.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <stdint.h> #include "Attribute.h" #include "AttributeCommon.h" #include "PayloadBuffer.h" #include "PCCTMC3Common.h" #include "quantization.h" namespace pcc { //============================================================================ // Opaque definitions (Internal detail) class PCCResidualsDecoder; //============================================================================ class AttributeDecoder : public AttributeDecoderIntf { public: void decode( const SequenceParameterSet& sps, const AttributeDescription& desc, const AttributeParameterSet& aps, const AttributeBrickHeader& abh, int geom_num_points_minus1, int minGeomNodeSizeLog2, const char* payload, size_t payloadLen, AttributeContexts& ctxtMem, PCCPointSet3& pointCloud) override; bool isReusable( const AttributeParameterSet& aps, const AttributeBrickHeader& abh) const override; protected: // todo(df): consider alternative encapsulation void decodeReflectancesLift( const AttributeDescription& desc, const AttributeParameterSet& aps, const AttributeBrickHeader& abh, const QpSet& qpSet, int geom_num_points_minus1, int minGeomNodeSizeLog2, PCCResidualsDecoder& decoder, PCCPointSet3& pointCloud); void decodeColorsLift( const AttributeDescription& desc, const AttributeParameterSet& aps, const AttributeBrickHeader& abh, const QpSet& qpSet, int geom_num_points_minus1, int minGeomNodeSizeLog2, PCCResidualsDecoder& decoder, PCCPointSet3& pointCloud); void decodeReflectancesPred( const AttributeDescription& desc, const AttributeParameterSet& aps, const AttributeBrickHeader& abh, const QpSet& qpSet, PCCResidualsDecoder& decoder, PCCPointSet3& pointCloud); void decodeColorsPred( const AttributeDescription& desc, const AttributeParameterSet& aps, const AttributeBrickHeader& abh, const QpSet& qpSet, PCCResidualsDecoder& decoder, PCCPointSet3& pointCloud); void decodeReflectancesRaht( const AttributeDescription& desc, const AttributeParameterSet& aps, const QpSet& qpSet, PCCResidualsDecoder& decoder, PCCPointSet3& pointCloud); void decodeColorsRaht( const AttributeDescription& desc, const AttributeParameterSet& aps, const QpSet& qpSet, PCCResidualsDecoder& decoder, PCCPointSet3& pointCloud); static void decodePredModeColor( const AttributeParameterSet& aps, Vec3<int32_t>& coeff, PCCPredictor& predictor); static void decodePredModeRefl( const AttributeParameterSet& aps, int32_t& coeff, PCCPredictor& predictor); private: AttributeLods _lods; }; //============================================================================ } /* namespace pcc */
4,638
31.900709
79
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/AttributeEncoder.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <stdint.h> #include <vector> #include "Attribute.h" #include "AttributeCommon.h" #include "PayloadBuffer.h" #include "PCCTMC3Common.h" #include "hls.h" #include "quantization.h" namespace pcc { //============================================================================ // Opaque definitions (Internal detail) class PCCResidualsEncoder; struct PCCResidualsEntropyEstimator; //============================================================================ class AttributeEncoder : public AttributeEncoderIntf { public: void encode( const SequenceParameterSet& sps, const AttributeDescription& desc, const AttributeParameterSet& attr_aps, AttributeBrickHeader& abh, AttributeContexts& ctxtMem, PCCPointSet3& pointCloud, PayloadBuffer* payload) override; bool isReusable( const AttributeParameterSet& aps, const AttributeBrickHeader& abh) const override; protected: // todo(df): consider alternative encapsulation void encodeReflectancesLift( const AttributeDescription& desc, const AttributeParameterSet& aps, const QpSet& qpSet, PCCPointSet3& pointCloud, PCCResidualsEncoder& encoder); void encodeColorsLift( const AttributeDescription& desc, const AttributeParameterSet& aps, const QpSet& qpSet, PCCPointSet3& pointCloud, PCCResidualsEncoder& encoder); void encodeReflectancesPred( const AttributeDescription& desc, const AttributeParameterSet& aps, const QpSet& qpSet, PCCPointSet3& pointCloud, PCCResidualsEncoder& encoder); void encodeColorsPred( const AttributeDescription& desc, const AttributeParameterSet& aps, const QpSet& qpSet, PCCPointSet3& pointCloud, PCCResidualsEncoder& encoder); void encodeReflectancesTransformRaht( const AttributeDescription& desc, const AttributeParameterSet& aps, const QpSet& qpSet, PCCPointSet3& pointCloud, PCCResidualsEncoder& encoder); void encodeColorsTransformRaht( const AttributeDescription& desc, const AttributeParameterSet& aps, const QpSet& qpSet, PCCPointSet3& pointCloud, PCCResidualsEncoder& encoder); static Vec3<int64_t> computeColorResiduals( const AttributeParameterSet& aps, const Vec3<attr_t> color, const Vec3<attr_t> predictedColor, const Vec3<int8_t> icpCoeff, const Quantizers& quant); static int computeColorDistortions( const AttributeDescription& desc, const Vec3<attr_t> color, const Vec3<attr_t> predictedColor, const Quantizers& quant); static void decidePredModeColor( const AttributeDescription& desc, const AttributeParameterSet& aps, const PCCPointSet3& pointCloud, const std::vector<uint32_t>& indexesLOD, const uint32_t predictorIndex, PCCPredictor& predictor, PCCResidualsEncoder& encoder, PCCResidualsEntropyEstimator& context, const Vec3<int8_t>& icpCoeff, const Quantizers& quant); static void encodePredModeColor( const AttributeParameterSet& aps, int predMode, Vec3<int32_t>& coeff); static int64_t computeReflectanceResidual( const uint64_t reflectance, const uint64_t predictedReflectance, const Quantizer& quant); static void decidePredModeRefl( const AttributeDescription& desc, const AttributeParameterSet& aps, const PCCPointSet3& pointCloud, const std::vector<uint32_t>& indexesLOD, const uint32_t predictorIndex, PCCPredictor& predictor, PCCResidualsEncoder& encoder, PCCResidualsEntropyEstimator& context, const Quantizer& quant); static void encodePredModeRefl( const AttributeParameterSet& aps, int predMode, int32_t& coeff); private: std::vector<int8_t> computeLastComponentPredictionCoeff( const AttributeParameterSet& aps, const std::vector<Vec3<int64_t>>& coeffs); std::vector<Vec3<int8_t>> computeInterComponentPredictionCoeffs( const AttributeParameterSet& aps, const PCCPointSet3& pointCloud); private: // The current attribute slice header AttributeBrickHeader* _abh; AttributeLods _lods; }; //============================================================================ } /* namespace pcc */
6,011
31.852459
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/BitReader.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> #include <cstdlib> namespace pcc { //============================================================================ template<class ForwardIt> class BitReader { public: BitReader(ForwardIt bs, ForwardIt bs_end) : _bs(bs), _bsEnd(bs_end), _bitMask(), _buffer() {} // return the current bytestream read position; ForwardIt pos() { return _bs; } bool read(); uint64_t readUn(int num_bits); int64_t readSn(int num_bits); uint64_t readUe(); int64_t readSe(); float readF(); template<typename T> void read(T* value) { *value = T(read()); } template<typename T> void readUn(int num_bits, T* value) { *value = T(readUn(num_bits)); } template<typename T> void readSn(int num_bits, T* value) { *value = T(readSn(num_bits)); } template<typename T> void readUe(T* value) { *value = T(readUe()); } template<typename T> void readSe(T* value) { *value = T(readSe()); } template<typename T> void readF(T* value) { *value = T(readF()); } void byteAlign(); private: ForwardIt _bs; ForwardIt _bsEnd; int _bitMask; uint8_t _buffer; }; //============================================================================ template<typename T> BitReader<T> makeBitReader(T start, T end) { return BitReader<T>(start, end); } //============================================================================ template<class ForwardIt> bool BitReader<ForwardIt>::read() { if (_bitMask == 0) { if (_bs == _bsEnd) return false; _buffer = *_bs; _bs++; _bitMask = 1 << 7; } bool value = _buffer & _bitMask; _bitMask >>= 1; return value; } //---------------------------------------------------------------------------- template<class ForwardIt> void BitReader<ForwardIt>::byteAlign() { _bitMask = 0; return; } //---------------------------------------------------------------------------- template<class ForwardIt> uint64_t BitReader<ForwardIt>::readUn(int num_bits) { uint64_t value = 0; for (int i = 0; i < num_bits; i++) { value <<= 1; value |= unsigned(read()); } return value; } //---------------------------------------------------------------------------- template<class ForwardIt> int64_t BitReader<ForwardIt>::readSn(int num_bits) { int64_t value = readUn(num_bits); bool sign = read(); return sign ? -value : value; } //---------------------------------------------------------------------------- template<class ForwardIt> uint64_t BitReader<ForwardIt>::readUe() { int len = 0; while (!read()) len++; uint64_t value = (1ull << len) | readUn(len); return value - 1; } //---------------------------------------------------------------------------- template<class ForwardIt> int64_t BitReader<ForwardIt>::readSe() { uint64_t value = readUe(); bool sign = value & 1; value = (value + sign) >> 1; return sign ? value : -value; } //---------------------------------------------------------------------------- template<class ForwardIt> float BitReader<ForwardIt>::readF() { uint32_t bits = uint32_t(readUn(32)); char* data = reinterpret_cast<char*>(&bits); return *reinterpret_cast<float*>(data); } //============================================================================ } // namespace pcc
5,145
22.934884
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/BitWriter.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include "PCCMisc.h" #include <cstdint> #include <cstdlib> namespace pcc { //============================================================================ template<class OutputIt> class BitWriter { public: BitWriter(OutputIt bs) : _bs(bs), _num_bits(), _buffer() {} void write(bool bit); // Write value using a fixed-width (num_bits) literal encoding (big endian). void writeUn(int num_bits, uint64_t value); template<typename T> void writeUn(int num_bits, const T& value) { writeUn(num_bits, uint64_t(value)); } // Write value using a fixed-width (num_bits+sign) literal encoding (big // endian). void writeSn(int num_bits, int64_t value); void writeUe(uint32_t value); // NB: probably best to think twice before using this method void writeUe64(uint64_t value); template<typename T> void writeUe(const T& value) { // Avoid accidental truncation constexpr bool use_writeUe64 = std::is_same<uint64_t, T>::value || std::is_same<int64_t, T>::value; static_assert(!use_writeUe64, "use explicit writeUe64()"); writeUe(uint32_t(value)); } void writeSe(int32_t value); void writeF(float value); void byteAlign(); private: OutputIt _bs; int _num_bits; uint8_t _buffer; }; //============================================================================ class InsertionCounter { public: InsertionCounter(int* counter) : _counter(counter) {} InsertionCounter& operator++(int) { return *this; } InsertionCounter& operator++() { return *this; } InsertionCounter& operator*() { return *this; } template<typename T> InsertionCounter& operator=(const T&) { (*_counter)++; return *this; } private: int* _counter; }; //============================================================================ template<typename T> BitWriter<T> makeBitWriter(T t) { return BitWriter<T>(t); } //---------------------------------------------------------------------------- template<class OutputIt> void BitWriter<OutputIt>::write(bool bit) { _buffer <<= 1; _buffer |= uint8_t(bit); _num_bits++; if (_num_bits == 8) { *_bs++ = static_cast<char>(_buffer); _buffer = 0; _num_bits = 0; } } //---------------------------------------------------------------------------- template<class OutputIt> void BitWriter<OutputIt>::byteAlign() { if (!_num_bits) return; _buffer <<= 8 - _num_bits; *_bs++ = static_cast<char>(_buffer); _buffer = 0; _num_bits = 0; } //---------------------------------------------------------------------------- template<class OutputIt> void BitWriter<OutputIt>::writeUn(int num_bits, uint64_t value) { if (!num_bits) return; for (uint64_t mask = uint64_t(1) << (num_bits - 1); mask; mask >>= 1) { write(!!(value & mask)); } } //---------------------------------------------------------------------------- template<class OutputIt> void BitWriter<OutputIt>::writeSn(int num_bits, int64_t value) { writeUn(num_bits, uint64_t(::llabs(value))); write(value < 0); } //---------------------------------------------------------------------------- template<class OutputIt> void BitWriter<OutputIt>::writeUe(uint32_t value) { value++; int len = ilog2(value); writeUn(len, 0); writeUn(len + 1, value); } //---------------------------------------------------------------------------- template<class OutputIt> void BitWriter<OutputIt>::writeUe64(uint64_t value) { value++; int len = ilog2(value); writeUn(len, 0); writeUn(len + 1, value); } //---------------------------------------------------------------------------- template<class OutputIt> void BitWriter<OutputIt>::writeSe(int32_t value) { bool sign = value > 0; value = uint32_t(::llabs(value)) << 1; writeUe(value - sign); } //---------------------------------------------------------------------------- template<class OutputIt> void BitWriter<OutputIt>::writeF(float value) { char* data = reinterpret_cast<char*>(&value); uint32_t val = *reinterpret_cast<uint32_t*>(data); writeUn(32, val); } //============================================================================ } // namespace pcc
5,981
25.469027
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/DualLutCoder.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cassert> #include <cstdint> #include "entropy.h" namespace pcc { //============================================================================ // A forward and inverse symbol to frequency-sorted index lookup table. // // Maintains mappings for the most @_lutSize frequent symbols from an // @_alphabetSize alphabet. // // Mappings are recomputed using frequency statistics maintained for // each symbol on a periodic basis following symbol insertion according // to an exponential back-off and maximum update period. // template<int _lutSize, int _alphabetSize> class FrequencySortingLut { public: // Implementation detail assumes that: // _alphabetSize * _maxHistogramCount <= UINT32_MAX static_assert(_alphabetSize <= 256, "Symbols must be no more than 8-bit"); // It makes little sense for the LUT to be bigger than the alphabet // xxx static_assert(_lutSize <= _alphabetSize, "LUT is too large"); static const int kMaxUpdatePeriod = 0x33333333; static const int kMaxHistogramCount = 1 << 24; FrequencySortingLut( int maxUpdatePeriod = kMaxUpdatePeriod, int _maxHistogramCount = kMaxHistogramCount, const uint8_t buffer[_lutSize] = nullptr); FrequencySortingLut(const FrequencySortingLut&) = default; FrequencySortingLut(FrequencySortingLut&&) = default; FrequencySortingLut& operator=(const FrequencySortingLut&) = default; FrequencySortingLut& operator=(FrequencySortingLut&&) = default; void init(const uint8_t buffer[_lutSize]); void reset() { _reset = true; } // Update the histogram entry for @symbol and recompute LUT if sufficient // symbols have been processed. void pushSymbol(int symbol); // The sorted index for @symbol int getIndex(int symbol) const { assert(unsigned(symbol) < _alphabetSize); return _toIndex[symbol]; } // The @index -th symbol int getSymbol(int index) const { assert(unsigned(index) < _lutSize); return _toSymbol[index]; } int end() const { return kUndefinedIndex; } private: static const int kInitialUpdatePeriod = 16; static const int kUndefinedIndex = -1; // Re-compute the LUT based on symbol histogram. void update(); // per-symbol occurence counts int _histogram[_alphabetSize]; // mapping of symbol to LUT index // NB: type must allow storage of distinct kUndefinedIndex int8_t _toIndex[_alphabetSize]; // mapping of LUT index to symbol uint8_t _toSymbol[_lutSize]; int _maxHistogramCount; unsigned _maxUpdatePeriod; unsigned _updatePeriod = kInitialUpdatePeriod; unsigned _symbolsUntilUpdate = kInitialUpdatePeriod; bool _reset = false; }; //============================================================================ // A forward and inverse cache of recently used symbols. // // A least recently used eviction policy is used to update the cache. template<int _cacheSize, int _alphabetSize> class FrequentSymbolCache { public: // Implementation detail assumes 8-bit alphabet: static_assert(_alphabetSize <= 256, "Symbols must be no more than 8-bit"); // It makes little sense for the LUT to be bigger than the alphabet static_assert(_cacheSize <= _alphabetSize, "LUT is larger than alphabet?"); FrequentSymbolCache(); FrequentSymbolCache(const FrequentSymbolCache&) = default; FrequentSymbolCache(FrequentSymbolCache&&) = default; FrequentSymbolCache& operator=(const FrequentSymbolCache&) = default; FrequentSymbolCache& operator=(FrequentSymbolCache&&) = default; void pushSymbol(int symbol); int getIndex(int symbol) const { assert(unsigned(symbol) < _alphabetSize); return _toIndex[symbol]; } int getSymbol(int index) const { assert(unsigned(index) < _cacheSize); return _toSymbol[index]; } int end() const { return kUndefinedIndex; } private: static const int kUndefinedIndex = -1; // mapping of symbol to cached index int8_t _toIndex[_alphabetSize]; // mapping of cached index to symbol uint8_t _toSymbol[_cacheSize]; unsigned _last; }; //============================================================================ template<bool _limitedContextMode> class DualLutCoder { static const int kLog2CacheSize = 4; static const int kCacheSize = 1 << kLog2CacheSize; static const int kLog2LutSize = 5; static const int kLutSize = 1 << kLog2LutSize; static const int kNumLutContexts = _limitedContextMode ? 5 : 31; public: DualLutCoder(); DualLutCoder(const uint8_t initTable[kLutSize]); DualLutCoder(const DualLutCoder&) = default; DualLutCoder(DualLutCoder&&) = default; DualLutCoder& operator=(const DualLutCoder&) = default; DualLutCoder& operator=(DualLutCoder&&) = default; void init(const uint8_t initTable[32]); void resetLut(); void encode(int symbol, EntropyEncoder* arithmeticEncoder); int decode(EntropyDecoder* arithmeticDecoder); private: void encodeFrequencySortedLutIndex(int index, EntropyEncoder* entropy); int decodeFrequencySortedLutIndex(EntropyDecoder* entropy); // bool _limitedContextMode; FrequentSymbolCache<kCacheSize, 256> _cache; FrequencySortingLut<kLutSize, 256> _adaptiveLut; AdaptiveBitModelFast _ctxLutHit; AdaptiveBitModelFast _ctxCacheHit; AdaptiveBitModelFast _ctxSymbolBit; AdaptiveBitModelFast _ctxLutIndex[kNumLutContexts]; }; //============================================================================ } // namespace pcc
7,234
31.59009
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/FixedPoint.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2019, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> namespace pcc { //============================================================================ class FixedPoint { public: // Number of fractional bits in fixed point representation static const int kFracBits = 15; static const int kOneHalf = 1 << (kFracBits - 1); // Fixed point value int64_t val; FixedPoint() = default; FixedPoint(const FixedPoint&) = default; FixedPoint(FixedPoint&&) = default; FixedPoint& operator=(const FixedPoint&) = default; FixedPoint& operator=(FixedPoint&&) = default; FixedPoint(int val) { this->operator=(int64_t(val)); } FixedPoint(int64_t val) { this->operator=(val); } FixedPoint(double val) { this->val = int64_t(val * (1 << kFracBits)); } // return the rounded integer value int64_t round(); void operator=(const int64_t val); void operator+=(const FixedPoint& that); void operator-=(const FixedPoint& that); void operator*=(const FixedPoint& that); void operator/=(const FixedPoint& that); }; //============================================================================ inline int64_t FixedPoint::round() { if (this->val > 0) return (kOneHalf + this->val) >> kFracBits; return -((kOneHalf - this->val) >> kFracBits); } //---------------------------------------------------------------------------- inline void FixedPoint::operator=(int64_t val) { if (val > 0) this->val = val << kFracBits; else this->val = -((-val) << kFracBits); } //---------------------------------------------------------------------------- inline void FixedPoint::operator+=(const FixedPoint& that) { this->val += that.val; } //---------------------------------------------------------------------------- inline void FixedPoint::operator-=(const FixedPoint& that) { this->val -= that.val; } //---------------------------------------------------------------------------- inline void FixedPoint::operator*=(const FixedPoint& that) { this->val *= that.val; if (this->val < 0) this->val = -((kOneHalf - this->val) >> kFracBits); else this->val = +((kOneHalf + this->val) >> kFracBits); } //============================================================================ } // namespace pcc
4,047
30.874016
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/OctreeNeighMap.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include "PCCMath.h" #include "geometry_octree.h" #include "ringbuf.h" #include "tables.h" #include <cassert> #include <memory> #include <vector> namespace pcc { //============================================================================ // Provides a mapping of (x,y,z) co-ordinate to a bit flag. // // Internal representation uses a morton code to access an array of flags. // // Updates to the array are made byte-wise, allowing 8 flags (in morton order) // to be stored in a single operation. class MortonMap3D { public: void resize(bool childOccupancyEnabled, const uint32_t cubeSizeLog2) { assert(cubeSizeLog2 < 10); const uint32_t halfCubeSizeLog2 = cubeSizeLog2 ? cubeSizeLog2 - 1 : 0; _cubeSizeLog2 = cubeSizeLog2; _cubeSize = 1 << cubeSizeLog2; _bufferSizeInBytes = 1 << (3 * cubeSizeLog2); _buffer.reset(new uint8_t[_bufferSizeInBytes]); if (childOccupancyEnabled) _childOccupancy.reset(new uint8_t[_bufferSizeInBytes << 3]); _updates.reserve(1 << 16); } int cubeSize() const { return _cubeSize; } int cubeSizeLog2() const { return _cubeSizeLog2; } // Removes all updates, zeros all map entries. Does not affect child map. void clear(); // Reverts all updates, zeroing affected map entries. // Only modified bytes are touched. void clearUpdates(); void setByte( const int32_t x, const int32_t y, const int32_t z, const uint8_t value) { assert( x >= 0 && y >= 0 && z >= 0 && x < _cubeSize && y < _cubeSize && z < _cubeSize); if (value) { const uint32_t byteIndex = getByteIndex(x, y, z); _buffer[byteIndex] = value; _updates.push_back(byteIndex); } } uint32_t get( const int32_t x, const int32_t y, const int32_t z, const int shiftX, const int shiftY, const int shiftZ) const { assert( x >= 0 && y >= 0 && z >= 0 && x < _cubeSize && y < _cubeSize && z < _cubeSize); return (_buffer[getByteIndex(x >> shiftX, y >> shiftY, z >> shiftZ)] >> getBitIndex(shiftX ? x : 0, shiftY ? y : 0, shiftZ ? z : 0)) & 1; } uint32_t getWithCheck( const int32_t x, const int32_t y, const int32_t z, const int shiftX, const int shiftY, const int shiftZ) const { if ( x < 0 || x >= _cubeSize || y < 0 || y >= _cubeSize || z < 0 || z >= _cubeSize) { return false; } return get(x, y, z, shiftX, shiftY, shiftZ); } uint32_t get(const int32_t x, const int32_t y, const int32_t z) const { assert( x >= 0 && y >= 0 && z >= 0 && x < _cubeSize && y < _cubeSize && z < _cubeSize); return get(x, y, z, 1, 1, 1); } uint32_t getWithCheck(const int32_t x, const int32_t y, const int32_t z) const { if ( x < 0 || x >= _cubeSize || y < 0 || y >= _cubeSize || z < 0 || z >= _cubeSize) { return false; } return getWithCheck(x, y, z, 1, 1, 1); } void setChildOcc(int32_t x, int32_t y, int32_t z, uint8_t childOccupancy) { _childOccupancy[getByteIndex(x, y, z)] = childOccupancy; } uint8_t getChildOcc(int32_t x, int32_t y, int32_t z) const { uint8_t childOccupancy = _childOccupancy[getByteIndex(x, y, z)]; return childOccupancy; } private: int32_t getBitIndex(const int32_t x, const int32_t y, const int32_t z) const { return (z & 1) + ((y & 1) << 1) + ((x & 1) << 2); } uint32_t getByteIndex(const int32_t x, const int32_t y, const int32_t z) const { return kMortonCode256X[x] | kMortonCode256Y[y] | kMortonCode256Z[z]; } int _cubeSize = 0; int _cubeSizeLog2 = 0; uint32_t _bufferSizeInBytes = 0; std::unique_ptr<uint8_t[]> _buffer; // A list of indexes in _buffer that are dirty std::vector<uint32_t> _updates; // Child occupancy values std::unique_ptr<uint8_t[]> _childOccupancy; }; //============================================================================ struct GeometryNeighPattern { // Mask indicating presence of neigbours of the corresponding tree node // 32 8 (y) // |/ // 2--n--1 (x) // /| // 4 16 (z) uint8_t neighPattern; // mask indicating the number of external child neighbours uint8_t adjacencyGt0; uint8_t adjacencyGt1; // mask indicating unoccupied external child neighbours uint8_t adjacencyUnocc; // occupancy map of {x-1, y-1, z-1} neighbours. uint8_t adjNeighOcc[3]; }; //============================================================================ // determine the occupancy pattern of the six neighbours of the node at // @position. If @adjacent_child_contextualization_enabled_flag is true, // the occupancy state of previously coded neighbours is used to refine // the neighbour pattern and derive external adjacency counts for each child. GeometryNeighPattern makeGeometryNeighPattern( bool adjacent_child_contextualization_enabled_flag, const Vec3<int32_t>& currentPosition, int codedAxesPrevLvl, int codedAxesCurLvl, const MortonMap3D& occupancyAtlas); // populate (if necessary) the occupancy atlas with occupancy information // from @fifo. void updateGeometryOccupancyAtlas( const Vec3<int32_t>& position, const int atlasShift, const ringbuf<PCCOctree3Node>& fifo, const ringbuf<PCCOctree3Node>::iterator& fifoCurrLvlEnd, MortonMap3D* occupancyAtlas, Vec3<int32_t>* atlasOrigin); void updateGeometryOccupancyAtlasOccChild( const Vec3<int32_t>& pos, uint8_t childOccupancy, MortonMap3D* occupancyAtlas); } // namespace pcc
7,339
30.502146
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/PCCMath.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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 PCCMath_h #define PCCMath_h #include <assert.h> #include <cstddef> #include <iostream> #include <limits> #include <math.h> #include <string.h> #include <type_traits> #include "PCCMisc.h" #include "tables.h" #include <algorithm> namespace pcc { /// Vector dim 3 template<typename T> class Vec3 { public: T* begin() { return &data[0]; } const T* begin() const { return &data[0]; } T* end() { return &data[3]; } const T* end() const { return &data[3]; } T& operator[](size_t i) { assert(i < 3); return data[i]; } const T& operator[](size_t i) const { assert(i < 3); return data[i]; } size_t getElementCount() const { return 3; } T& x() { return data[0]; } T& y() { return data[1]; } T& z() { return data[2]; } const T& x() const { return data[0]; } const T& y() const { return data[1]; } const T& z() const { return data[2]; } T& s() { return data[0]; } T& t() { return data[1]; } T& v() { return data[2]; } const T& s() const { return data[0]; } const T& t() const { return data[1]; } const T& v() const { return data[2]; } template<typename ResultT> ResultT getNorm2() const { return Vec3<ResultT>(*this) * Vec3<ResultT>(*this); } T getNorm1() const { return std::abs(data[0]) + std::abs(data[1]) + std::abs(data[2]); } T getNormInf() const { return std::max(data[2], std::max(abs(data[0]), abs(data[1]))); } // The minimum element T min() const { return std::min({data[0], data[1], data[2]}); } // The maximum element T max() const { return std::max({data[0], data[1], data[2]}); } // Applies std::abs to each element Vec3 abs() const { return {std::abs(data[0]), std::abs(data[1]), std::abs(data[2])}; } Vec3& operator=(const Vec3& rhs) { memcpy(data, rhs.data, sizeof(data)); return *this; } template<typename U> Vec3& operator+=(const typename pcc::Vec3<U>& rhs) { data[0] += rhs[0]; data[1] += rhs[1]; data[2] += rhs[2]; return *this; } template<typename U> Vec3& operator-=(const typename pcc::Vec3<U>& rhs) { data[0] -= rhs[0]; data[1] -= rhs[1]; data[2] -= rhs[2]; return *this; } template<typename U> Vec3& operator-=(U a) { data[0] -= a; data[1] -= a; data[2] -= a; return *this; } template<typename U> Vec3& operator+=(U a) { data[0] += a; data[1] += a; data[2] += a; return *this; } Vec3& operator<<=(int val) { data[0] <<= val; data[1] <<= val; data[2] <<= val; return *this; } Vec3& operator<<=(Vec3<int> val) { data[0] <<= val[0]; data[1] <<= val[1]; data[2] <<= val[2]; return *this; } Vec3& operator>>=(int val) { data[0] >>= val; data[1] >>= val; data[2] >>= val; return *this; } Vec3& operator>>=(Vec3<int> val) { data[0] >>= val[0]; data[1] >>= val[1]; data[2] >>= val[2]; return *this; } template<typename U> Vec3& operator/=(U a) { assert(a != 0); data[0] /= a; data[1] /= a; data[2] /= a; return *this; } template<typename U> Vec3& operator*=(U a) { data[0] *= a; data[1] *= a; data[2] *= a; return *this; } template<typename U> Vec3& operator=(const U a) { data[0] = a; data[1] = a; data[2] = a; return *this; } template<typename U> Vec3& operator=(const U* rhs) { data[0] = rhs[0]; data[1] = rhs[1]; data[2] = rhs[2]; return *this; } Vec3 operator-() const { return Vec3<T>(-data[0], -data[1], -data[2]); } template<typename U> friend Vec3<typename std::common_type<T, U>::type> operator+(const Vec3& lhs, const typename pcc::Vec3<U>& rhs) { return Vec3<typename std::common_type<T, U>::type>( lhs[0] + rhs[0], lhs[1] + rhs[1], lhs[2] + rhs[2]); } template<typename U> friend Vec3<typename std::enable_if< std::is_arithmetic<U>::value, typename std::common_type<T, U>::type>::type> operator+(const U lhs, const Vec3& rhs) { return Vec3<typename std::common_type<T, U>::type>( lhs + rhs[0], lhs + rhs[1], lhs + rhs[2]); } template<typename U> friend Vec3<typename std::enable_if< std::is_arithmetic<U>::value, typename std::common_type<T, U>::type>::type> operator+(const Vec3& lhs, const U rhs) { return Vec3<typename std::common_type<T, U>::type>( lhs[0] + rhs, lhs[1] + rhs, lhs[2] + rhs); } template<typename U> friend Vec3<typename std::common_type<T, U>::type> operator-(const Vec3& lhs, const typename pcc::Vec3<U>& rhs) { return Vec3<typename std::common_type<T, U>::type>( lhs[0] - rhs[0], lhs[1] - rhs[1], lhs[2] - rhs[2]); } template<typename U> friend Vec3<typename std::enable_if< std::is_arithmetic<U>::value, typename std::common_type<T, U>::type>::type> operator-(const U lhs, const Vec3& rhs) { return Vec3<typename std::common_type<T, U>::type>( lhs - rhs[0], lhs - rhs[1], lhs - rhs[2]); } template<typename U> friend Vec3<typename std::enable_if< std::is_arithmetic<U>::value, typename std::common_type<T, U>::type>::type> operator-(const Vec3& lhs, const U rhs) { return Vec3<typename std::common_type<T, U>::type>( lhs[0] - rhs, lhs[1] - rhs, lhs[2] - rhs); } template<typename U> friend Vec3<typename std::enable_if< std::is_arithmetic<U>::value, typename std::common_type<T, U>::type>::type> operator*(const U lhs, const Vec3& rhs) { return Vec3<typename std::common_type<T, U>::type>( lhs * rhs[0], lhs * rhs[1], lhs * rhs[2]); } // todo(df): make this elementwise? template<typename U> friend typename std::common_type<T, U>::type operator*(pcc::Vec3<T> lhs, const pcc::Vec3<U>& rhs) { return (lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2]); } template<typename U> friend Vec3<typename std::enable_if< std::is_arithmetic<U>::value, typename std::common_type<T, U>::type>::type> operator*(const Vec3& lhs, const U rhs) { return Vec3<typename std::common_type<T, U>::type>( lhs[0] * rhs, lhs[1] * rhs, lhs[2] * rhs); } template<typename U> friend Vec3<typename std::enable_if< std::is_arithmetic<U>::value, typename std::common_type<T, U>::type>::type> operator/(const Vec3& lhs, const U rhs) { assert(rhs != 0); return Vec3<typename std::common_type<T, U>::type>( lhs[0] / rhs, lhs[1] / rhs, lhs[2] / rhs); } friend Vec3 operator<<(const Vec3& lhs, int val) { return Vec3<T>(lhs[0] << val, lhs[1] << val, lhs[2] << val); } friend Vec3 operator<<(const Vec3& lhs, const Vec3<int>& val) { return Vec3<T>(lhs[0] << val[0], lhs[1] << val[1], lhs[2] << val[2]); } friend Vec3 operator>>(const Vec3& lhs, int val) { return Vec3<T>(lhs[0] >> val, lhs[1] >> val, lhs[2] >> val); } friend Vec3 operator>>(const Vec3& lhs, const Vec3<int>& val) { return Vec3<T>(lhs[0] >> val[0], lhs[1] >> val[1], lhs[2] >> val[2]); } bool operator<(const Vec3& rhs) const { if (data[0] == rhs[0]) { if (data[1] == rhs[1]) { return (data[2] < rhs[2]); } return (data[1] < rhs[1]); } return (data[0] < rhs[0]); } bool operator>(const Vec3& rhs) const { if (data[0] == rhs[0]) { if (data[1] == rhs[1]) { return (data[2] > rhs[2]); } return (data[1] > rhs[1]); } return (data[0] > rhs[0]); } bool operator==(const Vec3& rhs) const { return (data[0] == rhs[0] && data[1] == rhs[1] && data[2] == rhs[2]); } bool operator!=(const Vec3& rhs) const { return (data[0] != rhs[0] || data[1] != rhs[1] || data[2] != rhs[2]); } friend std::ostream& operator<<(std::ostream& os, const Vec3& vec) { os << vec[0] << " " << vec[1] << " " << vec[2]; return os; } friend std::istream& operator>>(std::istream& is, Vec3& vec) { is >> vec[0] >> vec[1] >> vec[2]; return is; } Vec3(const T a) { data[0] = data[1] = data[2] = a; } Vec3(const T x, const T y, const T z) { data[0] = x; data[1] = y; data[2] = z; } Vec3(const Vec3& vec) { data[0] = vec.data[0]; data[1] = vec.data[1]; data[2] = vec.data[2]; } template<typename U> Vec3(const typename pcc::Vec3<U>& vec) { data[0] = vec.data[0]; data[1] = vec.data[1]; data[2] = vec.data[2]; } Vec3() = default; ~Vec3(void) = default; private: T data[3]; template<typename U> friend class pcc::Vec3; }; template<typename T> struct Box3 { Vec3<T> min; Vec3<T> max; Box3() = default; Box3(T min, T max) : min(min), max(max) {} Box3(const Vec3<T>& min, const Vec3<T>& max) : min(min), max(max) {} template<typename ForwardIt> Box3(ForwardIt begin, ForwardIt end) : Box3(std::numeric_limits<T>::max(), std::numeric_limits<T>::lowest()) { for (auto it = begin; it != end; ++it) { auto& pt = *it; for (int k = 0; k < 3; ++k) { if (pt[k] > max[k]) max[k] = pt[k]; if (pt[k] < min[k]) min[k] = pt[k]; } } } bool contains(const Vec3<T> point) const { return !( point.x() < min.x() || point.x() > max.x() || point.y() < min.y() || point.y() > max.y() || point.z() < min.z() || point.z() > max.z()); } Box3 merge(const Box3& box) { min.x() = std::min(min.x(), box.min.x()); min.y() = std::min(min.y(), box.min.y()); min.z() = std::min(min.z(), box.min.z()); max.x() = std::max(max.x(), box.max.x()); max.y() = std::max(max.y(), box.max.y()); max.z() = std::max(max.z(), box.max.z()); return box; } bool intersects(const Box3& box) const { return max.x() >= box.min.x() && min.x() <= box.max.x() && max.y() >= box.min.y() && min.y() <= box.max.y() && max.z() >= box.min.z() && min.z() <= box.max.z(); } template<typename SquaredT> SquaredT getDist2(const Vec3<T>& point) const { using U = SquaredT; U dx = U(std::max(std::max(min[0] - point[0], T()), point[0] - max[0])); U dy = U(std::max(std::max(min[1] - point[1], T()), point[1] - max[1])); U dz = U(std::max(std::max(min[2] - point[2], T()), point[2] - max[2])); return dx * dx + dy * dy + dz * dz; } T getDist1(const Vec3<T>& point) const { T dx = T(std::max(std::max(min[0] - point[0], T()), point[0] - max[0])); T dy = T(std::max(std::max(min[1] - point[1], T()), point[1] - max[1])); T dz = T(std::max(std::max(min[2] - point[2], T()), point[2] - max[2])); return dx + dy + dz; } void insert(const Vec3<T>& point) { min.x() = std::min(min.x(), point.x()); min.y() = std::min(min.y(), point.y()); min.z() = std::min(min.z(), point.z()); max.x() = std::max(max.x(), point.x()); max.y() = std::max(max.y(), point.y()); max.z() = std::max(max.z(), point.z()); } friend std::ostream& operator<<(std::ostream& os, const Box3& box) { os << box.min[0] << " " << box.min[1] << " " << box.min[2] << " " << box.max[0] << " " << box.max[1] << " " << box.max[2]; return os; } friend std::istream& operator>>(std::istream& is, Box3& box) { is >> box.min[0] >> box.min[1] >> box.min[2] >> box.max[0] >> box.max[1] >> box.max[2]; return is; } }; //--------------------------------------------------------------------------- // element-wise multiplication of two vectors template<typename T, typename U> Vec3<typename std::common_type<T, U>::type> times(Vec3<T> lhs, const Vec3<U>& rhs) { return Vec3<typename std::common_type<T, U>::type>( lhs[0] * rhs[0], lhs[1] * rhs[1], lhs[2] * rhs[2]); } //--------------------------------------------------------------------------- typedef DEPRECATED_MSVC Vec3<double> PCCVector3D DEPRECATED; typedef DEPRECATED_MSVC Vec3<double> PCCPoint3D DEPRECATED; typedef DEPRECATED_MSVC Box3<double> PCCBox3D DEPRECATED; typedef DEPRECATED_MSVC Vec3<uint8_t> PCCColor3B DEPRECATED; template<typename T> using PCCVector3 DEPRECATED = Vec3<T>; //=========================================================================== struct Rational { int numerator; int denominator; Rational() : Rational(0, 1){}; Rational(int numerator) : Rational(numerator, 1){}; Rational(int numerator, int denominator) : numerator(numerator), denominator(denominator) {} Rational(float val); Rational(double val); operator double() const { return double(numerator) / double(denominator); } operator float() const { return float(numerator) / float(denominator); } }; //--------------------------------------------------------------------------- inline Rational reciprocal(const Rational x) { return Rational(x.denominator, x.numerator); } //=========================================================================== template<typename T> T PCCClip(const T& n, const T& lower, const T& upper) { return std::max(lower, std::min(n, upper)); } template<typename T> bool PCCApproximatelyEqual( T a, T b, T epsilon = std::numeric_limits<double>::epsilon()) { return fabs(a - b) <= ((fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon); } //--------------------------------------------------------------------------- inline int64_t mortonAddr(const int32_t x, const int32_t y, const int32_t z) { assert(x >= 0 && y >= 0 && z >= 0); int64_t answer = kMortonCode256X[(x >> 16) & 0xFF] | kMortonCode256Y[(y >> 16) & 0xFF] | kMortonCode256Z[(z >> 16) & 0xFF]; answer = answer << 24 | kMortonCode256X[(x >> 8) & 0xFF] | kMortonCode256Y[(y >> 8) & 0xFF] | kMortonCode256Z[(z >> 8) & 0xFF]; answer = answer << 24 | kMortonCode256X[x & 0xFF] | kMortonCode256Y[y & 0xFF] | kMortonCode256Z[z & 0xFF]; return answer; } //--------------------------------------------------------------------------- // Convert a vector position to morton order address. template<typename T> int64_t mortonAddr(const Vec3<T>& vec) { return mortonAddr(int(vec.x()), int(vec.y()), int(vec.z())); } //--------------------------------------------------------------------------- inline int64_t PCCClip(const int64_t& n, const int64_t& lower, const int64_t& upper) { return std::max(lower, std::min(n, upper)); } //--------------------------------------------------------------------------- // Integer division of @x by 2^shift, truncating towards zero. template<typename T> inline T divExp2(T x, int shift) { return x >= 0 ? x >> shift : -(-x >> shift); } //--------------------------------------------------------------------------- // Integer division of @x by 2^shift, rounding intermediate half values // to +Inf. inline int64_t divExp2RoundHalfUp(int64_t x, int shift) { if (!shift) return x; int64_t half = 1ll << (shift - 1); return (x + half) >> shift; } //--------------------------------------------------------------------------- // Integer division of @scalar by 2^shift, rounding intermediate half values // away from zero. inline int64_t divExp2RoundHalfInf(int64_t scalar, int shift) { if (!shift) return scalar; int64_t s0 = 1ll << (shift - 1); return scalar >= 0 ? (s0 + scalar) >> shift : -((s0 - scalar) >> shift); } //--------------------------------------------------------------------------- // Integer division of @scalar by 2^shift, rounding intermediate half values // away from zero. inline uint64_t divExp2RoundHalfInf(uint64_t scalar, int shift) { if (!shift) return scalar; return ((1ull << (shift - 1)) + scalar) >> shift; } //--------------------------------------------------------------------------- // Component-wise integer division of @vec by 2^shift, rounding intermediate // half values away from zero. template<typename T> inline Vec3<T> divExp2RoundHalfInf(Vec3<T> vec, int shift) { for (int k = 0; k < 3; ++k) vec[k] = divExp2RoundHalfInf(vec[k], shift); return vec; } //--------------------------------------------------------------------------- extern const uint16_t kDivApproxDivisor[256]; //--------------------------------------------------------------------------- inline int64_t divInvDivisorApprox(const uint64_t b, int32_t& log2InvScale) { assert(b > 0); const int32_t lutSizeLog2 = 8; const auto n = std::max(0, ilog2(b) + 1 - lutSizeLog2); const auto index = (b + ((1ull << n) >> 1)) >> n; assert(unsigned(index) <= (1 << lutSizeLog2)); log2InvScale = n + (lutSizeLog2 << 1); return kDivApproxDivisor[index - 1] + 1; } //--------------------------------------------------------------------------- inline int64_t divApprox(const int64_t a, const uint64_t b, const int32_t log2Scale) { assert(abs(a) < (1ull << 46)); int32_t log2InvScale; const int64_t invB = divInvDivisorApprox(b, log2InvScale); return (invB * a) >> (log2InvScale - log2Scale); } //--------------------------------------------------------------------------- template<unsigned NIter = 1> inline int64_t recipApprox(int64_t b, int32_t& log2Scale) { int log2ScaleOffset = 0; int32_t log2bPlusOne = ilog2(uint64_t(b)) + 1; if (log2bPlusOne > 31) { b >>= log2bPlusOne - 31; log2ScaleOffset -= log2bPlusOne - 31; } if (log2bPlusOne < 31) { b <<= 31 - log2bPlusOne; log2ScaleOffset += 31 - log2bPlusOne; } // Initial approximation: 48/17 - 32/17 * b with 28 bits decimal prec int64_t bRecip = ((0x2d2d2d2dLL << 31) - 0x1e1e1e1eLL * b) >> 28; for (unsigned i = 0; i < NIter; ++i) bRecip += bRecip * ((1LL << 31) - (b * bRecip >> 31)) >> 31; log2Scale = (31 << 1) - log2ScaleOffset; return bRecip; } //--------------------------------------------------------------------------- inline Vec3<int64_t> divApprox(const Vec3<int64_t> a, const uint64_t b, const int32_t log2Scale) { assert(abs(a[0]) < (1ull << 46)); assert(abs(a[1]) < (1ull << 46)); assert(abs(a[2]) < (1ull << 46)); int32_t log2InvScale; const int64_t invB = divInvDivisorApprox(b, log2InvScale); const int32_t n = log2InvScale - log2Scale; Vec3<int64_t> res; res[0] = (invB * a[0]) >> n; res[1] = (invB * a[1]) >> n; res[2] = (invB * a[2]) >> n; return res; } //--------------------------------------------------------------------------- inline Vec3<int64_t> divApproxRoundHalfInf( const Vec3<int64_t> a, const uint64_t b, const int32_t log2Scale) { assert(abs(a[0]) < (1ull << 46)); assert(abs(a[1]) < (1ull << 46)); assert(abs(a[2]) < (1ull << 46)); int32_t log2InvScale; const int64_t invB = divInvDivisorApprox(b, log2InvScale); const int32_t n = log2InvScale - log2Scale; Vec3<int64_t> res; res[0] = divExp2RoundHalfInf(invB * a[0], n); res[1] = divExp2RoundHalfInf(invB * a[1], n); res[2] = divExp2RoundHalfInf(invB * a[2], n); return res; } //--------------------------------------------------------------------------- inline int32_t isin0(const int32_t x, const int32_t log2Scale) { assert(log2Scale >= kLog2ISineAngleScale); assert(x >= 0); assert(x <= (1 << (log2Scale - 2))); const auto ds = log2Scale - kLog2ISineAngleScale; const auto b = (1 << ds); const auto i0 = (x >> ds); const auto x0 = i0 << ds; const auto d1 = x - x0; assert(i0 <= (1 << kLog2ISineAngleScale) >> 2); return kISine[i0] + ((d1 * (kISine[i0 + 1] - kISine[i0]) + (b >> 1)) >> ds); } //--------------------------------------------------------------------------- inline int32_t icos0(const int32_t x, const int32_t log2Scale) { assert(x >= 0); assert(x <= (1 << (log2Scale - 2))); return isin0((1 << (log2Scale - 2)) - x, log2Scale); } //--------------------------------------------------------------------------- inline int32_t isin(int32_t x, const int32_t log2Scale) { const auto L = 1 << (log2Scale - 1); x = std::min(std::max(x, -L), L); assert(abs(x) <= (1 << (log2Scale - 1))); const auto Q0 = 1 << (log2Scale - 2); if (x >= Q0) { return isin0((1 << (log2Scale - 1)) - x, log2Scale); } else if (x >= 0) { return isin0(x, log2Scale); } else if (x >= -Q0) { return -isin0(-x, log2Scale); } else { return -isin0((1 << (log2Scale - 1)) + x, log2Scale); } } //--------------------------------------------------------------------------- inline int32_t icos(int32_t x, const int32_t log2Scale) { const auto Q0 = 1 << (log2Scale - 2); const auto ax = std::min(abs(x), (1 << (log2Scale - 1))); return ax <= Q0 ? icos0(ax, log2Scale) : -icos0((1 << (log2Scale - 1)) - ax, log2Scale); } //--------------------------------------------------------------------------- } /* namespace pcc */ #endif /* PCCMath_h */
22,361
25.653159
79
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/PCCMisc.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <array> #include <cstddef> #include <cstdint> #include <iterator> #include <utility> #include <string> #include <vector> #if _MSC_VER # define DEPRECATED_MSVC __declspec(deprecated) # define DEPRECATED #else # define DEPRECATED_MSVC # define DEPRECATED __attribute__((deprecated)) #endif #if _MSC_VER && !defined(__attribute__) # define __attribute__(...) #endif namespace pcc { const uint32_t PCC_UNDEFINED_INDEX = -1; enum PCCEndianness { PCC_BIG_ENDIAN = 0, PCC_LITTLE_ENDIAN = 1 }; inline PCCEndianness PCCSystemEndianness() { uint32_t num = 1; return (*(reinterpret_cast<char*>(&num)) == 1) ? PCC_LITTLE_ENDIAN : PCC_BIG_ENDIAN; } //--------------------------------------------------------------------------- // Replace any occurence of %d with formatted number. The %d format // specifier may use the formatting conventions of snprintf(). std::string expandNum(const std::string& src, int num); //--------------------------------------------------------------------------- // Population count -- return the number of bits set in @x. // inline int popcnt(uint32_t x) { x = x - ((x >> 1) & 0x55555555u); x = (x & 0x33333333u) + ((x >> 2) & 0x33333333u); return ((x + (x >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24; } //--------------------------------------------------------------------------- // Population count -- return the number of bits set in @x. // inline int popcnt(uint8_t x) { uint32_t val = x * 0x08040201u; val >>= 3; val &= 0x11111111u; val *= 0x11111111u; return val >> 28; } //--------------------------------------------------------------------------- // Test if population count is greater than 1. // Returns non-zero if true. // inline uint32_t popcntGt1(uint32_t x) { return x & (x - 1); } //--------------------------------------------------------------------------- // Round @x up to next power of two. // inline uint32_t ceilpow2(uint32_t x) { x--; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x + 1; } //--------------------------------------------------------------------------- // Round @x up to next power of two. // inline uint64_t ceilpow2(uint64_t x) { x--; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); x = x | (x >> 32); return x + 1; } //--------------------------------------------------------------------------- // Compute \left\floor \text{log}_2(x) \right\floor. // NB: ilog2(0) = -1. inline int ilog2(uint32_t x) { x = ceilpow2(x + 1) - 1; return popcnt(x) - 1; } //--------------------------------------------------------------------------- // Compute \left\floor \text{log}_2(x) \right\floor. // NB: ilog2(0) = -1. inline int ilog2(uint64_t x) { x = ceilpow2(x + 1) - 1; return popcnt(uint32_t(x >> 32)) + popcnt(uint32_t(x)) - 1; } //--------------------------------------------------------------------------- // Compute \left\ceil \text{log}_2(x) \right\ceil. // NB: ceillog2(0) = 32. inline int ceillog2(uint32_t x) { return ilog2(x - 1) + 1; } //--------------------------------------------------------------------------- // The number of bits required to represent x. // NB: x must be >= 0. // NB: numBits(0) = 1. inline int numBits(int x) { return std::max(0, ilog2(uint32_t(x))) + 1; } //--------------------------------------------------------------------------- // rotate left by n bits. // If n is negative, the effect is to rotate right. // NB: Signed types are treated as unsigned. template<typename T> T rotateLeft(T val, int n) { n &= sizeof(T) * 8 - 1; using unsigned_t = typename std::make_unsigned<T>::type; return (unsigned_t(val) << n) | (unsigned_t(val) >> (8 * sizeof(val) - n)); } //--------------------------------------------------------------------------- // rotate right by n bits. // If n is negative, the effect is to rotate left. // NB: Signed types are treated as unsigned. template<typename T> T rotateRight(T val, int n) { n &= sizeof(T) * 8 - 1; using unsigned_t = typename std::make_unsigned<T>::type; return (unsigned_t(val) >> n) | (unsigned_t(val) << (8 * sizeof(val) - n)); } //--------------------------------------------------------------------------- // Compute an approximation of \left\floor \sqrt{x} \right\floor uint32_t isqrt(uint64_t x) __attribute__((const)); //--------------------------------------------------------------------------- // Compute an approximation of reciprocal sqrt uint64_t irsqrt(uint64_t a64) __attribute__((const)); //--------------------------------------------------------------------------- // Compute an approximation of atan2 int iatan2(int y, int x); //--------------------------------------------------------------------------- // Decrement the @axis-th dimension of 3D morton code @x. // inline int64_t morton3dAxisDec(int64_t val, int axis) { const int64_t mask0 = 0x9249249249249249llu << axis; return ((val & mask0) - 1 & mask0) | (val & ~mask0); } //--------------------------------------------------------------------------- // add the three dimentional addresses @a + @b; // inline uint64_t morton3dAdd(uint64_t a, uint64_t b) { uint64_t mask = 0x9249249249249249llu; uint64_t val = 0; for (int i = 0; i < 3; i++) { val |= (a | ~mask) + (b & mask) & mask; mask <<= 1; } return val; } //--------------------------------------------------------------------------- // Sort the elements in range [@first, @last) using a counting sort. // // The value of each element is determined by the function // @value_of(RandomIt::value_type) and must be in the range [0, Radix). // // A supplied output array of @counts represents the histogram of values, // and may be used to calculate the output position of each value span. // // NB: This is an in-place implementation and is not a stable sort. template<class RandomIt, class ValueOp, std::size_t Radix> void countingSort( RandomIt first, RandomIt last, std::array<int, Radix>& counts, ValueOp value_of) { // step 1: count each radix for (auto it = first; it != last; ++it) { counts[value_of(*it)]++; } // step 2: determine the output offsets std::array<RandomIt, Radix> ptrs = {{first}}; for (int i = 1; i < Radix; i++) { ptrs[i] = std::next(ptrs[i - 1], counts[i - 1]); } // step 3: re-order, completing each radix in turn. RandomIt ptr_orig_last = first; for (int i = 0; i < Radix; i++) { std::advance(ptr_orig_last, counts[i]); while (ptrs[i] != ptr_orig_last) { int radix = value_of(*ptrs[i]); std::iter_swap(ptrs[i], ptrs[radix]); ++ptrs[radix]; } } } //--------------------------------------------------------------------------- struct NoOp { template<typename... Args> void operator()(Args...) {} }; //--------------------------------------------------------------------------- template<typename It, typename ValueOp, typename AccumOp> void radixSort8WithAccum(int maxValLog2, It begin, It end, ValueOp op, AccumOp acc) { std::array<int, 8> counts = {}; countingSort(begin, end, counts, [=](decltype(*begin)& it) { return op(maxValLog2, it); }); acc(maxValLog2, counts); if (--maxValLog2 < 0) return; auto childBegin = begin; for (int i = 0; i < counts.size(); i++) { if (!counts[i]) continue; auto childEnd = std::next(childBegin, counts[i]); radixSort8WithAccum(maxValLog2, childBegin, childEnd, op, acc); childBegin = childEnd; } } //--------------------------------------------------------------------------- template<typename It, typename ValueOp> void radixSort8(int maxValLog2, It begin, It end, ValueOp op) { radixSort8WithAccum(maxValLog2, begin, end, op, NoOp()); } //============================================================================ // A wrapper to reverse the iteration order of a range based for loop template<typename T> struct fwd_is_reverse_iterator { T& obj; }; template<typename T> auto begin(fwd_is_reverse_iterator<T> w) -> decltype(w.obj.rbegin()) { return w.obj.rbegin(); } template<typename T> auto end(fwd_is_reverse_iterator<T> w) -> decltype(w.obj.rend()) { return w.obj.rend(); } template<typename T> fwd_is_reverse_iterator<T> inReverse(T&& obj) { return {obj}; } //---------------------------------------------------------------------------- } // namespace pcc
10,262
26.368
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/PCCPointSet.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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 PCCPointSet_h #define PCCPointSet_h #include <assert.h> #include <algorithm> #include <cmath> #include <cstddef> #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <string> #include <vector> #include "PCCMath.h" #include "PCCMisc.h" namespace pcc { //============================================================================ // The type used for internally representing attribute data typedef uint16_t attr_t; // The type used for internally representing positions typedef Vec3<int32_t> point_t; //============================================================================ class PCCPointSet3 { public: typedef point_t PointType; //========================================================================= // proxy object for use with iterator, allowing handling of PCCPointSet3's // structure-of-arrays as a single array. class iterator; class Proxy { friend class iterator; PCCPointSet3* parent_; size_t idx_; public: //----------------------------------------------------------------------- Proxy() : parent_(nullptr), idx_() {} Proxy(PCCPointSet3* parent, size_t idx) : parent_(parent), idx_(idx) {} //----------------------------------------------------------------------- PointType operator*() const { return (*parent_)[idx_]; } PointType& operator*() { return (*parent_)[idx_]; } //----------------------------------------------------------------------- // Swap the position of the current proxied point (including attributes) // with that of @other in the same PointSet. void swap(const Proxy& other) const { assert(parent_ == other.parent_); parent_->swapPoints(idx_, other.idx_); } //----------------------------------------------------------------------- }; //========================================================================= // iterator for use with stl algorithms class iterator { private: Proxy p_; public: typedef std::random_access_iterator_tag iterator_category; typedef const Proxy value_type; typedef std::ptrdiff_t difference_type; typedef const Proxy* pointer; typedef const Proxy& reference; //----------------------------------------------------------------------- iterator() = default; iterator(const iterator&) = default; //----------------------------------------------------------------------- explicit iterator(PCCPointSet3* parent) : p_{parent, 0} {} explicit iterator(PCCPointSet3* parent, size_t idx) : p_{parent, idx} {} //----------------------------------------------------------------------- // :: Iterator reference operator*() const { return p_; } //----------------------------------------------------------------------- iterator& operator++() { p_.idx_++; return *this; } //----------------------------------------------------------------------- // :: ForwardIterator iterator operator++(int) { iterator retval = *this; ++(*this); return retval; } //----------------------------------------------------------------------- pointer operator->() const { return &p_; } //----------------------------------------------------------------------- bool operator==(const iterator& other) const { return p_.idx_ == other.p_.idx_; } //----------------------------------------------------------------------- bool operator!=(const iterator& other) const { return !(*this == other); } //----------------------------------------------------------------------- // :: BidirectionalIterator iterator& operator--() { p_.idx_--; return *this; } //----------------------------------------------------------------------- iterator operator--(int) { iterator retval = *this; --(*this); return retval; } //----------------------------------------------------------------------- // :: RandomAccessIterator value_type operator[](difference_type n) { return Proxy{p_.parent_, p_.idx_ + n}; } //----------------------------------------------------------------------- iterator& operator+=(difference_type n) { p_.idx_ += n; return *this; } //----------------------------------------------------------------------- iterator operator+(difference_type n) const { iterator it(*this); it += n; return it; } //----------------------------------------------------------------------- iterator& operator-=(difference_type n) { p_.idx_ -= n; return *this; } //----------------------------------------------------------------------- iterator operator-(difference_type n) const { iterator it(*this); it -= n; return it; } //----------------------------------------------------------------------- difference_type operator-(const iterator& other) const { return p_.idx_ - other.p_.idx_; } //----------------------------------------------------------------------- }; //========================================================================= PCCPointSet3() { withColors = false; withReflectances = false; withFrameIndex = false; withLaserAngles = false; } PCCPointSet3(const PCCPointSet3&) = default; PCCPointSet3& operator=(const PCCPointSet3& rhs) = default; ~PCCPointSet3() = default; void swap(PCCPointSet3& other) { using std::swap; swap(positions, other.positions); swap(colors, other.colors); swap(reflectances, other.reflectances); swap(frameidx, other.frameidx); swap(laserAngles, other.laserAngles); swap(withColors, other.withColors); swap(withReflectances, other.withReflectances); swap(withFrameIndex, other.withFrameIndex); swap(withLaserAngles, other.withLaserAngles); } PointType operator[](const size_t index) const { assert(index < positions.size()); return positions[index]; } PointType& operator[](const size_t index) { assert(index < positions.size()); return positions[index]; } void swapPoints(std::vector<PointType>& other) { positions.swap(other); } Vec3<attr_t> getColor(const size_t index) const { assert(index < colors.size() && withColors); return colors[index]; } Vec3<attr_t>& getColor(const size_t index) { assert(index < colors.size() && withColors); return colors[index]; } void setColor(const size_t index, const Vec3<attr_t> color) { assert(index < colors.size() && withColors); colors[index] = color; } attr_t getReflectance(const size_t index) const { assert(index < reflectances.size() && withReflectances); return reflectances[index]; } attr_t& getReflectance(const size_t index) { assert(index < reflectances.size() && withReflectances); return reflectances[index]; } void setReflectance(const size_t index, const attr_t reflectance) { assert(index < reflectances.size() && withReflectances); reflectances[index] = reflectance; } bool hasReflectances() const { return withReflectances; } void addReflectances() { withReflectances = true; resize(getPointCount()); } void removeReflectances() { withReflectances = false; reflectances.resize(0); } uint8_t getFrameIndex(const size_t index) const { assert(index < frameidx.size() && withFrameIndex); return frameidx[index]; } uint8_t& getFrameIndex(const size_t index) { assert(index < frameidx.size() && withFrameIndex); return frameidx[index]; } void setFrameIndex(const size_t index, const uint8_t frameindex) { assert(index < frameidx.size() && withFrameIndex); frameidx[index] = frameindex; } bool hasFrameIndex() const { return withFrameIndex; } void addFrameIndex() { withFrameIndex = true; resize(getPointCount()); } void removeFrameIndex() { withFrameIndex = false; frameidx.resize(0); } int getLaserAngle(const size_t index) const { assert(index < laserAngles.size() && withLaserAngles); return laserAngles[index]; } int& getLaserAngle(const size_t index) { assert(index < laserAngles.size() && withLaserAngles); return laserAngles[index]; } void setLaserAngle(const size_t index, const int angle) { assert(index < laserAngles.size() && withLaserAngles); laserAngles[index] = angle; } bool hasLaserAngles() const { return withLaserAngles; } void addLaserAngles() { withLaserAngles = true; resize(getPointCount()); } void removeLaserAngles() { withLaserAngles = false; laserAngles.resize(0); } bool hasColors() const { return withColors; } void addColors() { withColors = true; resize(getPointCount()); } void removeColors() { withColors = false; colors.resize(0); } void addRemoveAttributes(bool withColors, bool withReflectances) { if (withColors) addColors(); else removeColors(); if (withReflectances) addReflectances(); else removeReflectances(); } void addRemoveAttributes(const PCCPointSet3& ref) { ref.hasColors() ? addColors() : removeColors(); ref.hasReflectances() ? addReflectances() : removeReflectances(); ref.hasLaserAngles() ? addLaserAngles() : removeLaserAngles(); } size_t getPointCount() const { return positions.size(); } void resize(const size_t size) { positions.resize(size); if (hasColors()) { colors.resize(size); } if (hasReflectances()) { reflectances.resize(size); } if (hasFrameIndex()) { frameidx.resize(size); } if (hasLaserAngles()) { laserAngles.resize(size); } } void reserve(const size_t size) { positions.reserve(size); if (hasColors()) { colors.reserve(size); } if (hasReflectances()) { reflectances.reserve(size); } if (hasFrameIndex()) { frameidx.reserve(size); } if (hasLaserAngles()) { laserAngles.reserve(size); } } void clear() { positions.clear(); colors.clear(); reflectances.clear(); frameidx.clear(); laserAngles.clear(); } size_t removeDuplicatePointInQuantizedPoint(int minGeomNodeSizeLog2) { for (int i = 0; i < positions.size(); i++) { PointType newPoint = positions[i]; if (minGeomNodeSizeLog2 > 0) { uint32_t mask = ((uint32_t)-1) << minGeomNodeSizeLog2; positions[i].x() = ((int32_t)(positions[i].x()) & mask); positions[i].y() = ((int32_t)(positions[i].y()) & mask); positions[i].z() = ((int32_t)(positions[i].z()) & mask); } } positions.erase( std::unique(positions.begin(), positions.end()), positions.end()); return positions.size(); } void append(const PCCPointSet3& src) { if (!getPointCount()) addRemoveAttributes(src); int dstEnd = positions.size(); int srcSize = src.positions.size(); resize(dstEnd + srcSize); std::copy( src.positions.begin(), src.positions.end(), std::next(positions.begin(), dstEnd)); if (hasColors() && src.hasColors()) std::copy( src.colors.begin(), src.colors.end(), std::next(colors.begin(), dstEnd)); if (hasReflectances() && src.hasReflectances()) std::copy( src.reflectances.begin(), src.reflectances.end(), std::next(reflectances.begin(), dstEnd)); if (hasLaserAngles()) std::copy( src.laserAngles.begin(), src.laserAngles.end(), std::next(laserAngles.begin(), dstEnd)); } void swapPoints(const size_t index1, const size_t index2) { assert(index1 < getPointCount()); assert(index2 < getPointCount()); std::swap((*this)[index1], (*this)[index2]); if (hasColors()) { std::swap(getColor(index1), getColor(index2)); } if (hasReflectances()) { std::swap(getReflectance(index1), getReflectance(index2)); } if (hasLaserAngles()) { std::swap(getLaserAngle(index1), getLaserAngle(index2)); } } Box3<int32_t> computeBoundingBox() const { Box3<int32_t> bbox( std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::lowest()); const size_t pointCount = getPointCount(); for (size_t i = 0; i < pointCount; ++i) { const auto& pt = (*this)[i]; for (int k = 0; k < 3; ++k) { if (pt[k] > bbox.max[k]) { bbox.max[k] = pt[k]; } if (pt[k] < bbox.min[k]) { bbox.min[k] = pt[k]; } } } return bbox; } //-------------------------------------------------------------------------- // Determine the bounding box of the set of points given by the indicies // given by iterating over [begin, end) template<typename ForwardIt> Box3<int32_t> computeBoundingBox(ForwardIt begin, ForwardIt end) const { Box3<int32_t> bbox( std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::lowest()); for (auto it = begin; it != end; ++it) { int i = *it; const auto& pt = (*this)[i]; for (int k = 0; k < 3; ++k) { if (pt[k] > bbox.max[k]) { bbox.max[k] = pt[k]; } if (pt[k] < bbox.min[k]) { bbox.min[k] = pt[k]; } } } return bbox; } //-------------------------------------------------------------------------- private: std::vector<PointType> positions; std::vector<Vec3<attr_t>> colors; std::vector<attr_t> reflectances; std::vector<uint8_t> frameidx; bool withColors; bool withReflectances; bool withFrameIndex; std::vector<int> laserAngles; bool withLaserAngles; }; //=========================================================================== // Swap the position of two points (including attributes) in the PointSet // as referenced by the proxies a and b. inline void swap(const PCCPointSet3::Proxy& a, const PCCPointSet3::Proxy& b) { a.swap(b); } //--------------------------------------------------------------------------- // Swap two point clouds inline void swap(PCCPointSet3& a, PCCPointSet3& b) { a.swap(b); } //--------------------------------------------------------------------------- } /* namespace pcc */ #endif /* PCCPointSet_h */
16,227
25.956811
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/PCCTMC3Decoder.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <functional> #include <map> #include "Attribute.h" #include "PayloadBuffer.h" #include "PCCMath.h" #include "PCCPointSet.h" #include "frame.h" #include "framectr.h" #include "geometry.h" #include "hls.h" namespace pcc { //============================================================================ struct DecoderParams { // For partial decoding (aka, scalable bitstreams), the number of octree // layers to skip during the decode process (attribute coding must take // this into account) int minGeomNodeSizeLog2; // A maximum number of points to partially decode. int decodeMaxPoints; // Number of fractional bits used in output position representation. int outputFpBits; }; //============================================================================ class PCCTMC3Decoder3 { public: class Callbacks; PCCTMC3Decoder3(const DecoderParams& params); PCCTMC3Decoder3(const PCCTMC3Decoder3&) = delete; PCCTMC3Decoder3(PCCTMC3Decoder3&&) = default; PCCTMC3Decoder3& operator=(const PCCTMC3Decoder3& rhs) = delete; PCCTMC3Decoder3& operator=(PCCTMC3Decoder3&& rhs) = default; ~PCCTMC3Decoder3(); void init(); int decompress(const PayloadBuffer* buf, Callbacks* callback); //========================================================================== void storeSps(SequenceParameterSet&& sps); void storeGps(GeometryParameterSet&& gps); void storeAps(AttributeParameterSet&& aps); void storeTileInventory(TileInventory&& inventory); //========================================================================== private: void activateParameterSets(const AttributeParamInventoryHdr& gbh); void activateParameterSets(const GeometryBrickHeader& gbh); int decodeGeometryBrick(const PayloadBuffer& buf); void decodeAttributeBrick(const PayloadBuffer& buf); void decodeConstantAttribute(const PayloadBuffer& buf); bool dectectFrameBoundary(const PayloadBuffer* buf); void outputCurrentCloud(Callbacks* callback); void startFrame(); //========================================================================== private: // Decoder specific parameters DecoderParams _params; // Indicates that pointcloud output should be suppressed at a frame boundary bool _suppressOutput; // Indicates that this is the start of a new frame. // NB: this is set to false quiet early in the decoding process bool _firstSliceInFrame; // Indicates whether the output has been initialised bool _outputInitialized; // Current identifier of payloads with the same geometry int _sliceId; // Identifies the previous slice in bistream order int _prevSliceId; // Cumulative frame counter FrameCtr _frameCtr; // Position of the slice in the translated+scaled co-ordinate system. Vec3<int> _sliceOrigin; // The point cloud currently being decoded PCCPointSet3 _currentPointCloud; // The accumulated decoded slices PCCPointSet3 _accumCloud; // The current output cloud CloudFrame _outCloud; // Point positions in spherical coordinates of the current slice std::vector<point_t> _posSph; // Received parameter sets, mapping parameter set id -> parameterset std::map<int, SequenceParameterSet> _spss; std::map<int, GeometryParameterSet> _gpss; std::map<int, AttributeParameterSet> _apss; // Metadata that allows slices/tiles to be indentified by their bounding box TileInventory _tileInventory; // The active SPS const SequenceParameterSet* _sps; const GeometryParameterSet* _gps; GeometryBrickHeader _gbh; // Memorized context buffers std::unique_ptr<GeometryOctreeContexts> _ctxtMemOctreeGeom; std::unique_ptr<PredGeomContexts> _ctxtMemPredGeom; std::vector<AttributeContexts> _ctxtMemAttrs; std::vector<int> _ctxtMemAttrSliceIds; // Attribute decoder for reuse between attributes of same slice std::unique_ptr<AttributeDecoderIntf> _attrDecoder; }; //---------------------------------------------------------------------------- class PCCTMC3Decoder3::Callbacks { public: virtual void onOutputCloud(const CloudFrame&) = 0; }; //============================================================================ } // namespace pcc
6,013
32.977401
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/PCCTMC3Encoder.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <functional> #include <map> #include <string> #include <vector> #include "Attribute.h" #include "PayloadBuffer.h" #include "PCCMath.h" #include "PCCPointSet.h" #include "frame.h" #include "geometry.h" #include "geometry_params.h" #include "hls.h" #include "partitioning.h" #include "pointset_processing.h" namespace pcc { //============================================================================ struct EncoderAttributeParams { // NB: this only makes sense for setting configurable parameters AttributeBrickHeader abh; // Threshold for choosing dist2 out of the population of nearest neighbour // distances. float dist2PercentileEstimate; }; //---------------------------------------------------------------------------- struct EncoderParams { SequenceParameterSet sps; GeometryParameterSet gps; GeometryBrickHeader gbh; // NB: information about attributes is split between the SPS and the APS. // => The SPS enumerates the attributes, the APS controls coding params. std::vector<AttributeParameterSet> aps; // Encoder specific parameters for attributes std::vector<EncoderAttributeParams> attr; // todo(df): this should go away std::map<std::string, int> attributeIdxMap; // Determine the sequence bonuding box using the first input frame bool autoSeqBbox; // Length of the source point cloud unit vectors. double srcUnitLength; // Scale factor used to define the coordinate system used for coding. // This is the coordinate system where slicing is performed. // P_cod = P_src * codedGeomScale double codedGeomScale; // Scale factor used to define the sequence coordinate system. // P_seq = P_src * seqGeomScale double seqGeomScale; // Scale factor used to define the external coordinate system. // P_ext = P_src * extGeomScale double extGeomScale; // Number of fractional bits used in output position representation. int outputFpBits; // Encoder specific parameters for geometry OctreeEncOpts geom; // Options for the predictive geometry coder PredGeomEncOpts predGeom; // Parameters that control partitioning PartitionParams partition; // attribute recolouring parameters RecolourParams recolour; // LiDAR head position Vec3<int> lidarHeadPosition; // number of expected lasers int numLasers; // floating Lasers' theta (have to be converted to fixed point in gps) std::vector<double> lasersTheta; // floating Lasers' H (have to be converted to fixed point in gps) std::vector<double> lasersZ; // per-slice trisoup node sizes std::vector<int> trisoupNodeSizesLog2; // Enable enforcement of level limits (encoder will abort if exceeded) bool enforceLevelLimits; // Qp used for IDCM quantisation (used to derive HLS values) int idcmQp; // precision expected for attributes after scaling with predgeom // and spherical coordinates int attrSphericalMaxLog2; }; //============================================================================ class PCCTMC3Encoder3 { public: class Callbacks; PCCTMC3Encoder3(); PCCTMC3Encoder3(const PCCTMC3Encoder3&) = delete; PCCTMC3Encoder3(PCCTMC3Encoder3&&) = default; PCCTMC3Encoder3& operator=(const PCCTMC3Encoder3& rhs) = delete; PCCTMC3Encoder3& operator=(PCCTMC3Encoder3&& rhs) = default; ~PCCTMC3Encoder3(); int compress( const PCCPointSet3& inputPointCloud, EncoderParams* params, Callbacks*, CloudFrame* reconstructedCloud = nullptr); void compressPartition( const PCCPointSet3& inputPointCloud, const PCCPointSet3& originPartCloud, EncoderParams* params, Callbacks*, CloudFrame* reconstructedCloud = nullptr); static void deriveParameterSets(EncoderParams* params); static void fixupParameterSets(EncoderParams* params); private: void appendSlice(PCCPointSet3& cloud); void encodeGeometryBrick(const EncoderParams*, PayloadBuffer* buf); SrcMappedPointSet quantization(const PCCPointSet3& src); private: PCCPointSet3 pointCloud; // Point positions in spherical coordinates of the current slice std::vector<point_t> _posSph; // Scale factor used to decimate the input point cloud. // Decimation is performed as if the input were scaled by // Round(P_src * inputDecimationScale) // and duplicate points removed. // todo: expose this parameter? double _inputDecimationScale; // Scale factor that defines coding coordinate system double _srcToCodingScale; // Sequence origin in terms of coding coordinate system Vec3<int> _originInCodingCoords; // Position of the slice in the translated+scaled co-ordinate system. Vec3<int> _sliceOrigin; // Size of the current slice Vec3<int> _sliceBoxWhd; // The active parameter sets const SequenceParameterSet* _sps; const GeometryParameterSet* _gps; std::vector<const AttributeParameterSet*> _aps; // Cached copy of the curent _gbh (after encoding geometry) GeometryBrickHeader _gbh; // Indicates that this is the start of a new frame bool _firstSliceInFrame; // Current identifier of payloads with the same geometry int _sliceId; // Identifies the previous slice in bistream order int _prevSliceId; // Identifies the current tile int _tileId; // Current frame number. // NB: only the log2_max_frame_ctr LSBs are sampled for frame_ctr int _frameCounter; // Memorized context buffers std::unique_ptr<GeometryOctreeContexts> _ctxtMemOctreeGeom; std::unique_ptr<PredGeomContexts> _ctxtMemPredGeom; std::vector<AttributeContexts> _ctxtMemAttrs; std::vector<int> _ctxtMemAttrSliceIds; }; //---------------------------------------------------------------------------- class PCCTMC3Encoder3::Callbacks { public: virtual void onOutputBuffer(const PayloadBuffer&) = 0; virtual void onPostRecolour(const PCCPointSet3&) = 0; }; //============================================================================ } // namespace pcc
7,766
30.445344
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/PayloadBuffer.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include "hls.h" #include <vector> namespace pcc { //============================================================================ struct PayloadBuffer : public std::vector<char> { PayloadType type; PayloadBuffer() = default; PayloadBuffer(PayloadType payload_type) : type(payload_type) { reserve(4096); } }; //============================================================================ } // namespace pcc
2,267
37.440678
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/RAHT.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> #include "FixedPoint.h" #include "quantization.h" #include "quantization.h" #include <vector> namespace pcc { void regionAdaptiveHierarchicalTransform( bool raht_prediction_enabled_flag, const int predictionThreshold[2], const QpSet& qpset, const Qps* pointQPOffset, int64_t* mortonCode, int* attributes, const int attribCount, const int voxelCount, int* coefficients); void regionAdaptiveHierarchicalInverseTransform( bool raht_prediction_enabled_flag, const int predictionThreshold[2], const QpSet& qpset, const Qps* pointQpOffset, int64_t* mortonCode, int* attributes, const int attribCount, const int voxelCount, int* coefficients); } /* namespace pcc */
2,558
35.557143
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/TMC3.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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 TMC3_h #define TMC3_h #define _CRT_SECURE_NO_WARNINGS #include "TMC3Config.h" #include "pcc_chrono.h" struct Parameters; typedef pcc::chrono::Stopwatch<pcc::chrono::utime_inc_children_clock> Stopwatch; bool ParseParameters(int argc, char* argv[], Parameters& params); int Compress(Parameters& params, Stopwatch&); int Decompress(Parameters& params, Stopwatch&); #endif /* TMC3_h */
2,224
39.454545
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/attribute_raw.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2021, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include "hls.h" #include "PayloadBuffer.h" #include "PCCPointSet.h" namespace pcc { //============================================================================ class AttrRawEncoder { public: static void encode( const SequenceParameterSet& sps, const AttributeDescription& desc, const AttributeParameterSet& attr_aps, AttributeBrickHeader& abh, PCCPointSet3& cloud, PayloadBuffer* payload); }; //============================================================================ class AttrRawDecoder { public: static void decode( const AttributeDescription& desc, const AttributeParameterSet& aps, const AttributeBrickHeader& abh, const char* payload, size_t payloadLen, PCCPointSet3& cloud); }; //============================================================================ } // namespace pcc
2,685
35.794521
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/colourspace.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> #include "PCCMath.h" namespace pcc { //============================================================================ template<template<typename> class T, typename Tv> T<Tv> transformGbrToYCbCrBt709(T<Tv>& gbr) { const Tv g = gbr[0]; const Tv b = gbr[1]; const Tv r = gbr[2]; const double y = PCCClip(std::round(0.212600 * r + 0.715200 * g + 0.072200 * b), 0., 255.); const double u = PCCClip( std::round(-0.114572 * r - 0.385428 * g + 0.5 * b + 128.0), 0., 255.); const double v = PCCClip( std::round(0.5 * r - 0.454153 * g - 0.045847 * b + 128.0), 0., 255.); return {Tv(y), Tv(u), Tv(v)}; } //============================================================================ template<template<typename> class T, typename Tv> T<Tv> transformYCbCrBt709ToGbr(T<Tv>& ycbcr) { const double y1 = ycbcr[0]; const double u1 = ycbcr[1] - 128.0; const double v1 = ycbcr[2] - 128.0; const double r = PCCClip(round(y1 /*- 0.00000 * u1*/ + 1.57480 * v1), 0.0, 255.0); const double g = PCCClip(round(y1 - 0.18733 * u1 - 0.46813 * v1), 0.0, 255.0); const double b = PCCClip(round(y1 + 1.85563 * u1 /*+ 0.00000 * v1*/), 0.0, 255.0); return {Tv(g), Tv(b), Tv(r)}; } //============================================================================ template<template<typename> class T, typename Tv> T<Tv> transformGbrToYCgCoR(int bitDepth, T<Tv>& gbr) { int g = gbr[0]; int b = gbr[1]; int r = gbr[2]; int co = r - b; int t = b + (co >> 1); int cg = g - t; int y = t + (cg >> 1); int offset = 1 << bitDepth; // NB: YCgCoR needs extra 1-bit for chroma return {Tv(y), Tv(cg + offset), Tv(co + offset)}; } //============================================================================ template<template<typename> class T, typename Tv> T<Tv> transformYCgCoRToGbr(int bitDepth, T<Tv>& ycgco) { int offset = 1 << bitDepth; int y0 = ycgco[0]; int cg = ycgco[1] - offset; int co = ycgco[2] - offset; int t = y0 - (cg >> 1); int g = cg + t; int b = t - (co >> 1); int r = co + b; int maxVal = (1 << bitDepth) - 1; g = PCCClip(g, 0, maxVal); b = PCCClip(b, 0, maxVal); r = PCCClip(r, 0, maxVal); return {Tv(g), Tv(b), Tv(r)}; } //============================================================================ } // namespace pcc
4,166
31.302326
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/constants.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> namespace pcc { //============================================================================ const uint32_t kAttributePredictionMaxNeighbourCount = 3; const uint32_t kAttributeResidualAlphabetSize = 255; const uint32_t kFixedPointWeightShift = 8; const uint32_t kFixedPointAttributeShift = 8; //============================================================================ } // namespace pcc
2,257
42.423077
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/coordinate_conversion.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2020, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include "PCCMath.h" namespace pcc { //============================================================================ // Converts points in the range [begin, end) from cartesian co-ordinates to // pseudo spherical coordinates (r, phi, laser), storing the results in dst. Box3<int> convertXyzToRpl( Vec3<int> laserOrigin, const int* laserThetaList, int numTheta, const Vec3<int>* begin, const Vec3<int>* end, Vec3<int>* dst); // Determines axes weights to normalise the axes of a bounding box. // forcedMaxLog2 > 0 allows a normalisation factor to be specified. Vec3<int> normalisedAxesWeights(Box3<int>& bbox, int forcedMaxLog2); // Offsets and weights points in the range [begin, end). void offsetAndScale( const Vec3<int>& minPos, const Vec3<int>& axisWeight, Vec3<int>* begin, Vec3<int>* end); //============================================================================ } // namespace pcc
2,754
40.119403
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/entropy.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include "entropydirac.h" #include "entropyutils.h" namespace pcc { using EntropyEncoder = EntropyEncoderWrapper<dirac::ArithmeticEncoder>; using EntropyDecoder = EntropyDecoderWrapper<dirac::ArithmeticDecoder>; } // namespace pcc
2,072
45.066667
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/entropychunk.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <stdexcept> namespace pcc { //============================================================================= // This multiplexer takes two input streams (one bytewise and one bitwise) // and assembles them into chunks within an output buffer class ChunkStreamBuilder { public: ChunkStreamBuilder(const ChunkStreamBuilder&) = delete; ChunkStreamBuilder(ChunkStreamBuilder&&) = delete; ChunkStreamBuilder& operator=(const ChunkStreamBuilder&) = delete; ChunkStreamBuilder& operator=(ChunkStreamBuilder&&) = delete; ChunkStreamBuilder() : _chunkBase(nullptr), _outputSizeRemaining(0) {} ChunkStreamBuilder(uint8_t* buf, size_t size) { reset(buf, size); } void reset(uint8_t* buf = nullptr, size_t size = 0); size_t size() const; void writeAecByte(uint8_t byte); void writeBypassBit(bool bit); void flush(); // Splice two chunk streams together. // Chunks chunkA and chunkB must be adjacent in memory. // // \param chunkA a pointer to the last chunk of the first stream // \param chunkB a pointer to the first chunk of the second stream // \param end pointer to one-past-the-end of the buffer containing A & B static void spliceChunkStreams(uint8_t* chunkA, uint8_t* chunkB, uint8_t* end); private: void reserveChunkByte(); void finaliseChunk(); void startNextChunk(); private: static const int kChunkSize = 256; // number of bytes remaining in the output buffer size_t _outputSizeRemaining; // number of bytes written to the output size_t _outputLength{0}; // start of the curernt chunk; uint8_t* _chunkBase; // number of bytes available in the current chunk int _chunkBytesRemaining; uint8_t* _aecPtr; uint8_t* _bypassPtr; int _bypassBitIdx; int _bypassByteAllocCounter; }; //============================================================================= inline void ChunkStreamBuilder::reset(uint8_t* buf, size_t size) { _outputLength = 0; if (!buf) return; // allocate the first chunk, (fixup the start address first) _chunkBase = buf - kChunkSize; _outputSizeRemaining = size; startNextChunk(); } //----------------------------------------------------------------------------- inline size_t ChunkStreamBuilder::size() const { return _outputLength; } //----------------------------------------------------------------------------- inline void ChunkStreamBuilder::writeAecByte(uint8_t byte) { reserveChunkByte(); *_aecPtr++ = byte; } //----------------------------------------------------------------------------- inline void ChunkStreamBuilder::writeBypassBit(bool bit) { if (_bypassByteAllocCounter < 1) { reserveChunkByte(); _bypassByteAllocCounter += 8; } _bypassByteAllocCounter--; if (--_bypassBitIdx < 0) { _bypassPtr--; _bypassBitIdx = 7; } *_bypassPtr = (*_bypassPtr << 1) | bit; } //----------------------------------------------------------------------------- inline void ChunkStreamBuilder::flush() { if (!_chunkBase) return; // if nothing has been written to the chunk, remove it if (_chunkBytesRemaining == kChunkSize - 1) { _outputLength -= kChunkSize; return; } finaliseChunk(); // if it isn't a full chunk, truncate _outputLength -= _chunkBytesRemaining; } //----------------------------------------------------------------------------- // Ensures that there is space to write a byte in the chunk. If not, // the current chunk is finalised and starts the next. inline void ChunkStreamBuilder::reserveChunkByte() { if (--_chunkBytesRemaining >= 0) return; // _chunkBytesRemaning is negative: set to zero (since there are none left) _chunkBytesRemaining = 0; finaliseChunk(); startNextChunk(); // reserve a byte from the chunk _chunkBytesRemaining--; } //----------------------------------------------------------------------------- inline void ChunkStreamBuilder::finaliseChunk() { int chunk_num_ae_bytes = _aecPtr - _chunkBase - 1; int bypassLen = kChunkSize - _chunkBytesRemaining - chunk_num_ae_bytes - 1; if (bypassLen) { // the number of padding bits (less the symtax element size) int chunk_bypass_num_flushed_bits = _bypassBitIdx - 3; // first, add padding bits to current partial byte *_bypassPtr <<= _bypassBitIdx; // there may be an extra byte at the end if last byte occupancy > 5 if (chunk_bypass_num_flushed_bits < 0) { *--_bypassPtr = 0; chunk_bypass_num_flushed_bits += 8; } *_bypassPtr |= uint8_t(chunk_bypass_num_flushed_bits); if (_chunkBytesRemaining) std::move( _bypassPtr, _chunkBase + kChunkSize, _chunkBase + chunk_num_ae_bytes + 1); } // write out the length of the aec data _chunkBase[0] = uint8_t(chunk_num_ae_bytes); } //----------------------------------------------------------------------------- inline void ChunkStreamBuilder::startNextChunk() { // start a new chunk if (_outputSizeRemaining < kChunkSize) throw std::runtime_error("Chunk buffer overflow"); // NB: reserves one byte for the aec length _chunkBytesRemaining = kChunkSize - 1; _chunkBase += kChunkSize; _aecPtr = _chunkBase + 1; _bypassPtr = _chunkBase + kChunkSize - 1; _bypassBitIdx = 8; _bypassByteAllocCounter = -3; _outputSizeRemaining -= kChunkSize; _outputLength += kChunkSize; } //============================================================================= class ChunkStreamReader { public: ChunkStreamReader(const ChunkStreamReader&) = delete; ChunkStreamReader(ChunkStreamReader&&) = delete; ChunkStreamReader& operator=(const ChunkStreamReader&) = delete; ChunkStreamReader& operator=(ChunkStreamReader&&) = delete; ChunkStreamReader() : _end(nullptr) , _aecBytesRemaining(0) , _aecNextChunk(nullptr) , _bypassNextChunk(nullptr) , _bypassAccumBitsRemaining(0) , _bypassBitsRemaining(0) {} ChunkStreamReader(uint8_t* buf, size_t size) { reset(buf, size); } void reset(const uint8_t* buf, size_t len); // Flush the current chunk and realign with the next stream in the input. void nextStream(); uint8_t readAecByte(); bool readBypassBit(); private: static const int kChunkSize = 256; // the limit of the buffer. Used for error checking const uint8_t* _end; // state for the aec substream int _aecBytesRemaining; const uint8_t* _aecByte; const uint8_t* _aecNextChunk; // state for the bypass substream const uint8_t* _bypassNextChunk; const uint8_t* _bypassByte; int _bypassAccumBitsRemaining; int _bypassBitsRemaining; uint8_t _bypassAccum; }; //============================================================================= inline void ChunkStreamReader::reset(const uint8_t* buf, size_t size) { _end = buf + size; _aecBytesRemaining = 0; _aecByte = nullptr; _aecNextChunk = buf; _bypassNextChunk = buf; _bypassByte = nullptr; _bypassAccumBitsRemaining = 0; _bypassBitsRemaining = 0; } //----------------------------------------------------------------------------- inline uint8_t ChunkStreamReader::readAecByte() { if (_aecBytesRemaining-- > 0) return *_aecByte++; const uint8_t* ptr = _aecNextChunk; int chunk_num_ae_bytes = 0; while (ptr < _end && !(chunk_num_ae_bytes = *ptr)) ptr += kChunkSize; if (ptr + chunk_num_ae_bytes >= _end) return 0xff; //throw std::runtime_error("aec buffer exceeded"); _aecNextChunk = ptr + kChunkSize; _aecByte = ptr + 1; _aecBytesRemaining = chunk_num_ae_bytes; _aecBytesRemaining--; return *_aecByte++; } //----------------------------------------------------------------------------- inline bool ChunkStreamReader::readBypassBit() { // extract bit from accumulator if (_bypassAccumBitsRemaining-- > 0) { int bit = !!(_bypassAccum & 0x80); _bypassAccum <<= 1; return bit; } // try to refil accumulator _bypassBitsRemaining -= 8; if (_bypassBitsRemaining > 0) { _bypassAccum = *_bypassByte--; _bypassAccumBitsRemaining = std::min(_bypassBitsRemaining, 8); return readBypassBit(); } // at end of current chunk, find next with bypass data const uint8_t* ptr = _bypassNextChunk; int chunk_num_ae_bytes = 0; while (ptr < _end && (chunk_num_ae_bytes = *ptr) == kChunkSize - 1) ptr += kChunkSize; // the last chunk may be truncated int chunkSize = kChunkSize; chunkSize = std::max(0, std::min(int(_end - ptr), chunkSize)); if (ptr + chunkSize - 1 >= _end) throw std::runtime_error("bypass buffer exceeded"); int chunk_bypass_num_flushed_bits = ptr[chunk_num_ae_bytes + 1] & 0x7; _bypassNextChunk = ptr + kChunkSize; _bypassByte = ptr + chunkSize - 1; _bypassAccum = *_bypassByte--; _bypassBitsRemaining = 8 * (chunkSize - chunk_num_ae_bytes) - chunk_bypass_num_flushed_bits - 11; _bypassAccumBitsRemaining = std::min(_bypassBitsRemaining, 8); return readBypassBit(); } //----------------------------------------------------------------------------- inline void ChunkStreamReader::nextStream() { // In the current figure, stream A is being parsed: // <----Stream A---->|<-Stream B ... // |--------|yyybbbxx|bbbbb|----- // Where, x is bypass data, y is aec data, and b is data from stream B. // // When switching to stream B, the the 'b' bytes from stream B that // appear in the last chunk of A must be realigned to B (ie, xx is removed). // The current chunk is the chunk containing the last AEC byte read // NB: it is guaranteed that there is at least one AEC byte in the last // chunk of A (since the AEC data is flushed after the bypass). assert(_bypassNextChunk <= _aecNextChunk); auto chunk = const_cast<uint8_t*>(_aecNextChunk) - kChunkSize; auto chunkAecLen = *chunk; // If there is no bypass data in the final aec chunk of A, everything is // already aligned: // |--------|yyybbbbb|bbbbb|----- if (_bypassNextChunk < _aecNextChunk) { auto next = chunk + 1 + chunkAecLen; reset(next, _end - next); return; } // Consume the end of the bypass stream. The last byte contains syntax elmt // chunk_bypass_num_flushed_bits. If more than five bits of the last byte // have been read, the last byte is the next byte. if (_bypassAccumBitsRemaining < 3) _bypassByte--; _bypassAccumBitsRemaining = 0; // |yyybbbxx| // chunk ^ | | | // chunkBp ^ | | // _bypassByte ^ | // chunkEnd ^ auto chunkEnd = std::min(chunk + kChunkSize, const_cast<uint8_t*>(_end)); auto chunkBp = chunk + chunkAecLen + 1; auto padLen = _bypassByte - chunkBp + 1; std::move_backward(chunkBp, const_cast<uint8_t*>(_bypassByte) + 1, chunkEnd); auto next = chunkEnd - padLen; reset(next, _end - next); } //============================================================================= // Since the start of the bypass data in an entropy chunk is aligned to the // end of the chunk (its written backwards), when a truncated chunk stream (ie // not multiple of 256 bytes) is concatenated with another stream, the // position of the bypass data is unknowable without a pointer. To avoid // this, the bypass data in the last chunk is moved to its expected location. // <-Stream A---->|<-Stream B ... // |--------|yyyxx|bbbbbbbb|----- // ^ expected end of A (xx) // Move xx to expected location: // |--------|yyybbbxx|bbbbb|----- inline void ChunkStreamBuilder::spliceChunkStreams( uint8_t* chunkA, uint8_t* chunkB, uint8_t* end) { auto chunkLen = chunkB - chunkA; // If the last chunk isn't truncated, there is nothing to do if (chunkLen == kChunkSize) return; // --------|yyyxx|bbbbbbbb|----- // chunkA ^ | // chunkB ^ // chunkAbp ^ // Save the bypass data in the last chunk of A int chunkAecLen = uint8_t(*chunkA); auto* chunkAbp = chunkA + 1 + chunkAecLen; auto chunkAbpLen = chunkB - chunkAbp; if (!chunkAbpLen) return; uint8_t tmpBuf[256]; std::copy_n(chunkAbp, chunkAbpLen, tmpBuf); // the amount by which to pad A with data from B // NB: this takes into account that B, at the end of the stream, is not // large enough to fill A. auto expectedChunkLen = std::min(ptrdiff_t(256), end - chunkA); auto padLen = expectedChunkLen - chunkLen; // Move initial part of stream B backwards, // Copy the saved bypass data to correct location std::move(chunkB, chunkB + padLen, chunkAbp); std::copy_n(tmpBuf, chunkAbpLen, chunkAbp + padLen); } //============================================================================= } // namespace pcc
14,508
29.164241
79
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/entropydirac.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include "dependencies/schroedinger/schroarith.h" #include "entropychunk.h" #include <algorithm> #include <assert.h> #include <stdlib.h> #include <algorithm> #include <memory> #include <vector> namespace pcc { namespace dirac { //========================================================================== struct SchroContext { uint16_t probability = 0x8000; // p=0.5 template<class... Args> void reset(Args...) { probability = 0x8000; } }; //-------------------------------------------------------------------------- // The approximate (7 bit) probability of a symbol being 1 or 0 according // to a context model. inline int approxSymbolProbability(int bit, SchroContext& model) { int p = std::max(1, model.probability >> 9); return bit ? 128 - p : p; } //========================================================================== struct SchroContextFixed { //uint16_t probability = 0x8000; // p=0.5 }; //========================================================================== // context definition that automatically binarises an m-ary symbol struct SchroMAryContext { SchroMAryContext() = default; SchroMAryContext(int numsyms) { set_alphabet(numsyms); } void set_alphabet(int numsyms); int numsyms; std::vector<uint16_t> probabilities; }; //========================================================================== struct InvalidContext { void set_alphabet(int) {} }; //========================================================================== class ArithmeticEncoder { public: ArithmeticEncoder() = default; ArithmeticEncoder(size_t bufferSize, std::nullptr_t) { setBuffer(bufferSize, nullptr); } //------------------------------------------------------------------------ void setBuffer(size_t size, uint8_t* buffer) { _bufSize = size; if (buffer) _buf = _bufWr = buffer; else { allocatedBuffer.reset(new uint8_t[size]); _buf = _bufWr = allocatedBuffer.get(); } } //------------------------------------------------------------------------ void enableBypassStream(bool cabac_bypass_stream_enabled_flag) { _cabac_bypass_stream_enabled_flag = cabac_bypass_stream_enabled_flag; } //------------------------------------------------------------------------ void start() { if (!_cabac_bypass_stream_enabled_flag) schro_arith_encode_init(&impl, &writeByteCallback, this); else { _chunkStream.reset(_bufWr, _bufSize); schro_arith_encode_init(&impl, &writeChunkCallback, &_chunkStream); } } //------------------------------------------------------------------------ size_t stop() { schro_arith_flush(&impl); if (_cabac_bypass_stream_enabled_flag) { _chunkStream.flush(); return _chunkStream.size(); } return _bufWr - _buf; } //------------------------------------------------------------------------ const char* buffer() { return reinterpret_cast<char*>(_buf); } //------------------------------------------------------------------------ void encode(int bit, SchroContextFixed&) { encode(bit); } //------------------------------------------------------------------------ void encode(int bit) { if (!_cabac_bypass_stream_enabled_flag) { uint16_t probability = 0x8000; // p=0.5 schro_arith_encode_bit(&impl, &probability, bit); return; } _chunkStream.writeBypassBit(bit); } //------------------------------------------------------------------------ void encode(int data, SchroMAryContext& model); //------------------------------------------------------------------------ void encode(int data, InvalidContext& model) { assert(0); } void encode(int bit, SchroContext& model) { schro_arith_encode_bit(&impl, &model.probability, bit); } //------------------------------------------------------------------------ private: static void writeByteCallback(uint8_t byte, void* thisptr) { auto _this = reinterpret_cast<ArithmeticEncoder*>(thisptr); if (_this->_bufSize == 0) throw std::runtime_error("Aec stream overflow"); _this->_bufSize--; *_this->_bufWr++ = byte; } //------------------------------------------------------------------------ static void writeChunkCallback(uint8_t byte, void* thisptr) { auto _this = reinterpret_cast<ChunkStreamBuilder*>(thisptr); _this->writeAecByte(byte); } //------------------------------------------------------------------------ private: ::SchroArith impl; uint8_t* _buf; uint8_t* _bufWr; size_t _bufSize; std::unique_ptr<uint8_t[]> allocatedBuffer; // Controls entropy coding method for bypass bins bool _cabac_bypass_stream_enabled_flag = false; ChunkStreamBuilder _chunkStream; }; //========================================================================== class ArithmeticDecoder { public: void setBuffer(size_t size, const char* buffer) { _buffer = reinterpret_cast<const uint8_t*>(buffer); _bufferLen = size; } //------------------------------------------------------------------------ void enableBypassStream(bool cabac_bypass_stream_enabled_flag) { _cabac_bypass_stream_enabled_flag = cabac_bypass_stream_enabled_flag; } //------------------------------------------------------------------------ void start() { if (_cabac_bypass_stream_enabled_flag) { _chunkReader.reset(_buffer, _bufferLen); schro_arith_decode_init(&impl, &readChunkCallback, &_chunkReader); } else { schro_arith_decode_init(&impl, &readByteCallback, this); } } //------------------------------------------------------------------------ void stop() { schro_arith_decode_flush(&impl); } //------------------------------------------------------------------------ // Terminate the arithmetic decoder, and reinitialise to start decoding // the next entropy stream. void flushAndRestart() { stop(); if (_cabac_bypass_stream_enabled_flag) { _chunkReader.nextStream(); schro_arith_decode_init(&impl, &readChunkCallback, &_chunkReader); } else { schro_arith_decode_init(&impl, &readByteCallback, this); } } //------------------------------------------------------------------------ int decode(SchroContextFixed&) { return decode(); } //------------------------------------------------------------------------ int decode() { if (!_cabac_bypass_stream_enabled_flag) { uint16_t probability = 0x8000; // p=0.5 return schro_arith_decode_bit(&impl, &probability); } return _chunkReader.readBypassBit(); } //------------------------------------------------------------------------ int decode(SchroMAryContext& model); //------------------------------------------------------------------------ int decode(InvalidContext& model) { assert(0); return 0; } //------------------------------------------------------------------------ int decode(SchroContext& model) { return schro_arith_decode_bit(&impl, &model.probability); } //------------------------------------------------------------------------ private: static uint8_t readByteCallback(void* thisptr) { auto _this = reinterpret_cast<ArithmeticDecoder*>(thisptr); if (!_this->_bufferLen) return 0xff; _this->_bufferLen--; return *_this->_buffer++; } //------------------------------------------------------------------------ static uint8_t readChunkCallback(void* thisptr) { auto _this = reinterpret_cast<ChunkStreamReader*>(thisptr); return _this->readAecByte(); } //------------------------------------------------------------------------ private: ::SchroArith impl; // the user supplied buffer. const uint8_t* _buffer; // the length of the user supplied buffer size_t _bufferLen; // Controls entropy coding method for bypass bins bool _cabac_bypass_stream_enabled_flag = false; // Parser for chunked bypass stream representation ChunkStreamReader _chunkReader; }; //========================================================================== } // namespace dirac using StaticBitModel = dirac::SchroContextFixed; using StaticMAryModel = dirac::InvalidContext; using AdaptiveBitModel = dirac::SchroContext; using AdaptiveBitModelFast = dirac::SchroContext; using AdaptiveMAryModel = dirac::SchroMAryContext; //============================================================================ } // namespace pcc
10,757
29.304225
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/entropyutils.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <algorithm> #include <stddef.h> namespace pcc { //============================================================================ // :: Entropy codec interface (Encoder) // // The base class must implement the following methods: // - void setBuffer(size_t size, const uint8_t *buffer); // - void start(); // - size_t stop(); // - void encode(int symbol, StaticBitModel&); // - void encode(int symbol, StaticMAryModel&); // - void encode(int symbol, AdaptiveBitModel&); // - void encode(int symbol, AdaptiveBitModelFast&); // - void encode(int symbol, AdaptiveMAryModel&); template<class Base> class EntropyEncoderWrapper : protected Base { public: using Base::Base; using Base::buffer; using Base::enableBypassStream; using Base::encode; using Base::setBuffer; using Base::start; using Base::stop; //-------------------------------------------------------------------------- // :: encoding / common binarisation methods void encodeExpGolomb(unsigned int symbol, int k, AdaptiveBitModel& bModel1); template<size_t NumPrefixCtx, size_t NumSuffixCtx> void encodeExpGolomb( unsigned int symbol, int k, AdaptiveBitModel (&ctxPrefix)[NumPrefixCtx], AdaptiveBitModel (&ctxSuffix)[NumSuffixCtx]); }; //============================================================================ // :: Entropy codec interface (Decoder) // // The base class must implement the following methods: // - void setBuffer(size_t size, const uint8_t *buffer); // - void start(); // - void stop(); // - int decode(StaticBitModel&); // - int decode(StaticMAryModel&); // - int decode(AdaptiveBitModel&); // - int decode(AdaptiveBitModelFast&); // - int decode(AdaptiveMAryModel&); template<class Base> class EntropyDecoderWrapper : protected Base { public: EntropyDecoderWrapper() : Base() {} using Base::decode; using Base::enableBypassStream; using Base::flushAndRestart; using Base::setBuffer; using Base::start; using Base::stop; //-------------------------------------------------------------------------- // :: encoding / common binarisation methods unsigned int decodeExpGolomb(int k, AdaptiveBitModel& bModel1); template<size_t NumPrefixCtx, size_t NumSuffixCtx> unsigned int decodeExpGolomb( int k, AdaptiveBitModel (&ctxPrefix)[NumPrefixCtx], AdaptiveBitModel (&ctxSuffix)[NumSuffixCtx]); }; //============================================================================ // :: Various binarisation forms inline unsigned long IntToUInt(long value) { return (value < 0) ? static_cast<unsigned long>(-1 - (2 * value)) : static_cast<unsigned long>(2 * value); } //---------------------------------------------------------------------------- inline long UIntToInt(unsigned long uiValue) { return (uiValue & 1) ? -(static_cast<long>((uiValue + 1) >> 1)) : (static_cast<long>(uiValue >> 1)); } //---------------------------------------------------------------------------- template<class Base> inline void EntropyEncoderWrapper<Base>::encodeExpGolomb( unsigned int symbol, int k, AdaptiveBitModel& ctxPrefix) { while (1) { if (symbol >= (1u << k)) { encode(1, ctxPrefix); symbol -= (1u << k); k++; } else { encode(0, ctxPrefix); while (k--) encode((symbol >> k) & 1); break; } } } //---------------------------------------------------------------------------- template<class Base> template<size_t NumPrefixCtx, size_t NumSuffixCtx> inline void EntropyEncoderWrapper<Base>::encodeExpGolomb( unsigned int symbol, int k, AdaptiveBitModel (&ctxPrefix)[NumPrefixCtx], AdaptiveBitModel (&ctxSuffix)[NumSuffixCtx]) { constexpr int maxPrefixIdx = NumPrefixCtx - 1; constexpr int maxSuffixIdx = NumSuffixCtx - 1; const int k0 = k; while (symbol >= (1u << k)) { encode(1, ctxPrefix[std::min(maxPrefixIdx, k - k0)]); symbol -= 1u << k; k++; } encode(0, ctxPrefix[std::min(maxPrefixIdx, k - k0)]); while (k--) encode((symbol >> k) & 1, ctxSuffix[std::min(maxSuffixIdx, k)]); } //---------------------------------------------------------------------------- template<class Base> inline unsigned int EntropyDecoderWrapper<Base>::decodeExpGolomb( int k, AdaptiveBitModel& ctxPrefix) { unsigned int l; int symbol = 0; int binary_symbol = 0; do { l = decode(ctxPrefix); if (l == 1) { symbol += (1 << k); k++; } } while (l != 0); while (k--) //next binary part if (decode() == 1) { binary_symbol |= (1 << k); } return static_cast<unsigned int>(symbol + binary_symbol); } //---------------------------------------------------------------------------- template<class Base> template<size_t NumPrefixCtx, size_t NumSuffixCtx> inline unsigned int EntropyDecoderWrapper<Base>::decodeExpGolomb( int k, AdaptiveBitModel (&ctxPrefix)[NumPrefixCtx], AdaptiveBitModel (&ctxSuffix)[NumSuffixCtx]) { constexpr int maxPrefixIdx = NumPrefixCtx - 1; constexpr int maxSuffixIdx = NumSuffixCtx - 1; const int k0 = k; unsigned int l; int symbol = 0; int binary_symbol = 0; do { l = decode(ctxPrefix[std::min(maxPrefixIdx, k - k0)]); if (l == 1) { symbol += (1 << k); k++; } } while (l != 0); while (k--) binary_symbol |= decode(ctxSuffix[std::min(maxSuffixIdx, k)]) << k; return static_cast<unsigned int>(symbol + binary_symbol); } //============================================================================ } // namespace pcc
7,386
29.651452
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/frame.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2021, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <vector> #include "PCCMath.h" #include "PCCPointSet.h" #include "hls.h" namespace pcc { //============================================================================ // Represents a frame in the encoder or decoder. struct CloudFrame { // The value of the decoder's reconstructed FrameCtr for this frame. int frameNum; // Defines the ordering of the position components (eg, xyz vs zyx) AxisOrder geometry_axis_order; // The length of the output cloud's unit vector. // The units of outputUnitLength is given by outputUnit. // // When outputUnit is ScaleUnit::kMetres, outputUnitLength is // measured in metres. // // When outputUnit is ScaleUnit::kDimensionless, outputUnitLength is // measured in units of an external coordinate system. double outputUnitLength; // The unit of the output cloud's unit vector ScaleUnit outputUnit; // The origin of the output cloud // NB: this respects geometry_axis_order. Vec3<int> outputOrigin; // Number of fractional bits in representaiton of cloud.positions. int outputFpBits; // Descriptions of each attribute. Attribute parameters in the description // are only applicable to this frame -- they may change in a subsequent frame std::vector<AttributeDescription> attrDesc; // The output point cloud. The coordinate system is defined by the // other parameters in this structure. // NB: Point positions respect geometry_axis_order. PCCPointSet3 cloud; // Determines parameters according to the sps. void setParametersFrom(const SequenceParameterSet& sps, int fixedPointBits); }; //============================================================================ // Scale point cloud geometry by global scale factor void scaleGeometry( PCCPointSet3& cloud, const SequenceParameterSet::GlobalScale& globalScale, int fixedPointFracBits); //============================================================================ } // namespace pcc
3,800
37.01
79
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/framectr.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2021, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ namespace pcc { //============================================================================ // A free-running frame counter, synchronised by updates class FrameCtr { public: operator int() const { return _frameCtr; } // Update the frame counter using the current value of frame_ctr_lsb. void update(int frame_ctr_lsb, int frame_ctr_lsb_bits); // Query whether frame_ctr_lsb does not match the current frame counter. bool isDifferentFrame(int frame_ctr_lsb, int frame_ctr_lsb_bits) const { return frame_ctr_lsb != (_frameCtr & ((1 << frame_ctr_lsb_bits) - 1)); } private: // The reconstructed frame counter value. int _frameCtr = 0; }; //---------------------------------------------------------------------------- inline void FrameCtr::update(int frame_ctr_lsb, int frame_ctr_lsb_bits) { int window = (1 << frame_ctr_lsb_bits) >> 1; int curLsb = unsigned(_frameCtr) & ((1 << frame_ctr_lsb_bits) - 1); int curMsb = unsigned(_frameCtr) >> frame_ctr_lsb_bits; if (frame_ctr_lsb < curLsb && curLsb - frame_ctr_lsb >= window) curMsb++; else if (frame_ctr_lsb > curLsb && frame_ctr_lsb - curLsb > window) curMsb--; _frameCtr = (curMsb << frame_ctr_lsb_bits) + frame_ctr_lsb; } //============================================================================ } // namespace pcc
3,146
38.835443
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/geometry.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <memory> #include <vector> #include "PCCPointSet.h" #include "geometry_params.h" #include "entropy.h" #include "hls.h" #include "partitioning.h" namespace pcc { //============================================================================ struct GeometryOctreeContexts; struct PredGeomContexts; //============================================================================ void encodeGeometryOctree( const OctreeEncOpts& opt, const GeometryParameterSet& gps, GeometryBrickHeader& gbh, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, std::vector<std::unique_ptr<EntropyEncoder>>& arithmeticEncoder); void decodeGeometryOctree( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, EntropyDecoder& arithmeticDecoder); void decodeGeometryOctreeScalable( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, int minGeomNodeSizeLog2, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, EntropyDecoder& arithmeticDecoder); //---------------------------------------------------------------------------- void encodeGeometryTrisoup( const OctreeEncOpts& opt, const GeometryParameterSet& gps, GeometryBrickHeader& gbh, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, std::vector<std::unique_ptr<EntropyEncoder>>& arithmeticEncoder); void decodeGeometryTrisoup( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, EntropyDecoder& arithmeticDecoder); //---------------------------------------------------------------------------- void encodePredictiveGeometry( const PredGeomEncOpts& opt, const GeometryParameterSet& gps, GeometryBrickHeader& gbh, PCCPointSet3& pointCloud, std::vector<Vec3<int32_t>>* reconPosSph, PredGeomContexts& ctxtMem, EntropyEncoder* arithmeticEncoder); void decodePredictiveGeometry( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, PCCPointSet3& pointCloud, std::vector<Vec3<int32_t>>* reconPosSph, PredGeomContexts& ctxtMem, EntropyDecoder& arithmeticDecoder); //============================================================================ } // namespace pcc
4,122
33.940678
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/geometry_intra_pred.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> #include "OctreeNeighMap.h" #include "PCCMath.h" namespace pcc { //============================================================================ void predictGeometryOccupancyIntra( const MortonMap3D& occupancyAtlas, Vec3<int32_t> pos, const int atlasShift, int* occupacyIsPredIntra, int* occupacyPredIntra); //============================================================================ } // namespace pcc
2,280
39.017544
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/geometry_octree.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> #include "DualLutCoder.h" #include "PCCMath.h" #include "PCCPointSet.h" #include "entropy.h" #include "geometry_params.h" #include "hls.h" #include "quantization.h" #include "ringbuf.h" #include "tables.h" namespace pcc { //============================================================================ const int MAX_NUM_DM_LEAF_POINTS = 2; //============================================================================ struct PCCOctree3Node { // 3D position of the current node's origin (local x,y,z = 0). Vec3<int32_t> pos; // Range of point indexes spanned by node uint32_t start; uint32_t end; // The current node's number of siblings plus one. // ie, the number of child nodes present in this node's parent. uint8_t numSiblingsPlus1; // The occupancy map used describing the current node and its siblings. uint8_t siblingOccupancy; // Indicatest hat the current node qualifies for IDCM bool idcmEligible; // The qp used for geometry quantisation. // NB: this qp value always uses a step size doubling interval of 8 qps int8_t qp; // angular uint8_t laserIndex = 255; }; //============================================================================ struct OctreeNodePlanar { // planar; first bit for x, second bit for y, third bit for z uint8_t planarPossible = 7; uint8_t planePosBits = 0; uint8_t planarMode = 0; }; //--------------------------------------------------------------------------- int neighPatternFromOccupancy(int pos, int occupancy); //--------------------------------------------------------------------------- uint8_t mapGeometryOccupancy(uint8_t occupancy, uint8_t neighPattern); uint8_t mapGeometryOccupancyInv(uint8_t occupancy, uint8_t neighPattern); //--------------------------------------------------------------------------- // Determine if a node is a leaf node based on size. // A node with all dimension = 0 is a leaf node. // NB: some dimensions may be less than zero if coding of that dimension // has already terminated. inline bool isLeafNode(const Vec3<int>& sizeLog2) { return sizeLog2[0] <= 0 && sizeLog2[1] <= 0 && sizeLog2[2] <= 0; } //--------------------------------------------------------------------------- // Generates an idcm enable mask uint32_t mkIdcmEnableMask(const GeometryParameterSet& gps); //--------------------------------------------------------------------------- // Determine if direct coding is permitted. // If tool is enabled: // - Block must not be near the bottom of the tree // - The parent / grandparent are sparsely occupied inline bool isDirectModeEligible( int intensity, int nodeSizeLog2, int nodeNeighPattern, const PCCOctree3Node& node, const PCCOctree3Node& child) { if (!intensity) return false; if (intensity == 1) return (nodeSizeLog2 >= 2) && (nodeNeighPattern == 0) && (child.numSiblingsPlus1 == 1) && (node.numSiblingsPlus1 <= 2); if (intensity == 2) return (nodeSizeLog2 >= 2) && (nodeNeighPattern == 0); // This is basically unconditionally enabled. // If a node is that is IDCM-eligible is not coded with IDCM and has only // one child, then it is likely that the child would also not be able to // be coded with IDCM (eg, it still contains > 2 unique points). if (intensity == 3) return (nodeSizeLog2 >= 2) && (child.numSiblingsPlus1 > 1); return false; } //--------------------------------------------------------------------------- // Select the neighbour pattern reduction table according to GPS config. inline const uint8_t* neighPattern64toR1(const GeometryParameterSet& gps) { if (gps.neighbour_avail_boundary_log2_minus1 > 0) return kNeighPattern64to9; return kNeighPattern64to6; } //--------------------------------------------------------------------------- struct CtxModelOctreeOccupancy { AdaptiveBitModelFast contexts[256]; static const int kCtxFactorShift = 3; AdaptiveBitModelFast& operator[](int idx) { return contexts[idx >> kCtxFactorShift]; } }; //--------------------------------------------------------------------------- // Encapsulates the derivation of ctxIdx for occupancy coding. class CtxMapOctreeOccupancy { public: struct CtxIdxMap { uint8_t b0[9]; uint8_t b1[18]; uint8_t b2[35]; uint8_t b3[68]; uint8_t b4[69]; uint8_t b5[134]; uint8_t b6[135]; uint8_t b7[136]; }; CtxMapOctreeOccupancy(); CtxMapOctreeOccupancy(const CtxMapOctreeOccupancy&); CtxMapOctreeOccupancy(CtxMapOctreeOccupancy&&); CtxMapOctreeOccupancy& operator=(const CtxMapOctreeOccupancy&); CtxMapOctreeOccupancy& operator=(CtxMapOctreeOccupancy&&); const uint8_t* operator[](int bit) const { return b[bit]; } uint8_t* operator[](int bit) { return b[bit]; } // return *ctxIdx and update *ctxIdx according to bit static uint8_t evolve(bool bit, uint8_t* ctxIdx); private: std::unique_ptr<CtxIdxMap> map; std::array<uint8_t*, 8> b; }; //---------------------------------------------------------------------------- inline uint8_t CtxMapOctreeOccupancy::evolve(bool bit, uint8_t* ctxIdx) { uint8_t retval = *ctxIdx; if (bit) *ctxIdx += kCtxMapOctreeOccupancyDelta[(255 - *ctxIdx) >> 4]; else *ctxIdx -= kCtxMapOctreeOccupancyDelta[*ctxIdx >> 4]; return retval; } //--------------------------------------------------------------------------- // generate an array of node sizes according to subsequent qtbt decisions std::vector<Vec3<int>> mkQtBtNodeSizeList( const GeometryParameterSet& gps, const QtBtParameters& qtbt, const GeometryBrickHeader& gbh); //--------------------------------------------------------------------------- inline Vec3<int> qtBtChildSize(const Vec3<int>& nodeSizeLog2, const Vec3<int>& childSizeLog2) { Vec3<int> bitpos = 0; for (int k = 0; k < 3; k++) { if (childSizeLog2[k] != nodeSizeLog2[k]) bitpos[k] = 1 << childSizeLog2[k]; } return bitpos; } //--------------------------------------------------------------------------- inline int nonSplitQtBtAxes(const Vec3<int>& nodeSizeLog2, const Vec3<int>& childSizeLog2) { int indicator = 0; for (int k = 0; k < 3; k++) { indicator <<= 1; indicator |= nodeSizeLog2[k] == childSizeLog2[k]; } return indicator; } //============================================================================ // Scales quantized positions used internally in angular coding. // // NB: this is not used to scale output positions since generated positions // are not clipped to node boundaries. // // NB: there are two different position representations used in the codec: // ppppppssssss = original position // ppppppqqqq00 = pos, (quantisation) node size aligned -> use scaleNs() // 00ppppppqqqq = pos, effective node size aligned -> use scaleEns() // where p are unquantised bits, q are quantised bits, and 0 are zero bits. class OctreeAngPosScaler { QuantizerGeom _quant; Vec3<uint32_t> _mask; int _qp; public: OctreeAngPosScaler(int qp, const Vec3<uint32_t>& quantMaskBits) : _quant(qp), _qp(qp), _mask(quantMaskBits) {} // Scale an effectiveNodeSize aligned position as the k-th position component. int scaleEns(int k, int pos) const; // Scale an effectiveNodeSize aligned position. Vec3<int> scaleEns(Vec3<int> pos) const; // Scale a NodeSize aligned position. Vec3<int> scaleNs(Vec3<int> pos) const; }; //---------------------------------------------------------------------------- inline int OctreeAngPosScaler::scaleEns(int k, int pos) const { if (!_qp) return pos; int shiftBits = QuantizerGeom::qpShift(_qp); int lowPart = pos & (_mask[k] >> shiftBits); int highPart = pos ^ lowPart; int lowPartScaled = _quant.scale(lowPart); return (highPart << shiftBits) + lowPartScaled; } //---------------------------------------------------------------------------- inline Vec3<int32_t> OctreeAngPosScaler::scaleEns(Vec3<int32_t> pos) const { if (!_qp) return pos; for (int k = 0; k < 3; k++) pos[k] = scaleEns(k, pos[k]); return pos; } //---------------------------------------------------------------------------- inline Vec3<int32_t> OctreeAngPosScaler::scaleNs(Vec3<int32_t> pos) const { if (!_qp) return pos; // convert pos to effectiveNodeSize form return scaleEns(pos >> QuantizerGeom::qpShift(_qp)); } //============================================================================ class AzimuthalPhiZi { public: AzimuthalPhiZi(int numLasers, const std::vector<int>& numPhi) : _delta(numLasers), _invDelta(numLasers) { for (int laserIndex = 0; laserIndex < numLasers; laserIndex++) { constexpr int k2pi = 6588397; // 2**20 * 2 * pi _delta[laserIndex] = k2pi / numPhi[laserIndex]; _invDelta[laserIndex] = int64_t((int64_t(numPhi[laserIndex]) << 30) / k2pi); } } const int delta(size_t idx) const { return _delta[idx]; } const int64_t invDelta(size_t idx) const { return _invDelta[idx]; } private: std::vector<int> _delta; std::vector<int64_t> _invDelta; }; //============================================================================ struct OctreePlanarBuffer { static constexpr unsigned numBitsC = 14; static constexpr unsigned numBitsAb = 5; static constexpr unsigned rowSize = 1; static_assert(numBitsC >= 0 && numBitsC <= 32, "0 <= numBitsC <= 32"); static_assert(numBitsAb >= 0 && numBitsAb <= 32, "0 <= numBitsAb <= 32"); static_assert(rowSize > 0, "rowSize must be greater than 0"); static constexpr unsigned shiftAb = 3; static constexpr int maskAb = ((1 << numBitsAb) - 1) << shiftAb; static constexpr int maskC = (1 << numBitsC) - 1; #pragma pack(push) #pragma pack(1) struct Elmt { // maximum of two position components unsigned int pos : numBitsAb; // -2: not used, -1: not planar, 0: plane 0, 1: plane 1 int planeIdx : 2; }; #pragma pack(pop) typedef Elmt Row[rowSize]; OctreePlanarBuffer(); OctreePlanarBuffer(const OctreePlanarBuffer& rhs); OctreePlanarBuffer(OctreePlanarBuffer&& rhs); ~OctreePlanarBuffer(); OctreePlanarBuffer& operator=(const OctreePlanarBuffer& rhs); OctreePlanarBuffer& operator=(OctreePlanarBuffer&& rhs); void resize(Vec3<int> numBufferRows); void clear(); // Access to a particular buffer column (dimension) Row* getBuffer(int dim) { return _col[dim]; } private: // Backing storage for the underlying buffer std::vector<Elmt> _buf; // Base pointers for the first, second and third position components. std::array<Row*, 3> _col = {{nullptr, nullptr, nullptr}}; }; //============================================================================ struct OctreePlanarState { OctreePlanarState(const GeometryParameterSet&); OctreePlanarState(const OctreePlanarState&); OctreePlanarState(OctreePlanarState&&); OctreePlanarState& operator=(const OctreePlanarState&); OctreePlanarState& operator=(OctreePlanarState&&); bool _planarBufferEnabled; OctreePlanarBuffer _planarBuffer; std::array<int, 3> _rate{{128 * 8, 128 * 8, 128 * 8}}; int _localDensity = 1024 * 4; std::array<int, 3> _rateThreshold; void initPlanes(const Vec3<int>& planarDepth); void updateRate(int occupancy, int numSiblings); void isEligible(bool eligible[3]); }; // determine if a 222 block is planar void setPlanesFromOccupancy(int occupancy, OctreeNodePlanar& planar); int maskPlanarX(const OctreeNodePlanar& planar); int maskPlanarY(const OctreeNodePlanar& planar); int maskPlanarZ(const OctreeNodePlanar& planar); void maskPlanar(OctreeNodePlanar& planar, int mask[3], int codedAxes); int determineContextAngleForPlanar( PCCOctree3Node& node, const Vec3<int>& nodeSizeLog2, const Vec3<int>& angularOrigin, const int* zLaser, const int* thetaLaser, const int numLasers, int deltaAngle, const AzimuthalPhiZi& phiZi, int* phiBuffer, int* contextAnglePhiX, int* contextAnglePhiY, Vec3<uint32_t> quantMasks); //---------------------------------------------------------------------------- int findLaser(point_t point, const int* thetaList, const int numTheta); //============================================================================ class GeometryOctreeContexts { public: void reset(); protected: AdaptiveBitModel _ctxSingleChild; AdaptiveBitModel _ctxDupPointCntGt0; AdaptiveBitModel _ctxDupPointCntGt1; AdaptiveBitModel _ctxDupPointCntEgl; AdaptiveBitModel _ctxBlockSkipTh; AdaptiveBitModel _ctxNumIdcmPointsGt1; AdaptiveBitModel _ctxSameZ; // IDCM unordered AdaptiveBitModel _ctxSameBitHighx[5]; AdaptiveBitModel _ctxSameBitHighy[5]; AdaptiveBitModel _ctxSameBitHighz[5]; // residual laser index AdaptiveBitModel _ctxThetaRes[3]; AdaptiveBitModel _ctxThetaResSign; AdaptiveBitModel _ctxThetaResExp; AdaptiveBitModel _ctxQpOffsetAbsGt0; AdaptiveBitModel _ctxQpOffsetSign; AdaptiveBitModel _ctxQpOffsetAbsEgl; // for planar mode xyz AdaptiveBitModel _ctxPlanarMode[3]; AdaptiveBitModel _ctxPlanarPlaneLastIndex[3][3][4]; AdaptiveBitModel _ctxPlanarPlaneLastIndexZ[3]; AdaptiveBitModel _ctxPlanarPlaneLastIndexAngular[4]; AdaptiveBitModel _ctxPlanarPlaneLastIndexAngularIdcm[4]; AdaptiveBitModel _ctxPlanarPlaneLastIndexAngularPhi[8]; AdaptiveBitModel _ctxPlanarPlaneLastIndexAngularPhiIDCM[8]; // For bitwise occupancy coding CtxModelOctreeOccupancy _ctxOccupancy; CtxMapOctreeOccupancy _ctxIdxMaps[18]; // For bytewise occupancy coding DualLutCoder<true> _bytewiseOccupancyCoder[10]; }; //---------------------------------------------------------------------------- inline void GeometryOctreeContexts::reset() { this->~GeometryOctreeContexts(); new (this) GeometryOctreeContexts; } //============================================================================ // :: octree encoder exposing internal ringbuffer void encodeGeometryOctree( const OctreeEncOpts& opt, const GeometryParameterSet& gps, GeometryBrickHeader& gbh, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, std::vector<std::unique_ptr<EntropyEncoder>>& arithmeticEncoders, pcc::ringbuf<PCCOctree3Node>* nodesRemaining); void decodeGeometryOctree( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, int skipLastLayers, PCCPointSet3& pointCloud, GeometryOctreeContexts& ctxtMem, EntropyDecoder& arithmeticDecoder, pcc::ringbuf<PCCOctree3Node>* nodesRemaining); //============================================================================ } // namespace pcc
16,357
29.575701
80
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/geometry_params.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2020, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once namespace pcc { //============================================================================= struct QtBtParameters { // maximum number of qtbt partitions before performing octree partitioning. int maxNumQtBtBeforeOt; // minimum size of qtbt partitions. int minQtbtSizeLog2; bool trisoupEnabled; bool angularTweakEnabled; int angularMaxNodeMinDimLog2ToSplitV; int angularMaxDiffToSplitZ; }; //---------------------------------------------------------------------------- struct OctreeEncOpts { QtBtParameters qtbt; // Method used to derive in-tree quantisation parameters enum class QpMethod { kUniform = 0, kRandom = 1, kByDensity = 2, } qpMethod; // Tree depth at which to apply geometry quantisation int qpOffsetDepth; // Node size (rather than depth) at which to apply geometry quantisation int qpOffsetNodeSizeLog2; }; //============================================================================= struct PredGeomEncOpts { enum SortMode { kNoSort, kSortMorton, kSortAzimuth, kSortRadius, kSortLaserAngle } sortMode; // limit on number of points per tree int maxPtsPerTree; // Reciprocal bin width used in azimuthal sorting. // 0 => full precision float azimuthSortRecipBinWidth; }; //============================================================================= } // namespace pcc
3,227
31.606061
79
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/geometry_predictive.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2020, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cmath> #include <cstdint> #include "entropy.h" #include "PCCMath.h" #include "hls.h" namespace pcc { //============================================================================ struct GPredicter { enum Mode { None, Delta, Linear2, Linear3 }; int32_t index[3]; int pgeom_min_radius; bool isValid(Mode mode); Vec3<int32_t> predict(const Vec3<int32_t>* points, Mode mode, bool angular); }; //============================================================================ struct GNode { static const int32_t MaxChildrenCount = 3; int numDups; int32_t parent; int32_t childrenCount; int32_t children[MaxChildrenCount]; }; //============================================================================ class PredGeomContexts { public: void reset(); protected: AdaptiveBitModel _ctxNumChildren[3]; AdaptiveBitModel _ctxPredMode[3]; AdaptiveBitModel _ctxResGt0[3]; AdaptiveBitModel _ctxSign[3]; AdaptiveBitModel _ctxNumBits[5][3][31]; AdaptiveBitModel _ctxNumDupPointsGt0; AdaptiveBitModel _ctxNumDupPoints; AdaptiveBitModel _ctxResidual2GtN[2][3]; AdaptiveBitModel _ctxSign2[3]; AdaptiveBitModel _ctxEG2Prefix[3][5]; AdaptiveBitModel _ctxEG2Suffix[3][4]; AdaptiveBitModel _ctxQpOffsetAbsGt0; AdaptiveBitModel _ctxQpOffsetSign; AdaptiveBitModel _ctxQpOffsetAbsEgl; AdaptiveBitModel _ctxPhiGtN[2]; AdaptiveBitModel _ctxSignPhi; AdaptiveBitModel _ctxEGPhi; AdaptiveBitModel _ctxResidualPhi[7]; AdaptiveBitModel _ctxEndOfTrees; }; //---------------------------------------------------------------------------- inline void PredGeomContexts::reset() { this->~PredGeomContexts(); new (this) PredGeomContexts; } //============================================================================ template<typename LookupFn> GPredicter makePredicter( int32_t curNodeIdx, GPredicter::Mode mode, int minRadius, LookupFn nodeIdxToParentIdx) { if (mode == GPredicter::None) mode = GPredicter::Delta; GPredicter predIdx; predIdx.pgeom_min_radius = minRadius; switch (mode) { default: case GPredicter::None: case GPredicter::Delta: case GPredicter::Linear2: case GPredicter::Linear3: for (int i = 0; i < int(mode); i++) { if (curNodeIdx < 0) break; predIdx.index[i] = curNodeIdx = nodeIdxToParentIdx(curNodeIdx); } break; } return predIdx; } //============================================================================ inline bool GPredicter::isValid(GPredicter::Mode mode) { int numPredictors = int(mode); for (int i = 0; i < numPredictors; i++) { if (this->index[i] < 0) return false; } return true; } //============================================================================ inline Vec3<int32_t> GPredicter::predict( const Vec3<int32_t>* points, GPredicter::Mode mode, bool angular) { Vec3<int32_t> pred; switch (mode) { case GPredicter::None: { pred = 0; if (angular) pred[0] = pgeom_min_radius; if (this->index[0] >= 0 && angular) { const auto& p0 = points[this->index[0]]; pred[1] = p0[1]; pred[2] = p0[2]; } break; } case GPredicter::Delta: { pred = points[this->index[0]]; break; } case GPredicter::Linear2: { const auto& p0 = points[this->index[0]]; const auto& p1 = points[this->index[1]]; pred = 2 * p0 - p1; break; } default: case GPredicter::Linear3: { const auto& p0 = points[this->index[0]]; const auto& p1 = points[this->index[1]]; const auto& p2 = points[this->index[2]]; pred = p0 + p1 - p2; break; } } return pred; } //============================================================================ class SphericalToCartesian { public: SphericalToCartesian(const GeometryParameterSet& gps) : log2ScaleRadius(gps.geom_angular_radius_inv_scale_log2) , log2ScalePhi(gps.geom_angular_azimuth_scale_log2_minus11 + 12) , tanThetaLaser(gps.angularTheta.data()) , zLaser(gps.angularZ.data()) {} Vec3<int32_t> operator()(Vec3<int32_t> sph) { int64_t r = sph[0] << log2ScaleRadius; int64_t z = divExp2RoundHalfInf( tanThetaLaser[sph[2]] * r << 2, log2ScaleTheta - log2ScaleZ); return Vec3<int32_t>(Vec3<int64_t>{ divExp2RoundHalfInf(r * icos(sph[1], log2ScalePhi), kLog2ISineScale), divExp2RoundHalfInf(r * isin(sph[1], log2ScalePhi), kLog2ISineScale), divExp2RoundHalfInf(z - zLaser[sph[2]], log2ScaleZ)}); } private: static constexpr int log2ScaleZ = 3; static constexpr int log2ScaleTheta = 20; int log2ScaleRadius; int log2ScalePhi; const int* tanThetaLaser; const int* zLaser; }; //============================================================================ class CartesianToSpherical { public: CartesianToSpherical(const GeometryParameterSet& gps) : sphToCartesian(gps) , log2ScaleRadius(gps.geom_angular_radius_inv_scale_log2) , scalePhi(1 << (gps.geom_angular_azimuth_scale_log2_minus11 + 12)) , numLasers(gps.angularTheta.size()) , tanThetaLaser(gps.angularTheta.data()) , zLaser(gps.angularZ.data()) {} Vec3<int32_t> operator()(Vec3<int32_t> xyz) { int64_t r0 = int64_t(std::round(hypot(xyz[0], xyz[1]))); int32_t thetaIdx = 0; int32_t minError = std::numeric_limits<int32_t>::max(); for (int idx = 0; idx < numLasers; ++idx) { int64_t z = divExp2RoundHalfInf( tanThetaLaser[idx] * r0 << 2, log2ScaleTheta - log2ScaleZ); int64_t z1 = divExp2RoundHalfInf(z - zLaser[idx], log2ScaleZ); int32_t err = abs(z1 - xyz[2]); if (err < minError) { thetaIdx = idx; minError = err; } } auto phi0 = std::round((atan2(xyz[1], xyz[0]) / (2.0 * M_PI)) * scalePhi); Vec3<int32_t> sphPos{int32_t(divExp2RoundHalfUp(r0, log2ScaleRadius)), int32_t(phi0), thetaIdx}; // local optmization auto minErr = (sphToCartesian(sphPos) - xyz).getNorm1(); int32_t dt0 = 0; int32_t dr0 = 0; for (int32_t dt = -2; dt <= 2 && minErr; ++dt) { for (int32_t dr = -2; dr <= 2; ++dr) { auto sphPosCand = sphPos + Vec3<int32_t>{dr, dt, 0}; auto err = (sphToCartesian(sphPosCand) - xyz).getNorm1(); if (err < minErr) { minErr = err; dt0 = dt; dr0 = dr; } } } sphPos[0] += dr0; sphPos[1] += dt0; return sphPos; } private: SphericalToCartesian sphToCartesian; static constexpr int32_t log2ScaleZ = 3; static constexpr int32_t log2ScaleTheta = 20; int32_t log2ScaleRadius; int32_t scalePhi; int numLasers; const int* tanThetaLaser; const int* zLaser; }; //============================================================================ } // namespace pcc
8,622
26.816129
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/geometry_trisoup.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> #include <vector> #include "PCCPointSet.h" #include "geometry_octree.h" #include "ringbuf.h" namespace pcc { //============================================================================ void determineTrisoupVertices( const ringbuf<PCCOctree3Node>& leaves, std::vector<bool>& segind, std::vector<uint8_t>& vertices, const PCCPointSet3& pointCloud, const int defaultBlockWidth); void decodeTrisoupCommon( const ringbuf<PCCOctree3Node>& leaves, const std::vector<bool>& segind, const std::vector<uint8_t>& vertices, PCCPointSet3& pointCloud, int defaultBlockWidth, int poistionClipValue, uint32_t samplingValue); //============================================================================ struct TrisoupSegment { Vec3<int32_t> startpos; // start point of edge segment Vec3<int32_t> endpos; // end point of edge segment int index; // index of segment, to reorder after sorting int uniqueIndex; // index of uniqueSegment int vertex; // distance along segment for intersection (else -1) }; struct TrisoupSegmentEnc : public TrisoupSegment { TrisoupSegmentEnc( const Vec3<int32_t>& startpos, const Vec3<int32_t>& endpos, int index, int uniqueIndex, int vertex, int count, int distanceSum) : TrisoupSegment{startpos, endpos, index, uniqueIndex, vertex} , count(count) , distanceSum(distanceSum) {} int count; // count of voxels adjacent to this segment int distanceSum; // sum of distances (along segment) of adjacent voxels }; //---------------------------------------------------------------------------- // comparison for sorting bool operator<(const TrisoupSegment& s1, const TrisoupSegment& s2); //============================================================================ } // namespace pcc
3,677
35.058824
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/io_hls.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include "PayloadBuffer.h" #include "hls.h" namespace pcc { //============================================================================ PayloadBuffer write(const SequenceParameterSet& sps); PayloadBuffer write(const SequenceParameterSet& sps, const GeometryParameterSet& gps); PayloadBuffer write(const SequenceParameterSet& sps, const AttributeParameterSet& aps); PayloadBuffer write(const SequenceParameterSet& sps, const TileInventory& inventory); PayloadBuffer write(const SequenceParameterSet& sps, const FrameBoundaryMarker& fbm); PayloadBuffer write( const SequenceParameterSet& sps, const AttributeParamInventoryHdr& inventory, const AttributeParameters& params); PayloadBuffer write(const UserData& ud); //---------------------------------------------------------------------------- // NB: parseSps, parseGps, parseAps, and parseTileInventory return values // using XYZ axes. // These must be converted to STV prior to use by the codec. // This is not done during parsing to emphasise that there is no parsing // dependency on the SPS. SequenceParameterSet parseSps(const PayloadBuffer& buf); GeometryParameterSet parseGps(const PayloadBuffer& buf); AttributeParameterSet parseAps(const PayloadBuffer& buf); TileInventory parseTileInventory(const PayloadBuffer& buf); FrameBoundaryMarker parseFrameBoundaryMarker(const PayloadBuffer& buf); UserData parseUserData(const PayloadBuffer& buf); AttributeParamInventoryHdr parseAttrParamInventoryHdr(const PayloadBuffer&); AttributeParameters& parseAttrParamInventory( const AttributeDescription& attr, const PayloadBuffer& buf, AttributeParameters& params); //---------------------------------------------------------------------------- void write( const SequenceParameterSet& sps, const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, PayloadBuffer* buf); void write( const SequenceParameterSet& sps, const AttributeParameterSet& aps, const AttributeBrickHeader& abh, PayloadBuffer* buf); // NB: parseGbh also parses the footer information GeometryBrickHeader parseGbh( const SequenceParameterSet& sps, const GeometryParameterSet& gps, const PayloadBuffer& buf, int* bytesReadHead, int* bytesReadFoot); AttributeBrickHeader parseAbh( const SequenceParameterSet& sps, const AttributeParameterSet& aps, const PayloadBuffer& buf, int* bytesRead); ConstantAttributeDataUnit parseConstantAttribute( const SequenceParameterSet& sps, const PayloadBuffer& buf); void write( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, const GeometryBrickFooter& gbf, PayloadBuffer* buf); GeometryBrickFooter parseGbf( const GeometryParameterSet& gps, const GeometryBrickHeader& gbh, const PayloadBuffer& buf, int* bytesRead); /** * Parse @buf, decoding only the parameter set, slice, tag. * NB: the returned header is intentionally incomplete. */ GeometryBrickHeader parseGbhIds(const PayloadBuffer& buf); /** * Parse @buf, decoding only the parameter set and slice ids. * NB: the returned header is intentionally incomplete. */ AttributeBrickHeader parseAbhIds(const PayloadBuffer& buf); //---------------------------------------------------------------------------- //============================================================================ } // namespace pcc
5,181
34.737931
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/io_tlv.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include "PayloadBuffer.h" #include <istream> #include <ostream> namespace pcc { //============================================================================ std::ostream& writeTlv(const PayloadBuffer& buf, std::ostream& os); std::istream& readTlv(std::istream& is, PayloadBuffer* buf); //============================================================================ } // namespace pcc
2,233
41.150943
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/osspecific.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once namespace pcc { // Create a directory at the given path. int mkdir(const char* path); } /* namespace pcc */
1,948
44.325581
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/partitioning.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> #include <vector> #include "PCCMath.h" #include "PCCPointSet.h" #include "hls.h" namespace pcc { //============================================================================ enum class PartitionMethod { // Don't partition input kNone = 0, // Partition according to uniform geometry kUniformGeom = 2, // Partition according to the depth of octree kOctreeUniform = 3, // TBD kUniformSquare = 4, // Paritition into n-point slices kNpoints = 5, }; //============================================================================ struct PartitionParams { // Method for partitioning a point cloud PartitionMethod method; // Depth of octree used in partitioning int octreeDepth; // Maximum number of points per slice int sliceMaxPoints; // Minimum number of points per slice int sliceMinPoints; // Baseline tile width. (0 => disabled) int tileSize; }; //============================================================================ struct Partition { // The *_slice_id to encode this partition with int sliceId; // The identifier of the tileset that describes the bounding box of all // slices with the same tile_id. A value of -1 indicates no tile_id // mapping. int tileId; // The value of geom_box_origin for this partition, using the // translated+scaled co-ordinate system. Vec3<int> origin; // Some metadata used by the partitioning process Vec3<int> location; // Point indexes of the source point cloud that form this partition. std::vector<int32_t> pointIndexes; }; //---------------------------------------------------------------------------- struct PartitionSet { TileInventory tileInventory; std::vector<Partition> slices; }; //============================================================================ std::vector<Partition> partitionByUniformGeom( const PartitionParams& params, const PCCPointSet3& cloud, int tileID, int paritionBoundaryLog2); std::vector<Partition> partitionByOctreeDepth( const PartitionParams& params, const PCCPointSet3& cloud, int tileID, bool splitByDepth = false); std::vector<Partition> partitionByUniformSquare( const PartitionParams& params, const PCCPointSet3& cloud, int tileID, int paritionBoundaryLog2); std::vector<Partition> partitionByNpts( const PartitionParams& params, const PCCPointSet3& cloud, int tileID); std::vector<Partition> partitionNone( const PartitionParams& params, const PCCPointSet3& cloud, int tileID); //============================================================================ std::vector<std::vector<int32_t>> tilePartition(const PartitionParams& params, const PCCPointSet3& cloud); //============================================================================ void refineSlicesByAdjacentInfo( const PartitionParams& params, const PCCPointSet3& inputPointCloud, Vec3<int> sliceArrNum, std::vector<Partition>& slices); //============================================================================ } // namespace pcc
4,884
30.11465
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/pcc_chrono.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <chrono> //=========================================================================== namespace pcc { namespace chrono { /** * Clock reporting elapsed user time of the current process and children. * * NB: under winapi, only child processes that have completed execution * via pcc::system() are reported. */ struct utime_inc_children_clock { typedef std::chrono::nanoseconds duration; typedef duration::rep rep; typedef duration::period period; typedef std::chrono::time_point<utime_inc_children_clock, duration> time_point; static constexpr bool is_steady = true; static time_point now() noexcept; }; } // namespace chrono } // namespace pcc //=========================================================================== namespace pcc { namespace chrono { /** * Measurement of cumulative elapsed time intervals. * * This timer acts like a stopwatch and may be used to measure the * cumulative periods between successive calls to start() and stop(). */ template<typename Clock> class Stopwatch { public: typedef typename Clock::duration duration; /// Reset the accumulated interval count. void reset(); /// Mark the beginning of a measurement period. void start(); /// Mark the end of a measurement period. /// /// @return the duration of the elapsed Clock time since start() duration stop(); /// The sum of the previous elapsed time intervals. /// /// NB: this excludes any currently active period marked by start(). /// /// @return cumulative elapsed time constexpr duration count() const { return cumulative_time_; } private: typename Clock::time_point start_time_; duration cumulative_time_{duration::zero()}; }; } // namespace chrono } // namespace pcc //--------------------------------------------------------------------------- template<typename Clock> void pcc::chrono::Stopwatch<Clock>::reset() { cumulative_time_ = cumulative_time_.zero(); } //--------------------------------------------------------------------------- template<typename Clock> void pcc::chrono::Stopwatch<Clock>::start() { start_time_ = Clock::now(); } //--------------------------------------------------------------------------- template<typename Clock> typename pcc::chrono::Stopwatch<Clock>::duration pcc::chrono::Stopwatch<Clock>::stop() { const auto& delta = duration(Clock::now() - start_time_); cumulative_time_ += delta; return delta; } //===========================================================================
4,415
31.955224
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/ply.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <array> #include <string> #include "PCCPointSet.h" namespace pcc { namespace ply { //============================================================================ // This defines the the attribute names to be used when reading/writing ply // files. The order of the names define the ordering used in the internal // point cloud representation. struct PropertyNameMap { // The names of the position attributes, typically {"x", "y", "z"} std::array<const char*, 3> position; }; //============================================================================ /// // Write @a pointCloud to a PLY file called @a fileName. // Each point position, pt, is converted prior to writing by: // pt' = pt * positionScale + offset // // @param pointCloud points to be written. // @param propertyNames Describes ply property names of pointcloud attributes. // @param positionScale scale factor for positions. // @param positionOffset offset for positions (after scaling). // @param fileName output filename. // @param asAscii PLY writing format (true => ascii, false => binary). bool write( const PCCPointSet3& pointCloud, const PropertyNameMap& propertyNames, double positionScale, Vec3<double> positionOffset, const std::string& fileName, bool asAscii); /// // Read @a pointCloud to a PLY file called @a fileName. // Point positions are scaled by positionScale and converted to integers. // bool read( const std::string& fileName, const PropertyNameMap& propertyNames, double positionScale, PCCPointSet3& cloud); //============================================================================ } // namespace ply } // namespace pcc
3,578
38.766667
81
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/pointset_processing.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <map> #include "PCCPointSet.h" #include "hls.h" namespace pcc { //============================================================================ struct RecolourParams { double distOffsetFwd; double distOffsetBwd; double maxGeometryDist2Fwd; double maxGeometryDist2Bwd; double maxAttributeDist2Fwd; double maxAttributeDist2Bwd; int searchRange; int numNeighboursFwd; int numNeighboursBwd; bool useDistWeightedAvgFwd; bool useDistWeightedAvgBwd; bool skipAvgIfIdenticalSourcePointPresentFwd; bool skipAvgIfIdenticalSourcePointPresentBwd; }; //============================================================================ // Represents a quatized point cloud with index mappings to source positions. struct SrcMappedPointSet { // A subsampled or quantised pointcloud generated from a source. PCCPointSet3 cloud; // Maps cloud indexes to the generating source index. std::vector<int> idxToSrcIdx; // Linked lists of source indexes that map to the same generated position. // Each element is the index of the next element in the chain. // The end of a chain is indicated by: srcIdxDupList[i] == i. std::vector<int> srcIdxDupList; }; //============================================================================ // Subsample a point cloud, retaining unique points only. // Uniqueness is assessed by quantising each position by a multiplicative // @sampleScale. Output points are quantised by @quantScale with rounding, // and translated by -@offset. // // NB: attributes are not processed. SrcMappedPointSet samplePositionsUniq( float sampleScale, float quantScale, Vec3<int> offset, const PCCPointSet3& src); //============================================================================ // Quantise the geometry of a point cloud, retaining unique points only. // Points in the @src point cloud are translated by -@offset, quantised by a // multiplicitive @scaleFactor with rounding, then clamped to @clamp. // // NB: attributes are not processed. SrcMappedPointSet quantizePositionsUniq( const float scaleFactor, const Vec3<int> offset, const Box3<int> clamp, const PCCPointSet3& src); //============================================================================ // Quantise the geometry of a point cloud, retaining duplicate points. // Points in the @src point cloud are translated by -@offset, then quantised // by a multiplicitive @scaleFactor with rounding. // // The destination and source point clouds may be the same object. // // NB: attributes are preserved void quantizePositions( const float scaleFactor, const Vec3<int> offset, const Box3<int> clamp, const PCCPointSet3& src, PCCPointSet3* dst); //============================================================================ // Clamp point co-ordinates in @cloud to @bbox, preserving attributes. void clampVolume(Box3<int32_t> bbox, PCCPointSet3* cloud); //============================================================================ // Determine colour attribute values from a reference/source point cloud. // For each point of the target p_t: // - Find the N_1 (1 < N_1) nearest neighbours in source to p_t and create // a set of points denoted by Ψ_1. // - Find the set of source points that p_t belongs to their set of N_2 // nearest neighbours. Denote this set of points by Ψ_2. // - Compute the distance-weighted average of points in Ψ_1 and Ψ_2 by: // \bar{Ψ}_k = ∑_{q∈Ψ_k} c(q)/Δ(q,p_t) // ----------------------- , // ∑_{q∈Ψ_k} 1/Δ(q,p_t) // // where Δ(a,b) denotes the Euclidian distance between the points a and b, // and c(q) denotes the colour of point q. Compute the average (or the // weighted average with the number of points of each set as the weights) // of \bar{Ψ}̅_1 and \bar{Ψ}̅_2 and transfer it to p_t. // // Differences in the scale and translation of the target and source point // clouds, is handled according to: // posInTgt = posInSrc * sourceToTargetScaleFactor - targetToSourceOffset bool recolourColour( const AttributeDescription& desc, const RecolourParams& params, const PCCPointSet3& source, double sourceToTargetScaleFactor, point_t targetToSourceOffset, PCCPointSet3& target); //============================================================================ // Determine reflectance attribute values from a reference/source point cloud. // For each point of the target p_t: // - Find the N_1 (1 < N_1) nearest neighbours in source to p_t and create // a set of points denoted by Ψ_1. // - Find the set of source points that p_t belongs to their set of N_2 // nearest neighbours. Denote this set of points by Ψ_2. // - Compute the distance-weighted average of points in Ψ_1 and Ψ_2 by: // \bar{Ψ}_k = ∑_{q∈Ψ_k} c(q)/Δ(q,p_t) // ----------------------- , // ∑_{q∈Ψ_k} 1/Δ(q,p_t) // // where Δ(a,b) denotes the Euclidian distance between the points a and b, // and c(q) denotes the colour of point q. Compute the average (or the // weighted average with the number of points of each set as the weights) // of \bar{Ψ}̅_1 and \bar{Ψ}̅_2 and transfer it to p_t. // // Differences in the scale and translation of the target and source point // clouds, is handled according to: // posInTgt = posInSrc * sourceToTargetScaleFactor - targetToSourceOffset bool recolourReflectance( const AttributeDescription& desc, const RecolourParams& cfg, const PCCPointSet3& source, double sourceToTargetScaleFactor, point_t targetToSourceOffset, PCCPointSet3& target); //============================================================================ // Recolour attributes based on a source/reference point cloud. // // Differences in the scale and translation of the target and source point // clouds, is handled according to: // posInTgt = posInSrc * sourceToTargetScaleFactor - tgtToSrcOffset int recolour( const AttributeDescription& desc, const RecolourParams& cfg, const PCCPointSet3& source, float sourceToTargetScaleFactor, point_t tgtToSrcOffset, PCCPointSet3* target); //============================================================================ void convertGbrToYCbCrBt709(PCCPointSet3&); void convertYCbCrBt709ToGbr(PCCPointSet3&); void convertGbrToYCgCoR(int bitDepth, PCCPointSet3&); void convertYCgCoRToGbr(int bitDepth, PCCPointSet3&); //============================================================================ // Generate index order sorted by azimuth angle. std::vector<int32_t> orderByAzimuth( PCCPointSet3&, int start, int end, int numDigit, Vec3<int32_t> origin); std::vector<int32_t> orderByRadius(PCCPointSet3&, int start, int end, Vec3<int32_t> origin); std::vector<int32_t> orderByLaserAngle( PCCPointSet3&, int start, int end, int numDigit, Vec3<int32_t> origin); // Sorts points according to azimuth angle. void sortByAzimuth( PCCPointSet3&, int start, int end, double recipBinWidth, Vec3<int32_t> origin = 0); void sortByRadius(PCCPointSet3&, int start, int end, Vec3<int32_t> origin = 0); void sortByLaserAngle( PCCPointSet3&, int start, int end, double recipBinWidth, Vec3<int32_t> origin = 0); //============================================================================ } // namespace pcc
9,130
36.731405
79
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/quantization.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2019, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <array> #include <vector> #include "constants.h" #include "PCCMath.h" namespace pcc { struct AttributeDescription; struct AttributeParameterSet; struct AttributeBrickHeader; //============================================================================ // Quantisation methods class Quantizer { public: // Derives step sizes from qp Quantizer(int qp); Quantizer(const Quantizer&) = default; Quantizer& operator=(const Quantizer&) = default; // The quantizer's step size int stepSize() const { return _stepSize; } // Quantise a value int64_t quantize(int64_t x) const; // Scale (inverse quantise) a quantised value int64_t scale(int64_t x) const; private: // Quantisation step size int _stepSize; // Reciprocal stepsize for forward quantisation optimisation int _stepSizeRecip; }; //--------------------------------------------------------------------------- inline int64_t Quantizer::quantize(int64_t x) const { // Forward quantisation avoids division by using the multiplicative inverse // with 18 fractional bits. int64_t fracBits = 18 + kFixedPointAttributeShift; // NB, the folowing offsets quantizes with a different deadzone to the // reconstruction function. int64_t offset = (1ll << fracBits) / 3; if (x >= 0) { return (x * _stepSizeRecip + offset) >> fracBits; } return -((offset - x * _stepSizeRecip) >> fracBits); } //--------------------------------------------------------------------------- inline int64_t Quantizer::scale(int64_t x) const { return x * _stepSize; } //============================================================================ // Encapslation of multi-component attribute quantizer values. typedef std::array<Quantizer, 2> Quantizers; typedef std::array<int, 2> Qps; typedef std::vector<Qps> QpLayers; //============================================================================ struct QpRegionOffset { Qps qpOffset; Box3<int32_t> region; }; typedef std::vector<QpRegionOffset> QpRegionList; //============================================================================ struct QpSet { QpLayers layers; QpRegionList regions; int maxQp; int fixedPointQpOffset; // Derive the quantizers at a given layer after applying qpOffset Quantizers quantizers(int qpLayer, Qps qpOffset) const; // Derive the quantizer for a point at a particular layer Quantizers quantizers(const Vec3<int32_t>& point, int qpLayer) const; Qps regionQpOffset(const Vec3<int32_t>& point) const; }; //============================================================================ // Determine the Qps for a particular layer in an attribute slice Qps deriveQps( const AttributeParameterSet& attr_aps, const AttributeBrickHeader& abh, int qpLayer); // Determine the base layer QPs for an attribute slice QpLayers deriveLayerQps( const AttributeParameterSet& attr_aps, const AttributeBrickHeader& abh); // Determine a list of Qp offsets per region QpRegionList deriveQpRegions( const AttributeParameterSet& attr_aps, const AttributeBrickHeader& abh); // Determine the Qp configuration for an attribute slice QpSet deriveQpSet( const AttributeDescription& attrDesc, const AttributeParameterSet& attr_aps, const AttributeBrickHeader& abh); //============================================================================ // Quantisation methods for geometry class QuantizerGeom { public: // Derives step sizes from qp QuantizerGeom(int qp) { _stepSize = (8 + (qp % 8)) << qpShift(qp); _stepSizeRecip = kQpStepRecip[qp % 8] >> qpShift(qp); } QuantizerGeom(const QuantizerGeom&) = default; QuantizerGeom& operator=(const QuantizerGeom&) = default; // The quantizer's step size int stepSize() const { return _stepSize; } // Quantise a value int64_t quantize(int64_t x) const; // Scale (inverse quantise) a quantised value int64_t scale(int64_t x) const; // The number of bits eliminated by a given qp static int qpShift(int qp) { return qp >> 3; } private: // Quantisation step size int _stepSize; // Reciprocal stepsize for forward quantisation optimisation int _stepSizeRecip; static const int _shift = 20; static const int32_t kQpStep[8]; static const int32_t kQpStepRecip[8]; }; //--------------------------------------------------------------------------- inline int64_t QuantizerGeom::quantize(int64_t x) const { // NB: geometry positions are only ever positive return (x * _stepSizeRecip + (1 << 19)) >> _shift; } //--------------------------------------------------------------------------- inline int64_t QuantizerGeom::scale(int64_t x) const { return (x * _stepSize + 4) >> 3; } //============================================================================ } // namespace pcc
6,614
29.344037
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/ringbuf.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstddef> #include <cstdint> #include <iterator> #include <memory> #include <type_traits> namespace pcc { //=========================================================================== // A ringbuf::iterator with RandomAccessIterator semantics. template<typename T> class ring_iterator { typedef typename std::remove_const<T>::type T_nonconst; typedef ring_iterator<T> iterator; typedef ring_iterator<const T_nonconst> const_iterator; // the backing store T* base_; // length of backing store size_t max_; // iterator's index into backing store size_t idx_; // notional start of ring buffer, used to determine index ordering const iterator* start_; public: typedef std::random_access_iterator_tag iterator_category; typedef T value_type; typedef std::ptrdiff_t difference_type; typedef T* pointer; typedef T& reference; //------------------------------------------------------------------------- explicit ring_iterator(T* base, size_t max, const iterator* start) : base_(base), max_(max), idx_(), start_(start) {} operator ring_iterator<const T_nonconst>() const { return *(const_iterator*)this; } //------------------------------------------------------------------------- // Iterator reference operator*() const { return base_[idx_]; } iterator& operator++() { idx_++; idx_ = idx_ == max_ ? 0 : idx_; return *this; } //------------------------------------------------------------------------- // InputIterator bool operator==(const iterator& other) const { return idx_ == other.idx_; } bool operator!=(const iterator& other) const { return !(*this == other); } pointer operator->() const { return &base_[idx_]; } iterator operator++(int) { iterator retval = *this; ++(*this); return retval; } //------------------------------------------------------------------------- // BidirectionalIterator iterator& operator--() { idx_ = idx_ == 0 ? max_ : idx_; idx_--; return *this; } iterator operator--(int) { iterator retval = *this; --(*this); return retval; } //------------------------------------------------------------------------- // RandomAccessIterator reference operator[](size_t n) { size_t idx = idx_ + n; if (idx_ >= max_) idx_ -= max_; return base_[idx]; } // Precondition: 0 < it + n < end; // ie, the calculated position is not modulo size(). iterator& operator+=(difference_type n) { idx_ += n; if (idx_ >= max_) { if (n > 0) idx_ -= max_; else idx_ += max_; } return *this; } // Precondition: 0 < it + n < end; // ie, the calculated position is not modulo size(). iterator operator+(difference_type n) const { iterator it(*this); it += n; return it; } // Precondition: 0 < it + n < end; // ie, the calculated position is not modulo size(). iterator& operator-=(difference_type n) { *this += -n; return *this; } // Precondition: 0 < it + n < end; // ie, the calculated position is not modulo size(). iterator operator-(difference_type n) const { iterator it(*this); it -= n; return it; } difference_type operator-(const iterator& other) const { size_t lin_pos_this = linear_idx(*start_, idx_); size_t lin_pos_other = linear_idx(*start_, other.idx_); return lin_pos_this - lin_pos_other; } bool operator<(const iterator& other) const { difference_type dist = operator-(other); return dist < 0; } bool operator<=(const iterator& other) const { difference_type dist = operator-(other); return dist <= 0; } bool operator>(const iterator& other) const { return !operator<=(other); } bool operator>=(const iterator& other) const { return !operator<(other); } //========================================================================= private: // calculate the linear position of idx_ with respect to origin static size_t linear_idx(const iterator& origin, size_t idx_) { difference_type dist = difference_type(idx_ - origin.idx_); if (dist < 0) dist += origin.max_; return size_t(dist); } }; //=========================================================================== // An indexed sequence cotainer allowing fast insertion and deletion at both // the head and tail. // // As opposed to std::deque, a pcc::ringbuf uses a fixed-sized backing store // that is not resized so as to avoid memory management calls when inserting // or erasing elements. To permit fast manipulation of the head and tail, // elements are not guaranteed to be stored contigiously. // // ## The complexity (efficiency) of common operations is as follows: // // - Random access -- constant O(1). // - Insertion / removal at the head or tail -- constant O(1). // - Insertion / removal of elements -- linear O(n). // // ## Incomplete implementation: // // The following methods are not implemented: // // - push_front, emplace_front, insert, emplace, at, swap. // // ## Iterator validity: // // - push_back, emplace_back do not invalidate any references to elements, // all iterators remain valid. // - pop_front, pop_back do not invalidate any references to non-erased // elements, and all iterators remain valid. template<typename T> class ringbuf { public: typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef std::ptrdiff_t difference_type; typedef ring_iterator<T> iterator; typedef ring_iterator<const T> const_iterator; //-------------------------------------------------------------------------- ringbuf() : buf_(nullptr) , capacity_(0) , rd_it_(iterator(buf_.get(), capacity_, &rd_it_)) , wr_it_(iterator(buf_.get(), capacity_, &rd_it_)) {} //-------------------------------------------------------------------------- ringbuf(size_t size) : buf_(static_cast<T*>(operator new[](sizeof(T) * (size + 1)))) , capacity_(size + 1) , rd_it_(iterator(buf_.get(), capacity_, &rd_it_)) , wr_it_(iterator(buf_.get(), capacity_, &rd_it_)) {} //-------------------------------------------------------------------------- ringbuf(ringbuf&& other) noexcept { *this = std::move(other); } //-------------------------------------------------------------------------- ringbuf& operator=(ringbuf&& rhs) noexcept { // unfortunately the iterators cannot be moved, since they hold a // pointer to the ringbuffer's internal iterator. // it_zero is used to extract the true iterator idx iterator it_zero = iterator(nullptr, 0, &it_zero); auto lhs_rd_idx = -(it_zero - rd_it_); auto lhs_wr_idx = -(it_zero - wr_it_); auto rhs_rd_idx = -(it_zero - rhs.rd_it_); auto rhs_wr_idx = -(it_zero - rhs.wr_it_); std::swap(buf_, rhs.buf_); std::swap(capacity_, rhs.capacity_); rd_it_ = iterator(buf_.get(), capacity_, &rd_it_); wr_it_ = iterator(buf_.get(), capacity_, &rd_it_); rd_it_ += rhs_rd_idx; wr_it_ += rhs_wr_idx; rhs.rd_it_ = iterator(rhs.buf_.get(), rhs.capacity_, &rhs.rd_it_); rhs.wr_it_ = iterator(rhs.buf_.get(), rhs.capacity_, &rhs.rd_it_); rhs.rd_it_ += lhs_rd_idx; rhs.wr_it_ += lhs_wr_idx; return *this; } //-------------------------------------------------------------------------- ~ringbuf() { while (rd_it_ != wr_it_) { pop_front(); } } //-------------------------------------------------------------------------- iterator begin() { return rd_it_; } iterator end() { return wr_it_; } const_iterator begin() const { return const_iterator(rd_it_); } const_iterator end() const { return const_iterator(wr_it_); } //-------------------------------------------------------------------------- bool empty() const { return begin() == end(); } //-------------------------------------------------------------------------- void push_back(const value_type& val) { emplace_back(val); } //-------------------------------------------------------------------------- void push_back(value_type&& val) { emplace_back(std::move(val)); } //-------------------------------------------------------------------------- template<class... Args> void emplace_back(Args&&... args) { new (&*wr_it_) T(args...); ++wr_it_; } //-------------------------------------------------------------------------- void pop_back() { --wr_it_; wr_it_->~T(); } //-------------------------------------------------------------------------- void pop_front() { rd_it_->~T(); ++rd_it_; } //-------------------------------------------------------------------------- reference front() { return *rd_it_; } //-------------------------------------------------------------------------- reference back() { return *std::prev(wr_it_); } //-------------------------------------------------------------------------- reference operator[](size_type idx) { return *std::next(rd_it_, idx); } //-------------------------------------------------------------------------- const_reference operator[](size_type idx) const { return *std::next(rd_it_, idx); } //-------------------------------------------------------------------------- void clear() { while (!empty()) { pop_front(); } } //-------------------------------------------------------------------------- size_t size() const { return size_t(end() - begin()); } //-------------------------------------------------------------------------- size_t capacity() const { return capacity_ - 1; } //-------------------------------------------------------------------------- private: struct operator_delete_arr { void operator()(T* ptr) { ::operator delete[](ptr); } }; std::unique_ptr<T[], operator_delete_arr> buf_; size_t capacity_; iterator rd_it_; iterator wr_it_; }; //=========================================================================== } /* namespace pcc */
11,962
27.757212
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/tables.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once #include <cstdint> namespace pcc { extern const uint8_t kNeighPatternInvMap[64][8]; extern const int numMaxOccupided[8]; // Symmetry reduction of 64 neighbour pattern to 10 extern const uint8_t kNeighPattern64to9[64]; extern const uint8_t kNeighPattern64to6[64]; extern const uint8_t kNeighPattern9to5[9]; extern const uint8_t kNeighPattern9to3[9]; extern const uint8_t kNeighPattern10to7[10]; extern const uint8_t kNeighPattern7to5[7]; // Identifies the X-Y rotation to be performed given a neighbour pattern // 0 => none // 1 => X 90° ACW (encoder) [kOccMapRotateX090] // 1 => X 270° ACW (decoder) [kOccMapRotateX270] // 2 => X 270° ACW, Y 180° [kOccMapRotateX270Y180] // 3 => X 90° ACW, Y 180° [kOccMapRotateX090Y180] extern const uint8_t kOccMapRotateXIdFromPattern[64]; extern const uint8_t kOccMapRotateX270[256]; extern const uint8_t LUT_rotx_mode2[256]; extern const uint8_t LUT_rotx_mode3[256]; extern const uint8_t kOccMapRotateX090[256]; extern const uint8_t kOccMapRotateX270Y180[256]; extern const uint8_t kOccMapRotateX090Y180[256]; // Identifies the Y rotation to be performed given a neighbour pattern // 0 => none // 1 => Y 270° ACW (encoder) [kOccMapRotateY270] // 1 => Y 90° ACW (decoder) [kOccMapRotateY090] extern const bool kOccMapRotateYIdFromPattern[64]; extern const uint8_t kOccMapRotateY090[256]; extern const uint8_t kOccMapRotateY270[256]; // Vertical mirroring permutation extern const uint8_t kOccMapMirrorXY[256]; // Identifies the Z rotation to be performed given a partial neighbour pattern // 0 => none // 1 => 270° ACW (decoder) [kOccMapRotateZ270] // 1 => 090° ACW (encoder) [kOccMapRotateZ090] // 2 => 180° [kOccMapRotateZ180] // 3 => 090° ACW (decoder) [kOccMapRotateZ090] // 3 => 270° ACW (encoder) [kOccMapRotateZ270] extern const uint8_t kOccMapRotateZIdFromPatternXY[16]; extern const uint8_t kOccMapRotateZ270[256]; extern const uint8_t kOccMapRotateZ180[256]; extern const uint8_t kOccMapRotateZ090[256]; // Geometry occupancy bit scan order for entropy coding extern const int8_t kOccBitCodingOrder[8]; // Geometry occupancy context map update table, represented as deltas to // current map entry value. extern const uint8_t kCtxMapOctreeOccupancyDelta[16]; // LUT initialisation table extern const uint8_t kDualLutOccupancyCoderInit[10][32]; //============================================================================ // Mapping of (x,y,z) components to 3D Morton code. extern const uint32_t kMortonCode256X[256]; extern const uint32_t kMortonCode256Y[256]; extern const uint32_t kMortonCode256Z[256]; //============================================================================ // Base quantisation step sizes extern const int16_t kQpStep[6]; // Reciprocal step size to avoid division during quantisation extern const int32_t kQpStepRecip[6]; //============================================================================ // LUT for sine function const int32_t kLog2ISineScale = 24; const int32_t kLog2ISineAngleScale = 12; extern const int32_t kISine[1026]; } /* namespace pcc */
4,935
39.793388
78
h
mpeg-pcc-tmc13
mpeg-pcc-tmc13-master/tmc3/version.h
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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. */ #pragma once namespace pcc { // Description of the software source version extern const char version[]; } /* namespace pcc */
1,954
43.431818
78
h
uwot
uwot-master/inst/include/RcppPerpendicular.h
// Taken from RcppParallel.h and then modified slightly to rename header guards // and namespaces to avoid any potential clashes. RcppParallel is licensed under // GPLv2 or later: // RcppPerpendicular.h a version of parallel for based on RcppParallel // Copyright (C) 2020 James Melville // // 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. #ifndef RCPP_PERPENDICULAR #define RCPP_PERPENDICULAR #include <thread> #include <utility> #include <vector> namespace RcppPerpendicular { using IndexRange = std::pair<std::size_t, std::size_t>; template <typename Worker> auto worker_thread(Worker &worker, const IndexRange &range) -> void { try { worker(range.first, range.second); } catch (...) { } } template <typename Worker> auto worker_thread_id(Worker &worker, const IndexRange &range, std::size_t thread_id) -> void { try { worker(range.first, range.second, thread_id); } catch (...) { } } // Function to calculate the ranges for a given input inline auto split_input_range(const IndexRange &range, std::size_t n_threads, std::size_t grain_size) -> std::vector<IndexRange> { // determine max number of threads if (n_threads == 0) { n_threads = std::thread::hardware_concurrency(); } // compute grain_size (including enforcing requested minimum) std::size_t length = range.second - range.first; if (n_threads == 1) { grain_size = length; } else if ((length % n_threads) == 0) { // perfect division grain_size = (std::max)(length / n_threads, grain_size); } else { // imperfect division, divide by threads - 1 grain_size = (std::max)(length / (n_threads - 1), grain_size); } // allocate ranges std::vector<IndexRange> ranges; std::size_t begin = range.first; while (begin < range.second) { std::size_t end = (std::min)(begin + grain_size, range.second); ranges.emplace_back(std::make_pair(begin, end)); begin = end; } return ranges; } // Execute the Worker over the IndexRange in parallel template <typename Worker> inline void parallel_for(std::size_t begin, std::size_t end, Worker &worker, std::size_t n_threads, std::size_t grain_size = 1) { if (n_threads > 0) { // split the work IndexRange input_range(begin, end); std::vector<IndexRange> ranges = split_input_range(input_range, n_threads, grain_size); std::vector<std::thread> threads; threads.reserve(ranges.size()); for (auto &range : ranges) { threads.push_back( std::thread(&worker_thread<Worker>, std::ref(worker), range)); } for (auto &thread : threads) { thread.join(); } } else { worker(begin, end); } } template <typename Worker> inline void parallel_for(std::size_t end, Worker &worker, std::size_t n_threads, std::size_t grain_size = 1) { parallel_for(0, end, worker, n_threads, grain_size); } template <typename Worker> inline void pfor(std::size_t begin, std::size_t end, Worker &worker, std::size_t n_threads, std::size_t grain_size = 1) { if (n_threads > 0) { IndexRange input_range(begin, end); std::vector<IndexRange> ranges = split_input_range(input_range, n_threads, grain_size); std::vector<std::thread> threads; for (std::size_t thread_id = 0; thread_id < ranges.size(); ++thread_id) { auto &range = ranges[thread_id]; threads.push_back(std::thread(&worker_thread_id<Worker>, std::ref(worker), range, thread_id)); } for (auto &thread : threads) { thread.join(); } } else { worker(begin, end, 0); } } template <typename Worker> inline void pfor(std::size_t end, Worker &worker, std::size_t n_threads, std::size_t grain_size = 1) { pfor(0, end, worker, n_threads, grain_size); } } // namespace RcppPerpendicular #endif // RCPP_PERPENDICULAR
4,606
30.554795
80
h
uwot
uwot-master/inst/include/uwot/connected_components.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. // Translated from the Python source code of: // scipy.sparse.csgraph.connected_components // Author: Jake Vanderplas -- <[email protected]> // License: BSD, (C) 2012 #ifndef UWOT_CONNECTED_COMPONENTS_H #define UWOT_CONNECTED_COMPONENTS_H namespace uwot { auto connected_components_undirected(std::size_t N, const std::vector<int> &indices1, const std::vector<int> &indptr1, const std::vector<int> &indices2, const std::vector<int> &indptr2) -> std::pair<unsigned int, std::vector<int>> { constexpr int VOID = -1; constexpr int END = -2; std::vector<int> labels(N, VOID); std::vector<int> SS(labels); unsigned int label = 0; auto SS_head = END; for (std::size_t v = 0; v < N; ++v) { auto vv = v; if (labels[vv] == VOID) { SS_head = vv; SS[vv] = END; while (SS_head != END) { vv = SS_head; SS_head = SS[vv]; labels[vv] = label; for (auto jj = indptr1[vv]; jj < indptr1[vv + 1]; ++jj) { auto ww = indices1[jj]; if (SS[ww] == VOID) { SS[ww] = SS_head; SS_head = ww; } } for (auto jj = indptr2[vv]; jj < indptr2[vv + 1]; ++jj) { auto ww = indices2[jj]; if (SS[ww] == VOID) { SS[ww] = SS_head; SS_head = ww; } } } ++label; } } return {label, labels}; } } // namespace uwot #endif // UWOT_CONNECTED_COMPONENTS_H
2,964
35.604938
79
h
uwot
uwot-master/inst/include/uwot/coords.h
// BSD 2-Clause License // // Copyright 2021 James Melville // // 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 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 // OF SUCH DAMAGE. #ifndef UWOT_COORDS_H #define UWOT_COORDS_H #include <memory> #include <utility> namespace uwot { // For normal UMAP, tail_embedding is NULL and we want to pass // a shallow copy of head_embedding as tail_embedding. // When updating new values, tail_embedding is the new coordinate to optimize // and gets passed as normal. struct Coords { std::vector<float> head_embedding; std::unique_ptr<std::vector<float>> tail_vec_ptr; Coords(std::vector<float> &head_embedding) : head_embedding(head_embedding), tail_vec_ptr(nullptr) {} Coords(std::vector<float> &head_embedding, std::vector<float> &tail_embedding) : head_embedding(head_embedding), tail_vec_ptr(new std::vector<float>(tail_embedding)) {} auto get_tail_embedding() -> std::vector<float> & { if (tail_vec_ptr) { return *tail_vec_ptr; } else { return head_embedding; } } auto get_head_embedding() -> std::vector<float> & { return head_embedding; } }; } // namespace uwot #endif
2,356
36.412698
80
h
uwot
uwot-master/inst/include/uwot/epoch.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. #ifndef UWOT_EPOCH_H #define UWOT_EPOCH_H #include "sampler.h" #include "update.h" namespace uwot { template <typename Worker, typename Progress, typename Parallel> void optimize_layout(Worker &worker, Progress &progress, unsigned int n_epochs, Parallel &parallel) { for (auto n = 0U; n < n_epochs; n++) { run_epoch(worker, n, n_epochs, parallel); if (progress.is_aborted()) { break; } progress.report(); } } template <typename Worker, typename Parallel> void run_epoch(Worker &worker, std::size_t epoch, std::size_t n_epochs, Parallel &parallel) { worker.epoch_begin(epoch, n_epochs); parallel.pfor(worker.n_items, worker); worker.epoch_end(epoch, n_epochs, parallel); } // Gradient: the type of gradient used in the optimization // Update: type of update to the embedding coordinates template <typename Gradient, typename Update, typename RngFactory> struct EdgeWorker { const Gradient gradient; Update &update; const std::vector<unsigned int> &positive_head; const std::vector<unsigned int> &positive_tail; uwot::Sampler sampler; std::size_t ndim; std::size_t n_tail_vertices; std::size_t n_items; std::size_t n_threads; RngFactory rng_factory; EdgeWorker(const Gradient &gradient, Update &update, const std::vector<unsigned int> &positive_head, const std::vector<unsigned int> &positive_tail, uwot::Sampler &sampler, std::size_t ndim, std::size_t n_tail_vertices, std::size_t n_threads) : gradient(gradient), update(update), positive_head(positive_head), positive_tail(positive_tail), sampler(sampler), ndim(ndim), n_tail_vertices(n_tail_vertices), n_items(positive_head.size()), n_threads(std::max(n_threads, std::size_t{1})), rng_factory(this->n_threads) {} void epoch_begin(std::size_t epoch, std::size_t n_epochs) { rng_factory.reseed(); sampler.epoch = epoch; update.epoch_begin(epoch, n_epochs); } template <typename Parallel> void epoch_end(std::size_t epoch, std::size_t n_epochs, Parallel &parallel) { update.epoch_end(epoch, n_epochs, parallel); } void operator()(std::size_t begin, std::size_t end, std::size_t thread_id) { // Each window gets its own PRNG state, to prevent locking inside the loop. auto prng = rng_factory.create(end); // displacement between two points, cost of reallocating inside the loop // is noticeable, also cheaper to calculate it once in the d2 calc std::vector<float> disp(ndim); for (auto edge = begin; edge < end; edge++) { process_edge(update, gradient, sampler, prng, positive_head, positive_tail, ndim, n_tail_vertices, edge, thread_id, disp); } } }; template <typename Gradient, typename Update, typename RngFactory> struct NodeWorker { const Gradient gradient; Update &update; const std::vector<unsigned int> &positive_head; const std::vector<unsigned int> &positive_tail; const std::vector<unsigned int> &positive_ptr; uwot::Sampler sampler; std::size_t ndim; std::size_t n_tail_vertices; std::size_t n_items; RngFactory rng_factory; NodeWorker(const Gradient &gradient, Update &update, const std::vector<unsigned int> &positive_head, const std::vector<unsigned int> &positive_tail, const std::vector<unsigned int> &positive_ptr, uwot::Sampler &sampler, std::size_t ndim, std::size_t n_tail_vertices) : gradient(gradient), update(update), positive_head(positive_head), positive_tail(positive_tail), positive_ptr(positive_ptr), sampler(sampler), ndim(ndim), n_tail_vertices(n_tail_vertices), n_items(positive_ptr.size() - 1), rng_factory(n_items) {} void epoch_begin(std::size_t epoch, std::size_t n_epochs) { rng_factory.reseed(); sampler.epoch = epoch; update.epoch_begin(epoch, n_epochs); } template <typename Parallel> void epoch_end(std::size_t epoch, std::size_t n_epochs, Parallel &parallel) { update.epoch_end(epoch, n_epochs, parallel); } void operator()(std::size_t begin, std::size_t end, std::size_t thread_id) { std::vector<float> disp(ndim); for (auto p = begin; p < end; p++) { auto prng = rng_factory.create(p); for (auto edge = positive_ptr[p]; edge < positive_ptr[p + 1]; edge++) { process_edge(update, gradient, sampler, prng, positive_head, positive_tail, ndim, n_tail_vertices, edge, thread_id, disp); } } } }; } // namespace uwot #endif // UWOT_EPOCH_H
5,987
37.632258
80
h
uwot
uwot-master/inst/include/uwot/gradient.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. #ifndef UWOT_GRADIENT_H #define UWOT_GRADIENT_H #include <cmath> #include <limits> #include <vector> namespace uwot { inline auto clamp(float v, float lo, float hi) -> float { float t = v < lo ? lo : v; return t > hi ? hi : t; } // return the squared euclidean distance between two points x[px] and y[py] // also store the displacement between x[px] and y[py] in diffxy // there is a small but noticeable performance improvement by doing so // rather than recalculating it in the gradient step inline auto d2diff(const std::vector<float> &x, std::size_t px, const std::vector<float> &y, std::size_t py, std::size_t ndim, float dist_eps, std::vector<float> &diffxy) -> float { float d2 = 0.0; for (std::size_t d = 0; d < ndim; d++) { float diff = x[px + d] - y[py + d]; diffxy[d] = diff; d2 += diff * diff; } return (std::max)(dist_eps, d2); } // The gradient for the dth component of the displacement between two point, // which for Euclidean distance in the output is invariably grad_coeff * (X - Y) // Different methods clamp the magnitude of the gradient to different values template <typename Gradient> auto grad_d(const Gradient &gradient, const std::vector<float> &disp, std::size_t d, float grad_coeff) -> float { return gradient.clamp_grad(grad_coeff * disp[d]); } template <typename Gradient> auto grad_attr(const Gradient &gradient, const std::vector<float> &head_embedding, std::size_t dj, const std::vector<float> &tail_embedding, std::size_t dk, std::size_t ndim, std::vector<float> &disp) -> float { static const float dist_eps = std::numeric_limits<float>::epsilon(); float d2 = d2diff(head_embedding, dj, tail_embedding, dk, ndim, dist_eps, disp); return gradient.grad_attr(d2, dj, dk); } template <typename Gradient> auto grad_rep(const Gradient &gradient, const std::vector<float> &head_embedding, std::size_t dj, const std::vector<float> &tail_embedding, std::size_t dk, std::size_t ndim, std::vector<float> &disp) -> float { static const float dist_eps = std::numeric_limits<float>::epsilon(); float d2 = d2diff(head_embedding, dj, tail_embedding, dk, ndim, dist_eps, disp); return gradient.grad_rep(d2, dj, dk); } // https://martin.ankerl.com/2012/01/25/optimized-approximative-pow-in-c-and-cpp/ // an approximation to pow inline auto fastPrecisePow(float a, float b) -> float { // calculate approximation with fraction of the exponent int e = static_cast<int>(b); union { double d; int x[2]; } u = {a}; u.x[1] = static_cast<int>((b - static_cast<double>(e)) * static_cast<double>(u.x[1] - 1072632447) + 1072632447.0); u.x[0] = 0; // exponentiation by squaring with the exponent's integer part // double r = u.d makes everything much slower, not sure why double r = 1.0; while (e) { if (e & 1) { r *= a; } a *= a; e >>= 1; } return static_cast<float>(r * u.d); } // Class templated on the powfun function as suggested by Aaron Lun template <float (*powfun)(float, float)> class base_umap_gradient { public: base_umap_gradient(float a, float b, float gamma) : a(a), b(b), a_b_m2(-2.0 * a * b), gamma_b_2(2.0 * gamma * b){}; // Compared to the UMAP Python implementation, instead of doing d2^(b-1) // we can save a power calculation by using d2^b / d2 auto grad_attr(float d2, std::size_t, std::size_t) const -> float { float pd2b = powfun(d2, b); return (a_b_m2 * pd2b) / (d2 * (a * pd2b + 1.0)); } auto grad_rep(float d2, std::size_t, std::size_t) const -> float { return gamma_b_2 / ((0.001 + d2) * (a * powfun(d2, b) + 1.0)); } auto clamp_grad(float grad_d) const -> float { return clamp(grad_d, clamp_lo, clamp_hi); } static const constexpr float clamp_hi = 4.0; static const constexpr float clamp_lo = -4.0; private: float a; float b; float a_b_m2; float gamma_b_2; }; // UMAP using standard power function using umap_gradient = base_umap_gradient<std::pow>; // apUMAP: UMAP with an approximate power calculation using apumap_gradient = base_umap_gradient<fastPrecisePow>; // t-UMAP: the UMAP function with a = 1, and b = 1, which results in the Cauchy // distribution as used in t-SNE. This massively simplifies the gradient, // removing the pow calls, resulting in a noticeable speed increase (50% with // MNIST), although the resulting embedding has a larger spread than the // default. Also gamma is absent from this, because I believe it to be // un-necessary in the UMAP cost function. class tumap_gradient { public: tumap_gradient() = default; auto grad_attr(float d2, std::size_t, std::size_t) const -> float { return -2.0 / (d2 + 1.0); } auto grad_rep(float d2, std::size_t, std::size_t) const -> float { return 2.0 / ((0.001 + d2) * (d2 + 1.0)); } auto clamp_grad(float grad_d) const -> float { return clamp(grad_d, clamp_lo, clamp_hi); } static const constexpr float clamp_hi = 4.0; static const constexpr float clamp_lo = -4.0; }; // UMAP where a varies for each observation class umapai_gradient { public: umapai_gradient(const std::vector<float> &ai, float b, std::size_t ndim) : ai(ai), b(b), ndim(ndim), b_m2(-2.0 * b), b_2(2.0 * b) {} auto clamp_grad(float grad_d) const -> float { return clamp(grad_d, clamp_lo, clamp_hi); } static const constexpr float clamp_hi = 4.0; static const constexpr float clamp_lo = -4.0; auto grad_attr(float d2, std::size_t i, std::size_t j) const -> float { auto a = ai[i / ndim] * ai[j / ndim]; float pd2b = std::pow(d2, b); return (a * b_m2 * pd2b) / (d2 * (a * pd2b + 1.0)); } auto grad_rep(float d2, std::size_t i, std::size_t j) const -> float { auto a = ai[i / ndim] * ai[j / ndim]; return b_2 / ((0.001 + d2) * (a * std::pow(d2, b) + 1.0)); } private: std::vector<float> ai; float b; std::size_t ndim; float b_m2; float b_2; }; class umapai2_gradient { public: umapai2_gradient(const std::vector<float> &ai, const std::vector<float> &aj, float b, std::size_t ndim) : ai(ai), aj(aj), b(b), ndim(ndim), b_m2(-2.0 * b), b_2(2.0 * b) {} auto clamp_grad(float grad_d) const -> float { return clamp(grad_d, clamp_lo, clamp_hi); } static const constexpr float clamp_hi = 4.0; static const constexpr float clamp_lo = -4.0; auto grad_attr(float d2, std::size_t i, std::size_t j) const -> float { auto a = ai[i / ndim] * aj[j / ndim]; float pd2b = std::pow(d2, b); return (a * b_m2 * pd2b) / (d2 * (a * pd2b + 1.0)); } auto grad_rep(float d2, std::size_t i, std::size_t j) const -> float { auto a = ai[i / ndim] * aj[j / ndim]; return b_2 / ((0.001 + d2) * (a * std::pow(d2, b) + 1.0)); } private: std::vector<float> ai; std::vector<float> aj; float b; std::size_t ndim; float b_m2; float b_2; }; class largevis_gradient { public: largevis_gradient(float gamma) : gamma_2(gamma * 2.0) {} auto grad_attr(float d2, std::size_t, std::size_t) const -> float { return -2.0 / (d2 + 1.0); } auto grad_rep(float d2, std::size_t, std::size_t) const -> float { return gamma_2 / ((0.1 + d2) * (d2 + 1.0)); } auto clamp_grad(float grad_d) const -> float { return clamp(grad_d, clamp_lo, clamp_hi); } static const constexpr float clamp_hi = 5.0; static const constexpr float clamp_lo = -5.0; private: float gamma_2; }; } // namespace uwot #endif // UWOT_GRADIENT_H
8,961
34.283465
81
h
uwot
uwot-master/inst/include/uwot/optimize.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. #ifndef UWOT_OPTIMIZE_H #define UWOT_OPTIMIZE_H #include <vector> namespace uwot { float linear_decay(double val, std::size_t epoch, std::size_t n_epochs) { return val * (1.0 - (static_cast<float>(epoch) / static_cast<float>(n_epochs))); } float linear_grow(double val, std::size_t epoch, std::size_t n_epochs) { return val * (static_cast<float>(epoch) / static_cast<float>(n_epochs)); } struct Sgd { float initial_alpha; float alpha; Sgd(float alpha) : initial_alpha(alpha), alpha(alpha){}; void update(std::vector<float> &v, std::vector<float> &grad, std::size_t i) { v[i] += alpha * grad[i]; } void epoch_end(std::size_t epoch, std::size_t n_epochs) { alpha = linear_decay(initial_alpha, epoch, n_epochs); } }; struct Adam { float initial_alpha; float alpha; float beta1; float beta2; float beta11; // 1 - beta1 float beta1t; // beta1 ^ t float beta21; // 1 - beta2 float beta2t; // beta2 ^ t float eps; // rather than calculate the debiased values for m and v (mhat and vhat) // directly, fold them into a scaling factor for alpha as described at the // end of the first paragraph of section 2 of the Adam paper // technically you also need to rescale eps (given as eps-hat in the paper) float epsc; // scaled eps float ad_scale; // scaled alpha std::vector<float> mt; std::vector<float> vt; Adam(float alpha, float beta1, float beta2, float eps, std::size_t vec_size) : initial_alpha(alpha), alpha(alpha), beta1(beta1), beta2(beta2), beta11(1.0 - beta1), beta1t(beta1), beta21(1.0 - beta2), beta2t(beta2), eps(eps), epsc(eps * sqrt(beta21)), ad_scale(alpha * sqrt(beta21) / beta11), mt(vec_size), vt(vec_size) {} void update(std::vector<float> &v, std::vector<float> &grad, std::size_t i) { // this takes advantage of updating in-place to give a more compact version // of mt[i] = beta1 * mt[i] + beta11 * grad[i] etc. vt[i] += beta21 * (grad[i] * grad[i] - vt[i]); mt[i] += beta11 * (grad[i] - mt[i]); // ad_scale and epsc handle the debiasing v[i] += ad_scale * mt[i] / (sqrt(vt[i]) + epsc); } void epoch_end(std::size_t epoch, std::size_t n_epochs) { alpha = linear_decay(initial_alpha, epoch, n_epochs); // update debiasing factors beta1t *= beta1; beta2t *= beta2; float sqrt_b2t1 = sqrt(1.0 - beta2t); // rescale alpha and eps to take account of debiasing ad_scale = alpha * sqrt_b2t1 / (1.0 - beta1t); epsc = sqrt_b2t1 * eps; } }; } // namespace uwot #endif // UWOT_OPTIMIZE_H
3,937
33.243478
79
h
uwot
uwot-master/inst/include/uwot/perplexity.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. #ifndef UWOT_PERPLEXITY_H #define UWOT_PERPLEXITY_H #include <atomic> #include <cmath> #include <limits> #include <vector> namespace uwot { auto find_beta(const std::vector<double> &d2, double target, double tol, std::size_t n_iter, std::size_t &n_window_search_fails) -> double { constexpr auto double_max = (std::numeric_limits<double>::max)(); double beta = 1.0; double lo = 0.0; double hi = double_max; // best value seen is used only if binary search fails // (usually only happens if there are multiple degenerate distances) double beta_best = beta; double adiff_min = double_max; bool converged = false; // neighbors of i not including itself auto n_true_neighbors = d2.size(); for (std::size_t iter = 0; iter < n_iter; iter++) { double Z = 0.0; double H = 0.0; double sum_D2_W = 0.0; for (std::size_t k = 0; k < n_true_neighbors; k++) { double W = std::exp(-d2[k] * beta); Z += W; sum_D2_W += d2[k] * W; } if (Z > 0) { H = std::log(Z) + beta * sum_D2_W / Z; } double adiff = std::abs(H - target); if (adiff < tol) { converged = true; break; } // store best beta in case binary search fails if (adiff < adiff_min) { adiff_min = adiff; beta_best = beta; } if (H < target) { hi = beta; beta = 0.5 * (lo + hi); } else { lo = beta; if (hi == double_max) { beta *= 2.0; } else { beta = 0.5 * (lo + hi); } } } if (!converged) { ++n_window_search_fails; beta = beta_best; } return beta; } void perplexity_search(std::size_t i, const std::vector<double> &nn_dist, std::size_t n_neighbors, double target, double tol, std::size_t n_iter, std::vector<double> &d2, std::vector<double> &nn_weights, bool save_sigmas, std::vector<double> &sigmas, std::size_t &n_window_search_fails) { auto i_begin = n_neighbors * i; // log-sum-exp trick // shift squared distances by minimum (distances are already sorted) // D2, W and Z are their shifted versions // but P (and hence Shannon entropy) is unchanged // the self neighbor is ignored leading to some +/- 1 in loops and indexing double dmin = nn_dist[i_begin + 1] * nn_dist[i_begin + 1]; for (std::size_t k = 1; k < n_neighbors; k++) { d2[k - 1] = nn_dist[i_begin + k] * nn_dist[i_begin + k] - dmin; } double beta = find_beta(d2, target, tol, n_iter, n_window_search_fails); double Z = 0.0; for (std::size_t k = 0; k < n_neighbors - 1; k++) { double W = std::exp(-d2[k] * beta); Z += W; // no longer need d2 at this point, store final W there d2[k] = W; } for (std::size_t k = 1; k < n_neighbors; k++) { nn_weights[i_begin + k] = d2[k - 1] / Z; } if (save_sigmas) { sigmas[i] = 1 / sqrt(beta); } } void perplexity_search(std::size_t begin, std::size_t end, const std::vector<double> &nn_dist, std::size_t n_neighbors, double target, double tol, std::size_t n_iter, std::vector<double> &res, bool save_sigmas, std::vector<double> &sigmas, std::atomic_size_t &n_search_fails) { // number of binary search failures in this window std::size_t n_window_search_fails = 0; std::vector<double> d2(n_neighbors - 1, 0.0); for (std::size_t i = begin; i < end; i++) { perplexity_search(i, nn_dist, n_neighbors, target, tol, n_iter, d2, res, save_sigmas, sigmas, n_window_search_fails); } // Update global count of failures n_search_fails += n_window_search_fails; } } // namespace uwot #endif // UWOT_PERPLEXITY_H
5,173
31.955414
79
h
uwot
uwot-master/inst/include/uwot/sampler.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. #ifndef UWOT_SAMPLER_H #define UWOT_SAMPLER_H #include <vector> namespace uwot { // Weighted edge sampler class Sampler { public: std::size_t epoch; Sampler(const std::vector<float> &epochs_per_sample, float negative_sample_rate) : epoch(0), epochs_per_sample(epochs_per_sample), epoch_of_next_sample(epochs_per_sample), epochs_per_negative_sample(epochs_per_sample.size()), epoch_of_next_negative_sample(epochs_per_sample.size()) { std::size_t esz = epochs_per_sample.size(); float nsr = 1.0 / negative_sample_rate; for (std::size_t i = 0; i < esz; i++) { epochs_per_negative_sample[i] = epochs_per_sample[i] * nsr; epoch_of_next_negative_sample[i] = epochs_per_negative_sample[i]; } } auto is_sample_edge(std::size_t edge) const -> bool { return epoch_of_next_sample[edge] <= epoch; } auto get_num_neg_samples(std::size_t edge) const -> std::size_t { return static_cast<std::size_t>( (epoch - epoch_of_next_negative_sample[edge]) / epochs_per_negative_sample[edge]); } void next_sample(std::size_t edge, std::size_t num_neg_samples) { epoch_of_next_sample[edge] += epochs_per_sample[edge]; epoch_of_next_negative_sample[edge] += num_neg_samples * epochs_per_negative_sample[edge]; } private: std::vector<float> epochs_per_sample; std::vector<float> epoch_of_next_sample; std::vector<float> epochs_per_negative_sample; std::vector<float> epoch_of_next_negative_sample; }; } // namespace uwot #endif // UWOT_SAMPLER_H
2,917
36.896104
79
h
uwot
uwot-master/inst/include/uwot/smooth_knn.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. #ifndef UWOT_SMOOTH_KNN_H #define UWOT_SMOOTH_KNN_H #include <atomic> #include <cmath> #include <limits> #include <numeric> #include <vector> #include "RcppPerpendicular.h" namespace uwot { // Welford-style mean calculation auto mean_average(const std::vector<double> &v, std::size_t begin, std::size_t end) -> double { long double mean = 0.0; auto b1 = 1 - begin; for (auto i = begin; i < end; ++i) { mean += (v[i] - mean) / (i + b1); } return static_cast<double>(mean); } auto mean_average(const std::vector<double> &v) -> double { return mean_average(v, 0, v.size()); } // nn_dist is sorted non-decreasing nearest neighbor distances // nzero_begin points to the index of the first non-zero distance // nzero_end points to one past the index of the last non-zero distance // (n_neighbors + 1) auto find_rho(const std::vector<double> &nn_dist, std::size_t nzero_begin, std::size_t nzero_end, double local_connectivity, double tol) -> double { double rho = 0.0; auto nnzero = nzero_end - nzero_begin; if (nnzero >= local_connectivity) { auto index = static_cast<int>(std::floor(local_connectivity)); double interpolation = local_connectivity - index; if (index > 0) { rho = nn_dist[nzero_begin + index - 1]; if (interpolation >= tol) { // rho = (1 - interp) * rho + interp * d_{i+1} rho += interpolation * (nn_dist[nzero_begin + index] - rho); } } else if (nnzero > 0) { // typical code-path: rho is the smallest non-zero distance rho = interpolation * nn_dist[nzero_begin]; } } else if (nnzero > 0) { // not enough non-zero distances, return the largest non-zero distance rho = nn_dist[nzero_end - 1]; } return rho; } // Find the normalization factor for the smoothed distances auto find_sigma(const std::vector<double> &nn_dist, std::size_t i_begin, std::size_t i_end, double target, double rho, double tol, std::size_t n_iter, std::size_t &n_window_search_fails) -> double { constexpr auto double_max = (std::numeric_limits<double>::max)(); // best value seen is used only if binary search fails // NB there is already a safeguard against sigma getting too large // so this is less of a problem than with the perplexity search double sigma = 1.0; double sigma_best = sigma; double adiff_min = double_max; double lo = 0.0; double hi = double_max; bool converged = false; for (std::size_t iter = 0; iter < n_iter; iter++) { double val = 0.0; // NB i_begin should point to the first non-self neighbor for (auto j = i_begin; j < i_end; j++) { auto rj = nn_dist[j] - rho; val += rj <= 0.0 ? 1.0 : std::exp(-rj / sigma); } double adiff = std::abs(val - target); if (adiff < tol) { converged = true; break; } // store best sigma in case binary search fails (usually in the presence // of multiple degenerate distances) if (adiff < adiff_min) { adiff_min = adiff; sigma_best = sigma; } if (val > target) { hi = sigma; sigma = 0.5 * (lo + hi); } else { lo = sigma; if (hi == double_max) { sigma *= 2; } else { sigma = 0.5 * (lo + hi); } } } if (!converged) { ++n_window_search_fails; sigma = sigma_best; } return sigma; } // NB nn_dist must be in sorted non-decreasing order void smooth_knn(std::size_t i, const std::vector<double> &nn_dist, const std::vector<std::size_t> &nn_ptr, bool skip_first, const std::vector<double> &target, double local_connectivity, double tol, std::size_t n_iter, double min_k_dist_scale, double mean_distances, bool save_sigmas, std::vector<double> &nn_weights, std::vector<double> &sigmas, std::vector<double> &rhos, std::size_t &n_window_search_fails) { // i_begin points to start of ith distances // i_end points to one past end of ith distances auto i_begin = 0; auto i_end = 0; auto n_neighbors = 0; // Space optimization for kNN (typical case): store the number of neighbors // as the only entry in nn_ptr if (nn_ptr.size() == 1) { n_neighbors = nn_ptr[0]; i_begin = n_neighbors * i; i_end = i_begin + n_neighbors; } else { i_begin = nn_ptr[i]; i_end = nn_ptr[i + 1]; n_neighbors = i_end - i_begin; } // nzero_begin points to start of ith non-zero distances auto nzero_begin = i_end; for (auto j = i_begin; j < i_end; j++) { if (nn_dist[j] > 0.0) { nzero_begin = j; break; } } auto rho = find_rho(nn_dist, nzero_begin, i_end, local_connectivity, tol); double targeti = target.size() == 1 ? target[0] : target[i]; // in case where self-distance (0) is passed as the nearest neighbor, skip // first item in neighbors when calculating sigma auto sigma = find_sigma(nn_dist, i_begin + (skip_first ? 1 : 0), i_end, targeti, rho, tol, n_iter, n_window_search_fails); // safeguard sigma if (rho > 0.0) { sigma = (std::max)(min_k_dist_scale * mean_average(nn_dist, i_begin, i_end), sigma); } else { sigma = (std::max)(min_k_dist_scale * mean_distances, sigma); } // create the final membership strengths for (auto j = i_begin; j < i_end; j++) { auto rj = nn_dist[j] - rho; nn_weights[j] = rj <= 0.0 ? 1.0 : std::exp(-rj / sigma); } if (save_sigmas) { sigmas[i] = sigma; rhos[i] = rho; } } void smooth_knn(std::size_t begin, std::size_t end, const std::vector<double> &nn_dist, const std::vector<std::size_t> &nn_ptr, bool skip_first, const std::vector<double> &target, double local_connectivity, double tol, std::size_t n_iter, double min_k_dist_scale, double mean_distances, bool save_sigmas, std::vector<double> &nn_weights, std::vector<double> &sigmas, std::vector<double> &rhos, std::atomic_size_t &n_search_fails) { // number of binary search failures in this window std::size_t n_window_search_fails = 0; for (std::size_t i = begin; i < end; i++) { smooth_knn(i, nn_dist, nn_ptr, skip_first, target, local_connectivity, tol, n_iter, min_k_dist_scale, mean_distances, save_sigmas, nn_weights, sigmas, rhos, n_window_search_fails); } // Update global count of failures n_search_fails += n_window_search_fails; } auto reset_local_metric(const std::vector<double> &probabilities, std::size_t i_begin, std::size_t i_end, double target, double tol, std::size_t n_iter, std::size_t &n_window_search_fails) -> double { constexpr auto double_max = (std::numeric_limits<double>::max)(); double lo = 0.0; double hi = double_max; double mid = 1.0; double mid_best = mid; double adiff_min = double_max; bool converged = false; for (std::size_t iter = 0; iter < n_iter; iter++) { double psum = 0.0; for (auto j = i_begin; j < i_end; j++) { psum += std::pow(probabilities[j], mid); } double adiff = std::abs(psum - target); if (adiff < tol) { converged = true; break; } if (adiff < adiff_min) { adiff_min = adiff; mid_best = mid; } if (psum < target) { hi = mid; mid = 0.5 * (lo + hi); } else { lo = mid; if (hi == double_max) { mid *= 2; } else { mid = 0.5 * (lo + hi); } } } if (!converged) { ++n_window_search_fails; mid = mid_best; } return mid; } void reset_local_metric(std::vector<double> &probabilities, const std::vector<std::size_t> &prob_ptr, std::size_t i, double target, double tol, std::size_t n_iter, std::size_t &n_window_search_fails) { auto i_begin = prob_ptr[i]; auto i_end = prob_ptr[i + 1]; auto mid = reset_local_metric(probabilities, i_begin, i_end, target, tol, n_iter, n_window_search_fails); // create the final membership strengths for (auto j = i_begin; j < i_end; j++) { probabilities[j] = std::pow(probabilities[j], mid); } } void reset_local_metric(std::size_t begin, std::size_t end, std::vector<double> &probabilities, const std::vector<std::size_t> &prob_ptr, double target, double tol, std::size_t n_iter, std::atomic_size_t &n_search_fails) { std::size_t n_window_search_fails = 0; for (auto i = begin; i < end; i++) { reset_local_metric(probabilities, prob_ptr, i, target, tol, n_iter, n_window_search_fails); } n_search_fails += n_window_search_fails; } } // namespace uwot #endif // UWOT_SMOOTH_KNN_H
10,311
32.480519
80
h
uwot
uwot-master/inst/include/uwot/supervised.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. #include <algorithm> #include <cmath> #include <limits> #include <vector> #ifndef UWOT_SUPERVISED_H #define UWOT_SUPERVISED_H namespace uwot { void fast_intersection(const std::vector<int> &rows, const std::vector<int> &cols, std::vector<double> &values, const std::vector<int> &target, double unknown_dist = 1.0, double far_dist = 5.0, int na = (std::numeric_limits<int>::min)() ) { double ex_unknown = std::exp(-unknown_dist); double ex_far = std::exp(-far_dist); auto len = values.size(); for (std::size_t nz = 0; nz < len; ++nz) { auto i = rows[nz]; auto j = cols[nz]; if (target[i] == na || target[j] == na) { values[nz] = values[nz] * ex_unknown; } else if (target[i] != target[j]) { values[nz] = values[nz] * ex_far; } } } void general_sset_intersection( const std::vector<int> &indptr1, const std::vector<int> &indices1, const std::vector<double> &data1, const std::vector<int> &indptr2, const std::vector<int> &indices2, const std::vector<double> &data2, const std::vector<int> &result_row, const std::vector<int> &result_col, std::vector<double> &result_val, double mix_weight = 0.5) { double left_min = (std::max)(*std::min_element(data1.begin(), data1.end()) / 2.0, 1.0e-8); double right_min = (std::max)(*std::min_element(data2.begin(), data2.end()) / 2.0, 1.0e-8); for (std::size_t idx = 0; idx < result_row.size(); idx++) { auto i = result_col[idx]; auto j = result_row[idx]; double left_val = left_min; for (auto k = indptr1[i]; k < indptr1[i + 1]; k++) { if (indices1[k] == j) { left_val = data1[k]; } } double right_val = right_min; for (auto k = indptr2[i]; k < indptr2[i + 1]; k++) { if (indices2[k] == j) { right_val = data2[k]; } } if (left_val > left_min || right_val > right_min) { if (mix_weight < 0.5) { result_val[idx] = left_val * std::pow(right_val, (mix_weight / (1.0 - mix_weight))); } else { result_val[idx] = right_val * std::pow(left_val, (((1.0 - mix_weight) / mix_weight))); } } } } void general_sset_union( const std::vector<int> &indptr1, const std::vector<int> &indices1, const std::vector<double> &data1, const std::vector<int> &indptr2, const std::vector<int> &indices2, const std::vector<double> &data2, const std::vector<int> &result_row, const std::vector<int> &result_col, std::vector<double> &result_val, double mix_weight = 0.5) { double left_min = (std::max)(*std::min_element(data1.begin(), data1.end()) / 2.0, 1.0e-8); double right_min = (std::max)(*std::min_element(data2.begin(), data2.end()) / 2.0, 1.0e-8); for (std::size_t idx = 0; idx < result_row.size(); idx++) { auto i = result_col[idx]; auto j = result_row[idx]; double left_val = left_min; for (auto k = indptr1[i]; k < indptr1[i + 1]; k++) { if (indices1[k] == j) { left_val = data1[k]; } } double right_val = right_min; for (auto k = indptr2[i]; k < indptr2[i + 1]; k++) { if (indices2[k] == j) { right_val = data2[k]; } } result_val[idx] = left_val + right_val - left_val * right_val; } } } // namespace uwot #endif // UWOT_SUPERVISED_H
4,775
33.114286
80
h
uwot
uwot-master/inst/include/uwot/tauprng.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. // Three-component combined Tausworthe "taus88" PRNG from L'Ecuyer 1996. #ifndef UWOT_TAUPRNG_H #define UWOT_TAUPRNG_H namespace uwot { struct tau_prng { uint64_t state0; uint64_t state1; // technically this needs to always be > 7 uint64_t state2; // and this should be > 15 static constexpr uint64_t MAGIC0{4294967294}; static constexpr uint64_t MAGIC1{4294967288}; static constexpr uint64_t MAGIC2{4294967280}; tau_prng(uint64_t state0, uint64_t state1, uint64_t state2) : state0(state0), state1(state1 > 7 ? state1 : 8), state2(state2 > 15 ? state2 : 16) {} auto operator()() -> int32_t { state0 = (((state0 & MAGIC0) << 12) & 0xffffffff) ^ ((((state0 << 13) & 0xffffffff) ^ state0) >> 19); state1 = (((state1 & MAGIC1) << 4) & 0xffffffff) ^ ((((state1 << 2) & 0xffffffff) ^ state1) >> 25); state2 = (((state2 & MAGIC2) << 17) & 0xffffffff) ^ ((((state2 << 3) & 0xffffffff) ^ state2) >> 11); return state0 ^ state1 ^ state2; } // return a value in (0, n] auto operator()(std::size_t n) -> std::size_t { std::size_t result = (*this)() % n; return result; } }; } // namespace uwot #endif // UWOT_TAUPRNG_H
2,575
36.882353
79
h
uwot
uwot-master/inst/include/uwot/transform.h
// BSD 2-Clause License // // Copyright 2020 James Melville // // 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 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 // OF SUCH DAMAGE. #ifndef UWOT_TRANSFORM_H #define UWOT_TRANSFORM_H namespace uwot { inline auto sum_nbrs(std::size_t i, const std::vector<float> &train_embedding, const std::vector<int> &nn_index, std::size_t n_neighbors, std::size_t ndim, std::vector<double> &sumc) -> void { for (std::size_t j = 0; j < n_neighbors; j++) { auto nbr = nn_index[i * n_neighbors + j]; for (std::size_t k = 0; k < ndim; k++) { sumc[k] += train_embedding[ndim * nbr + k]; } } } inline auto sum_nbrs_weighted(std::size_t i, const std::vector<float> &train_embedding, const std::vector<int> &nn_index, std::size_t n_neighbors, std::size_t ndim, const std::vector<float> &nn_weights, std::vector<double> &sumc, double &sumw) -> void { std::size_t i_nbrs = i * n_neighbors; for (std::size_t j = 0; j < n_neighbors; j++) { auto w = nn_weights[i_nbrs + j]; sumw += w; auto nbr = nn_index[i_nbrs + j]; for (std::size_t k = 0; k < ndim; k++) { sumc[k] += train_embedding[ndim * nbr + k] * w; } } } void init_by_mean(std::size_t begin, std::size_t end, std::size_t ndim, std::size_t n_neighbors, const std::vector<int> &nn_index, const std::vector<float> &nn_weights, std::size_t n_test_vertices, const std::vector<float> &train_embedding, std::size_t n_train_vertices, std::vector<float> &embedding) { bool weighted = nn_weights.size() > 0; std::vector<double> sumc(ndim); for (std::size_t i = begin; i < end; i++) { std::fill(sumc.begin(), sumc.end(), 0.0); double sumw = 0.0; // cost of checking this boolean N times is not going to be a bottleneck if (weighted) { sum_nbrs_weighted(i, train_embedding, nn_index, n_neighbors, ndim, nn_weights, sumc, sumw); } else { sumw = static_cast<double>(n_neighbors); sum_nbrs(i, train_embedding, nn_index, n_neighbors, ndim, sumc); } for (std::size_t k = 0; k < ndim; k++) { embedding[ndim * i + k] = sumc[k] / sumw; } } } } // namespace uwot #endif // UWOT_TRANSFORM_H
3,657
39.197802
80
h
uwot
uwot-master/inst/include/uwot/update.h
// BSD 2-Clause License // // Copyright 2021 James Melville // // 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 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 // OF SUCH DAMAGE. #ifndef UWOT_UPDATE_H #define UWOT_UPDATE_H #include "gradient.h" #include "optimize.h" #include "sampler.h" namespace uwot { // (User-supplied) callback to be invoked at the end of each epoch // e.g. to plot or save coordinates for diagnostic purposes struct EpochCallback { virtual void operator()(std::size_t epoch, std::size_t n_epochs, const std::vector<float> &head_embedding, const std::vector<float> &tail_embedding) = 0; virtual ~EpochCallback() {} }; struct DoNothingCallback : EpochCallback { void operator()(std::size_t, std::size_t, const std::vector<float> &, const std::vector<float> &) override {} }; template <typename Update, typename Gradient, typename Prng> inline void process_edge(Update &update, Gradient &gradient, Sampler &sampler, Prng &prng, const std::vector<unsigned int> &positive_head, const std::vector<unsigned int> &positive_tail, std::size_t ndim, std::size_t n_tail_vertices, std::size_t edge, std::size_t thread_id, std::vector<float> &disp) { if (!sampler.is_sample_edge(edge)) { return; } const std::size_t dj = ndim * positive_head[edge]; const std::size_t dk = ndim * positive_tail[edge]; // j and k are joined by an edge: push them together update_attract(update, gradient, dj, dk, ndim, disp, thread_id); // Negative sampling step: assume any other point (dkn) is a -ve example std::size_t n_neg_samples = sampler.get_num_neg_samples(edge); for (std::size_t p = 0; p < n_neg_samples; p++) { const std::size_t dkn = prng(n_tail_vertices) * ndim; if (dj == dkn) { continue; } // push them apart update_repel(update, gradient, dj, dkn, ndim, disp, thread_id); } sampler.next_sample(edge, n_neg_samples); } template <typename Update, typename Gradient> inline void update_attract(Update &update, const Gradient &gradient, std::size_t dj, std::size_t dk, std::size_t ndim, std::vector<float> &disp, std::size_t key) { float grad_coeff = grad_attr(gradient, update.head_embedding, dj, update.tail_embedding, dk, ndim, disp); for (std::size_t d = 0; d < ndim; d++) { update.attract(dj, dk, d, grad_d(gradient, disp, d, grad_coeff), key); } } template <typename Update, typename Gradient> inline void update_repel(Update &update, const Gradient &gradient, std::size_t dj, std::size_t dk, std::size_t ndim, std::vector<float> &disp, std::size_t key) { float grad_coeff = grad_rep(gradient, update.head_embedding, dj, update.tail_embedding, dk, ndim, disp); for (std::size_t d = 0; d < ndim; d++) { update.repel(dj, dk, d, grad_d(gradient, disp, d, grad_coeff), key); } } // Function to decide whether to move both vertices in an edge // Default empty version does nothing: used in umap_transform when // some of the vertices should be held fixed template <bool DoMoveVertex = false> inline void update_vec(std::vector<float> &, float, std::size_t, std::size_t) {} // Specialization to move vertex/update gradient: used in umap when both // vertices in an edge should be moved template <> inline void update_vec<true>(std::vector<float> &vec, float val, std::size_t i, std::size_t j) { vec[i + j] += val; } // If DoMoveTailVertex = true, graph is symmetric and head and tail point to the // same data. So we can just update the head coord i with double the gradient // now and not worry about updating it when it shows up in the edge list as tail // point j template <bool DoMoveTailVertex = true> inline void update_head_grad_vec(std::vector<float> &vec, std::size_t i, float val) { vec[i] += 2.0 * val; } // Specialization for DoMoveTailVertex = true. In this case the edges are not // symmetric and the tail embedding should be held fixed, so the head node only // get one lot of gradient updating template <> inline void update_head_grad_vec<false>(std::vector<float> &vec, std::size_t i, float val) { vec[i] += val; } // DoMoveVertex: true if both ends of a positive edge should be updated template <bool DoMoveVertex> struct InPlaceUpdate { std::vector<float> &head_embedding; std::vector<float> &tail_embedding; Sgd opt; std::unique_ptr<EpochCallback> epoch_callback; InPlaceUpdate(std::vector<float> &head_embedding, std::vector<float> &tail_embedding, float alpha, EpochCallback *epoch_callback) : head_embedding(head_embedding), tail_embedding(tail_embedding), opt(alpha), epoch_callback(std::move(epoch_callback)) {} inline void attract(std::size_t dj, std::size_t dk, std::size_t d, float grad_d, std::size_t) { float update_d = opt.alpha * grad_d; head_embedding[dj + d] += update_d; // we don't only always want points in the tail to move // e.g. if adding new points to an existing embedding update_vec<DoMoveVertex>(tail_embedding, -update_d, d, dk); } inline void repel(std::size_t dj, std::size_t dk, std::size_t d, float grad_d, std::size_t) { head_embedding[dj + d] += opt.alpha * grad_d; // Python implementation doesn't move the negative sample but as Damrich // and Hamprecht (2021) note, it ought to. However they also note it has // no qualitative effect on the results. This is presumably because // including this repulsion is the same as doubling the negative sample rate // which doesn't have a huge effect on going from the default of 5 to 10 // update_vec<DoMoveVertex>(tail_embedding, opt.alpha * -grad_d, d, dk); } inline void epoch_begin(std::size_t, std::size_t) {} template <typename Parallel> void epoch_end(std::size_t epoch, std::size_t n_epochs, Parallel &) { opt.epoch_end(epoch, n_epochs); (*epoch_callback)(epoch, n_epochs, head_embedding, tail_embedding); } }; // 1. When DoMoveVertex is true then we want to update the head and tail nodes // of an edge. In this case the head and tail coordinates point to the same data // so it doesn't matter whether we calculate the gradient for or update the // coordinates in head or tail. // 2. When DoMoveVertex is false then the head and tail coordinates point to // different data. The tail coordinates are fixed in this case, so again they // do not move. Hence both so in both cases we only ever need to update the head // coordinates. template <bool DoMoveVertex, typename Opt> struct BatchUpdate { std::vector<float> &head_embedding; std::vector<float> &tail_embedding; Opt &opt; std::vector<float> gradient; std::unique_ptr<EpochCallback> epoch_callback; BatchUpdate(std::vector<float> &head_embedding, std::vector<float> &tail_embedding, Opt &opt, EpochCallback *epoch_callback) : head_embedding(head_embedding), tail_embedding(tail_embedding), opt(opt), gradient(head_embedding.size()), epoch_callback(std::move(epoch_callback)) {} BatchUpdate(BatchUpdate &&other) : head_embedding(other.head_embedding), tail_embedding(other.tail_embedding), opt(other.opt), gradient(other.head_embedding.size()), epoch_callback(std::move(other.epoch_callback)) {} inline void attract(std::size_t dj, std::size_t dk, std::size_t d, float grad_d, std::size_t) { update_head_grad_vec<DoMoveVertex>(gradient, dj + d, grad_d); } inline void repel(std::size_t dj, std::size_t dk, std::size_t d, float grad_d, std::size_t) { gradient[dj + d] += grad_d; } void epoch_begin(std::size_t, std::size_t) { std::fill(gradient.begin(), gradient.end(), 0.0f); } template <typename Parallel> void epoch_end(std::size_t epoch, std::size_t n_epochs, Parallel &parallel) { auto worker = [&](std::size_t begin, std::size_t end, std::size_t) { for (std::size_t i = begin; i < end; i++) { // head_embedding[i] += opt.alpha * gradient[i]; opt.update(head_embedding, gradient, i); } }; parallel.pfor(head_embedding.size(), worker); opt.epoch_end(epoch, n_epochs); (*epoch_callback)(epoch, n_epochs, head_embedding, tail_embedding); } }; } // namespace uwot #endif // UWOT_UPDATE_H
9,808
41.098712
80
h
uwot
uwot-master/src/nn_parallel.h
// UWOT -- An R package for dimensionality reduction using UMAP // // Copyright (C) 2020 James Melville // // This file is part of UWOT // // UWOT 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. // // UWOT 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 UWOT. If not, see <http://www.gnu.org/licenses/>. #include <vector> #include "RcppAnnoy.h" #if ANNOY_VERSION >= Annoy_Version(1,17,3) typedef Annoy::AnnoyIndexSingleThreadedBuildPolicy AnnoyIndexThreadedBuildPolicy; struct UwotAnnoyEuclidean { using Distance = Annoy::Euclidean; using S = int32_t; using T = float; }; struct UwotAnnoyCosine { using Distance = Annoy::Angular; using S = int32_t; using T = float; }; struct UwotAnnoyManhattan { using Distance = Annoy::Manhattan; using S = int32_t; using T = float; }; struct UwotAnnoyHamming { using Distance = Annoy::Hamming; using S = int32_t; using T = uint64_t; }; #else typedef AnnoyIndexSingleThreadedBuildPolicy AnnoyIndexThreadedBuildPolicy; struct UwotAnnoyEuclidean { using Distance = Euclidean; using S = int32_t; using T = float; }; struct UwotAnnoyCosine { using Distance = Angular; using S = int32_t; using T = float; }; struct UwotAnnoyManhattan { using Distance = Manhattan; using S = int32_t; using T = float; }; struct UwotAnnoyHamming { using Distance = Hamming; using S = int32_t; using T = uint64_t; }; #endif // of 'if ANNOY_VERSION >= Annoy_Version(1,17,3)' template <typename UwotAnnoyDistance> struct NNWorker { const std::string &index_name; const std::vector<double> &mat; std::size_t nrow; std::size_t ncol; std::size_t n_neighbors; std::size_t search_k; std::vector<int> idx; std::vector<typename UwotAnnoyDistance::T> dists; #if ANNOY_VERSION >= Annoy_Version(1,17,3) Annoy::AnnoyIndex<typename UwotAnnoyDistance::S, typename UwotAnnoyDistance::T, typename UwotAnnoyDistance::Distance, Kiss64Random, AnnoyIndexThreadedBuildPolicy> index; #else AnnoyIndex<typename UwotAnnoyDistance::S, typename UwotAnnoyDistance::T, typename UwotAnnoyDistance::Distance, Kiss64Random, AnnoyIndexThreadedBuildPolicy> index; #endif NNWorker(const std::string &index_name, const std::vector<double> &mat, std::size_t ncol, std::size_t n_neighbors, std::size_t search_k) : index_name(index_name), mat(mat), nrow(mat.size() / ncol), ncol(ncol), n_neighbors(n_neighbors), search_k(search_k), idx(nrow * n_neighbors, -1), dists(nrow * n_neighbors), index(ncol) { index.load(index_name.c_str()); } ~NNWorker() { index.unload(); } void operator()(std::size_t begin, std::size_t end) { for (auto i = begin; i < end; i++) { std::vector<typename UwotAnnoyDistance::T> fv(ncol); for (std::size_t j = 0; j < ncol; j++) { fv[j] = mat[i + j * nrow]; } std::vector<typename UwotAnnoyDistance::S> result; std::vector<typename UwotAnnoyDistance::T> distances; index.get_nns_by_vector(fv.data(), n_neighbors, search_k, &result, &distances); if (result.size() != n_neighbors || distances.size() != n_neighbors) { break; } for (std::size_t j = 0; j < n_neighbors; j++) { dists[i + j * nrow] = distances[j]; idx[i + j * nrow] = result[j]; } } } };
3,859
27.175182
81
h
uwot
uwot-master/src/rng.h
// UWOT -- An R package for dimensionality reduction using UMAP // // Copyright (C) 2018 James Melville // // This file is part of UWOT // // UWOT 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. // // UWOT 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 UWOT. If not, see <http://www.gnu.org/licenses/>. #ifndef UWOT_RNG_H #define UWOT_RNG_H #include <limits> // linked from dqrng #include "convert_seed.h" #include "pcg_random.hpp" #include "uwot/tauprng.h" // NOT THREAD SAFE // based on code in the dqsample package static uint64_t random64() { return static_cast<uint64_t>( R::runif(0, 1) * static_cast<double>((std::numeric_limits<uint64_t>::max)())); } // NOT THREAD SAFE static uint32_t random32() { return static_cast<uint32_t>( R::runif(0, 1) * static_cast<double>((std::numeric_limits<uint32_t>::max)())); } struct batch_tau_factory { std::size_t n_rngs; std::vector<uint64_t> seeds; static const constexpr std::size_t seeds_per_rng = 3; batch_tau_factory() : n_rngs(1), seeds(seeds_per_rng * n_rngs) {} batch_tau_factory(std::size_t n_rngs) : n_rngs(n_rngs), seeds(seeds_per_rng * n_rngs) {} void reseed() { for (std::size_t i = 0; i < seeds.size(); i++) { seeds[i] = random64(); } } uwot::tau_prng create(std::size_t n) { const std::size_t idx = n * seeds_per_rng; return uwot::tau_prng(seeds[idx], seeds[idx + 1], seeds[idx + 2]); } }; struct pcg_prng { pcg32 gen; pcg_prng(uint64_t seed) { gen.seed(seed); } // return a value in (0, n] inline std::size_t operator()(std::size_t n) { std::size_t result = gen(n); return result; } }; struct batch_pcg_factory { std::size_t n_rngs; std::vector<uint32_t> seeds; static const constexpr std::size_t seeds_per_rng = 2; batch_pcg_factory() : n_rngs(1), seeds(seeds_per_rng * n_rngs) {} batch_pcg_factory(std::size_t n_rngs) : n_rngs(n_rngs), seeds(seeds_per_rng * n_rngs) {} void reseed() { for (std::size_t i = 0; i < seeds.size(); i++) { seeds[i] = random32(); } } pcg_prng create(std::size_t n) { uint32_t pcg_seeds[2] = {seeds[n * seeds_per_rng], seeds[n * seeds_per_rng + 1]}; return pcg_prng(dqrng::convert_seed<uint64_t>(pcg_seeds, 2)); } }; // For backwards compatibility in non-batch mode struct tau_factory { uint64_t seed1; uint64_t seed2; tau_factory(std::size_t) : seed1(0), seed2(0) { seed1 = random64(); seed2 = random64(); } void reseed() { seed1 = random64(); seed2 = random64(); } uwot::tau_prng create(std::size_t seed) { return uwot::tau_prng(seed1, seed2, uint64_t{seed}); } }; struct pcg_factory { uint32_t seed1; pcg_factory(std::size_t) : seed1(random32()) {} void reseed() { seed1 = random32(); } pcg_prng create(std::size_t seed) { uint32_t seeds[2] = {seed1, static_cast<uint32_t>(seed)}; return pcg_prng(dqrng::convert_seed<uint64_t>(seeds, 2)); } }; #endif // UWOT_RNG_H
3,471
25.105263
72
h
uwot
uwot-master/src/rparallel.h
// UWOT -- An R package for dimensionality reduction using UMAP // // Copyright (C) 2021 James Melville // // This file is part of UWOT // // UWOT 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. // // UWOT 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 UWOT. If not, see <http://www.gnu.org/licenses #ifndef UWOT_RPARALLEL_H #define UWOT_RPARALLEL_H #include "RcppPerpendicular.h" struct RParallel { std::size_t n_threads; std::size_t grain_size; RParallel(std::size_t n_threads, std::size_t grain_size) : n_threads(n_threads), grain_size(grain_size) {} template <typename Worker> void pfor(std::size_t n_items, Worker &worker) { RcppPerpendicular::pfor(n_items, worker, n_threads, grain_size); } template <typename Worker> void pfor(std::size_t begin, std::size_t end, Worker &worker) { RcppPerpendicular::pfor(begin, end, worker, n_threads, grain_size); } }; struct RSerial { template <typename Worker> void pfor(std::size_t n_items, Worker &worker) { pfor(0, n_items, worker); } template <typename Worker> void pfor(std::size_t begin, std::size_t end, Worker &worker) { worker(begin, end, 0); } }; #endif // UWOT_RPARALLEL_H
1,656
29.685185
77
h
uwot
uwot-master/src/rprogress.h
// UWOT -- An R package for dimensionality reduction using UMAP // // Copyright (C) 2021 James Melville // // This file is part of UWOT // // UWOT 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. // // UWOT 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 UWOT. If not, see <http://www.gnu.org/licenses #ifndef UWOT_RPROGRESS_H #define UWOT_RPROGRESS_H // [[Rcpp::depends(RcppProgress)]] #include <progress.hpp> struct RProgress { Progress progress; bool verbose; RProgress(std::size_t n_epochs, bool verbose) : progress(n_epochs, verbose), verbose(verbose) {} auto is_aborted() -> bool { bool aborted = Progress::check_abort(); if (aborted) { progress.cleanup(); } return aborted; } void report() { if (verbose) { progress.increment(); } } }; #endif // UWOT_RPROGRESS_H
1,302
25.591837
72
h
null
fantasia3d.unofficial-main/render/renderutils/c_src/common.h
/* * Copyright (c) 2020-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. * * NVIDIA CORPORATION, its affiliates and licensors retain all intellectual * property and proprietary rights in and to this material, related * documentation and any modifications thereto. Any use, reproduction, * disclosure or distribution of this material and related documentation * without an express license agreement from NVIDIA CORPORATION or * its affiliates is strictly prohibited. */ #pragma once #include <cuda.h> #include <stdint.h> #include "vec3f.h" #include "vec4f.h" #include "tensor.h" dim3 getLaunchBlockSize(int maxWidth, int maxHeight, dim3 dims); dim3 getLaunchGridSize(dim3 blockSize, dim3 dims); #ifdef __CUDACC__ #ifdef _MSC_VER #define M_PI 3.14159265358979323846f #endif __host__ __device__ static inline dim3 getWarpSize(dim3 blockSize) { return dim3( min(blockSize.x, 32u), min(max(32u / blockSize.x, 1u), min(32u, blockSize.y)), min(max(32u / (blockSize.x * blockSize.y), 1u), min(32u, blockSize.z)) ); } __device__ static inline float clamp(float val, float mn, float mx) { return min(max(val, mn), mx); } #else dim3 getWarpSize(dim3 blockSize); #endif
1,218
28.731707
101
h
null
fantasia3d.unofficial-main/render/renderutils/c_src/cubemap.h
/* * Copyright (c) 2020-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. * * NVIDIA CORPORATION, its affiliates and licensors retain all intellectual * property and proprietary rights in and to this material, related * documentation and any modifications thereto. Any use, reproduction, * disclosure or distribution of this material and related documentation * without an express license agreement from NVIDIA CORPORATION or * its affiliates is strictly prohibited. */ #pragma once #include "common.h" struct DiffuseCubemapKernelParams { Tensor cubemap; Tensor out; dim3 gridSize; }; struct SpecularCubemapKernelParams { Tensor cubemap; Tensor bounds; Tensor out; dim3 gridSize; float costheta_cutoff; float roughness; }; struct SpecularBoundsKernelParams { float costheta_cutoff; Tensor out; dim3 gridSize; };
907
22.282051
80
h
null
fantasia3d.unofficial-main/render/renderutils/c_src/loss.h
/* * Copyright (c) 2020-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. * * NVIDIA CORPORATION, its affiliates and licensors retain all intellectual * property and proprietary rights in and to this material, related * documentation and any modifications thereto. Any use, reproduction, * disclosure or distribution of this material and related documentation * without an express license agreement from NVIDIA CORPORATION or * its affiliates is strictly prohibited. */ #pragma once #include "common.h" enum TonemapperType { TONEMAPPER_NONE = 0, TONEMAPPER_LOG_SRGB = 1 }; enum LossType { LOSS_L1 = 0, LOSS_MSE = 1, LOSS_RELMSE = 2, LOSS_SMAPE = 3 }; struct LossKernelParams { Tensor img; Tensor target; Tensor out; dim3 gridSize; TonemapperType tonemapper; LossType loss; };
896
22
80
h