source
stringlengths
3
92
c
stringlengths
26
2.25M
GB_unop__identity_int8_int16.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_int8_int16 // op(A') function: GB_unop_tran__identity_int8_int16 // C type: int8_t // A type: int16_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int8_t z = (int8_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = (int8_t) aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_int8_int16 ( int8_t *Cx, // Cx and Ax may be aliased const int16_t *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (int16_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int16_t aij = Ax [p] ; int8_t z = (int8_t) aij ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int16_t aij = Ax [p] ; int8_t z = (int8_t) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_int8_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_subassign_12_and_20.c
//------------------------------------------------------------------------------ // GB_subassign_12_and_20: C(I,J)<M or !M,repl> += A ; using S //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Method 12: C(I,J)<M,repl> += A ; using S // Method 20: C(I,J)<!M,repl> += A ; using S // M: present // Mask_comp: true or false // C_replace: true // accum: present // A: matrix // S: constructed // C: not bitmap: use GB_bitmap_assign instead // M, A: any sparsity structure. #include "GB_subassign_methods.h" GrB_Info GB_subassign_12_and_20 ( GrB_Matrix C, // input: const GrB_Index *I, const int64_t ni, const int64_t nI, const int Ikind, const int64_t Icolon [3], const GrB_Index *J, const int64_t nj, const int64_t nJ, const int Jkind, const int64_t Jcolon [3], const GrB_Matrix M, const bool Mask_struct, // if true, use the only structure of M const bool Mask_comp, // if true, !M, else use M const GrB_BinaryOp accum, const GrB_Matrix A, GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (!GB_IS_BITMAP (C)) ; ASSERT (!GB_IS_FULL (C)) ; ASSERT (!GB_aliased (C, M)) ; // NO ALIAS of C==M ASSERT (!GB_aliased (C, A)) ; // NO ALIAS of C==A //-------------------------------------------------------------------------- // S = C(I,J) //-------------------------------------------------------------------------- GB_EMPTY_TASKLIST ; GB_OK (GB_subassign_symbolic (S, C, I, ni, J, nj, true, Context)) ; //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- GB_MATRIX_WAIT_IF_JUMBLED (M) ; GB_MATRIX_WAIT_IF_JUMBLED (A) ; GB_GET_C ; // C must not be bitmap GB_GET_MASK ; GB_GET_A ; GB_GET_S ; GB_GET_ACCUM ; //-------------------------------------------------------------------------- // Method 12: C(I,J)<M,repl> += A ; using S // Method 20: C(I,J)<!M,repl> += A ; using S //-------------------------------------------------------------------------- // Time: all entries in S+A must be traversed, so Omega(nnz(S)+nnz(A)) is // required. All cases of the mask (0, 1, or not present) must be // considered, because of the C_replace descriptor being true. //-------------------------------------------------------------------------- // Parallel: A+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20) //-------------------------------------------------------------------------- if (A_is_bitmap) { // all of IxJ must be examined GB_SUBASSIGN_IXJ_SLICE ; } else { // traverse all A+S GB_SUBASSIGN_TWO_SLICE (A, S) ; } //-------------------------------------------------------------------------- // phase 1: create zombies, update entries, and count pending tuples //-------------------------------------------------------------------------- if (A_is_bitmap) { //---------------------------------------------------------------------- // phase1: A is bitmap //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_IXJ_TASK_DESCRIPTOR_PHASE1 (iA_start, iA_end) ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t j = kfirst ; j <= klast ; j++) { //-------------------------------------------------------------- // get S(iA_start:iA_end,j) //-------------------------------------------------------------- GB_GET_VECTOR_FOR_IXJ (S, iA_start) ; int64_t pA_start = j * Avlen ; //-------------------------------------------------------------- // get M(:,j) //-------------------------------------------------------------- int64_t pM_start, pM_end ; GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ; bool mjdense = (pM_end - pM_start) == Mvlen ; //-------------------------------------------------------------- // do a 2-way merge of S(iA_start:iA_end,j) and A(ditto,j) //-------------------------------------------------------------- for (int64_t iA = iA_start ; iA < iA_end ; iA++) { int64_t pA = pA_start + iA ; bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iA) ; bool Afound = Ab [pA] ; if (Sfound && !Afound) { // S (i,j) is present but A (i,j) is not GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ; if (Mask_comp) mij = !mij ; if (!mij) { // ----[C . 0] or [X . 0]--------------------------- // [X . 0]: action: ( X ): still a zombie // [C . 0]: C_repl: action: ( delete ): now zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; } GB_NEXT (S) ; } else if (!Sfound && Afound) { // S (i,j) is not present, A (i,j) is present GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ; if (Mask_comp) mij = !mij ; if (mij) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) task_pending++ ; } } else if (Sfound && Afound) { // both S (i,j) and A (i,j) present GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ; if (Mask_comp) mij = !mij ; GB_C_S_LOOKUP ; if (mij) { // ----[C A 1] or [X A 1]--------------------------- // [C A 1]: action: ( =A ): A to C no accum // [C A 1]: action: ( =C+A ): apply accum // [X A 1]: action: ( undelete ): zombie lives GB_withaccum_C_A_1_matrix ; } else { // ----[C A 0] or [X A 0]--------------------------- // [X A 0]: action: ( X ): still a zombie // [C A 0]: C_repl: action: ( delete ): now zombie GB_DELETE_ENTRY ; } GB_NEXT (S) ; } } } GB_PHASE1_TASK_WRAPUP ; } } else { //---------------------------------------------------------------------- // phase1: A is hypersparse, sparse, or full //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_TASK_DESCRIPTOR_PHASE1 ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t k = kfirst ; k <= klast ; k++) { //-------------------------------------------------------------- // get A(:,j) and S(:,j) //-------------------------------------------------------------- int64_t j = GBH (Zh, k) ; GB_GET_MAPPED (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X, Avlen); GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen); //-------------------------------------------------------------- // get M(:,j) //-------------------------------------------------------------- int64_t pM_start, pM_end ; GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ; bool mjdense = (pM_end - pM_start) == Mvlen ; //-------------------------------------------------------------- // do a 2-way merge of S(:,j) and A(:,j) //-------------------------------------------------------------- // jC = J [j] ; or J is a colon expression // int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and A (:,j) have entries while (pS < pS_end && pA < pA_end) { int64_t iS = GBI (Si, pS, Svlen) ; int64_t iA = GBI (Ai, pA, Avlen) ; if (iS < iA) { // S (i,j) is present but A (i,j) is not GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iS) ; if (Mask_comp) mij = !mij ; if (!mij) { // ----[C . 0] or [X . 0]--------------------------- // [X . 0]: action: ( X ): still a zombie // [C . 0]: C_repl: action: ( delete ): now zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; } GB_NEXT (S) ; } else if (iA < iS) { // S (i,j) is not present, A (i,j) is present GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ; if (Mask_comp) mij = !mij ; if (mij) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) task_pending++ ; } GB_NEXT (A) ; } else { // both S (i,j) and A (i,j) present GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ; if (Mask_comp) mij = !mij ; GB_C_S_LOOKUP ; if (mij) { // ----[C A 1] or [X A 1]--------------------------- // [C A 1]: action: ( =A ): A to C no accum // [C A 1]: action: ( =C+A ): apply accum // [X A 1]: action: ( undelete ): zombie lives GB_withaccum_C_A_1_matrix ; } else { // ----[C A 0] or [X A 0]--------------------------- // [X A 0]: action: ( X ): still a zombie // [C A 0]: C_repl: action: ( delete ): now zombie GB_DELETE_ENTRY ; } GB_NEXT (S) ; GB_NEXT (A) ; } } // while list S (:,j) has entries. List A (:,j) exhausted. while (pS < pS_end) { int64_t iS = GBI (Si, pS, Svlen) ; GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iS) ; if (Mask_comp) mij = !mij ; if (!mij) { // ----[C . 0] or [X . 0]------------------------------- // [X . 0]: action: ( X ): still a zombie // [C . 0]: C_repl: action: ( delete ): becomes zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; } GB_NEXT (S) ; } // while list A (:,j) has entries. List S (:,j) exhausted. while (pA < pA_end) { // S (i,j) is not present, A (i,j) is present int64_t iA = GBI (Ai, pA, Avlen) ; GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ; if (Mask_comp) mij = !mij ; if (mij) { // ----[. A 1]------------------------------------------ // [. A 1]: action: ( insert ) task_pending++ ; } GB_NEXT (A) ; } } GB_PHASE1_TASK_WRAPUP ; } } //-------------------------------------------------------------------------- // phase 2: insert pending tuples //-------------------------------------------------------------------------- GB_PENDING_CUMSUM ; if (A_is_bitmap) { //---------------------------------------------------------------------- // phase2: A is bitmap //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_IXJ_TASK_DESCRIPTOR_PHASE2 (iA_start, iA_end) ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t j = kfirst ; j <= klast ; j++) { //-------------------------------------------------------------- // get S(iA_start:iA_end,j) //-------------------------------------------------------------- GB_GET_VECTOR_FOR_IXJ (S, iA_start) ; int64_t pA_start = j * Avlen ; //-------------------------------------------------------------- // get M(:,j) //-------------------------------------------------------------- int64_t pM_start, pM_end ; GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ; bool mjdense = (pM_end - pM_start) == Mvlen ; //-------------------------------------------------------------- // do a 2-way merge of S(iA_start:iA_end,j) and A(ditto,j) //-------------------------------------------------------------- // jC = J [j] ; or J is a colon expression int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; for (int64_t iA = iA_start ; iA < iA_end ; iA++) { int64_t pA = pA_start + iA ; bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iA) ; bool Afound = Ab [pA] ; if (!Sfound && Afound) { // S (i,j) is not present, A (i,j) is present GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ; if (Mask_comp) mij = !mij ; if (mij) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; } } else if (Sfound) { // S (i,j) present GB_NEXT (S) ; } } } GB_PHASE2_TASK_WRAPUP ; } } else { //---------------------------------------------------------------------- // phase2: A is hypersparse, sparse, or full //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_TASK_DESCRIPTOR_PHASE2 ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t k = kfirst ; k <= klast ; k++) { //-------------------------------------------------------------- // get A(:,j) and S(:,j) //-------------------------------------------------------------- int64_t j = GBH (Zh, k) ; GB_GET_MAPPED (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X, Avlen); GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen); //-------------------------------------------------------------- // get M(:,j) //-------------------------------------------------------------- int64_t pM_start, pM_end ; GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ; bool mjdense = (pM_end - pM_start) == Mvlen ; //-------------------------------------------------------------- // do a 2-way merge of S(:,j) and A(:,j) //-------------------------------------------------------------- // jC = J [j] ; or J is a colon expression int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and A (:,j) have entries while (pS < pS_end && pA < pA_end) { int64_t iS = GBI (Si, pS, Svlen) ; int64_t iA = GBI (Ai, pA, Avlen) ; if (iS < iA) { // S (i,j) is present but A (i,j) is not GB_NEXT (S) ; } else if (iA < iS) { // S (i,j) is not present, A (i,j) is present GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ; if (Mask_comp) mij = !mij ; if (mij) { // ----[. A 1]-------------------------------------- // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; } GB_NEXT (A) ; } else { // both S (i,j) and A (i,j) present GB_NEXT (S) ; GB_NEXT (A) ; } } // while list A (:,j) has entries. List S (:,j) exhausted. while (pA < pA_end) { // S (i,j) is not present, A (i,j) is present int64_t iA = GBI (Ai, pA, Avlen) ; GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ; if (Mask_comp) mij = !mij ; if (mij) { // ----[. A 1]------------------------------------------ // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; } GB_NEXT (A) ; } } GB_PHASE2_TASK_WRAPUP ; } } //-------------------------------------------------------------------------- // finalize the matrix and return result //-------------------------------------------------------------------------- GB_SUBASSIGN_WRAPUP ; }
cosapi.h
#ifndef COS_COS_COSAPI_H #define COS_COS_COSAPI_H /** * C Object System * COS api * * Copyright 2006+ Laurent Deniau <laurent.deniau@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef COS_COS_COS_H #error "COS: use <cos/cos/cos.h> instead of <cos/cos/cosapi.h>" #endif // low-level API void cos_init(void); void cos_deinit(void); double cos_initDuration(void); // in second. double cos_deinitDuration(void); // in second. BOOL cos_object_isKindOf(OBJ,const struct Class*); BOOL cos_object_changeClass(OBJ,const struct Class*); BOOL cos_object_unsafeChangeClass(OBJ,const struct Class*,const struct Class*); struct Generic* cos_generic_get(U32); struct Generic* cos_generic_getWithStr(STR); struct Class* cos_class_get(U32); struct Class* cos_class_getWithStr(STR); struct Class* cos_property_getWithStr(STR); BOOL cos_class_isSubclassOf (const struct Class*, const struct Class*); U32 cos_class_readProperties (const struct Class*,U32,const struct Class**,U32); U32 cos_class_writeProperties(const struct Class*,U32,const struct Class**,U32); IMP1 cos_method_get1(SEL,U32); IMP2 cos_method_get2(SEL,U32,U32); IMP3 cos_method_get3(SEL,U32,U32,U32); IMP4 cos_method_get4(SEL,U32,U32,U32,U32); IMP5 cos_method_get5(SEL,U32,U32,U32,U32,U32); IMP1 cos_method_lookup1(SEL,U32); IMP2 cos_method_lookup2(SEL,U32,U32); IMP3 cos_method_lookup3(SEL,U32,U32,U32); IMP4 cos_method_lookup4(SEL,U32,U32,U32,U32); IMP5 cos_method_lookup5(SEL,U32,U32,U32,U32,U32); /* inlined functions (see cos/cos/dispatch.h) IMP1 cos_method_fastLookup1(SEL,U32); IMP2 cos_method_fastLookup2(SEL,U32,U32); IMP3 cos_method_fastLookup3(SEL,U32,U32,U32); IMP4 cos_method_fastLookup4(SEL,U32,U32,U32,U32); IMP5 cos_method_fastLookup5(SEL,U32,U32,U32,U32,U32); BOOL cos_method_understand1(SEL,U32); BOOL cos_method_understand2(SEL,U32,U32); BOOL cos_method_understand3(SEL,U32,U32,U32); BOOL cos_method_understand4(SEL,U32,U32,U32,U32); BOOL cos_method_understand5(SEL,U32,U32,U32,U32,U32); */ char* cos_method_name(const struct Method*,char*,U32); char* cos_method_call(SEL,OBJ*,char*,U32); char* cos_method_callName(const struct Method*,OBJ*,char*,U32); void (*cos_method_trace)(STR,int,BOOL,const struct Method*,OBJ*); void cos_method_clearCache1(void); void cos_method_clearCache2(void); void cos_method_clearCache3(void); void cos_method_clearCache4(void); void cos_method_clearCache5(void); void cos_method_clearCaches(void); void cos_contract_invariant1(OBJ,STR,int); void cos_contract_invariant2(OBJ,OBJ,STR,int); void cos_contract_invariant3(OBJ,OBJ,OBJ,STR,int); void cos_contract_invariant4(OBJ,OBJ,OBJ,OBJ,STR,int); void cos_contract_invariant5(OBJ,OBJ,OBJ,OBJ,OBJ,STR,int); int cos_contract_setLevel (int lvl); // return previous level void cos_exception_assert (STR,STR,int) __attribute__((__noreturn__)); void cos_exception_errno (int,STR,int) __attribute__((__noreturn__)); void cos_exception_badcast(OBJ,const struct Class*,STR,int) __attribute__((__noreturn__)); void cos_exception_throw (OBJ,STR,int) __attribute__((__noreturn__)); BOOL cos_exception_catch (OBJ,OBJ); BOOL cos_exception_uncaught(void); void cos_exception_initContext(struct cos_exception_context*); void cos_exception_deinitContext(struct cos_exception_context*); cos_exception_handler cos_exception_setTerminate(cos_exception_handler); void cos_functor_overflow(void); void cos_functor_underflow(void) __attribute__((__noreturn__)); void cos_functor_clearContext(void); void cos_module_load(STR*); // null terminated array of module names /* NOTE-INFO: loggers - prototype: void cos_xxx(STR fmt, ...); - a '\n' is automatically added to the end - they can be turned on/off with cos_logmsg_set. - all these handlers display on cos_logmsg_out [default=stderr] - to access to cos_logmsg_out, you must include cos/cos/debug.h */ #define cos_trace(...) \ cos_logmsg(COS_LOGMSG_TRACE,__FILE__,__LINE__,__VA_ARGS__) #define cos_debug(...) \ cos_logmsg(COS_LOGMSG_DEBUG,__FILE__,__LINE__,__VA_ARGS__) #define cos_info(...) \ cos_logmsg(COS_LOGMSG_INFO ,__FILE__,__LINE__,__VA_ARGS__) #define cos_warn( ...) \ cos_logmsg(COS_LOGMSG_WARN ,__FILE__,__LINE__,__VA_ARGS__) #define cos_error(...) \ cos_logmsg(COS_LOGMSG_ERROR,__FILE__,__LINE__,__VA_ARGS__) #define cos_abort(...) \ cos_logmsg(COS_LOGMSG_ABORT,__FILE__,__LINE__,__VA_ARGS__) #define cos_logmsg(lvl,file,line,...) \ ((void)(cos_logmsg_level_ <= (lvl) && (cos_logmsg_(lvl,file,line,__VA_ARGS__),0))) // topic-specific debug #define COS_DEBUG_IF(topic,...) \ ((void)(COS_PP_CAT(DEBUG_,topic) && (cos_debug(__VA_ARGS__),0))) void cos_logmsg_(int,STR,int,STR,...) __attribute__((__format__(__printf__,4,5))); int cos_logmsg_setLevel(int lvl); // return previous level /* NOTE-INFO: auto ctor the following function-like macro is useful to define automatic ctor for classes deriving from Object (or at equivalent level) */ #define cos_object_auto(cls) \ {{ COS_CLS_NAME(cls).Behavior.id, COS_RC_AUTO }} /*********************************************************** * Implementation */ // COS symbols init void cos_symbol_init(void); void cos_symbol_register(struct Any**, STR tag); // next-method void cos_method_nextClear(void); void cos_method_nextInit(FCT*,SEL,U32,U32,struct Class* const*); // 2nd and 3rd levels dispatch IMP1 cos_method_fastLookup1_(struct cos_method_slot1*restrict*restrict,SEL,U32); IMP2 cos_method_fastLookup2_(struct cos_method_slot2*restrict*restrict,SEL,U32,U32); IMP3 cos_method_fastLookup3_(struct cos_method_slot3*restrict*restrict,SEL,U32,U32,U32); IMP4 cos_method_fastLookup4_(struct cos_method_slot4*restrict*restrict,SEL,U32,U32,U32,U32); IMP5 cos_method_fastLookup5_(struct cos_method_slot5*restrict*restrict,SEL,U32,U32,U32,U32,U32); BOOL cos_method_understand1_(struct cos_method_slot1*restrict*restrict,SEL,U32); BOOL cos_method_understand2_(struct cos_method_slot2*restrict*restrict,SEL,U32,U32); BOOL cos_method_understand3_(struct cos_method_slot3*restrict*restrict,SEL,U32,U32,U32); BOOL cos_method_understand4_(struct cos_method_slot4*restrict*restrict,SEL,U32,U32,U32,U32); BOOL cos_method_understand5_(struct cos_method_slot5*restrict*restrict,SEL,U32,U32,U32,U32,U32); // logger message level (not thread safe) extern int cos_logmsg_level_; /*********************************************************** * Inlined functions */ #if defined(_OPENMP) || COS_HAS_TLS || !COS_HAS_POSIX // -------------------- #ifdef _OPENMP #include <omp.h> #endif static cos_inline struct cos_functor_context* cos_functor_context(void) { extern __thread struct cos_functor_context cos_functor_context_; #ifdef _OPENMP #pragma omp threadprivate(cos_functor_context_) #endif return &cos_functor_context_; COS_UNUSED(cos_functor_context); } static cos_inline struct cos_method_cache1* cos_method_cache1(void) { extern __thread struct cos_method_cache1 cos_method_cache1_; #ifdef _OPENMP #pragma omp threadprivate(cos_method_cache1_) #endif return &cos_method_cache1_; COS_UNUSED(cos_method_cache1); } static cos_inline struct cos_method_cache2* cos_method_cache2(void) { extern __thread struct cos_method_cache2 cos_method_cache2_; #ifdef _OPENMP #pragma omp threadprivate(cos_method_cache2_) #endif return &cos_method_cache2_; COS_UNUSED(cos_method_cache2); } static cos_inline struct cos_method_cache3* cos_method_cache3(void) { extern __thread struct cos_method_cache3 cos_method_cache3_; #ifdef _OPENMP #pragma omp threadprivate(cos_method_cache3_) #endif return &cos_method_cache3_; COS_UNUSED(cos_method_cache3); } static cos_inline struct cos_method_cache4* cos_method_cache4(void) { extern __thread struct cos_method_cache4 cos_method_cache4_; #ifdef _OPENMP #pragma omp threadprivate(cos_method_cache4_) #endif return &cos_method_cache4_; COS_UNUSED(cos_method_cache4); } static cos_inline struct cos_method_cache5* cos_method_cache5(void) { extern __thread struct cos_method_cache5 cos_method_cache5_; #ifdef _OPENMP #pragma omp threadprivate(cos_method_cache5_) #endif return &cos_method_cache5_; COS_UNUSED(cos_method_cache5); } static cos_inline struct cos_exception_context* cos_exception_context(void) { extern __thread struct cos_exception_context *cos_exception_cxt_; #ifdef _OPENMP #pragma omp threadprivate(cos_exception_cxt_) #endif return cos_exception_cxt_; COS_UNUSED(cos_exception_context); } #else // !defined(_OPENMP) && !COS_HAS_TLS && COS_HAS_POSIX ----------------- #if COS_HAS_POSIX #include <pthread.h> #endif struct cos_exception_context* cos_exception_context (void); struct cos_functor_context* cos_functor_context_init(void); struct cos_method_cache1* cos_method_cache1_init (void); struct cos_method_cache2* cos_method_cache2_init (void); struct cos_method_cache3* cos_method_cache3_init (void); struct cos_method_cache4* cos_method_cache4_init (void); struct cos_method_cache5* cos_method_cache5_init (void); static cos_inline struct cos_functor_context* cos_functor_context(void) { struct cos_functor_context *context; extern int cos_functor_context_key_init; extern pthread_key_t cos_functor_context_key; if (! cos_functor_context_key_init || !(context = pthread_getspecific(cos_functor_context_key))) context = cos_functor_context_init(); return context; COS_UNUSED(cos_functor_context); } static cos_inline struct cos_method_cache1* cos_method_cache1(void) { struct cos_method_cache1 *cache; extern int cos_method_cache1_key_init; extern pthread_key_t cos_method_cache1_key; if (! cos_method_cache1_key_init || !(cache = pthread_getspecific(cos_method_cache1_key))) cache = cos_method_cache1_init(); return cache; COS_UNUSED(cos_method_cache1); } static cos_inline struct cos_method_cache2* cos_method_cache2(void) { struct cos_method_cache2 *cache; extern int cos_method_cache2_key_init; extern pthread_key_t cos_method_cache2_key; if (! cos_method_cache2_key_init || !(cache = pthread_getspecific(cos_method_cache2_key))) cache = cos_method_cache2_init(); return cache; COS_UNUSED(cos_method_cache2); } static cos_inline struct cos_method_cache3* cos_method_cache3(void) { struct cos_method_cache3 *cache; extern int cos_method_cache3_key_init; extern pthread_key_t cos_method_cache3_key; if (! cos_method_cache3_key_init || !(cache = pthread_getspecific(cos_method_cache3_key))) cache = cos_method_cache3_init(); return cache; COS_UNUSED(cos_method_cache3); } static cos_inline struct cos_method_cache4* cos_method_cache4(void) { struct cos_method_cache4 *cache; extern int cos_method_cache4_key_init; extern pthread_key_t cos_method_cache4_key; if (! cos_method_cache4_key_init || !(cache = pthread_getspecific(cos_method_cache4_key))) cache = cos_method_cache4_init(); return cache; COS_UNUSED(cos_method_cache4); } static cos_inline struct cos_method_cache5* cos_method_cache5(void) { struct cos_method_cache5 *cache; extern int cos_method_cache5_key_init; extern pthread_key_t cos_method_cache5_key; if (! cos_method_cache5_key_init || !(cache = pthread_getspecific(cos_method_cache5_key))) cache = cos_method_cache5_init(); return cache; COS_UNUSED(cos_method_cache5); } #endif // ------------------------------------------------ static cos_inline OBJ cos_ident(OBJ obj) { return obj; COS_UNUSED(cos_ident); } static cos_inline U32 cos_object_id(OBJ obj) { return ((struct Any*)obj)->_id; COS_UNUSED(cos_object_id); } static cos_inline OBJ cos_object_setId(OBJ obj, U32 id) { return ((struct Any*)obj)->_id = id, obj; COS_UNUSED(cos_object_setId); } static cos_inline OBJ cos_object_setIdAuto(OBJ res, OBJ obj) { ((struct Any*)res)->_id = ((struct Any*)obj)->_id; ((struct Any*)res)->_rc = COS_RC_AUTO; return res; COS_UNUSED(cos_object_setIdAuto); } static cos_inline I32 cos_object_rc(OBJ obj) { return ((struct Any*)obj)->_rc; COS_UNUSED(cos_object_rc); } static cos_inline OBJ cos_object_setRc(OBJ obj, I32 rc) { return ((struct Any*)obj)->_rc = rc, obj; COS_UNUSED(cos_object_setRc); } static cos_inline OBJ cos_object_incRc(OBJ obj) { return ((struct Any*)obj)->_rc++, obj; COS_UNUSED(cos_object_incRc); } static cos_inline OBJ cos_object_decRc(OBJ obj) { return ((struct Any*)obj)->_rc--, obj; COS_UNUSED(cos_object_decRc); } static cos_inline struct Class* cos_object_class(OBJ obj) { return cos_class_get(cos_object_id(obj)); COS_UNUSED(cos_object_class); } static cos_inline struct Class* cos_object_superClass(OBJ obj) { return cos_object_class(obj)->spr; COS_UNUSED(cos_object_superClass); } static cos_inline STR cos_object_className(OBJ obj) { return cos_object_class(obj)->str; COS_UNUSED(cos_object_className); } static cos_inline U32 cos_class_id(const struct Class *cls) { return cls->Behavior.id; COS_UNUSED(cos_class_id); } static cos_inline U32 cos_generic_id(SEL sel) { return sel->Behavior.id; COS_UNUSED(cos_generic_id); } static cos_inline BOOL cos_object_isa(OBJ obj, const struct Class *cls) { return cos_object_id(obj) == cos_class_id(cls); COS_UNUSED(cos_object_isa); } static cos_inline void* cos_object_cast(OBJ obj, const struct Class *cls) { return obj && cos_object_isa(obj, cls) ? obj : 0; COS_UNUSED(cos_object_cast); } static cos_inline void* cos_object_ecast(OBJ obj, const struct Class *cls, STR file, int line) { if (obj && cos_object_isa(obj, cls)) return obj; cos_exception_badcast(obj, cls, file, line); COS_UNUSED(cos_object_ecast); } static cos_inline void* cos_object_dyncast(OBJ obj, const struct Class *cls) { return obj && (cos_object_isa(obj, cls) || cos_object_isKindOf(obj, cls)) ? obj : 0; COS_UNUSED(cos_object_dyncast); } static cos_inline void* cos_object_edyncast(OBJ obj, const struct Class *cls, STR file, int line) { if (obj && ( cos_object_isa (obj, cls) || cos_object_isKindOf(obj, cls))) return obj; cos_exception_badcast(obj, cls, file, line); COS_UNUSED(cos_object_edyncast); } static cos_inline BOOL cos_arginfo_isObject(struct cos_generic_arginfo *info) { return !info->size; COS_UNUSED(cos_arginfo_isObject); } static cos_inline U32 cos_arginfo_size(struct cos_generic_arginfo *info) { return info->size ? info->size : sizeof(OBJ); COS_UNUSED(cos_arginfo_size); } static cos_inline struct cos_functor_context* cos_functor_ensure(int n) { struct cos_functor_context *cxt = cos_functor_context(); if (cxt->top + n > cxt->end) cos_functor_overflow(); return cxt; COS_UNUSED(cos_functor_ensure); } static cos_inline struct cos_functor_context* cos_functor_require(int n) { struct cos_functor_context *cxt = cos_functor_context(); if (cxt->stk + n > cxt->top) cos_functor_underflow(); return cxt; COS_UNUSED(cos_functor_require); } static cos_inline struct cos_exception_protect cos_exception_protect(struct cos_exception_protect *ptr, OBJ const *obj) { struct cos_exception_context *cxt = cos_exception_context(); ptr->prv = cxt->stk; ptr->obj = obj; cxt->stk = ptr; return *ptr; COS_UNUSED(cos_exception_protect); } static cos_inline struct cos_exception_extendedProtect cos_exception_objectProtect(struct cos_exception_extendedProtect *ptr, OBJ const *alt, FCT1 fct) { struct cos_exception_context *cxt = cos_exception_context(); ptr->prv = cxt->stk; ptr->obj = (OBJ*)COS_YES; ptr->alt = (void *const*)alt; ptr->fct = (FCTV)fct; cxt->stk = (void*)ptr; return *ptr; COS_UNUSED(cos_exception_objectProtect); } static cos_inline struct cos_exception_extendedProtect cos_exception_extendedProtect(struct cos_exception_extendedProtect *ptr, void *const *alt, FCTV fct) { struct cos_exception_context *cxt = cos_exception_context(); ptr->prv = cxt->stk; ptr->obj = (OBJ*)COS_YES; ptr->alt = alt; ptr->fct = fct; cxt->stk = (void*)ptr; return *ptr; COS_UNUSED(cos_exception_extendedProtect); } #endif // COS_COS_COSAPI_H
sorw.c
#include <stdio.h> #include <math.h> #include <string.h> #include <sys/time.h> #include <omp.h> #define M 700 double compute_error(double solution[][M + 2], double u[][M + 2], const int m); int sor(double unew[][M + 2], double uold[][M + 2], double solution[][M + 2], const double omega, const double tol, const int m); int main(void) { /* Solution of Laplace's Equation. ============================== ! *** ! *** Uxx + Uyy = 0 ! *** 0 <= x <= pi, 0 <= y <= pi ! *** U(x,pi) = sin(x), U(x,0) = U(0,y) = U(pi,y) = 0 ! *** ! *** then U(x,y) = (sinh(y)*sin(x)) / sinh(pi) ! *** ! *** Should converge with ! *** tol = 0.001 and M = 20 in 42 iterations. ! *** and with tol = 0.001 and M = 100 in 198 iterations. */ const int m = M; // struct timeval tic, toc; double unew[m + 2][m + 2] = {{ 0 }}; double solution[m + 2][m + 2] = {{ 0 }}; double uold[m + 2][m + 2] = {{ 0 }}; int i, j; // gettimeofday(&tic, NULL); const double begin = omp_get_wtime(); const double pi = 4.0 * atan(1.0); const double h = pi / (m + 1); #pragma omp parallel for private(i) shared(uold) schedule(static, 100) for(i = 0; i < m + 2; ++i) { uold[i][M + 1] = sin(i * h); } #pragma omp parallel for private(i, j) shared(uold) schedule(static, 100) for(i = 0; i < m + 2; ++i) { for(j = i + 1; j < m + 1 + i; ++j) { uold[i][j - i] = (j - i) * h * uold[i][M + 1]; } } #pragma omp parallel for private(i, j) shared(solution) schedule(static, 100) for(i = 0; i < m + 2; ++i) { for(j = i + 1; j < m + 2 + i; ++j) { solution[i][j - i] = sinh((j - i) * h) * sin(i * h) / sinh(pi); } } const double omega = 2.0 / ( 1.0 + sin(pi / (m + 1)) ); const double tol = 0.001; const int iters = sor(unew, uold, solution, omega, tol, m); // gettimeofday(&toc, NULL); const double end = omp_get_wtime(); printf(" \n"); printf(" Omega = %f\n", omega); printf(" It took %d iterations.\n", iters); // printf("Total time = %f\n\n\n", (double) (toc.tv_usec - tic.tv_usec) / 1000000 + // (double) (toc.tv_sec - tic.tv_sec)); printf("Total time = %f\n\n\n", end - begin); return 0; } double compute_error(double solution[][M + 2], double u[][M + 2], const int m) { double error = 0.0; int i, j; // #pragma omp parallel for for(i = 1; i < m + 1; ++i) { for(j = 1; j < m + 1; ++j) { const double abs_diff = fabs(solution[i][j] - u[i][j]); if(error < abs_diff) { error = abs_diff; } } } return error; } int sor(double unew[][M + 2], double uold[][M + 2], double solution[][M + 2], const double omega, const double tol, const int m) { int i, j; for(i = 0; i < m + 2; ++i) { unew[i][m + 1] = uold[i][m + 1]; unew[m + 1][i] = uold[m + 1][i]; unew[i][0] = uold[i][0]; unew[0][i] = uold[0][i]; } int iters = 0; double error = compute_error(solution, uold, m); while(error > tol) { //#pragma omp parallel for for(i = 1; i < m + 1; ++i) { for(j = 2 + i; j < m + 1 + i; ++j) { unew[i][j - i] = uold[i][j - i] + 0.25 * omega * (unew[i - 1][j - i] + unew[i][j - 1 - i] + uold[i + 1][j - i] + uold[i][j + 1 - i] - 4.0 * uold[i][j - i]); } } //#pragma omp parallel for private(i) for(i = 1; i < m + 1; ++i) { memcpy(&uold[i][1], &unew[i][1], m * sizeof(double)); //for(j = 1; j < m + 1; ++j) //{ // uold[i][j] = unew[i][j]; //} } ++iters; if(iters % 20 == 0) { error = compute_error(solution, uold, m); // puts("sdf"); } } return iters; }
DRB028-privatemissing-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. 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 disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. */ /* tmp should be annotated as private to avoid race condition. Data race pairs: tmp@65:5 vs. tmp@66:12 tmp@65:5 vs. tmp@65:5 */ #include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; int tmp; int len=100; int a[100]; #pragma omp target data map(a[0:len]) #pragma omp target parallel for for (i=0;i<len;i++) a[i]=i; #pragma omp target data map(a[0:len]) #pragma omp target parallel for private(tmp) for (i=0;i<len;i++) { tmp =a[i]+i; a[i] = tmp; } printf("a[50]=%d\n", a[50]); return 0; }
second_omp_exemple.c
// second_omp_exemple.c // compile with: /openmp /* ############################################################################# ## DESCRIPTION: Simple exemple to read a name and show your Threads - OpenMp. ## NAME: second_omp_exemple.c ## AUTHOR: Lucca Pessoa da Silva Matos ## DATE: 10.04.2020 ## VERSION: 1.0 ## EXEMPLE: ## PS C:\> gcc -fopenmp -o second_omp_exemple second_omp_exemple.c ##############################################################################*/ // ============================================================================= // LIBRARYS // ============================================================================= #include <omp.h> #include <stdio.h> #include <locale.h> #include <stdlib.h> // ============================================================================= // MACROS // ============================================================================= #define NAME_SIZE 256 // ============================================================================= // CALL FUNCTIONS // ============================================================================= void cabecalho(); void set_portuguese(); // ============================================================================= // MAIN // ============================================================================= int main(int argc, char const *argv[]){ set_portuguese(); cabecalho(); int thread_id, num_threads; // Alocando. char *name = malloc(NAME_SIZE); // Verificando. if (name == NULL){ printf("Sorry... We dont have memory :(\n"); return 1; } printf("\nHey coder! What's your name? "); scanf("%[^\n]s",name); printf("\nHello %s. Nice to meet you.\n", name); printf("\n1 - We are out of the parallel context.\n\n"); // Fork #pragma omp parallel { thread_id = omp_get_thread_num(); num_threads = omp_get_num_threads(); printf("Hey %s! I'm Thread %d - Total %d!\n", name, thread_id, num_threads); } // Join printf("\n2 - We are out of the parallel context.\n\n"); return 0; } // ============================================================================= // FUNCTIONS // ============================================================================= void set_portuguese(){ setlocale(LC_ALL, "Portuguese"); } void cabecalho(){ printf("\n**************************************************"); printf("\n* *"); printf("\n* *"); printf("\n* PROGRAMACAO PARALELA COM OPENMP - LUCCA PESSOA *"); printf("\n* *"); printf("\n* *"); printf("\n**************************************************\n"); }
resize-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file resize-inl.h * \brief image resize operator using opencv and only support bilinear resize * \author Jake Lee */ #ifndef MXNET_OPERATOR_IMAGE_RESIZE_INL_H_ #define MXNET_OPERATOR_IMAGE_RESIZE_INL_H_ #include <mxnet/base.h> #include <vector> #include "../mxnet_op.h" #include "../operator_common.h" #include "image_utils.h" #if MXNET_USE_OPENCV #include <opencv2/opencv.hpp> #endif // MXNET_USE_OPENCV namespace mxnet { namespace op { namespace image { using namespace mshadow; #if MXNET_USE_CUDA template <typename DType, typename T, typename Acctype> void ResizeImplCUDA(Stream<gpu>* s, const T input, const T output); #endif // MXNET_USE_CUDA struct ResizeParam : public dmlc::Parameter<ResizeParam> { mxnet::Tuple<int> size; bool keep_ratio; int interp; DMLC_DECLARE_PARAMETER(ResizeParam) { DMLC_DECLARE_FIELD(size) .set_default(mxnet::Tuple<int>()) .describe("Size of new image. Could be (width, height) or (size)"); DMLC_DECLARE_FIELD(keep_ratio) .describe( "Whether to resize the short edge or both edges to `size`, " "if size is give as an integer.") .set_default(false); DMLC_DECLARE_FIELD(interp).set_default(1).describe( "Interpolation method for resizing. By default uses bilinear interpolation" "Options are INTER_NEAREST - a nearest-neighbor interpolation" "INTER_LINEAR - a bilinear interpolation" "INTER_AREA - resampling using pixel area relation" "INTER_CUBIC - a bicubic interpolation over 4x4 pixel neighborhood" "INTER_LANCZOS4 - a Lanczos interpolation over 8x8 pixel neighborhood" "Note that the GPU version only support bilinear interpolation(1)"); } }; // handle the keep ratio param inline SizeParam GetHeightAndWidth(int data_h, int data_w, const ResizeParam& param) { CHECK((param.size.ndim() == 1) || (param.size.ndim() == 2)) << "Input size dimension must be 1 or 2, but got " << param.size.ndim(); int resized_h; int resized_w; if (param.size.ndim() == 1) { CHECK_GT(param.size[0], 0) << "Input size should be greater than 0, but got " << param.size[0]; if (!param.keep_ratio) { resized_h = param.size[0]; resized_w = param.size[0]; } else { if (data_h > data_w) { resized_w = param.size[0]; resized_h = static_cast<int>(data_h * resized_w / data_w); } else { resized_h = param.size[0]; resized_w = static_cast<int>(data_w * resized_h / data_h); } } } else { CHECK_GT(param.size[0], 0) << "Input width should be greater than 0, but got " << param.size[0]; CHECK_GT(param.size[1], 0) << "Input height should be greater than 0, but got " << param.size[1]; resized_h = param.size[1]; resized_w = param.size[0]; } return SizeParam(resized_h, resized_w); } inline bool ResizeShapeImpl(const ResizeParam& param, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { // input attrs should only be (h, w, c) or (n, h, w, c) CHECK((in_attrs->at(0).ndim() == 3U) || (in_attrs->at(0).ndim() == 4U)) << "Input image dimension should be 3 or 4 but got " << in_attrs->at(0).ndim(); const auto& ishape = (*in_attrs)[0]; SizeParam size; if (ishape.ndim() == 3) { size = GetHeightAndWidth(ishape[H], ishape[W], param); SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape({size.height, size.width, ishape[C]})); } else { size = GetHeightAndWidth(ishape[kH], ishape[kW], param); SHAPE_ASSIGN_CHECK( *out_attrs, 0, mxnet::TShape({ishape[N], size.height, size.width, ishape[kC]})); } return true; } inline bool ResizeShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { const ResizeParam& param = nnvm::get<ResizeParam>(attrs.parsed); return ResizeShapeImpl(param, in_attrs, out_attrs); } inline void ResizeImpl(const std::vector<TBlob>& inputs, const std::vector<TBlob>& outputs, const int height, const int width, const int interp, const int input_index = 0, const int output_index = 0) { #if MXNET_USE_OPENCV CHECK_NE(inputs[0].type_flag_, mshadow::kFloat16) << "opencv image mat doesn't support fp16"; CHECK((inputs[0].type_flag_ != mshadow::kInt32) || (inputs[0].type_flag_ != mshadow::kInt64)) << "opencv resize doesn't support int32, int64"; // mapping to opencv matrix element type according to channel const int DTYPE[] = {CV_32F, CV_64F, -1, CV_8U, CV_32S}; if (inputs[0].ndim() == 3) { const int cv_type = CV_MAKETYPE(DTYPE[inputs[0].type_flag_], inputs[0].shape_[C]); cv::Mat buf(inputs[0].shape_[H], inputs[0].shape_[W], cv_type, inputs[0].dptr_); cv::Mat dst(outputs[0].shape_[H], outputs[0].shape_[W], cv_type, outputs[0].dptr_); cv::resize(buf, dst, cv::Size(width, height), 0, 0, interp); CHECK(!dst.empty()); CHECK_EQ(static_cast<void*>(dst.ptr()), outputs[0].dptr_); } else { const int cv_type = CV_MAKETYPE(DTYPE[inputs[0].type_flag_], inputs[0].shape_[kC]); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { cv::Mat buf(inputs[0].shape_[kH], inputs[0].shape_[kW], cv_type, inputs[0].dptr<DType>() + input_index); cv::Mat dst(outputs[0].shape_[kH], outputs[0].shape_[kW], cv_type, outputs[0].dptr<DType>() + output_index); cv::resize(buf, dst, cv::Size(width, height), 0, 0, interp); CHECK(!dst.empty()); CHECK_EQ(static_cast<void*>(dst.ptr()), outputs[0].dptr<DType>() + output_index); }); } #else LOG(FATAL) << "Build with USE_OPENCV=1 for image resize operator."; #endif // MXNET_USE_OPENCV } template <typename xpu> inline void ResizeImplWrapper(const ResizeParam& param, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<TBlob>& outputs) { SizeParam size; if (std::is_same<xpu, gpu>::value) { #if MXNET_USE_CUDA CHECK(param.interp == 1) << "interp should be 1 for using Resize on GPU."; mshadow::Stream<gpu>* s = ctx.get_stream<gpu>(); MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { if (inputs[0].ndim() == 3) { Tensor<gpu, 3, DType> input = inputs[0].get<gpu, 3, DType>(s); Tensor<gpu, 3, DType> output = outputs[0].get<gpu, 3, DType>(s); ResizeImplCUDA<DType, Tensor<gpu, 3, DType>, float>(s, input, output); } else { Tensor<gpu, 4, DType> input = inputs[0].get<gpu, 4, DType>(s); Tensor<gpu, 4, DType> output = outputs[0].get<gpu, 4, DType>(s); ResizeImplCUDA<DType, Tensor<gpu, 4, DType>, float>(s, input, output); } }); #endif // MXNET_USE_CUDA } else if (inputs[0].ndim() == 3) { size = GetHeightAndWidth(inputs[0].shape_[H], inputs[0].shape_[W], param); ResizeImpl(inputs, outputs, size.height, size.width, param.interp); } else { size = GetHeightAndWidth(inputs[0].shape_[kH], inputs[0].shape_[kW], param); const auto batch_size = inputs[0].shape_[N]; const auto input_step = inputs[0].shape_[kH] * inputs[0].shape_[kW] * inputs[0].shape_[kC]; const auto output_step = size.height * size.width * inputs[0].shape_[kC]; #pragma omp parallel for for (auto i = 0; i < batch_size; ++i) { ResizeImpl( inputs, outputs, size.height, size.width, param.interp, i * input_step, i * output_step); } } } template <typename xpu> inline void Resize(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(outputs.size(), 1U); const ResizeParam& param = nnvm::get<ResizeParam>(attrs.parsed); ResizeImplWrapper<xpu>(param, ctx, inputs, outputs); } } // namespace image } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_IMAGE_RESIZE_INL_H_
cg.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "globals.h" #include "randdp.h" #include "timers.h" #include <omp.h> //--------------------------------------------------------------------- #define CACHE_LINE_SIZE_PAD 128 #define INT_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(int) #define DOUBLE_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(double) /* common / main_int_mem / */ static int colidx[NZ]; static int rowstr[NA+1]; static int iv[NA]; static int arow[NA]; static int acol[NAZ]; /* common / main_flt_mem / */ static double aelt[NAZ]; static double a[NZ]; static double x[NA+2]; static double z[NA+2]; static double p[NA+2]; static double q[NA+2]; static double r[NA+2]; /* common / partit_size / */ static int naa; static int nzz; static int firstrow; static int lastrow; static int firstcol; static int lastcol; /* common /urando/ */ static double amult; static double tran; /* common /timers/ */ static logical timeron; //--------------------------------------------------------------------- //--------------------------------------------------------------------- static void conj_grad(int colidx[], int rowstr[], double x[], double z[], double a[], double p[], double q[], double r[], double *rnorm); static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int firstrow, int lastrow, int firstcol, int lastcol, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int iv[]); static void sparse(double a[], int colidx[], int rowstr[], int n, int nz, int nozer, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int firstrow, int lastrow, int nzloc[], double rcond, double shift); static void sprnvc(int n, int nz, int nn1, double v[], int iv[]); static int icnvrt(double x, int ipwr2); static void vecset(int n, double v[], int iv[], int *nzv, int i, double val); //--------------------------------------------------------------------- int main(int argc, char *argv[]) { omp_set_num_threads(omp_get_num_procs()); int i, j, k, it; double zeta; double rnorm; double norm_temp1, norm_temp2; double t, mflops, tmax; //char Class; logical verified; double zeta_verify_value, epsilon, err; char *t_names[T_last]; for (i = 0; i < T_last; i++) { timer_clear(i); } timer_start(T_init); firstrow = 0; lastrow = NA-1; firstcol = 0; lastcol = NA-1; zeta_verify_value = VALID_RESULT; printf("\nCG start...\n\n"); printf(" Size: %11d\n", NA); printf(" Iterations: %5d\n", NITER); printf("\n"); naa = NA; nzz = NZ; //--------------------------------------------------------------------- // Inialize random number generator //--------------------------------------------------------------------- tran = 314159265.0; amult = 1220703125.0; zeta = randlc(&tran, amult); //--------------------------------------------------------------------- // //--------------------------------------------------------------------- makea(naa, nzz, a, colidx, rowstr, firstrow, lastrow, firstcol, lastcol, arow, (int (*)[NONZER+1])(void*)acol, (double (*)[NONZER+1])(void*)aelt, iv); //--------------------------------------------------------------------- // Note: as a result of the above call to makea: // values of j used in indexing rowstr go from 0 --> lastrow-firstrow // values of colidx which are col indexes go from firstcol --> lastcol // So: // Shift the col index vals from actual (firstcol --> lastcol ) // to local, i.e., (0 --> lastcol-firstcol) //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(i,j,k) { #pragma omp for nowait for (j = 0; j < lastrow - firstrow + 1; j++) { for (k = rowstr[j]; k < rowstr[j+1]; k++) { colidx[k] = colidx[k] - firstcol; } } //--------------------------------------------------------------------- // set starting vector to (1, 1, .... 1) //--------------------------------------------------------------------- #pragma omp for nowait for (i = 0; i < NA+1; i++) { x[i] = 1.0; } #pragma omp for nowait for (j = 0; j < lastcol - firstcol + 1; j++) { q[j] = 0.0; z[j] = 0.0; r[j] = 0.0; p[j] = 0.0; } } zeta = 0.0; //--------------------------------------------------------------------- //----> // Do one iteration untimed to init all code and data page tables //----> (then reinit, start timing, to niter its) //--------------------------------------------------------------------- for (it = 1; it <= 1; it++) { //--------------------------------------------------------------------- // The call to the conjugate gradient routine: //--------------------------------------------------------------------- conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm); //--------------------------------------------------------------------- // zeta = shift + 1/(x.z) // So, first: (x.z) // Also, find norm of z // So, first: (z.z) //--------------------------------------------------------------------- norm_temp1 = 0.0; norm_temp2 = 0.0; #pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2) for (j = 0; j < lastcol - firstcol + 1; j++) { norm_temp1 = norm_temp1 + x[j] * z[j]; norm_temp2 = norm_temp2 + z[j] * z[j]; } norm_temp2 = 1.0 / sqrt(norm_temp2); //--------------------------------------------------------------------- // Normalize z to obtain x //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { x[j] = norm_temp2 * z[j]; } } // end of do one iteration untimed //--------------------------------------------------------------------- // set starting vector to (1, 1, .... 1) //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(i) for (i = 0; i < NA+1; i++) { x[i] = 1.0; } zeta = 0.0; timer_stop(T_init); printf(" Initialization time = %15.3f seconds\n", timer_read(T_init)); timer_start(T_bench); //--------------------------------------------------------------------- //----> // Main Iteration for inverse power method //----> //--------------------------------------------------------------------- for (it = 1; it <= NITER; it++) { //--------------------------------------------------------------------- // The call to the conjugate gradient routine: //--------------------------------------------------------------------- if (timeron) timer_start(T_conj_grad); conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm); if (timeron) timer_stop(T_conj_grad); //--------------------------------------------------------------------- // zeta = shift + 1/(x.z) // So, first: (x.z) // Also, find norm of z // So, first: (z.z) //--------------------------------------------------------------------- norm_temp1 = 0.0; norm_temp2 = 0.0; #pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2) for (j = 0; j < lastcol - firstcol + 1; j++) { norm_temp1 = norm_temp1 + x[j]*z[j]; norm_temp2 = norm_temp2 + z[j]*z[j]; } norm_temp2 = 1.0 / sqrt(norm_temp2); zeta = SHIFT + 1.0 / norm_temp1; if (it == 1) printf("\n iteration ||r|| zeta\n"); printf(" %5d %20.14E%20.13f\n", it, rnorm, zeta); //--------------------------------------------------------------------- // Normalize z to obtain x //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { x[j] = norm_temp2 * z[j]; } } // end of main iter inv pow meth timer_stop(T_bench); //--------------------------------------------------------------------- // End of timed section //--------------------------------------------------------------------- t = timer_read(T_bench); printf("\nComplete...\n"); epsilon = 1.0e-10; err = fabs(zeta - zeta_verify_value) / zeta_verify_value; if (err <= epsilon) { verified = true; printf(" VERIFICATION SUCCESSFUL\n"); printf(" Zeta is %20.13E\n", zeta); printf(" Error is %20.13E\n", err); } else { verified = false; printf(" VERIFICATION FAILED\n"); printf(" Zeta %20.13E\n", zeta); printf(" The correct zeta is %20.13E\n", zeta_verify_value); } printf("\n\nExecution time : %lf seconds\n\n", t); return 0; } //--------------------------------------------------------------------- // Floaging point arrays here are named as in spec discussion of // CG algorithm //--------------------------------------------------------------------- static void conj_grad(int colidx[], int rowstr[], double x[], double z[], double a[], double p[], double q[], double r[], double *rnorm) { int j, k, j1, j2, j3; int cgit, cgitmax = 25; double d, sum, rho, rho0, alpha, beta; int total_num = naa+1; int residue = (total_num)%8; int rho_num = lastcol-firstcol+1; int residue2 = (rho_num)%8; //--------------------------------------------------------------------- // Initialize the CG algorithm: //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j, k) { #pragma omp for nowait for (k = 0; k < residue; k++) { q[k] = 0.0; z[k] = 0.0; r[k] = x[k]; p[k] = x[k]; } #pragma omp for nowait for (j2 = residue; j2 < total_num; j2=j2+8) { r[j2] = x[j2]; r[j2+1] = x[j2+1]; r[j2+2] = x[j2+2]; r[j2+3] = x[j2+3]; r[j2+4] = x[j2+4]; r[j2+5] = x[j2+5]; r[j2+6] = x[j2+6]; r[j2+7] = x[j2+7]; } #pragma omp for nowait for (j = residue; j < total_num; j=j+8) { q[j] = 0.0; q[j+1] = 0.0; q[j+2] = 0.0; q[j+3] = 0.0; q[j+4] = 0.0; q[j+5] = 0.0; q[j+6] = 0.0; q[j+7] = 0.0; } #pragma omp for nowait for (j1 = residue; j1 < total_num; j1=j1+8) { z[j1] = 0.0; z[j1+1] = 0.0; z[j1+2] = 0.0; z[j1+3] = 0.0; z[j1+4] = 0.0; z[j1+5] = 0.0; z[j1+6] = 0.0; z[j1+7] = 0.0; } #pragma omp for nowait for (j3 = residue; j3 < total_num; j3=j3+8) { p[j3] = x[j3]; p[j3+1] = x[j3+1]; p[j3+2] = x[j3+2]; p[j3+3] = x[j3+3]; p[j3+4] = x[j3+4]; p[j3+5] = x[j3+5]; p[j3+6] = x[j3+6]; p[j3+7] = x[j3+7]; } //--------------------------------------------------------------------- // rho = r.r // Now, obtain the norm of r: First, sum squares of r elements locally... //--------------------------------------------------------------------- //#pragma omp for reduction(+:rho) #pragma omp single for (j = 0; j < residue2; j++) { rho = rho + r[j]*r[j]; } #pragma omp for reduction(+:rho) for(j=residue2; j<rho_num; j+=8){ rho = rho + r[j]*r[j] + r[j+1]*r[j+1] + r[j+2]*r[j+2] + r[j+3]*r[j+3] + r[j+4]*r[j+4] + r[j+5]*r[j+5] + r[j+6]*r[j+6] + r[j+7]*r[j+7]; } } //--------------------------------------------------------------------- //----> // The conj grad iteration loop //----> //--------------------------------------------------------------------- for (cgit = 1; cgit <= cgitmax; cgit++) { //--------------------------------------------------------------------- // q = A.p // The partition submatrix-vector multiply: use workspace w //--------------------------------------------------------------------- // // NOTE: this version of the multiply is actually (slightly: maybe %5) // faster on the sp2 on 16 nodes than is the unrolled-by-2 version // below. On the Cray t3d, the reverse is true, i.e., the // unrolled-by-two version is some 10% faster. // The unrolled-by-8 version below is significantly faster // on the Cray t3d - overall speed of code is 1.5 times faster. rho0 = rho; d = 0.0; rho = 0.0; #pragma omp parallel default(shared) private(j, k, sum) { #pragma omp for for (j = 0; j <= lastrow-firstrow+1; j++) { int iresidue; int i = rowstr[j]; iresidue = (rowstr[j+1]-i) % 8; sum = 0.0; for (k = i; k <= i+iresidue-1; k++) { sum = sum + a[k] * p[colidx[k]]; } for (k = i+iresidue; k <= rowstr[j+1]-8; k += 8) { sum = sum + a[k ] * p[colidx[k ]] + a[k+1] * p[colidx[k+1]] + a[k+2] * p[colidx[k+2]] + a[k+3] * p[colidx[k+3]] + a[k+4] * p[colidx[k+4]] + a[k+5] * p[colidx[k+5]] + a[k+6] * p[colidx[k+6]] + a[k+7] * p[colidx[k+7]]; } q[j] = sum; } } //--------------------------------------------------------------------- // Obtain p.q //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { //#pragma omp for reduction(+:d) #pragma omp single for (j = 0; j < residue2; j+=1) { d = d + p[j]*q[j]; } #pragma omp for reduction(+:d) for (j = residue2; j < rho_num; j+=8) { d = d + p[j]*q[j] + p[j+1]*q[j+1] + p[j+2]*q[j+2] + p[j+3]*q[j+3] + p[j+4]*q[j+4] + p[j+5]*q[j+5] + p[j+6]*q[j+6] + p[j+7]*q[j+7]; } } //--------------------------------------------------------------------- // Obtain alpha = rho / (p.q) //--------------------------------------------------------------------- alpha = rho0 / d; //--------------------------------------------------------------------- // Save a temporary of rho //--------------------------------------------------------------------- //--------------------------------------------------------------------- // Obtain z = z + alpha*p // and r = r - alpha*q //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp single for (j = 0; j < residue2; j+=1) { z[j] = z[j] + alpha*p[j]; r[j] = r[j] - alpha*q[j]; } #pragma omp for reduction(+:d) for (j = residue2; j < rho_num; j+=8) { z[j] = z[j] + alpha*p[j]; z[j+1] = z[j+1] + alpha*p[j+1]; z[j+2] = z[j+2] + alpha*p[j+2]; z[j+3] = z[j+3] + alpha*p[j+3]; z[j+4] = z[j+4] + alpha*p[j+4]; z[j+5] = z[j+5] + alpha*p[j+5]; z[j+6] = z[j+6] + alpha*p[j+6]; z[j+7] = z[j+7] + alpha*p[j+7]; r[j] = r[j] - alpha*q[j]; r[j+1] = r[j+1] - alpha*q[j+1]; r[j+2] = r[j+2] - alpha*q[j+2]; r[j+3] = r[j+3] - alpha*q[j+3]; r[j+4] = r[j+4] - alpha*q[j+4]; r[j+5] = r[j+5] - alpha*q[j+5]; r[j+6] = r[j+6] - alpha*q[j+6]; r[j+7] = r[j+7] - alpha*q[j+7]; } } //--------------------------------------------------------------------- // rho = r.r // Now, obtain the norm of r: First, sum squares of r elements locally... //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp single for (j = 0; j < residue2; j++) { rho = rho + r[j]*r[j]; } #pragma omp for reduction(+:rho) for (j = residue2; j < rho_num; j+=8) { rho = rho + r[j]*r[j] + r[j+1]*r[j+1] + r[j+2]*r[j+2] + r[j+3]*r[j+3] + r[j+4]*r[j+4] + r[j+5]*r[j+5] + r[j+6]*r[j+6] + r[j+7]*r[j+7]; } } //--------------------------------------------------------------------- // Obtain beta: //--------------------------------------------------------------------- beta = rho / rho0; //--------------------------------------------------------------------- // p = r + beta*p //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp single for (j = 0; j < residue2; j+=1) { p[j] = r[j] + beta*p[j]; } #pragma omp for for (j = residue2; j < rho_num; j+=8) { p[j] = r[j] + beta*p[j]; p[j+1] = r[j+1] + beta*p[j+1]; p[j+2] = r[j+2] + beta*p[j+2]; p[j+3] = r[j+3] + beta*p[j+3]; p[j+4] = r[j+4] + beta*p[j+4]; p[j+5] = r[j+5] + beta*p[j+5]; p[j+6] = r[j+6] + beta*p[j+6]; p[j+7] = r[j+7] + beta*p[j+7]; } } } // end of do cgit=1,cgitmax //--------------------------------------------------------------------- // Compute residual norm explicitly: ||r|| = ||x - A.z|| // First, form A.z // The partition submatrix-vector multiply //--------------------------------------------------------------------- sum = 0.0; #pragma omp parallel default(shared) private(j, d) shared(sum) { #pragma omp for for (j = 0; j < rho_num; j++) { d = 0.0; int iresidue; int i = rowstr[j]; iresidue = (rowstr[j+1] - i)%8; for (k=i; k<i+iresidue; k++){ d = d+ a[k]*z[colidx[k]]; } for (k = i+iresidue; k < rowstr[j+1]; k+=8) { d = d + a[k]*z[colidx[k]] + a[k+1]*z[colidx[k+1]] + a[k+2]*z[colidx[k+2]] + a[k+3]*z[colidx[k+3]] + a[k+4]*z[colidx[k+4]] + a[k+5]*z[colidx[k+5]] + a[k+6]*z[colidx[k+6]] + a[k+7]*z[colidx[k+7]]; } r[j] = d; } //--------------------------------------------------------------------- // At this point, r contains A.z //--------------------------------------------------------------------- #pragma omp single for (j = 0; j < residue2; j+=1) { double d_tmp = x[j] - r[j]; sum = sum + d_tmp*d_tmp; } #pragma omp for reduction(+:sum) for (j = residue2; j < rho_num; j+=8) { sum = sum + (x[j]-r[j])*(x[j]-r[j]) + (x[j+1]-r[j+1])*(x[j+1]-r[j+1]) + (x[j+2]-r[j+2])*(x[j+2]-r[j+2]) + (x[j+3]-r[j+3])*(x[j+3]-r[j+3]) + (x[j+4]-r[j+4])*(x[j+4]-r[j+4]) + (x[j+5]-r[j+5])*(x[j+5]-r[j+5]) + (x[j+6]-r[j+6])*(x[j+6]-r[j+6]) + (x[j+7]-r[j+7])*(x[j+7]-r[j+7]); } } *rnorm = sqrt(sum); } //--------------------------------------------------------------------- // generate the test problem for benchmark 6 // makea generates a sparse matrix with a // prescribed sparsity distribution // // parameter type usage // // input // // n i number of cols/rows of matrix // nz i nonzeros as declared array size // rcond r*8 condition number // shift r*8 main diagonal shift // // output // // a r*8 array for nonzeros // colidx i col indices // rowstr i row pointers // // workspace // // iv, arow, acol i // aelt r*8 //--------------------------------------------------------------------- static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int firstrow, int lastrow, int firstcol, int lastcol, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int iv[]) { int iouter, ivelt, nzv, nn1; int ivc[NONZER+1]; double vc[NONZER+1]; //--------------------------------------------------------------------- // nonzer is approximately (int(sqrt(nnza /n))); //--------------------------------------------------------------------- //--------------------------------------------------------------------- // nn1 is the smallest power of two not less than n //--------------------------------------------------------------------- nn1 = 1; do { nn1 = 2 * nn1; } while (nn1 < n); //--------------------------------------------------------------------- // Generate nonzero positions and save for the use in sparse. //--------------------------------------------------------------------- for (iouter = 0; iouter < n; iouter++) { nzv = NONZER; sprnvc(n, nzv, nn1, vc, ivc); vecset(n, vc, ivc, &nzv, iouter+1, 0.5); arow[iouter] = nzv; for (ivelt = 0; ivelt < nzv; ivelt++) { acol[iouter][ivelt] = ivc[ivelt] - 1; aelt[iouter][ivelt] = vc[ivelt]; } } //--------------------------------------------------------------------- // ... make the sparse matrix from list of elements with duplicates // (iv is used as workspace) //--------------------------------------------------------------------- sparse(a, colidx, rowstr, n, nz, NONZER, arow, acol, aelt, firstrow, lastrow, iv, RCOND, SHIFT); } //--------------------------------------------------------------------- // rows range from firstrow to lastrow // the rowstr pointers are defined for nrows = lastrow-firstrow+1 values //--------------------------------------------------------------------- static void sparse(double a[], int colidx[], int rowstr[], int n, int nz, int nozer, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int firstrow, int lastrow, int nzloc[], double rcond, double shift) { int nrows; //--------------------------------------------------- // generate a sparse matrix from a list of // [col, row, element] tri //--------------------------------------------------- int i, j, j1, j2, nza, k, kk, nzrow, jcol; double size, scale, ratio, va; logical cont40; //--------------------------------------------------------------------- // how many rows of result //--------------------------------------------------------------------- nrows = lastrow - firstrow + 1; //--------------------------------------------------------------------- // ...count the number of triples in each row //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < nrows+1; j++) { rowstr[j] = 0; } for (i = 0; i < n; i++) { for (nza = 0; nza < arow[i]; nza++) { j = acol[i][nza] + 1; rowstr[j] = rowstr[j] + arow[i]; } } rowstr[0] = 0; for (j = 1; j < nrows+1; j++) { rowstr[j] = rowstr[j] + rowstr[j-1]; } nza = rowstr[nrows] - 1; //--------------------------------------------------------------------- // ... rowstr(j) now is the location of the first nonzero // of row j of a //--------------------------------------------------------------------- if (nza > nz) { printf("Space for matrix elements exceeded in sparse\n"); printf("nza, nzmax = %d, %d\n", nza, nz); exit(EXIT_FAILURE); } //--------------------------------------------------------------------- // ... preload data pages //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j, k) for (j = 0; j < nrows; j++) { for (k = rowstr[j]; k < rowstr[j+1]; k++) { a[k] = 0.0; colidx[k] = -1; } nzloc[j] = 0; } //--------------------------------------------------------------------- // ... generate actual values by summing duplicates //--------------------------------------------------------------------- size = 1.0; ratio = pow(rcond, (1.0 / (double)(n))); for (i = 0; i < n; i++) { for (nza = 0; nza < arow[i]; nza++) { j = acol[i][nza]; scale = size * aelt[i][nza]; for (nzrow = 0; nzrow < arow[i]; nzrow++) { jcol = acol[i][nzrow]; va = aelt[i][nzrow] * scale; //-------------------------------------------------------------------- // ... add the identity * rcond to the generated matrix to bound // the smallest eigenvalue from below by rcond //-------------------------------------------------------------------- if (jcol == j && j == i) { va = va + rcond - shift; } cont40 = false; for (k = rowstr[j]; k < rowstr[j+1]; k++) { if (colidx[k] > jcol) { //---------------------------------------------------------------- // ... insert colidx here orderly //---------------------------------------------------------------- for (kk = rowstr[j+1]-2; kk >= k; kk--) { if (colidx[kk] > -1) { a[kk+1] = a[kk]; colidx[kk+1] = colidx[kk]; } } colidx[k] = jcol; a[k] = 0.0; cont40 = true; break; } else if (colidx[k] == -1) { colidx[k] = jcol; cont40 = true; break; } else if (colidx[k] == jcol) { //-------------------------------------------------------------- // ... mark the duplicated entry //-------------------------------------------------------------- nzloc[j] = nzloc[j] + 1; cont40 = true; break; } } if (cont40 == false) { printf("internal error in sparse: i=%d\n", i); exit(EXIT_FAILURE); } a[k] = a[k] + va; } } size = size * ratio; } //--------------------------------------------------------------------- // ... remove empty entries and generate final results //--------------------------------------------------------------------- for (j = 1; j < nrows; j++) { nzloc[j] = nzloc[j] + nzloc[j-1]; } for (j = 0; j < nrows; j++) { if (j > 0) { j1 = rowstr[j] - nzloc[j-1]; } else { j1 = 0; } j2 = rowstr[j+1] - nzloc[j]; nza = rowstr[j]; for (k = j1; k < j2; k++) { a[k] = a[nza]; colidx[k] = colidx[nza]; nza = nza + 1; } } #pragma omp parallel for default(shared) private(j) for (j = 1; j < nrows+1; j++) { rowstr[j] = rowstr[j] - nzloc[j-1]; } nza = rowstr[nrows] - 1; } //--------------------------------------------------------------------- // generate a sparse n-vector (v, iv) // having nzv nonzeros // // mark(i) is set to 1 if position i is nonzero. // mark is all zero on entry and is reset to all zero before exit // this corrects a performance bug found by John G. Lewis, caused by // reinitialization of mark on every one of the n calls to sprnvc //--------------------------------------------------------------------- static void sprnvc(int n, int nz, int nn1, double v[], int iv[]) { int nzv, ii, i; double vecelt, vecloc; nzv = 0; while (nzv < nz) { vecelt = randlc(&tran, amult); //--------------------------------------------------------------------- // generate an integer between 1 and n in a portable manner //--------------------------------------------------------------------- vecloc = randlc(&tran, amult); i = icnvrt(vecloc, nn1) + 1; if (i > n) continue; //--------------------------------------------------------------------- // was this integer generated already? //--------------------------------------------------------------------- logical was_gen = false; for (ii = 0; ii < nzv; ii++) { if (iv[ii] == i) { was_gen = true; break; } } if (was_gen) continue; v[nzv] = vecelt; iv[nzv] = i; nzv = nzv + 1; } } //--------------------------------------------------------------------- // scale a double precision number x in (0,1) by a power of 2 and chop it //--------------------------------------------------------------------- static int icnvrt(double x, int ipwr2) { return (int)(ipwr2 * x); } //--------------------------------------------------------------------- // set ith element of sparse vector (v, iv) with // nzv nonzeros to val //--------------------------------------------------------------------- static void vecset(int n, double v[], int iv[], int *nzv, int i, double val) { int k; logical set; set = false; for (k = 0; k < *nzv; k++) { if (iv[k] == i) { v[k] = val; set = true; } } if (set == false) { v[*nzv] = val; iv[*nzv] = i; *nzv = *nzv + 1; } }
parallelBad.c
#include <civlc.cvh> int main() { int counter = 0; #pragma omp parallel if (counter == 0) counter++; $assert(counter == 1); }
convolution_1x1_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv1x1s1_sgemm_transform_kernel_fp16sa_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { const float* kernel = _kernel; // interleave kernel_tm.create(8 * 8, inch / 8 + inch % 8, outch / 8 + outch % 8, (size_t)2u, 1); int p = 0; for (; p + 7 < outch; p += 8) { const float* kernel0 = kernel + (p + 0) * inch; const float* kernel1 = kernel + (p + 1) * inch; const float* kernel2 = kernel + (p + 2) * inch; const float* kernel3 = kernel + (p + 3) * inch; const float* kernel4 = kernel + (p + 4) * inch; const float* kernel5 = kernel + (p + 5) * inch; const float* kernel6 = kernel + (p + 6) * inch; const float* kernel7 = kernel + (p + 7) * inch; __fp16* ktmp = kernel_tm.channel(p / 8); for (int q = 0; q < inch; q++) { // kernel0...7 0 ktmp[0] = (__fp16)kernel0[0]; ktmp[1] = (__fp16)kernel1[0]; ktmp[2] = (__fp16)kernel2[0]; ktmp[3] = (__fp16)kernel3[0]; ktmp[4] = (__fp16)kernel4[0]; ktmp[5] = (__fp16)kernel5[0]; ktmp[6] = (__fp16)kernel6[0]; ktmp[7] = (__fp16)kernel7[0]; ktmp += 8; kernel0 += 1; kernel1 += 1; kernel2 += 1; kernel3 += 1; kernel4 += 1; kernel5 += 1; kernel6 += 1; kernel7 += 1; } } for (; p < outch; p++) { const float* kernel0 = kernel + p * inch; __fp16* ktmp = kernel_tm.channel(p / 8 + p % 8); for (int q = 0; q < inch; q++) { ktmp[0] = (__fp16)kernel0[0]; ktmp++; kernel0++; } } } static void conv1x1s1_sgemm_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; const __fp16* bias = _bias; // interleave Mat tmp(8 * 8, inch / 8 + inch % 8, size / 8 + size % 8, 2u, opt.workspace_allocator); { int nn_size = size >> 3; int remain_size_start = nn_size << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = ii * 8; const __fp16* img0 = bottom_blob.channel(0); img0 += i; __fp16* tmpptr = tmp.channel(i / 8); for (int q = 0; q < inch; q++) { vst1q_f16(tmpptr, vld1q_f16(img0)); tmpptr += 8; img0 += bottom_blob.cstep; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { const __fp16* img0 = bottom_blob.channel(0); img0 += i; __fp16* tmpptr = tmp.channel(i / 8 + i % 8); for (int q = 0; q < inch; q++) { tmpptr[0] = img0[0]; tmpptr++; img0 += bottom_blob.cstep; } } } int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; __fp16* outptr0 = top_blob.channel(p); __fp16* outptr1 = top_blob.channel(p + 1); __fp16* outptr2 = top_blob.channel(p + 2); __fp16* outptr3 = top_blob.channel(p + 3); __fp16* outptr4 = top_blob.channel(p + 4); __fp16* outptr5 = top_blob.channel(p + 5); __fp16* outptr6 = top_blob.channel(p + 6); __fp16* outptr7 = top_blob.channel(p + 7); const __fp16 zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; const __fp16* biasptr = bias ? bias + p : zeros; float16x8_t _bias0 = vld1q_f16(biasptr); int i = 0; for (; i + 7 < size; i += 8) { const __fp16* tmpptr = tmp.channel(i / 8); const __fp16* kptr = kernel.channel(p / 8); int q = 0; float16x8_t _sum0 = vdupq_laneq_f16(_bias0, 0); float16x8_t _sum1 = vdupq_laneq_f16(_bias0, 1); float16x8_t _sum2 = vdupq_laneq_f16(_bias0, 2); float16x8_t _sum3 = vdupq_laneq_f16(_bias0, 3); float16x8_t _sum4 = vdupq_laneq_f16(_bias0, 4); float16x8_t _sum5 = vdupq_laneq_f16(_bias0, 5); float16x8_t _sum6 = vdupq_laneq_f16(_bias0, 6); float16x8_t _sum7 = vdupq_laneq_f16(_bias0, 7); for (; q + 7 < inch; q += 8) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _p1 = vld1q_f16(tmpptr + 8); float16x8_t _p2 = vld1q_f16(tmpptr + 16); float16x8_t _p3 = vld1q_f16(tmpptr + 24); float16x8_t _p4 = vld1q_f16(tmpptr + 32); float16x8_t _p5 = vld1q_f16(tmpptr + 40); float16x8_t _p6 = vld1q_f16(tmpptr + 48); float16x8_t _p7 = vld1q_f16(tmpptr + 56); float16x8_t _k0 = vld1q_f16(kptr); float16x8_t _k1 = vld1q_f16(kptr + 8); float16x8_t _k2 = vld1q_f16(kptr + 16); float16x8_t _k3 = vld1q_f16(kptr + 24); float16x8_t _k4 = vld1q_f16(kptr + 32); float16x8_t _k5 = vld1q_f16(kptr + 40); float16x8_t _k6 = vld1q_f16(kptr + 48); float16x8_t _k7 = vld1q_f16(kptr + 56); _sum0 = vfmaq_laneq_f16(_sum0, _p0, _k0, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p0, _k0, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p0, _k0, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p0, _k0, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p0, _k0, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p0, _k0, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p0, _k0, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p0, _k0, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p1, _k1, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p1, _k1, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p1, _k1, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p1, _k1, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p1, _k1, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p1, _k1, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p1, _k1, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p1, _k1, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p2, _k2, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p2, _k2, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p2, _k2, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p2, _k2, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p2, _k2, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p2, _k2, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p2, _k2, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p2, _k2, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p3, _k3, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p3, _k3, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p3, _k3, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p3, _k3, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p3, _k3, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p3, _k3, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p3, _k3, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p3, _k3, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p4, _k4, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p4, _k4, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p4, _k4, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p4, _k4, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p4, _k4, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p4, _k4, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p4, _k4, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p4, _k4, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p5, _k5, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p5, _k5, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p5, _k5, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p5, _k5, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p5, _k5, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p5, _k5, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p5, _k5, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p5, _k5, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p6, _k6, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p6, _k6, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p6, _k6, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p6, _k6, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p6, _k6, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p6, _k6, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p6, _k6, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p6, _k6, 7); _sum0 = vfmaq_laneq_f16(_sum0, _p7, _k7, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p7, _k7, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p7, _k7, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p7, _k7, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p7, _k7, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p7, _k7, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p7, _k7, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p7, _k7, 7); tmpptr += 64; kptr += 64; } for (; q < inch; q++) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _k0 = vld1q_f16(kptr); _sum0 = vfmaq_laneq_f16(_sum0, _p0, _k0, 0); _sum1 = vfmaq_laneq_f16(_sum1, _p0, _k0, 1); _sum2 = vfmaq_laneq_f16(_sum2, _p0, _k0, 2); _sum3 = vfmaq_laneq_f16(_sum3, _p0, _k0, 3); _sum4 = vfmaq_laneq_f16(_sum4, _p0, _k0, 4); _sum5 = vfmaq_laneq_f16(_sum5, _p0, _k0, 5); _sum6 = vfmaq_laneq_f16(_sum6, _p0, _k0, 6); _sum7 = vfmaq_laneq_f16(_sum7, _p0, _k0, 7); tmpptr += 8; kptr += 8; } vst1q_f16(outptr0, _sum0); vst1q_f16(outptr1, _sum1); vst1q_f16(outptr2, _sum2); vst1q_f16(outptr3, _sum3); vst1q_f16(outptr4, _sum4); vst1q_f16(outptr5, _sum5); vst1q_f16(outptr6, _sum6); vst1q_f16(outptr7, _sum7); outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; outptr4 += 8; outptr5 += 8; outptr6 += 8; outptr7 += 8; } for (; i < size; i++) { const __fp16* tmpptr = tmp.channel(i / 8 + i % 8); const __fp16* kptr = kernel.channel(p / 8); int q = 0; float16x8_t _sum0 = _bias0; for (; q + 7 < inch; q += 8) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _k0 = vld1q_f16(kptr); float16x8_t _k1 = vld1q_f16(kptr + 8); float16x8_t _k2 = vld1q_f16(kptr + 16); float16x8_t _k3 = vld1q_f16(kptr + 24); float16x8_t _k4 = vld1q_f16(kptr + 32); float16x8_t _k5 = vld1q_f16(kptr + 40); float16x8_t _k6 = vld1q_f16(kptr + 48); float16x8_t _k7 = vld1q_f16(kptr + 56); _sum0 = vfmaq_laneq_f16(_sum0, _k0, _p0, 0); _sum0 = vfmaq_laneq_f16(_sum0, _k1, _p0, 1); _sum0 = vfmaq_laneq_f16(_sum0, _k2, _p0, 2); _sum0 = vfmaq_laneq_f16(_sum0, _k3, _p0, 3); _sum0 = vfmaq_laneq_f16(_sum0, _k4, _p0, 4); _sum0 = vfmaq_laneq_f16(_sum0, _k5, _p0, 5); _sum0 = vfmaq_laneq_f16(_sum0, _k6, _p0, 6); _sum0 = vfmaq_laneq_f16(_sum0, _k7, _p0, 7); tmpptr += 8; kptr += 64; } for (; q < inch; q++) { float16x8_t _p0 = vld1q_dup_f16(tmpptr); float16x8_t _k0 = vld1q_f16(kptr); _sum0 = vfmaq_f16(_sum0, _k0, _p0); tmpptr += 1; kptr += 8; } vst1q_lane_f16(outptr0, _sum0, 0); vst1q_lane_f16(outptr1, _sum0, 1); vst1q_lane_f16(outptr2, _sum0, 2); vst1q_lane_f16(outptr3, _sum0, 3); vst1q_lane_f16(outptr4, _sum0, 4); vst1q_lane_f16(outptr5, _sum0, 5); vst1q_lane_f16(outptr6, _sum0, 6); vst1q_lane_f16(outptr7, _sum0, 7); outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out0 = top_blob.channel(p); const __fp16 bias0 = bias ? bias[p] : 0.f; __fp16* outptr0 = out0; int i = 0; for (; i + 7 < size; i += 8) { const __fp16* tmpptr = tmp.channel(i / 8); const __fp16* kptr = kernel.channel(p / 8 + p % 8); int q = 0; float16x8_t _sum0 = vdupq_n_f16(bias0); for (; q + 7 < inch; q += 8) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _p1 = vld1q_f16(tmpptr + 8); float16x8_t _p2 = vld1q_f16(tmpptr + 16); float16x8_t _p3 = vld1q_f16(tmpptr + 24); float16x8_t _p4 = vld1q_f16(tmpptr + 32); float16x8_t _p5 = vld1q_f16(tmpptr + 40); float16x8_t _p6 = vld1q_f16(tmpptr + 48); float16x8_t _p7 = vld1q_f16(tmpptr + 56); float16x8_t _k0 = vld1q_f16(kptr); _sum0 = vfmaq_laneq_f16(_sum0, _p0, _k0, 0); _sum0 = vfmaq_laneq_f16(_sum0, _p1, _k0, 1); _sum0 = vfmaq_laneq_f16(_sum0, _p2, _k0, 2); _sum0 = vfmaq_laneq_f16(_sum0, _p3, _k0, 3); _sum0 = vfmaq_laneq_f16(_sum0, _p4, _k0, 4); _sum0 = vfmaq_laneq_f16(_sum0, _p5, _k0, 5); _sum0 = vfmaq_laneq_f16(_sum0, _p6, _k0, 6); _sum0 = vfmaq_laneq_f16(_sum0, _p7, _k0, 7); tmpptr += 64; kptr += 8; } for (; q < inch; q++) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _k0 = vld1q_dup_f16(kptr); _sum0 = vfmaq_f16(_sum0, _p0, _k0); tmpptr += 8; kptr += 1; } vst1q_f16(outptr0, _sum0); outptr0 += 8; } for (; i < size; i++) { const __fp16* tmpptr = tmp.channel(i / 8 + i % 8); const __fp16* kptr = kernel.channel(p / 8 + p % 8); int q = 0; float16x8_t _sum0 = vdupq_n_f16(0.f); for (; q + 7 < inch; q += 8) { float16x8_t _p0 = vld1q_f16(tmpptr); float16x8_t _k0 = vld1q_f16(kptr); _sum0 = vfmaq_f16(_sum0, _p0, _k0); tmpptr += 8; kptr += 8; } __fp16 sum0 = bias0 + vaddvq_f32(vcvt_f32_f16(vadd_f16(vget_low_f16(_sum0), vget_high_f16(_sum0)))); for (; q < inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } // // NOTE sgemm // for (; p<outch; p++) // { // Mat out0 = top_blob.channel(p); // // const __fp16 bias0 = bias ? bias[p] : 0.f; // // __fp16* outptr0 = out0; // // for (int i=0; i<size; i++) // { // __fp16 sum = bias0; // // const __fp16* kptr = _kernel.channel(p/8 + p%8); // // for (int q=0; q<inch; q++) // { // const __fp16* img0 = bottom_blob.channel(q); // // sum += img0[i] * kptr[0]; // kptr ++; // } // // outptr0[i] = sum; // } // } }
joseph3d_back_2.c
/** * @file joseph3d_back_2.c */ #include<stdio.h> #include<stdlib.h> #include<math.h> #include<omp.h> #include "ray_cube_intersection.h" void joseph3d_back_2(const float *xstart, const float *xend, float *img, const float *img_origin, const float *voxsize, const float *p, long long nlors, const int *img_dim) { long long i; int n0 = img_dim[0]; int n1 = img_dim[1]; int n2 = img_dim[2]; float voxsize0 = voxsize[0]; float voxsize1 = voxsize[1]; float voxsize2 = voxsize[2]; float img_origin0 = img_origin[0]; float img_origin1 = img_origin[1]; float img_origin2 = img_origin[2]; # pragma omp parallel for schedule(static) for(i = 0; i < nlors; i++) { if(p[i] != 0) { float d0, d1, d2, d0_sq, d1_sq, d2_sq; float cs0, cs1, cs2, cf; float lsq, cos0_sq, cos1_sq, cos2_sq; unsigned short direction; int i0, i1, i2; int i0_floor, i1_floor, i2_floor; int i0_ceil, i1_ceil, i2_ceil; float x_pr0, x_pr1, x_pr2; float tmp_0, tmp_1, tmp_2; float xstart0 = xstart[i*3 + 0]; float xstart1 = xstart[i*3 + 1]; float xstart2 = xstart[i*3 + 2]; float xend0 = xend[i*3 + 0]; float xend1 = xend[i*3 + 1]; float xend2 = xend[i*3 + 2]; unsigned char intersec; float t1, t2; float istart_f, iend_f, tmp; int istart, iend; // test whether the ray between the two detectors is most parallel // with the 0, 1, or 2 axis d0 = xend0 - xstart0; d1 = xend1 - xstart1; d2 = xend2 - xstart2; //----------- //--- test whether ray and cube intersect intersec = ray_cube_intersection(xstart0, xstart1, xstart2, img_origin0 - 1*voxsize0, img_origin1 - 1*voxsize1, img_origin2 - 1*voxsize2, img_origin0 + n0*voxsize0, img_origin1 + n1*voxsize1, img_origin2 + n2*voxsize2, d0, d1, d2, &t1, &t2); if (intersec == 1) { d0_sq = d0*d0; d1_sq = d1*d1; d2_sq = d2*d2; lsq = d0_sq + d1_sq + d2_sq; cos0_sq = d0_sq / lsq; cos1_sq = d1_sq / lsq; cos2_sq = d2_sq / lsq; cs0 = sqrtf(cos0_sq); cs1 = sqrtf(cos1_sq); cs2 = sqrtf(cos2_sq); direction = 0; if ((cos1_sq >= cos0_sq) && (cos1_sq >= cos2_sq)) { direction = 1; } if ((cos2_sq >= cos0_sq) && (cos2_sq >= cos1_sq)) { direction = 2; } if(direction == 0) { // case where ray is most parallel to the 0 axis // we step through the volume along the 0 direction // factor for correctiong voxel size and |cos(theta)| cf = voxsize0/cs0; //--- check where ray enters / leaves cube istart_f = (xstart0 + t1*d0 - img_origin0) / voxsize0; iend_f = (xstart0 + t2*d0 - img_origin0) / voxsize0; if (istart_f > iend_f){ tmp = iend_f; iend_f = istart_f; istart_f = tmp; } istart = (int)floor(istart_f); iend = (int)ceil(iend_f); if (istart < 0){istart = 0;} if (iend >= n0){iend = n0;} // check in which "plane" the start and end points are // we have to do this to avoid that we include voxels // that are "outside" the line segment bewteen xstart and xend // !! for these calculations we overwrite the istart_f and iend_f variables !! istart_f = (xstart0 - img_origin0) / voxsize0; iend_f = (xend0 - img_origin0) / voxsize0; if (istart_f > iend_f){ tmp = iend_f; iend_f = istart_f; istart_f = tmp; } if (istart < (int)floor(istart_f)){istart = (int)floor(istart_f);} if (iend >= (int)ceil(iend_f)){iend = (int)ceil(iend_f);} //--- for(i0 = istart; i0 < iend; i0++) { // get the indices where the ray intersects the image plane x_pr1 = xstart1 + (img_origin0 + i0*voxsize0 - xstart0)*d1 / d0; x_pr2 = xstart2 + (img_origin0 + i0*voxsize0 - xstart0)*d2 / d0; i1_floor = (int)floor((x_pr1 - img_origin1)/voxsize1); i1_ceil = i1_floor + 1; i2_floor = (int)floor((x_pr2 - img_origin2)/voxsize2); i2_ceil = i2_floor + 1; // calculate the distances to the floor normalized to [0,1] // for the bilinear interpolation tmp_1 = (x_pr1 - (i1_floor*voxsize1 + img_origin1)) / voxsize1; tmp_2 = (x_pr2 - (i2_floor*voxsize2 + img_origin2)) / voxsize2; if ((i1_floor >= 0) && (i1_floor < n1) && (i2_floor >= 0) && (i2_floor < n2)) { #pragma omp atomic img[n1*n2*i0 + n2*i1_floor + i2_floor] += (p[i] * (1 - tmp_1) * (1 - tmp_2) * cf); } if ((i1_ceil >= 0) && (i1_ceil < n1) && (i2_floor >= 0) && (i2_floor < n2)) { #pragma omp atomic img[n1*n2*i0 + n2*i1_ceil + i2_floor] += (p[i] * tmp_1 * (1 - tmp_2) * cf); } if ((i1_floor >= 0) && (i1_floor < n1) && (i2_ceil >= 0) && (i2_ceil < n2)) { #pragma omp atomic img[n1*n2*i0 + n2*i1_floor + i2_ceil] += (p[i] * (1 - tmp_1) * tmp_2 * cf); } if ((i1_ceil >= 0) && (i1_ceil < n1) && (i2_ceil >= 0) && (i2_ceil < n2)) { #pragma omp atomic img[n1*n2*i0 + n2*i1_ceil + i2_ceil] += (p[i] * tmp_1 * tmp_2 * cf); } } } // --------------------------------------------------------------------------------- if(direction == 1) { // case where ray is most parallel to the 1 axis // we step through the volume along the 1 direction // factor for correctiong voxel size and |cos(theta)| cf = voxsize1/cs1; //--- check where ray enters / leaves cube istart_f = (xstart1 + t1*d1 - img_origin1) / voxsize1; iend_f = (xstart1 + t2*d1 - img_origin1) / voxsize1; if (istart_f > iend_f){ tmp = iend_f; iend_f = istart_f; istart_f = tmp; } istart = (int)floor(istart_f); iend = (int)ceil(iend_f); if (istart < 0){istart = 0;} if (iend >= n1){iend = n1;} // check in which "plane" the start and end points are // we have to do this to avoid that we include voxels // that are "outside" the line segment bewteen xstart and xend // !! for these calculations we overwrite the istart_f and iend_f variables !! istart_f = (xstart1 - img_origin1) / voxsize1; iend_f = (xend1 - img_origin1) / voxsize1; if (istart_f > iend_f){ tmp = iend_f; iend_f = istart_f; istart_f = tmp; } if (istart < (int)floor(istart_f)){istart = (int)floor(istart_f);} if (iend >= (int)ceil(iend_f)){iend = (int)ceil(iend_f);} //--- for(i1 = istart; i1 < iend; i1++) { // get the indices where the ray intersects the image plane x_pr0 = xstart0 + (img_origin1 + i1*voxsize1 - xstart1)*d0 / d1; x_pr2 = xstart2 + (img_origin1 + i1*voxsize1 - xstart1)*d2 / d1; i0_floor = (int)floor((x_pr0 - img_origin0)/voxsize0); i0_ceil = i0_floor + 1; i2_floor = (int)floor((x_pr2 - img_origin2)/voxsize2); i2_ceil = i2_floor + 1; // calculate the distances to the floor normalized to [0,1] // for the bilinear interpolation tmp_0 = (x_pr0 - (i0_floor*voxsize0 + img_origin0)) / voxsize0; tmp_2 = (x_pr2 - (i2_floor*voxsize2 + img_origin2)) / voxsize2; if ((i0_floor >= 0) && (i0_floor < n0) && (i2_floor >= 0) && (i2_floor < n2)) { #pragma omp atomic img[n1*n2*i0_floor + n2*i1 + i2_floor] += (p[i] * (1 - tmp_0) * (1 - tmp_2) * cf); } if ((i0_ceil >= 0) && (i0_ceil < n0) && (i2_floor >= 0) && (i2_floor < n2)) { #pragma omp atomic img[n1*n2*i0_ceil + n2*i1 + i2_floor] += (p[i] * tmp_0 * (1 - tmp_2) * cf); } if ((i0_floor >= 0) && (i0_floor < n0) && (i2_ceil >= 0) && (i2_ceil < n2)) { #pragma omp atomic img[n1*n2*i0_floor + n2*i1 + i2_ceil] += (p[i] * (1 - tmp_0) * tmp_2 * cf); } if((i0_ceil >= 0) && (i0_ceil < n0) && (i2_ceil >= 0) && (i2_ceil < n2)) { #pragma omp atomic img[n1*n2*i0_ceil + n2*i1 + i2_ceil] += (p[i] * tmp_0 * tmp_2 * cf); } } } //--------------------------------------------------------------------------------- if (direction == 2) { // case where ray is most parallel to the 2 axis // we step through the volume along the 2 direction // factor for correctiong voxel size and |cos(theta)| cf = voxsize2/cs2; //--- check where ray enters / leaves cube istart_f = (xstart2 + t1*d2 - img_origin2) / voxsize2; iend_f = (xstart2 + t2*d2 - img_origin2) / voxsize2; if (istart_f > iend_f){ tmp = iend_f; iend_f = istart_f; istart_f = tmp; } istart = (int)floor(istart_f); iend = (int)ceil(iend_f); if (istart < 0){istart = 0;} if (iend >= n2){iend = n2;} // check in which "plane" the start and end points are // we have to do this to avoid that we include voxels // that are "outside" the line segment bewteen xstart and xend // !! for these calculations we overwrite the istart_f and iend_f variables !! istart_f = (xstart2 - img_origin2) / voxsize2; iend_f = (xend2 - img_origin2) / voxsize2; if (istart_f > iend_f){ tmp = iend_f; iend_f = istart_f; istart_f = tmp; } if (istart < (int)floor(istart_f)){istart = (int)floor(istart_f);} if (iend >= (int)ceil(iend_f)){iend = (int)ceil(iend_f);} //--- for(i2 = istart; i2 < iend; i2++) { // get the indices where the ray intersects the image plane x_pr0 = xstart0 + (img_origin2 + i2*voxsize2 - xstart2)*d0 / d2; x_pr1 = xstart1 + (img_origin2 + i2*voxsize2 - xstart2)*d1 / d2; i0_floor = (int)floor((x_pr0 - img_origin0)/voxsize0); i0_ceil = i0_floor + 1; i1_floor = (int)floor((x_pr1 - img_origin1)/voxsize1); i1_ceil = i1_floor + 1; // calculate the distances to the floor normalized to [0,1] // for the bilinear interpolation tmp_0 = (x_pr0 - (i0_floor*voxsize0 + img_origin0)) / voxsize0; tmp_1 = (x_pr1 - (i1_floor*voxsize1 + img_origin1)) / voxsize1; if ((i0_floor >= 0) && (i0_floor < n0) && (i1_floor >= 0) && (i1_floor < n1)) { #pragma omp atomic img[n1*n2*i0_floor + n2*i1_floor + i2] += (p[i] * (1 - tmp_0) * (1 - tmp_1) * cf); } if ((i0_ceil >= 0) && (i0_ceil < n0) && (i1_floor >= 0) && (i1_floor < n1)) { #pragma omp atomic img[n1*n2*i0_ceil + n2*i1_floor + i2] += (p[i] * tmp_0 * (1 - tmp_1) * cf); } if ((i0_floor >= 0) && (i0_floor < n0) && (i1_ceil >= 0) && (i1_ceil < n1)) { #pragma omp atomic img[n1*n2*i0_floor + n2*i1_ceil + i2] += (p[i] * (1 - tmp_0) * tmp_1 * cf); } if ((i0_ceil >= 0) && (i0_ceil < n0) && (i1_ceil >= 0) && (i1_ceil < n1)) { #pragma omp atomic img[n1*n2*i0_ceil + n2*i1_ceil + i2] += (p[i] * tmp_0 * tmp_1 * cf); } } } } } } }
616fb_dev.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include "omp.h" #include <stdio.h> #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; double section1; double section2; }; void bf0(float *restrict r18_vec, float *restrict r19_vec, float *restrict r20_vec, float *restrict r21_vec, float *restrict r34_vec, float *restrict r35_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw); void bf1(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r17_vec, float *restrict r18_vec, float *restrict r19_vec, float *restrict r20_vec, float *restrict r21_vec, float *restrict r34_vec, float *restrict r35_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int t1, const int t2, const int x1_blk0_size, const int x_M, const int x_m, const int y1_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw); int ForwardTTI(struct dataobj *restrict block_sizes_vec, struct dataobj *restrict damp_vec, struct dataobj *restrict delta_vec, const float dt, struct dataobj *restrict epsilon_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict phi_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict theta_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, const int x_size, const int y_size, const int z_size, const int sp_zi_m, const int time_M, const int time_m, struct profiler *timers, const int x1_blk0_size, const int x_M, const int x_m, const int y1_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int nthreads_nonaffine) { int(*restrict block_sizes) __attribute__((aligned(64))) = (int(*))block_sizes_vec->data; float(*restrict delta)[delta_vec->size[1]][delta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[delta_vec->size[1]][delta_vec->size[2]])delta_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict phi)[phi_vec->size[1]][phi_vec->size[2]] __attribute__((aligned(64))) = (float(*)[phi_vec->size[1]][phi_vec->size[2]])phi_vec->data; float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data; float(*restrict save_src_v)[save_src_v_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_v_vec->size[1]])save_src_v_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; float(*restrict theta)[theta_vec->size[1]][theta_vec->size[2]] __attribute__((aligned(64))) = (float(*)[theta_vec->size[1]][theta_vec->size[2]])theta_vec->data; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data; float(*r21)[y_size + 1][z_size + 1]; posix_memalign((void **)&r21, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1])); float(*r20)[y_size + 1][z_size + 1]; posix_memalign((void **)&r20, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1])); float(*r19)[y_size + 1][z_size + 1]; posix_memalign((void **)&r19, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1])); float(*r18)[y_size + 1][z_size + 1]; posix_memalign((void **)&r18, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1])); float(*r17)[y_size + 1][z_size + 1]; posix_memalign((void **)&r17, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1])); float(*r34)[y_size + 1][z_size + 1]; posix_memalign((void **)&r34, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1])); float(*r35)[y_size + 1][z_size + 1]; posix_memalign((void **)&r35, 64, sizeof(float[x_size + 1][y_size + 1][z_size + 1])); /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); /* Begin section0 */ #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(1) schedule(static, 1) for (int x = x_m - 1; x <= x_M; x += 1) { for (int y = y_m - 1; y <= y_M; y += 1) { #pragma omp simd aligned(delta, phi, theta : 32) for (int z = z_m - 1; z <= z_M; z += 1) { r21[x + 1][y + 1][z + 1] = cos(phi[x + 4][y + 4][z + 4]); r20[x + 1][y + 1][z + 1] = sin(theta[x + 4][y + 4][z + 4]); r19[x + 1][y + 1][z + 1] = sin(phi[x + 4][y + 4][z + 4]); r18[x + 1][y + 1][z + 1] = cos(theta[x + 4][y + 4][z + 4]); r17[x + 1][y + 1][z + 1] = sqrt(2 * delta[x + 4][y + 4][z + 4] + 1); } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000; int y0_blk0_size = 8; //block_sizes[3]; int x0_blk0_size = 8; //block_sizes[2]; int yb_size = 16; // block_sizes[1]; int xb_size = 16; //block_sizes[0]; int sf = 4; int t_blk_size = 2 * sf * (time_M - time_m); printf(" Tiles: %d, %d ::: Blocks %d, %d \n", xb_size, yb_size, x0_blk0_size, y0_blk0_size); for (int t_blk = time_m; t_blk < sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block { for (int xb = x_m; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size) { //printf(" Change of outer xblock %d \n", xb); for (int yb = y_m; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size) { //printf(" Timestep tw: %d, Updating x: %d y: %d \n", xb, yb); for (int time = t_blk, t0 = (time) % (3), t1 = (time + 1) % (3), t2 = (time + 2) % (3); time <= 1 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1))) % (3), t1 = (((time / sf) % (time_M - time_m + 1)) + 1) % (3), t2 = (((time / sf) % (time_M - time_m + 1)) + 2) % (3)) { int tw = ((time / sf) % (time_M - time_m + 1)); struct timeval start_section1, end_section1; gettimeofday(&start_section1, NULL); /* Begin section1 */ //bf0((float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, x_size, y_size, z_size, time, t0, x0_blk0_size, x_M - (x_M - x_m + 2) % (x0_blk0_size), x_m - 1, y0_blk0_size, y_M - (y_M - y_m + 2) % (y0_blk0_size), y_m - 1, z_M, z_m, nthreads, xb, yb, xb_size, yb_size, tw); bf0((float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, x_size, y_size, z_size, time, t0, x0_blk0_size, x_M, x_m , y0_blk0_size, y_M , y_m , z_M, z_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf("\n BF0 - 1 IS OVER"); //bf0((float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, x_size, y_size, z_size, time, t0, x0_blk0_size, x_M - (x_M - x_m + 2) % (x0_blk0_size), x_m - 1, (y_M - y_m + 2) % (y0_blk0_size), y_M, y_M - (y_M - y_m + 2) % (y0_blk0_size) + 1, z_M, z_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf(" BF0 - 2 IS OVER"); //bf0((float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, x_size, y_size, z_size, time, t0, (x_M - x_m + 2) % (x0_blk0_size), x_M, x_M - (x_M - x_m + 2) % (x0_blk0_size) + 1, y0_blk0_size, y_M - (y_M - y_m + 2) % (y0_blk0_size), y_m - 1, z_M, z_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf(" BF0 - 3 IS OVER"); //bf0((float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, x_size, y_size, z_size, time, t0, (x_M - x_m + 2) % (x0_blk0_size), x_M, x_M - (x_M - x_m + 2) % (x0_blk0_size) + 1, (y_M - y_m + 2) % (y0_blk0_size), y_M, y_M - (y_M - y_m + 2) % (y0_blk0_size) + 1, z_M, z_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf(" BF0 - 4 IS OVER"); /*==============================================*/ //bf1(damp_vec, dt, epsilon_vec, (float *)r17, (float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, vp_vec, nnz_sp_source_mask_vec, sp_source_mask_vec, save_src_u_vec, save_src_v_vec, source_id_vec, source_mask_vec, x_size, y_size, z_size, time, t0, t1, t2, x1_blk0_size, -2 + x_M - (x_M - x_m + 1) % (x1_blk0_size), x_m, y1_blk0_size, -2 + y_M - (y_M - y_m + 1) % (y1_blk0_size), y_m, z_M, z_m, sp_zi_m, nthreads, xb, yb, xb_size, yb_size, tw); bf1(damp_vec, dt, epsilon_vec, (float *)r17, (float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, vp_vec, nnz_sp_source_mask_vec, sp_source_mask_vec, save_src_u_vec, save_src_v_vec, source_id_vec, source_mask_vec, x_size, y_size, z_size, time, t0, t1, t2, x0_blk0_size, x_M, x_m, y0_blk0_size, y_M, y_m, z_M, z_m, sp_zi_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf("\n BF1 - 1 IS OVER"); //bf1(damp_vec, dt, epsilon_vec, (float *)r17, (float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, vp_vec, nnz_sp_source_mask_vec, sp_source_mask_vec, save_src_u_vec, save_src_v_vec, source_id_vec, source_mask_vec, x_size, y_size, z_size, time, t0, t1, t2, x1_blk0_size, x_M - (x_M - x_m + 1) % (x1_blk0_size), x_m, (y_M - y_m + 1) % (y1_blk0_size), y_M, y_M - (y_M - y_m + 1) % (y1_blk0_size) + 1, z_M, z_m, sp_zi_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf(" BF1 - 2 IS OVER"); //bf1(damp_vec, dt, epsilon_vec, (float *)r17, (float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, vp_vec, nnz_sp_source_mask_vec, sp_source_mask_vec, save_src_u_vec, save_src_v_vec, source_id_vec, source_mask_vec, x_size, y_size, z_size, time, t0, t1, t2, (x_M - x_m + 1) % (x1_blk0_size), x_M, x_M - (x_M - x_m + 1) % (x1_blk0_size) + 1, y1_blk0_size, y_M - (y_M - y_m + 1) % (y1_blk0_size), y_m, z_M, z_m, sp_zi_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf(" BF1 - 3 IS OVER"); //bf1(damp_vec, dt, epsilon_vec, (float *)r17, (float *)r18, (float *)r19, (float *)r20, (float *)r21, (float *)r34, (float *)r35, u_vec, v_vec, vp_vec, nnz_sp_source_mask_vec, sp_source_mask_vec, save_src_u_vec, save_src_v_vec, source_id_vec, source_mask_vec, x_size, y_size, z_size, time, t0, t1, t2, (x_M - x_m + 1) % (x1_blk0_size), x_M, x_M - (x_M - x_m + 1) % (x1_blk0_size) + 1, (y_M - y_m + 1) % (y1_blk0_size), y_M, y_M - (y_M - y_m + 1) % (y1_blk0_size) + 1, z_M, z_m, sp_zi_m, nthreads, xb, yb, xb_size, yb_size, tw); //printf(" BF1 - 4 IS OVER"); /* End section1 */ gettimeofday(&end_section1, NULL); timers->section1 += (double)(end_section1.tv_sec - start_section1.tv_sec) + (double)(end_section1.tv_usec - start_section1.tv_usec) / 1000000; } } } } /* for (int time = time_m, t1 = (time + 1) % (3); time <= time_M; time += 1, t1 = (time + 1) % (3)) { struct timeval start_section2, end_section2; gettimeofday(&start_section2, NULL); Begin section2 #pragma omp parallel num_threads(nthreads_nonaffine) { int chunk_size = (int)(fmax(1, (1.0F / 3.0F) * (x_M - x_m + 1) / nthreads_nonaffine)); #pragma omp for collapse(1) schedule(dynamic, chunk_size) for (int x = x_m; x <= x_M; x += 1) { for (int y = y_m; y <= y_M; y += 1) { } } } End section2 gettimeofday(&end_section2, NULL); timers->section2 += (double)(end_section2.tv_sec - start_section2.tv_sec) + (double)(end_section2.tv_usec - start_section2.tv_usec) / 1000000; } */ free(r21); free(r20); free(r19); free(r18); free(r17); free(r34); free(r35); return 0; } void bf0(float *restrict r18_vec, float *restrict r19_vec, float *restrict r20_vec, float *restrict r21_vec, float *restrict r34_vec, float *restrict r35_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int x0_blk0_size, const int x_M, const int x_m, const int y0_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw) { float(*restrict r18)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r18_vec; float(*restrict r19)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r19_vec; float(*restrict r20)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r20_vec; float(*restrict r21)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r21_vec; float(*restrict r34)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r34_vec; float(*restrict r35)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r35_vec; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data; if (x0_blk0_size == 0) { return; } #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(1) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size) { //printf(" Change of inner x0_blk0 %d \n", x0_blk0); for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++) { //printf(" bf0 Timestep tw: %d, Updating x: %d y: %d \n", tw, x-time+1, y-time+1); #pragma omp simd aligned(u, v : 32) for (int z = z_m - 1 ; z <= z_M; z += 1) { //printf(" bf0 Updating x: %d y: %d z: %d \n", x - time + 1, y - time + 1, z + 1); float r39 = -v[t0][x - time + 4][y - time + 4][z + 4]; r35[x - time + 1][y - time + 1][z + 1] = 1.0e-1F * (-(r39 + v[t0][x - time + 4][y - time + 4][z + 5]) * r18[x - time + 1][y - time + 1][z + 1] - (r39 + v[t0][x - time + 4][y - time + 5][z + 4]) * r19[x - time + 1][y - time + 1][z + 1] * r20[x - time + 1][y - time + 1][z + 1] - (r39 + v[t0][x - time + 5][y - time + 4][z + 4]) * r20[x - time + 1][y - time + 1][z + 1] * r21[x - time + 1][y - time + 1][z + 1]); float r40 = -u[t0][x - time + 4][y - time + 4][z + 4]; r34[x - time + 1][y - time + 1][z + 1] = 1.0e-1F * (-(r40 + u[t0][x - time + 4][y - time + 4][z + 5]) * r18[x - time + 1][y - time + 1][z + 1] - (r40 + u[t0][x - time + 4][y - time + 5][z + 4]) * r19[x - time + 1][y - time + 1][z + 1] * r20[x - time + 1][y - time + 1][z + 1] - (r40 + u[t0][x - time + 5][y - time + 4][z + 4]) * r20[x - time + 1][y - time + 1][z + 1] * r21[x - time + 1][y - time + 1][z + 1]); } } } } } } } void bf1(struct dataobj *restrict damp_vec, const float dt, struct dataobj *restrict epsilon_vec, float *restrict r17_vec, float *restrict r18_vec, float *restrict r19_vec, float *restrict r20_vec, float *restrict r21_vec, float *restrict r34_vec, float *restrict r35_vec, struct dataobj *restrict u_vec, struct dataobj *restrict v_vec, struct dataobj *restrict vp_vec, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict save_src_u_vec, struct dataobj *restrict save_src_v_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, const int x_size, const int y_size, const int z_size, const int time, const int t0, const int t1, const int t2, const int x1_blk0_size, const int x_M, const int x_m, const int y1_blk0_size, const int y_M, const int y_m, const int z_M, const int z_m, const int sp_zi_m, const int nthreads, const int xb, const int yb, const int xb_size, const int yb_size, const int tw) { float(*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[damp_vec->size[1]][damp_vec->size[2]])damp_vec->data; float(*restrict epsilon)[epsilon_vec->size[1]][epsilon_vec->size[2]] __attribute__((aligned(64))) = (float(*)[epsilon_vec->size[1]][epsilon_vec->size[2]])epsilon_vec->data; float(*restrict r17)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r17_vec; float(*restrict r18)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r18_vec; float(*restrict r19)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r19_vec; float(*restrict r20)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r20_vec; float(*restrict r21)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r21_vec; float(*restrict r34)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r34_vec; float(*restrict r35)[y_size + 1][z_size + 1] __attribute__((aligned(64))) = (float(*)[y_size + 1][z_size + 1]) r35_vec; float(*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__((aligned(64))) = (float(*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]])u_vec->data; float(*restrict v)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_vec->size[1]][v_vec->size[2]][v_vec->size[3]])v_vec->data; float(*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[vp_vec->size[1]][vp_vec->size[2]])vp_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src_u)[save_src_u_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_u_vec->size[1]])save_src_u_vec->data; float(*restrict save_src_v)[save_src_v_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_v_vec->size[1]])save_src_v_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; //printf("In bf1 \n"); if (x1_blk0_size == 0) { return; } #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(1) schedule(dynamic, 1) for (int x1_blk0 = max((x_m + time), xb - 2 ); x1_blk0 <= +min((x_M + time), (xb - 2 + xb_size)); x1_blk0 += x1_blk0_size) { //printf(" Change of inner x1_blk0 %d \n", x1_blk0); for (int y1_blk0 = max((y_m + time), yb - 2 ); y1_blk0 <= +min((y_M + time), (yb - 2 + yb_size)); y1_blk0 += y1_blk0_size) { for (int x = x1_blk0; x <= min(min((x_M + time), (xb - 2 + xb_size - 1)), (x1_blk0 + x1_blk0_size - 1)); x++) { for (int y = y1_blk0; y <= min(min((y_M + time), (yb - 2 + yb_size - 1)), (y1_blk0 + y1_blk0_size - 1)); y++) { //printf(" bf1 Timestep tw: %d, Updating x: %d y: %d \n", tw, x - time + 4, y - time + 4); #pragma omp simd aligned(damp, epsilon, u, v, vp : 32) for (int z = z_m; z <= z_M; z += 1) { //printf(" bf1 Updating x: %d y: %d z: %d \n", x - time + 4, y - time + 4, z + 4); //printf(" bf1 Updating x: %d y: %d z: %d \n", x - time + 4, y - time + 4, z + 4); float r46 = 1.0 / dt; float r45 = 1.0 / (dt * dt); float r44 = r18[x - time + 1][y - time + 1][z] * r35[x - time + 1][y - time + 1][z] - r18[x - time + 1][y - time + 1][z + 1] * r35[x - time + 1][y - time + 1][z + 1] + r19[x - time + 1][y - time][z + 1] * r20[x - time + 1][y - time][z + 1] * r35[x - time + 1][y - time][z + 1] - r19[x - time + 1][y - time + 1][z + 1] * r20[x - time + 1][y - time + 1][z + 1] * r35[x - time + 1][y - time + 1][z + 1] + r20[x - time][y - time + 1][z + 1] * r21[x - time][y - time + 1][z + 1] * r35[x - time][y - time + 1][z + 1] - r20[x - time + 1][y - time + 1][z + 1] * r21[x - time + 1][y - time + 1][z + 1] * r35[x - time + 1][y - time + 1][z + 1]; float r43 = pow(vp[x - time + 4][y - time + 4][z + 4], -2); float r42 = 1.0e-1F * (-r18[x - time + 1][y - time + 1][z] * r34[x - time + 1][y - time + 1][z] + r18[x - time + 1][y - time + 1][z + 1] * r34[x - time + 1][y - time + 1][z + 1] - r19[x - time + 1][y - time][z + 1] * r20[x - time + 1][y - time][z + 1] * r34[x - time + 1][y - time][z + 1] + r19[x - time + 1][y - time + 1][z + 1] * r20[x - time + 1][y - time + 1][z + 1] * r34[x - time + 1][y - time + 1][z + 1] - r20[x - time][y - time + 1][z + 1] * r21[x - time][y - time + 1][z + 1] * r34[x - time][y - time + 1][z + 1] + r20[x - time + 1][y - time + 1][z + 1] * r21[x - time + 1][y - time + 1][z + 1] * r34[x - time + 1][y - time + 1][z + 1]) - 8.33333315e-4F * (u[t0][x - time + 2][y - time + 4][z + 4] + u[t0][x - time + 4][y - time + 2][z + 4] + u[t0][x - time + 4][y - time + 4][z + 2] + u[t0][x - time + 4][y - time + 4][z + 6] + u[t0][x - time + 4][y - time + 6][z + 4] + u[t0][x - time + 6][y - time + 4][z + 4]) + 1.3333333e-2F * (u[t0][x - time + 3][y - time + 4][z + 4] + u[t0][x - time + 4][y - time + 3][z + 4] + u[t0][x - time + 4][y - time + 4][z + 3] + u[t0][x - time + 4][y - time + 4][z + 5] + u[t0][x - time + 4][y - time + 5][z + 4] + u[t0][x - time + 5][y - time + 4][z + 4]) - 7.49999983e-2F * u[t0][x - time + 4][y - time + 4][z + 4]; float r41 = 1.0 / (r43 * r45 + r46 * damp[x - time + 1][y - time + 1][z + 1]); float r32 = r45 * (-2.0F * u[t0][x - time + 4][y - time + 4][z + 4] + u[t2][x - time + 4][y - time + 4][z + 4]); float r33 = r45 * (-2.0F * v[t0][x - time + 4][y - time + 4][z + 4] + v[t2][x - time + 4][y - time + 4][z + 4]); u[t1][x - time + 4][y - time + 4][z + 4] = r41 * ((-r32) * r43 + r42 * (2 * epsilon[x - time + 4][y - time + 4][z + 4] + 1) + 1.0e-1F * r44 * r17[x - time + 1][y - time + 1][z + 1] + r46 * (damp[x - time + 1][y - time + 1][z + 1] * u[t0][x - time + 4][y - time + 4][z + 4])); v[t1][x - time + 4][y - time + 4][z + 4] = r41 * ((-r33) * r43 + r42 * r17[x - time + 1][y - time + 1][z + 1] + 1.0e-1F * r44 + r46 * (damp[x - time + 1][y - time + 1][z + 1] * v[t0][x - time + 4][y - time + 4][z + 4])); } //int sp_zi_M = nnz_sp_source_mask[x - time][y - time] - 1; for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time] - 1; sp_zi += 1) { int zind = sp_source_mask[x - time][y - time][sp_zi]; float r22 = save_src_u[tw][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; //#pragma omp atomic update u[t1][x - time + 4][y - time + 4][zind + 4] += r22; float r23 = save_src_v[tw][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; //#pragma omp atomic update v[t1][x - time + 4][y - time + 4][zind + 4] += r23; //printf("Source injection at time %d , at : x: %d, y: %d, %d, %f, %f \n", tw, x - time + 4, y - time + 4, zind + 4, r22, r23); } } } } } } } /* Backdoor edit at Wed Sep 9 19:03:00 2020*/
GB_assign_zombie4.c
//------------------------------------------------------------------------------ // GB_assign_zombie4: delete entries in C(i,:) for C_replace_phase //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // For GrB_Row_assign or GrB_Col_assign, C(i,J)<M,repl>=..., if C_replace is // true, and mask M is present, then any entry C(i,j) outside the list J must // be deleted, if M(0,j)=0. // GB_assign_zombie3 and GB_assign_zombie4 are transposes of each other. #include "GB_assign.h" void GB_assign_zombie4 ( GrB_Matrix Z, // the matrix C, or a copy const GrB_Matrix M, const bool Mask_comp, const int64_t i, // index of entries to delete const GrB_Index *J, const int64_t nJ, const int Jkind, const int64_t Jcolon [3], GB_Context Context ) { //-------------------------------------------------------------------------- // get Z //-------------------------------------------------------------------------- const int64_t *restrict Zh = Z->h ; const int64_t *restrict Zp = Z->p ; const int64_t Znvec = Z->nvec ; int64_t *restrict Zi = Z->i ; int64_t nzombies = Z->nzombies ; const int64_t zorig = nzombies ; //-------------------------------------------------------------------------- // get M //-------------------------------------------------------------------------- const int64_t *restrict Mh = M->h ; const int64_t *restrict Mp = M->p ; const GB_void *restrict Mx = M->x ; const size_t msize = M->type->size ; const GB_cast_function cast_M = GB_cast_factory (GB_BOOL_code, M->type->code) ; const int64_t Mnvec = M->nvec ; const bool M_is_hyper = M->is_hyper ; //-------------------------------------------------------------------------- // determine the number of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (Znvec, chunk, nthreads_max) ; int ntasks = (nthreads == 1) ? 1 : (64 * nthreads) ; //-------------------------------------------------------------------------- // delete entries in Z(i,:) //-------------------------------------------------------------------------- // The entry Z(i,j) is deleted if j is not in the J, and if M(0,j)=0 (if // the mask is not complemented) or M(0.j)=1 (if the mask is complemented. #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (int taskid = 0 ; taskid < ntasks ; taskid++) { int64_t kfirst, klast ; GB_PARTITION (kfirst, klast, Znvec, taskid, ntasks) ; for (int64_t k = kfirst ; k < klast ; k++) { //------------------------------------------------------------------ // get Z(:,j) and determine if j is outside the list J //------------------------------------------------------------------ int64_t j = (Zh == NULL) ? k : Zh [k] ; bool j_outside = !GB_ij_is_in_list (J, nJ, j, Jkind, Jcolon) ; if (j_outside) { //-------------------------------------------------------------- // j is not in J; find Z(i,j) //-------------------------------------------------------------- int64_t pZ = Zp [k] ; int64_t pZ_end = Zp [k+1] ; int64_t pright = pZ_end - 1 ; bool found, is_zombie ; GB_BINARY_ZOMBIE (i, Zi, pZ, pright, found, zorig, is_zombie) ; //-------------------------------------------------------------- // delete Z(i,j) if found, not a zombie, and M(0,j) allows it //-------------------------------------------------------------- if (found && !is_zombie) { //---------------------------------------------------------- // Z(i,j) is a live entry not in the Z(I,J) submatrix //---------------------------------------------------------- // Check the mask M to see if it should be deleted. int64_t pM, pM_end ; int64_t pleft = 0 ; int64_t pright = Mnvec - 1 ; GB_lookup (M_is_hyper, Mh, Mp, &pleft, pright, j, &pM, &pM_end) ; bool mij = false ; if (pM < pM_end) { // found it cast_M (&mij, Mx +(pM*msize), 0) ; } if (Mask_comp) { // negate the mask if Mask_comp is true mij = !mij ; } if (!mij) { // delete Z(i,j) by marking it as a zombie nzombies++ ; Zi [pZ] = GB_FLIP (i) ; } } } } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- Z->nzombies = nzombies ; }
stats.c
//----------------------------------------------------------------------------- // stats.c // // Project: EPA SWMM5 // Version: 5.1 // Date: 03/20/14 (Build 5.1.001) // 09/15/14 (Build 5.1.007) // 03/19/15 (Build 5.1.008) // 08/01/16 (Build 5.1.011) // 03/14/17 (Build 5.1.012) // 05/10/18 (Build 5.1.013) // Author: L. Rossman (EPA) // R. Dickinson (CDM) // // Simulation statistics functions. // // Build 5.1.007: // - Exfiltration losses added to storage node statistics. // // Build 5.1.008: // - Support for updating groundwater statistics added. // - Support for updating maximum reported nodal depths added. // - OpenMP parallelization applied to updating node and link flow statistics. // - Updating of time that conduit is upstrm/dnstrm full was modified. // // Build 5.1.011: // - Surcharging is now evaluated only under dynamic wave flow routing and // storage nodes cannot be classified as surcharged. // // Build 5.1.012: // - Time step statistics now evaluated only in non-steady state periods. // - Check for full conduit flow now accounts for number of barrels. // // Build 5.1.013: // - Include omp.h protected against lack of compiler support for OpenMP. // - Statistics on impervious and pervious runoff totals added. // - Storage nodes with a non-zero surcharge depth (e.g. enclosed tanks) // can now be classified as being surcharged. //----------------------------------------------------------------------------- #define _CRT_SECURE_NO_DEPRECATE #include <stdlib.h> #include <string.h> #include <math.h> #include "headers.h" #include "swmm5.h" #if defined(_OPENMP) //(5.1.013) #include <omp.h> #endif //----------------------------------------------------------------------------- // Shared variables //----------------------------------------------------------------------------- #define MAX_STATS 5 static TSysStats SysStats; static TMaxStats MaxMassBalErrs[MAX_STATS]; static TMaxStats MaxCourantCrit[MAX_STATS]; static TMaxStats MaxFlowTurns[MAX_STATS]; static double SysOutfallFlow; //----------------------------------------------------------------------------- // Exportable variables (shared with statsrpt.c) //----------------------------------------------------------------------------- TSubcatchStats* SubcatchStats; TNodeStats* NodeStats; TLinkStats* LinkStats; TStorageStats* StorageStats; TOutfallStats* OutfallStats; TPumpStats* PumpStats; double MaxOutfallFlow; double MaxRunoffFlow; //----------------------------------------------------------------------------- // Imported variables //----------------------------------------------------------------------------- extern double* NodeInflow; // defined in massbal.c extern double* NodeOutflow; // defined in massbal.c //----------------------------------------------------------------------------- // External functions (declared in funcs.h) //----------------------------------------------------------------------------- // stats_open (called from swmm_start in swmm5.c) // stats_close (called from swmm_end in swmm5.c) // stats_report (called from swmm_end in swmm5.c) // stats_updateSubcatchStats (called from subcatch_getRunoff) // stats_updateGwaterStats (called from gwater_getGroundwater) // stats_updateFlowStats (called from routing_execute) // stats_updateCriticalTimeCount (called from getVariableStep in dynwave.c) // stats_updateMaxNodeDepth (called from output_saveNodeResults) //----------------------------------------------------------------------------- // Local functions //----------------------------------------------------------------------------- static void stats_updateNodeStats(int node, double tStep, DateTime aDate); static void stats_updateLinkStats(int link, double tStep, DateTime aDate); static void stats_findMaxStats(void); static void stats_updateMaxStats(TMaxStats maxStats[], int i, int j, double x); //============================================================================= int stats_open() // // Input: none // Output: returns an error code // Purpose: opens the simulation statistics system. // { int j, k; // --- set all pointers to NULL NodeStats = NULL; LinkStats = NULL; StorageStats = NULL; OutfallStats = NULL; PumpStats = NULL; // --- allocate memory for & initialize subcatchment statistics SubcatchStats = NULL; if ( Nobjects[SUBCATCH] > 0 ) { SubcatchStats = (TSubcatchStats *) calloc(Nobjects[SUBCATCH], sizeof(TSubcatchStats)); if ( !SubcatchStats ) { report_writeErrorMsg(ERR_MEMORY, ""); return ErrorCode; } for (j=0; j<Nobjects[SUBCATCH]; j++) { SubcatchStats[j].precip = 0.0; SubcatchStats[j].runon = 0.0; SubcatchStats[j].evap = 0.0; SubcatchStats[j].infil = 0.0; SubcatchStats[j].runoff = 0.0; SubcatchStats[j].maxFlow = 0.0; SubcatchStats[j].impervRunoff = 0.0; //(5.1.013) SubcatchStats[j].pervRunoff = 0.0; // } for (j=0; j<Nobjects[SUBCATCH]; j++) { if ( Subcatch[j].groundwater == NULL ) continue; Subcatch[j].groundwater->stats.avgUpperMoist = 0.0; Subcatch[j].groundwater->stats.avgWaterTable = 0.0; Subcatch[j].groundwater->stats.infil = 0.0; Subcatch[j].groundwater->stats.latFlow = 0.0; Subcatch[j].groundwater->stats.deepFlow = 0.0; Subcatch[j].groundwater->stats.evap = 0.0; Subcatch[j].groundwater->stats.maxFlow = 0.0; } } // --- allocate memory for node & link stats if ( Nobjects[LINK] > 0 ) { NodeStats = (TNodeStats *) calloc(Nobjects[NODE], sizeof(TNodeStats)); LinkStats = (TLinkStats *) calloc(Nobjects[LINK], sizeof(TLinkStats)); if ( !NodeStats || !LinkStats ) { report_writeErrorMsg(ERR_MEMORY, ""); return ErrorCode; } } // --- initialize node stats if ( NodeStats ) for ( j = 0; j < Nobjects[NODE]; j++ ) { NodeStats[j].avgDepth = 0.0; NodeStats[j].maxDepth = 0.0; NodeStats[j].maxDepthDate = StartDateTime; NodeStats[j].maxRptDepth = 0.0; NodeStats[j].volFlooded = 0.0; NodeStats[j].timeFlooded = 0.0; NodeStats[j].timeSurcharged = 0.0; NodeStats[j].timeCourantCritical = 0.0; NodeStats[j].totLatFlow = 0.0; NodeStats[j].maxLatFlow = 0.0; NodeStats[j].maxInflow = 0.0; NodeStats[j].maxOverflow = 0.0; NodeStats[j].maxPondedVol = 0.0; NodeStats[j].maxInflowDate = StartDateTime; NodeStats[j].maxOverflowDate = StartDateTime; } // --- initialize link stats if ( LinkStats ) for ( j = 0; j < Nobjects[LINK]; j++ ) { LinkStats[j].maxFlow = 0.0; LinkStats[j].maxVeloc = 0.0; LinkStats[j].maxDepth = 0.0; LinkStats[j].timeSurcharged = 0.0; LinkStats[j].timeFullUpstream = 0.0; LinkStats[j].timeFullDnstream = 0.0; LinkStats[j].timeFullFlow = 0.0; LinkStats[j].timeCapacityLimited = 0.0; LinkStats[j].timeCourantCritical = 0.0; for (k=0; k<MAX_FLOW_CLASSES; k++) LinkStats[j].timeInFlowClass[k] = 0.0; LinkStats[j].flowTurns = 0; LinkStats[j].flowTurnSign = 0; } // --- allocate memory for & initialize storage unit statistics if ( Nnodes[STORAGE] > 0 ) { StorageStats = (TStorageStats *) calloc(Nnodes[STORAGE], sizeof(TStorageStats)); if ( !StorageStats ) { report_writeErrorMsg(ERR_MEMORY, ""); return ErrorCode; } else for ( k = 0; k < Nobjects[NODE]; k++ ) { if ( Node[k].type != STORAGE ) continue; j = Node[k].subIndex; StorageStats[j].initVol = Node[k].newVolume; StorageStats[j].avgVol = 0.0; StorageStats[j].maxVol = 0.0; StorageStats[j].maxFlow = 0.0; StorageStats[j].evapLosses = 0.0; StorageStats[j].exfilLosses = 0.0; StorageStats[j].maxVolDate = StartDateTime; } } // --- allocate memory for & initialize outfall statistics if ( Nnodes[OUTFALL] > 0 ) { OutfallStats = (TOutfallStats *) calloc(Nnodes[OUTFALL], sizeof(TOutfallStats)); if ( !OutfallStats ) { report_writeErrorMsg(ERR_MEMORY, ""); return ErrorCode; } else for ( j = 0; j < Nnodes[OUTFALL]; j++ ) { OutfallStats[j].avgFlow = 0.0; OutfallStats[j].maxFlow = 0.0; OutfallStats[j].totalPeriods = 0; if ( Nobjects[POLLUT] > 0 ) { OutfallStats[j].totalLoad = (double *) calloc(Nobjects[POLLUT], sizeof(double)); if ( !OutfallStats[j].totalLoad ) { report_writeErrorMsg(ERR_MEMORY, ""); return ErrorCode; } for (k=0; k<Nobjects[POLLUT]; k++) OutfallStats[j].totalLoad[k] = 0.0; } else OutfallStats[j].totalLoad = NULL; } } // --- allocate memory & initialize pumping statistics if ( Nlinks[PUMP] > 0 ) { PumpStats = (TPumpStats *) calloc(Nlinks[PUMP], sizeof(TPumpStats)); if ( !PumpStats ) { report_writeErrorMsg(ERR_MEMORY, ""); return ErrorCode; } else for ( j = 0; j < Nlinks[PUMP]; j++ ) { PumpStats[j].utilized = 0.0; PumpStats[j].minFlow = 0.0; PumpStats[j].avgFlow = 0.0; PumpStats[j].maxFlow = 0.0; PumpStats[j].volume = 0.0; PumpStats[j].energy = 0.0; PumpStats[j].startUps = 0; PumpStats[j].offCurveLow = 0.0; PumpStats[j].offCurveHigh = 0.0; } } // --- initialize system stats MaxRunoffFlow = 0.0; MaxOutfallFlow = 0.0; SysStats.maxTimeStep = 0.0; SysStats.minTimeStep = RouteStep; SysStats.avgTimeStep = 0.0; SysStats.avgStepCount = 0.0; SysStats.steadyStateCount = 0.0; return 0; } //============================================================================= void stats_close() // // Input: none // Output: // Purpose: closes the simulation statistics system. // { int j; FREE(SubcatchStats); FREE(NodeStats); FREE(LinkStats); FREE(StorageStats); if ( OutfallStats ) { for ( j=0; j<Nnodes[OUTFALL]; j++ ) FREE(OutfallStats[j].totalLoad); FREE(OutfallStats); } FREE(PumpStats); } //============================================================================= void stats_report() // // Input: none // Output: none // Purpose: reports simulation statistics. // { // --- report flow routing accuracy statistics if ( Nobjects[LINK] > 0 && RouteModel != NO_ROUTING ) { stats_findMaxStats(); report_writeMaxStats(MaxMassBalErrs, MaxCourantCrit, MAX_STATS); report_writeMaxFlowTurns(MaxFlowTurns, MAX_STATS); report_writeSysStats(&SysStats); } // --- report summary statistics statsrpt_writeReport(); } //============================================================================= void stats_updateSubcatchStats(int j, double rainVol, double runonVol, double evapVol, double infilVol, double impervVol, double pervVol, double runoffVol, double runoff) // // Input: j = subcatchment index // rainVol = rainfall + snowfall volume (ft3) // runonVol = runon volume from other subcatchments (ft3) // evapVol = evaporation volume (ft3) // infilVol = infiltration volume (ft3) // impervVol = impervious runoff volume (ft3) // pervVol = pervious runoff volume (ft3) // runoffVol = runoff volume (ft3) // runoff = runoff rate (cfs) // Output: none // Purpose: updates totals of runoff components for a specific subcatchment. // { SubcatchStats[j].precip += rainVol; SubcatchStats[j].runon += runonVol; SubcatchStats[j].evap += evapVol; SubcatchStats[j].infil += infilVol; SubcatchStats[j].runoff += runoffVol; SubcatchStats[j].maxFlow = MAX(SubcatchStats[j].maxFlow, runoff); SubcatchStats[j].impervRunoff += impervVol; //(5.1.013) SubcatchStats[j].pervRunoff += pervVol; // } //============================================================================= void stats_updateGwaterStats(int j, double infil, double evap, double latFlow, double deepFlow, double theta, double waterTable, double tStep) { Subcatch[j].groundwater->stats.infil += infil * tStep; Subcatch[j].groundwater->stats.evap += evap * tStep; Subcatch[j].groundwater->stats.latFlow += latFlow * tStep; Subcatch[j].groundwater->stats.deepFlow += deepFlow * tStep; Subcatch[j].groundwater->stats.avgUpperMoist += theta * tStep; Subcatch[j].groundwater->stats.avgWaterTable += waterTable * tStep; Subcatch[j].groundwater->stats.finalUpperMoist = theta; Subcatch[j].groundwater->stats.finalWaterTable = waterTable; if ( fabs(latFlow) > fabs(Subcatch[j].groundwater->stats.maxFlow) ) { Subcatch[j].groundwater->stats.maxFlow = latFlow; } } //============================================================================= void stats_updateMaxRunoff() // // Input: none // Output: updates global variable MaxRunoffFlow // Purpose: updates value of maximum system runoff rate. // { int j; double sysRunoff = 0.0; for (j=0; j<Nobjects[SUBCATCH]; j++) sysRunoff += Subcatch[j].newRunoff; MaxRunoffFlow = MAX(MaxRunoffFlow, sysRunoff); } //============================================================================= void stats_updateMaxNodeDepth(int j, double depth) // // Input: j = node index // depth = water depth at node at current reporting time (ft) // Output: none // Purpose: updates a node's maximum depth recorded at reporting times. // { if ( NodeStats != NULL ) NodeStats[j].maxRptDepth = MAX(NodeStats[j].maxRptDepth, depth); } //============================================================================= void stats_updateFlowStats(double tStep, DateTime aDate, int stepCount, int steadyState) // // Input: tStep = routing time step (sec) // aDate = current date/time // stepCount = # steps required to solve routing at current time period // steadyState = TRUE if steady flow conditions exist // Output: none // Purpose: updates various flow routing statistics at current time period. // { int j; // --- update stats only after reporting period begins if ( aDate < ReportStart ) return; SysOutfallFlow = 0.0; // --- update node & link stats #pragma omp parallel num_threads(NumThreads) { #pragma omp for for ( j=0; j<Nobjects[NODE]; j++ ) stats_updateNodeStats(j, tStep, aDate); #pragma omp for for ( j=0; j<Nobjects[LINK]; j++ ) stats_updateLinkStats(j, tStep, aDate); } // --- update count of times in steady state SysStats.steadyStateCount += steadyState; // --- update time step stats if not in steady state if ( steadyState == FALSE ) { // --- skip initial time step for min. value) if ( OldRoutingTime > 0 ) { SysStats.minTimeStep = MIN(SysStats.minTimeStep, tStep); } SysStats.avgTimeStep += tStep; SysStats.maxTimeStep = MAX(SysStats.maxTimeStep, tStep); // --- update iteration step count stats SysStats.avgStepCount += stepCount; } // --- update max. system outfall flow MaxOutfallFlow = MAX(MaxOutfallFlow, SysOutfallFlow); } //============================================================================= void stats_updateCriticalTimeCount(int node, int link) // // Input: node = node index // link = link index // Output: none // Purpose: updates count of times a node or link was time step-critical. // { if ( node >= 0 ) NodeStats[node].timeCourantCritical += 1.0; else if ( link >= 0 ) LinkStats[link].timeCourantCritical += 1.0; } //============================================================================= void stats_updateNodeStats(int j, double tStep, DateTime aDate) // // Input: j = node index // tStep = routing time step (sec) // aDate = current date/time // Output: none // Purpose: updates flow statistics for a node. // { int k, p; double newVolume = Node[j].newVolume; double newDepth = Node[j].newDepth; double yCrown = Node[j].crownElev - Node[j].invertElev; int canPond = (AllowPonding && Node[j].pondedArea > 0.0); // --- update depth statistics NodeStats[j].avgDepth += newDepth; if ( newDepth > NodeStats[j].maxDepth ) { NodeStats[j].maxDepth = newDepth; NodeStats[j].maxDepthDate = aDate; } // --- update flooding, ponding, and surcharge statistics if ( Node[j].type != OUTFALL ) { if ( newVolume > Node[j].fullVolume || Node[j].overflow > 0.0 ) { NodeStats[j].timeFlooded += tStep; NodeStats[j].volFlooded += Node[j].overflow * tStep; if ( canPond ) NodeStats[j].maxPondedVol = MAX(NodeStats[j].maxPondedVol, (newVolume - Node[j].fullVolume)); } // --- for dynamic wave routing, classify a node as //(5.1.013) // surcharged if its water level exceeds its crown elev. if (RouteModel == DW) //(5.1.013) { if ((Node[j].type != STORAGE || Node[j].surDepth > 0.0) && //(5.1.013) newDepth + Node[j].invertElev + FUDGE >= Node[j].crownElev) { NodeStats[j].timeSurcharged += tStep; } } } // --- update storage statistics if ( Node[j].type == STORAGE ) { k = Node[j].subIndex; StorageStats[k].avgVol += newVolume; StorageStats[k].evapLosses += Storage[Node[j].subIndex].evapLoss; StorageStats[k].exfilLosses += Storage[Node[j].subIndex].exfilLoss; newVolume = MIN(newVolume, Node[j].fullVolume); if ( newVolume > StorageStats[k].maxVol ) { StorageStats[k].maxVol = newVolume; StorageStats[k].maxVolDate = aDate; } StorageStats[k].maxFlow = MAX(StorageStats[k].maxFlow, Node[j].outflow); } // --- update outfall statistics if ( Node[j].type == OUTFALL ) { k = Node[j].subIndex; if ( Node[j].inflow >= MIN_RUNOFF_FLOW ) { OutfallStats[k].avgFlow += Node[j].inflow; OutfallStats[k].maxFlow = MAX(OutfallStats[k].maxFlow, Node[j].inflow); OutfallStats[k].totalPeriods++; } for (p=0; p<Nobjects[POLLUT]; p++) { OutfallStats[k].totalLoad[p] += Node[j].inflow * Node[j].newQual[p] * tStep; } SysOutfallFlow += Node[j].inflow; } // --- update inflow statistics NodeStats[j].totLatFlow += ( (Node[j].oldLatFlow + Node[j].newLatFlow) * 0.5 * tStep ); if ( fabs(Node[j].newLatFlow) > fabs(NodeStats[j].maxLatFlow) ) NodeStats[j].maxLatFlow = Node[j].newLatFlow; if ( Node[j].inflow > NodeStats[j].maxInflow ) { NodeStats[j].maxInflow = Node[j].inflow; NodeStats[j].maxInflowDate = aDate; } // --- update overflow statistics if ( Node[j].overflow > NodeStats[j].maxOverflow ) { NodeStats[j].maxOverflow = Node[j].overflow; NodeStats[j].maxOverflowDate = aDate; } } //============================================================================= void stats_updateLinkStats(int j, double tStep, DateTime aDate) // // Input: j = link index // tStep = routing time step (sec) // aDate = current date/time // Output: none // Purpose: updates flow statistics for a link. // { int k; double q, v; double dq; // --- update max. flow dq = Link[j].newFlow - Link[j].oldFlow; q = fabs(Link[j].newFlow); if ( q > LinkStats[j].maxFlow ) { LinkStats[j].maxFlow = q; LinkStats[j].maxFlowDate = aDate; } // --- update max. velocity v = link_getVelocity(j, q, Link[j].newDepth); if ( v > LinkStats[j].maxVeloc ) { LinkStats[j].maxVeloc = v; } // --- update max. depth if ( Link[j].newDepth > LinkStats[j].maxDepth ) { LinkStats[j].maxDepth = Link[j].newDepth; } if ( Link[j].type == PUMP ) { if ( q >= Link[j].qFull ) LinkStats[j].timeFullFlow += tStep; if ( q > MIN_RUNOFF_FLOW ) { k = Link[j].subIndex; PumpStats[k].minFlow = MIN(PumpStats[k].minFlow, q); PumpStats[k].maxFlow = LinkStats[j].maxFlow; PumpStats[k].avgFlow += q; PumpStats[k].volume += q*tStep; PumpStats[k].utilized += tStep; PumpStats[k].energy += link_getPower(j)*tStep/3600.0; if ( Link[j].flowClass == DN_DRY ) PumpStats[k].offCurveLow += tStep; if ( Link[j].flowClass == UP_DRY ) PumpStats[k].offCurveHigh += tStep; if ( Link[j].oldFlow < MIN_RUNOFF_FLOW ) PumpStats[k].startUps++; PumpStats[k].totalPeriods++; LinkStats[j].timeSurcharged += tStep; LinkStats[j].timeFullUpstream += tStep; LinkStats[j].timeFullDnstream += tStep; } } else if ( Link[j].type == CONDUIT ) { // --- update time under normal flow & inlet control if ( Link[j].normalFlow ) LinkStats[j].timeNormalFlow += tStep; if ( Link[j].inletControl ) LinkStats[j].timeInletControl += tStep; // --- update flow classification distribution k = Link[j].flowClass; if ( k >= 0 && k < MAX_FLOW_CLASSES ) { ++LinkStats[j].timeInFlowClass[k]; } // --- update time conduit is full k = Link[j].subIndex; if ( q >= Link[j].qFull * (double)Conduit[k].barrels ) LinkStats[j].timeFullFlow += tStep; if ( Conduit[k].capacityLimited ) LinkStats[j].timeCapacityLimited += tStep; switch (Conduit[k].fullState) { case ALL_FULL: LinkStats[j].timeSurcharged += tStep; LinkStats[j].timeFullUpstream += tStep; LinkStats[j].timeFullDnstream += tStep; break; case UP_FULL: LinkStats[j].timeFullUpstream += tStep; break; case DN_FULL: LinkStats[j].timeFullDnstream += tStep; } } // --- update flow turn count k = LinkStats[j].flowTurnSign; LinkStats[j].flowTurnSign = SGN(dq); if ( fabs(dq) > 0.001 && k * LinkStats[j].flowTurnSign < 0 ) LinkStats[j].flowTurns++; } //============================================================================= void stats_findMaxStats() // // Input: none // Output: none // Purpose: finds nodes & links with highest mass balance errors // & highest times Courant time-step critical. // { int j; double x; // --- initialize max. stats arrays for (j=0; j<MAX_STATS; j++) { MaxMassBalErrs[j].objType = NODE; MaxMassBalErrs[j].index = -1; MaxMassBalErrs[j].value = -1.0; MaxCourantCrit[j].index = -1; MaxCourantCrit[j].value = -1.0; MaxFlowTurns[j].index = -1; MaxFlowTurns[j].value = -1.0; } // --- find links with most flow turns if ( StepCount > 2 ) { for (j=0; j<Nobjects[LINK]; j++) { x = 100.0 * LinkStats[j].flowTurns / (2./3.*(StepCount-2)); stats_updateMaxStats(MaxFlowTurns, LINK, j, x); } } // --- find nodes with largest mass balance errors for (j=0; j<Nobjects[NODE]; j++) { // --- skip terminal nodes and nodes with negligible inflow if ( Node[j].degree <= 0 ) continue; if ( NodeInflow[j] <= 0.1 ) continue; // --- evaluate mass balance error // (Note: NodeInflow & NodeOutflow include any initial and final // stored volumes, respectively). if ( NodeInflow[j] > 0.0 ) x = 1.0 - NodeOutflow[j] / NodeInflow[j]; else if ( NodeOutflow[j] > 0.0 ) x = -1.0; else x = 0.0; stats_updateMaxStats(MaxMassBalErrs, NODE, j, 100.0*x); } // --- stop if not using a variable time step if ( RouteModel != DW || CourantFactor == 0.0 ) return; // --- find nodes most frequently Courant critical if ( StepCount == 0 ) return; for (j=0; j<Nobjects[NODE]; j++) { x = NodeStats[j].timeCourantCritical / StepCount; stats_updateMaxStats(MaxCourantCrit, NODE, j, 100.0*x); } // --- find links most frequently Courant critical for (j=0; j<Nobjects[LINK]; j++) { x = LinkStats[j].timeCourantCritical / StepCount; stats_updateMaxStats(MaxCourantCrit, LINK, j, 100.0*x); } } //============================================================================= void stats_updateMaxStats(TMaxStats maxStats[], int i, int j, double x) // // Input: maxStats[] = array of critical statistics values // i = object category (NODE or LINK) // j = object index // x = value of statistic for the object // Output: none // Purpose: updates the collection of most critical statistics // { int k; TMaxStats maxStats1, maxStats2; maxStats1.objType = i; maxStats1.index = j; maxStats1.value = x; for (k=0; k<MAX_STATS; k++) { if ( fabs(maxStats1.value) > fabs(maxStats[k].value) ) { maxStats2 = maxStats[k]; maxStats[k] = maxStats1; maxStats1 = maxStats2; } } } int stats_getNodeStat(int index, TNodeStats **nodeStats) // // Input: index // element = element to return // Return: value // Purpose: Gets a Node Stat for toolkitAPI // { // Perform memcopy memcpy(*nodeStats, &NodeStats[index], sizeof(TNodeStats)); // Convert units // Current Average Depth (*nodeStats)->avgDepth *= (UCF(LENGTH) / (double)StepCount); // Current Maximum Depth (*nodeStats)->maxDepth *= UCF(LENGTH); // Current Maximum Lateral Inflow (*nodeStats)->maxLatFlow *= UCF(FLOW); // Current Maximum Inflow (*nodeStats)->maxInflow *= UCF(FLOW); // Cumulative Lateral Inflow (*nodeStats)->totLatFlow *= UCF(VOLUME); // Time Courant Critical (hrs) (*nodeStats)->timeCourantCritical /= 3600.0; // Cumulative Flooded Volume (*nodeStats)->volFlooded *= UCF(VOLUME); // Time Flooded (hrs) (*nodeStats)->timeFlooded /= 3600.0; // Current Maximum Overflow (*nodeStats)->maxOverflow *= UCF(FLOW); // Current Maximum Ponding Volume (*nodeStats)->maxPondedVol *= UCF(VOLUME); // Time Surcharged (*nodeStats)->timeSurcharged /= 3600.0; return 0; } int stats_getStorageStat(int index, TStorageStats **storageStats) // // Input: subindex // element = element to return // Return: value // Purpose: Gets a Storage Stat for toolkitAPI // { // Fetch sub index int k = Node[index].subIndex; // Copy Structure memcpy(*storageStats, &StorageStats[k], sizeof(TStorageStats)); // Convert units // Initial Volume (*storageStats)->initVol *= UCF(VOLUME); // Current Average Volume (*storageStats)->avgVol *= (UCF(VOLUME) / (double)StepCount); // Current Maximum Volume (*storageStats)->maxVol *= UCF(VOLUME); // Current Maximum Flow (*storageStats)->maxFlow *= UCF(FLOW); // Current Evaporation Volume (*storageStats)->evapLosses *= UCF(VOLUME); // Current Exfiltration Volume (*storageStats)->exfilLosses *= UCF(VOLUME); return 0; } int stats_getOutfallStat(int index, TOutfallStats **outfallStats) // // Input: subindex // element = element to return // Return: value // Purpose: Gets a Outfall Stat for toolkitAPI // { int k, p; double *temp; // fetch sub index k = Node[index].subIndex; // Copy Structure temp = (*outfallStats)->totalLoad; memcpy(*outfallStats, &(OutfallStats[k]), sizeof(TOutfallStats)); (*outfallStats)->totalLoad = temp; // Perform Deep Copy of Pollutants Results if (Nobjects[POLLUT] > 0) memcpy((*outfallStats)->totalLoad, OutfallStats[k].totalLoad, sizeof(double)*Nobjects[POLLUT]); // Perform unit conversions if ((*outfallStats)->totalPeriods > 0 ) (*outfallStats)->avgFlow *= (UCF(FLOW) / (double) (*outfallStats)->totalPeriods); else (*outfallStats)->avgFlow *= 0.0; // Current Maximum Flow (*outfallStats)->maxFlow *= UCF(FLOW); // Convert Mass Units if (Nobjects[POLLUT] > 0) { for (p = 0; p < Nobjects[POLLUT]; p++) { if (Pollut[p].units == COUNT) (*outfallStats)->totalLoad[p] = LOG10((*outfallStats)->totalLoad[p]); else (*outfallStats)->totalLoad[p] *= (LperFT3 * Pollut[p].mcf); } } return 0; } int stats_getLinkStat(int index, TLinkStats **linkStats) // // Input: index // element = element to return // Return: value // Purpose: Gets a Link Stat for toolkitAPI // { // Copy Structure memcpy(*linkStats, &LinkStats[index], sizeof(TLinkStats)); // Cumulative Maximum Flowrate (*linkStats)->maxFlow *= UCF(FLOW); // Cumulative Maximum Velocity (*linkStats)->maxVeloc *= UCF(LENGTH); // Cumulative Maximum Depth (*linkStats)->maxDepth *= UCF(LENGTH); // Cumulative Time Normal Flow (*linkStats)->timeNormalFlow /= 3600.0; // Cumulative Time Inlet Control (*linkStats)->timeInletControl /= 3600.0; // Cumulative Time Surcharged (*linkStats)->timeSurcharged /= 3600.0; // Cumulative Time Upstream Full (*linkStats)->timeFullUpstream /= 3600.0; // Cumulative Time Downstream Full (*linkStats)->timeFullDnstream /= 3600.0; // Cumulative Time Full Flow (*linkStats)->timeFullFlow /= 3600.0; // Cumulative Time Capacity limited (*linkStats)->timeCapacityLimited /= 3600.0; // Cumulative Time Courant Critical Flow (*linkStats)->timeCourantCritical /= 3600.0; return 0; } int stats_getPumpStat(int index, TPumpStats **pumpStats) // // Input: subindex // element = element to return // Return: value // Purpose: Gets a Pump Stat for toolkitAPI // { // fetch sub index int k = Link[index].subIndex; // Copy Structure memcpy(*pumpStats, &PumpStats[k], sizeof(TPumpStats)); // Convert units // Cumulative Minimum Flow (*pumpStats)->minFlow *= UCF(FLOW); // Cumulative Average Flow if ((*pumpStats)->totalPeriods > 0) { (*pumpStats)->avgFlow *= (UCF(FLOW) / (double) (*pumpStats)->totalPeriods); } else { (*pumpStats)->avgFlow *= 0.0; } // Cumulative Maximum Flow (*pumpStats)->maxFlow *= UCF(FLOW); // Cumulative Pumping Volume (*pumpStats)->volume *= UCF(VOLUME); return 0; } int stats_getSubcatchStat(int index, TSubcatchStats **subcatchStats) // // Input: index // element = element to return // Return: value // Purpose: Gets a Subcatchment Stat for toolkitAPI // { memcpy(*subcatchStats, &(SubcatchStats[index]), sizeof(TSubcatchStats)); // Cumulative Rainfall Depth (*subcatchStats)->precip *= (UCF(RAINDEPTH) / Subcatch[index].area); // Cumulative Runon Volume (*subcatchStats)->runon *= UCF(VOLUME); // Cumulative Evaporation Volume (*subcatchStats)->evap *= UCF(VOLUME); // Cumulative Infiltration Volume (*subcatchStats)->infil *= UCF(VOLUME); // Cumulative Runoff Volume (*subcatchStats)->runoff *= UCF(VOLUME); // Maximum Runoff Rate (*subcatchStats)->maxFlow *= UCF(FLOW); // Impervious Runoff (*subcatchStats)->impervRunoff *= UCF(VOLUME); // Pervious Runoff (*subcatchStats)->pervRunoff *= UCF(VOLUME); return 0; }
pooling_2x2.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void pooling2x2s2_max_neon(const Mat& bottom_blob, Mat& top_blob, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int tailstep = w - 2*outw + w; #pragma omp parallel for num_threads(opt.num_threads) for (int q=0; q<inch; q++) { const float* img0 = bottom_blob.channel(q); float* outptr = top_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw - (nn << 2); #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "prfm pldl1keep, [%1, #256] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v0.4s, v1.4s}, [%1], #32 \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "fmax v0.4s, v0.4s, v2.4s \n" "fmax v1.4s, v1.4s, v3.4s \n" "fmaxp v2.4s, v0.4s, v1.4s \n" "subs %w0, %w0, #1 \n" "st1 {v2.4s}, [%3], #16 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(outptr) // %3 : "0"(nn), "1"(r0), "2"(r1), "3"(outptr) : "cc", "memory", "v0", "v1", "v2", "v3" ); } #else if (nn > 0) { asm volatile( "0: \n" "pld [%1, #256] \n" "pld [%2, #256] \n" "vld1.f32 {d0-d3}, [%1]! \n" "vld1.f32 {d4-d7}, [%2]! \n" "vmax.f32 q0, q0, q2 \n" "vmax.f32 q1, q1, q3 \n" "vpmax.f32 d4, d0, d1 \n" "vpmax.f32 d5, d2, d3 \n" "subs %0, #1 \n" "vst1.f32 {d4-d5}, [%3]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(outptr) // %3 : "0"(nn), "1"(r0), "2"(r1), "3"(outptr) : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float max0 = std::max(r0[0], r0[1]); float max1 = std::max(r1[0], r1[1]); *outptr = std::max(max0, max1); r0 += 2; r1 += 2; outptr++; } r0 += tailstep; r1 += tailstep; } } }
render.c
#include "render.h" #if BYTE_ORDER == BIG_ENDIAN #define to_little_endian16(x) __builtin_bswap16((uint16_t) (x)) #else #define to_little_endian16(x) (x) #endif #define FRAMES_DIRECTORY_PATH "frames/" #define FRAME_FILE_NAME_PREFIX FRAMES_DIRECTORY_PATH "frame_" #define WITCH_CONSTANT 6.f #define RENDER_RADIUS (15.93738f / WITCH_CONSTANT) // See https://en.wikipedia.org/wiki/Witch_of_Agnesi static inline float witch_of_Agnesi(const vec v) { return 1/(1 + sq(WITCH_CONSTANT) * norm_sq(v)); } static inline void colour_pixel(uint8_t * restrict p, const vec r) { if unlikely(norm_sq(r) < RENDER_RADIUS) { *p = (uint8_t) fminf(127.f, *p + 127.f * witch_of_Agnesi(r)); } } static void to_BMP(const int W, const int H, const uint8_t canvas[][W]) { assert(!(W & 0b11) && "Not implemented: canvas width is not a multiple of 4"); static int frame_counter = -1; ++frame_counter; // TODO: Make endian independent struct BMP_Header { // From https://en.wikipedia.org/wiki/BMP_file_format char BM[2]; // Used to identify the BMP file uint32_t file_size; // In bytes unsigned : 16; unsigned : 16; uint32_t offset; // Offset to image data in bytes from beginning of file (54 bytes) uint32_t dib_header_size; // DIB Header size in bytes (40 bytes) int32_t width_px; int32_t height_px; uint16_t num_planes; // Must be 1 uint16_t bits_per_pixel; uint32_t compression_type; uint32_t image_size_bytes; // Image size in bytes signed : 32; signed : 32; uint32_t num_colours; unsigned : 32; } __attribute__((packed)) header = { .BM = {'B', 'M'}, .file_size = sizeof(struct BMP_Header) + (256 * 4 * 1) + (W * H * 1), .offset = sizeof(struct BMP_Header) + (256 * 4 * 1), .dib_header_size = 40, .width_px = W, .height_px = H, .num_planes = 1, .bits_per_pixel = 8, // Grayscale .compression_type = 0, .image_size_bytes = W * H * 1, .num_colours = 1 << 8 }; assert(sizeof(header) == 54 && "BMP header has proper size"); static char file_name[] = FRAME_FILE_NAME_PREFIX "000000.bmp"; assert(frame_counter <= 999999 && "Frame number can be represented within 6 decimal digits"); sprintf(file_name + sizeof(FRAME_FILE_NAME_PREFIX) - 1, "%06d.bmp", frame_counter); FILE *fp = fopen(file_name, "wb"); if (!fp) { perror("Error on file creation"); exit(EXIT_FAILURE); } fwrite(&header, 1, sizeof(header), fp); uint8_t shades_of_gray[256][4]; for (int i = 0; i < 256; ++i) { shades_of_gray[i][0] = i; shades_of_gray[i][1] = i; shades_of_gray[i][2] = i; shades_of_gray[i][3] = 0; } fwrite(shades_of_gray, 4, 256, fp); fwrite(canvas, 1, W * H, fp); fclose(fp); } static void to_GIF(const int W, const int H, const int T, const uint8_t frame[][H][W], const float FPS, const char * filename) { assert(W > 0); assert(H > 0); assert(T > 0); assert(FPS > 0); if (roundf(100.f / FPS) < 2) { puts("Warning: high fps GIFs are not widely supported."); } // Uncompressed GIF file // See https://en.wikipedia.org/wiki/GIF#Uncompressed_GIF for reference and // https://en.wikipedia.org/wiki/File:Quilt_design_as_46x46_uncompressed_GIF.gif for an example // In order to keep one byte per pixel // NOTE: Used macros to keep GCC happy #define BIT_DEPTH 7 #define NUMBER_OF_COLOURS (1 << BIT_DEPTH) struct __attribute__((packed)) GIF_Header { // From https://www.w3.org/Graphics/GIF/spec-gif89a.txt char signature[3]; char version[3]; uint16_t width_px; uint16_t height_px; unsigned global_colour_table_size : 3; unsigned _sort : 1; unsigned colour_resolution : 3; unsigned global_colour_table : 1; uint8_t background_colour_index; uint8_t _aspect_ratio; uint8_t colour_table[NUMBER_OF_COLOURS][3]; } header = { .signature = {'G', 'I', 'F'}, .version = {'8', '9', 'a'}, .width_px = to_little_endian16(W), .height_px = to_little_endian16(H), .global_colour_table_size = BIT_DEPTH - 1, .colour_resolution = 8 - 1, .global_colour_table = true, .background_colour_index = 0, // Unused fields ._sort = 0, ._aspect_ratio = 0 }; // Grayscale (128 colours) for (int i = 0; i < NUMBER_OF_COLOURS; ++i) { header.colour_table[i][0] = i * 2; header.colour_table[i][1] = i * 2; header.colour_table[i][2] = i * 2; } struct __attribute__((packed)) Application_Extension { // From https://en.wikipedia.org/wiki/GIF#Animated_GIF uint8_t extension_introducer; uint8_t application_label; uint8_t block_size; char application_identifier[8]; char application_authentication_code[3]; } const netscape_application_block = { .extension_introducer = '!', .application_label = 0xFF, .block_size = 11, .application_identifier = {'N', 'E', 'T', 'S', 'C', 'A', 'P', 'E'}, .application_authentication_code = {'2', '.', '0'} }; struct __attribute__((packed)) Netscape_Data_Subblock { // From https://en.wikipedia.org/wiki/GIF#Animated_GIF uint8_t block_size; uint8_t subblock_index; uint16_t number_of_repetitions; uint8_t block_terminator; } const netscape_subblock = { .block_size = 3, .subblock_index = 1, .number_of_repetitions = to_little_endian16(0), .block_terminator = 0 }; struct __attribute__((packed)) Graphics_Control_Extension { // From https://www.w3.org/Graphics/GIF/spec-gif89a.txt char extension_introducer; char graphic_control_label; uint8_t block_size; unsigned transparency : 1; unsigned wait_for_user_input : 1; unsigned diposal_method : 3; unsigned _reserved: 3; uint16_t delay; uint8_t transparent_colour_index; uint8_t block_terminator; } GCE = { .extension_introducer = '!', .graphic_control_label = 0xF9, .block_size = 4, .transparency = false, .wait_for_user_input = false, .diposal_method = 0, .delay = to_little_endian16((uint16_t) roundf(100.f / FPS)), .transparent_colour_index = 0, .block_terminator = 0, // Unused fields ._reserved = 0 }; struct __attribute__((packed)) Image_Descriptor { // From https://www.w3.org/Graphics/GIF/spec-gif89a.txt char image_separator; uint16_t left; uint16_t top; uint16_t width; uint16_t height; unsigned _local_colour_table_size : 3; unsigned _reserved : 2; unsigned _sort : 1; unsigned _interlace : 1; unsigned local_colour_table : 1; } const image_descriptor = { .image_separator = ',', .left = to_little_endian16(0), .top = to_little_endian16(0), .width = to_little_endian16(W), .height = to_little_endian16(H), .local_colour_table = false, // Unused fields ._local_colour_table_size = 0, ._reserved = 0, ._sort = 0, ._interlace = 0 }; const uint8_t LZW_minimum_code_size = BIT_DEPTH; const char GIF_file_terminator = ';'; FILE *fp = fopen(filename, "wb"); if (!fp) { perror("Error on file creation"); exit(EXIT_FAILURE); } fwrite(&header, 1, sizeof(header), fp); fwrite(&netscape_application_block, 1, sizeof(netscape_application_block), fp); fwrite(&netscape_subblock, 1, sizeof(netscape_subblock), fp); for (int t = 0; t < T; ++t) { // GCE.delay = (t+1 < T) ? GCE.delay : 1.0f * 100; fwrite(&GCE, 1, sizeof(GCE), fp); fwrite(&image_descriptor, 1, sizeof(image_descriptor), fp); fwrite(&LZW_minimum_code_size, 1, sizeof(LZW_minimum_code_size), fp); // One byte will be used to store the length and another for the 'CLEAR' code const uint8_t data_block_length = (0b1 << BIT_DEPTH) - 2; const uint8_t CLEAR = 0b1 << BIT_DEPTH; int i; for (i = 0; i < W * H - data_block_length; i += data_block_length) { fwrite((uint8_t []) {data_block_length+1, CLEAR}, 2, sizeof(uint8_t), fp); fwrite(&frame[t][0][0] + i, data_block_length, sizeof(uint8_t), fp); } fwrite((uint8_t []) {W * H - i + 1, CLEAR}, 2, sizeof(uint8_t), fp); fwrite(&frame[t][0][0] + i, W * H - i, sizeof(uint8_t), fp); const uint8_t STOP = CLEAR + 1; fwrite((char []) {1, STOP, 0}, 3, sizeof(char), fp); } fwrite((char *) &GIF_file_terminator, 1, sizeof(char), fp); if (fclose(fp)) { perror("Error while closing file"); exit(EXIT_FAILURE); } #undef NUMBER_OF_COLOURS #undef BIT_DEPTH } void render__frames(const int n, vec positions[][n], const int n_frames, const int W, const int H, uint8_t frame[][H][W], const float box_radius) { const vec canvas_origin = { .x = W / 2.f, .y = H / 2.f }; #pragma omp parallel for schedule(auto) for (int f = 0; f < n_frames; ++f) { int s = 0; int t = 0; for (int i = 0; i < H; ++i) { vec v = {.y = -(i - canvas_origin.y) * box_radius / (W / 2.f)}; while ((s < n) && (positions[f][s].y - RENDER_RADIUS > v.y)) { ++s; } while ((t < n) && (positions[f][t].y + RENDER_RADIUS > v.y)) { ++t; } for (int j = 0; j < W; ++j) { v.x = (j - canvas_origin.x) * box_radius / (W / 2.f); for (int k = s; k < t; ++k) { vec r = sub(v, positions[f][k]); #ifdef PBC r = physics__periodic_boundary_shift(r, box_radius); #endif colour_pixel(&frame[f][i][j], r); } #ifdef PBC if unlikely(v.y > box_radius - RENDER_RADIUS) { for (int k = n-1; k >= 0; --k) { if (positions[f][k].y + 2 * box_radius - RENDER_RADIUS > v.y) { break; } vec r = sub(v, to_vec(positions[f][k].x, positions[f][k].y + 2 * box_radius)); r = physics__periodic_boundary_shift(r, box_radius); colour_pixel(&frame[f][i][j], r); } } else if unlikely(v.y < -box_radius + RENDER_RADIUS) { for (int k = 0; k < n; ++k) { if (positions[f][k].y - 2 * box_radius + RENDER_RADIUS < v.y) { break; } vec r = sub(v, to_vec(positions[f][k].x, positions[f][k].y - 2 * box_radius)); r = physics__periodic_boundary_shift(r, box_radius); colour_pixel(&frame[f][i][j], r); } } #endif } } } } void render__animation(const int W, const int H, const int T, const uint8_t frame[][H][W], const float FPS, const char * filename) { // system("convert -delay 2 " FRAME_FILE_NAME_PREFIX "*.bmp animation.gif"); to_GIF(W, H, T, frame, FPS, filename); } inline void render__test_BMP() { const int N = 1 << 11; uint8_t (*canvas)[N] = malloc(N*N); if (!canvas) { perror("Error on frame creation"); exit(EXIT_FAILURE); } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { canvas[i][j] = roundf(((i ^ j) & (N-1)) * 256.f / N); } } to_BMP(N, N, canvas); free(canvas); }
GB_unop__identity_fp64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_fp64_fc64) // op(A') function: GB (_unop_tran__identity_fp64_fc64) // C type: double // A type: GxB_FC64_t // cast: double cij = (double) creal (aij) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ double z = (double) creal (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = (double) creal (aij) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP64 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fp64_fc64) ( double *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; double z = (double) creal (aij) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; double z = (double) creal (aij) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fp64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
get_max_threads.c
// RUN: %compile-run-and-check #include <omp.h> #include <stdio.h> int main(){ int max_threads = -1; int num_threads = -1; #pragma omp target map(tofrom: max_threads) max_threads = omp_get_max_threads(); #pragma omp target parallel map(tofrom: num_threads) { #pragma omp master num_threads = omp_get_num_threads(); } // CHECK: Max Threads: 128, Num Threads: 128 printf("Max Threads: %d, Num Threads: %d\n", max_threads, num_threads); return 0; }
convolutiondepthwise_3x3_pack8_fp16.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convdw3x3s1_fp16_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); __m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + g * 8) : _mm256_set1_ps(0.f); const unsigned short* k0 = (const unsigned short*)kernel.row(g); float* outptr0 = out.row(0); const Mat img0 = bottom_blob.channel(g); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); __m256 _k00 = loadfp16(k0); __m256 _k01 = loadfp16(k0 + 8); __m256 _k02 = loadfp16(k0 + 16); __m256 _k10 = loadfp16(k0 + 24); __m256 _k11 = loadfp16(k0 + 32); __m256 _k12 = loadfp16(k0 + 40); __m256 _k20 = loadfp16(k0 + 48); __m256 _k21 = loadfp16(k0 + 56); __m256 _k22 = loadfp16(k0 + 64); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 7 < outw; j += 8) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_k00, _r01, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k01, _r02, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k02, _r03, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k10, _r11, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k11, _r12, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k12, _r13, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k20, _r21, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k21, _r22, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k22, _r23, _sum1); __m256 _sum2 = _bias0; __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _r24 = _mm256_loadu_ps(r2 + 32); _mm256_storeu_ps(outptr0 + 8, _sum1); _sum2 = _mm256_comp_fmadd_ps(_k00, _r02, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k01, _r03, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k02, _r04, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k10, _r12, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k11, _r13, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k12, _r14, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k20, _r22, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k21, _r23, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k22, _r24, _sum2); __m256 _sum3 = _bias0; __m256 _r05 = _mm256_loadu_ps(r0 + 40); __m256 _r15 = _mm256_loadu_ps(r1 + 40); __m256 _r25 = _mm256_loadu_ps(r2 + 40); _mm256_storeu_ps(outptr0 + 16, _sum2); _sum3 = _mm256_comp_fmadd_ps(_k00, _r03, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k01, _r04, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k02, _r05, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k10, _r13, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k11, _r14, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k12, _r15, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k20, _r23, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k21, _r24, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k22, _r25, _sum3); __m256 _sum4 = _bias0; __m256 _r06 = _mm256_loadu_ps(r0 + 48); __m256 _r16 = _mm256_loadu_ps(r1 + 48); __m256 _r26 = _mm256_loadu_ps(r2 + 48); _mm256_storeu_ps(outptr0 + 24, _sum3); _sum4 = _mm256_comp_fmadd_ps(_k00, _r04, _sum4); _sum4 = _mm256_comp_fmadd_ps(_k01, _r05, _sum4); _sum4 = _mm256_comp_fmadd_ps(_k02, _r06, _sum4); _sum4 = _mm256_comp_fmadd_ps(_k10, _r14, _sum4); _sum4 = _mm256_comp_fmadd_ps(_k11, _r15, _sum4); _sum4 = _mm256_comp_fmadd_ps(_k12, _r16, _sum4); _sum4 = _mm256_comp_fmadd_ps(_k20, _r24, _sum4); _sum4 = _mm256_comp_fmadd_ps(_k21, _r25, _sum4); _sum4 = _mm256_comp_fmadd_ps(_k22, _r26, _sum4); __m256 _sum5 = _bias0; __m256 _r07 = _mm256_loadu_ps(r0 + 56); __m256 _r17 = _mm256_loadu_ps(r1 + 56); __m256 _r27 = _mm256_loadu_ps(r2 + 56); _mm256_storeu_ps(outptr0 + 32, _sum4); _sum5 = _mm256_comp_fmadd_ps(_k00, _r05, _sum5); _sum5 = _mm256_comp_fmadd_ps(_k01, _r06, _sum5); _sum5 = _mm256_comp_fmadd_ps(_k02, _r07, _sum5); _sum5 = _mm256_comp_fmadd_ps(_k10, _r15, _sum5); _sum5 = _mm256_comp_fmadd_ps(_k11, _r16, _sum5); _sum5 = _mm256_comp_fmadd_ps(_k12, _r17, _sum5); _sum5 = _mm256_comp_fmadd_ps(_k20, _r25, _sum5); _sum5 = _mm256_comp_fmadd_ps(_k21, _r26, _sum5); _sum5 = _mm256_comp_fmadd_ps(_k22, _r27, _sum5); __m256 _sum6 = _bias0; __m256 _r08 = _mm256_loadu_ps(r0 + 64); __m256 _r18 = _mm256_loadu_ps(r1 + 64); __m256 _r28 = _mm256_loadu_ps(r2 + 64); _mm256_storeu_ps(outptr0 + 40, _sum5); _sum6 = _mm256_comp_fmadd_ps(_k00, _r06, _sum6); _sum6 = _mm256_comp_fmadd_ps(_k01, _r07, _sum6); _sum6 = _mm256_comp_fmadd_ps(_k02, _r08, _sum6); _sum6 = _mm256_comp_fmadd_ps(_k10, _r16, _sum6); _sum6 = _mm256_comp_fmadd_ps(_k11, _r17, _sum6); _sum6 = _mm256_comp_fmadd_ps(_k12, _r18, _sum6); _sum6 = _mm256_comp_fmadd_ps(_k20, _r26, _sum6); _sum6 = _mm256_comp_fmadd_ps(_k21, _r27, _sum6); _sum6 = _mm256_comp_fmadd_ps(_k22, _r28, _sum6); __m256 _sum7 = _bias0; __m256 _r09 = _mm256_loadu_ps(r0 + 72); __m256 _r19 = _mm256_loadu_ps(r1 + 72); __m256 _r29 = _mm256_loadu_ps(r2 + 72); _mm256_storeu_ps(outptr0 + 48, _sum6); _sum7 = _mm256_comp_fmadd_ps(_k00, _r07, _sum7); _sum7 = _mm256_comp_fmadd_ps(_k01, _r08, _sum7); _sum7 = _mm256_comp_fmadd_ps(_k02, _r09, _sum7); _sum7 = _mm256_comp_fmadd_ps(_k10, _r17, _sum7); _sum7 = _mm256_comp_fmadd_ps(_k11, _r18, _sum7); _sum7 = _mm256_comp_fmadd_ps(_k12, _r19, _sum7); _sum7 = _mm256_comp_fmadd_ps(_k20, _r27, _sum7); _sum7 = _mm256_comp_fmadd_ps(_k21, _r28, _sum7); _sum7 = _mm256_comp_fmadd_ps(_k22, _r29, _sum7); _mm256_storeu_ps(outptr0 + 56, _sum7); r0 += 64; r1 += 64; r2 += 64; outptr0 += 64; } for (; j + 3 < outw; j += 4) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_k00, _r01, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k01, _r02, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k02, _r03, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k10, _r11, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k11, _r12, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k12, _r13, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k20, _r21, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k21, _r22, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k22, _r23, _sum1); __m256 _sum2 = _bias0; __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _r24 = _mm256_loadu_ps(r2 + 32); _mm256_storeu_ps(outptr0 + 8, _sum1); _sum2 = _mm256_comp_fmadd_ps(_k00, _r02, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k01, _r03, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k02, _r04, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k10, _r12, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k11, _r13, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k12, _r14, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k20, _r22, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k21, _r23, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k22, _r24, _sum2); __m256 _sum3 = _bias0; __m256 _r05 = _mm256_loadu_ps(r0 + 40); __m256 _r15 = _mm256_loadu_ps(r1 + 40); __m256 _r25 = _mm256_loadu_ps(r2 + 40); _mm256_storeu_ps(outptr0 + 16, _sum2); _sum3 = _mm256_comp_fmadd_ps(_k00, _r03, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k01, _r04, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k02, _r05, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k10, _r13, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k11, _r14, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k12, _r15, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k20, _r23, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k21, _r24, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k22, _r25, _sum3); _mm256_storeu_ps(outptr0 + 24, _sum3); r0 += 32; r1 += 32; r2 += 32; outptr0 += 32; } for (; j + 1 < outw; j += 2) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_k00, _r01, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k01, _r02, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k02, _r03, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k10, _r11, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k11, _r12, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k12, _r13, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k20, _r21, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k21, _r22, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k22, _r23, _sum1); _mm256_storeu_ps(outptr0 + 8, _sum1); r0 += 16; r1 += 16; r2 += 16; outptr0 += 16; } for (; j < outw; j++) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k22, _r22, _sum0); _mm256_storeu_ps(outptr0, _sum0); r0 += 8; r1 += 8; r2 += 8; outptr0 += 8; } r0 += 2 * 8; r1 += 2 * 8; r2 += 2 * 8; } } } static void convdw3x3s2_fp16_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const int tailstep = (w - 2 * outw + w) * 8; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); __m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + g * 8) : _mm256_set1_ps(0.f); const unsigned short* k0 = (const unsigned short*)kernel.row(g); float* outptr0 = out.row(0); const Mat img0 = bottom_blob.channel(g); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); __m256 _k00 = loadfp16(k0); __m256 _k01 = loadfp16(k0 + 8); __m256 _k02 = loadfp16(k0 + 16); __m256 _k10 = loadfp16(k0 + 24); __m256 _k11 = loadfp16(k0 + 32); __m256 _k12 = loadfp16(k0 + 40); __m256 _k20 = loadfp16(k0 + 48); __m256 _k21 = loadfp16(k0 + 56); __m256 _k22 = loadfp16(k0 + 64); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _r24 = _mm256_loadu_ps(r2 + 32); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_k00, _r02, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k01, _r03, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k02, _r04, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k10, _r12, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k11, _r13, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k12, _r14, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k20, _r22, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k21, _r23, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k22, _r24, _sum1); __m256 _sum2 = _bias0; __m256 _r05 = _mm256_loadu_ps(r0 + 40); __m256 _r15 = _mm256_loadu_ps(r1 + 40); __m256 _r25 = _mm256_loadu_ps(r2 + 40); __m256 _r06 = _mm256_loadu_ps(r0 + 48); __m256 _r16 = _mm256_loadu_ps(r1 + 48); __m256 _r26 = _mm256_loadu_ps(r2 + 48); _mm256_storeu_ps(outptr0 + 8, _sum1); _sum2 = _mm256_comp_fmadd_ps(_k00, _r04, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k01, _r05, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k02, _r06, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k10, _r14, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k11, _r15, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k12, _r16, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k20, _r24, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k21, _r25, _sum2); _sum2 = _mm256_comp_fmadd_ps(_k22, _r26, _sum2); __m256 _sum3 = _bias0; __m256 _r07 = _mm256_loadu_ps(r0 + 56); __m256 _r17 = _mm256_loadu_ps(r1 + 56); __m256 _r27 = _mm256_loadu_ps(r2 + 56); __m256 _r08 = _mm256_loadu_ps(r0 + 64); __m256 _r18 = _mm256_loadu_ps(r1 + 64); __m256 _r28 = _mm256_loadu_ps(r2 + 64); _mm256_storeu_ps(outptr0 + 16, _sum2); _sum3 = _mm256_comp_fmadd_ps(_k00, _r06, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k01, _r07, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k02, _r08, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k10, _r16, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k11, _r17, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k12, _r18, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k20, _r26, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k21, _r27, _sum3); _sum3 = _mm256_comp_fmadd_ps(_k22, _r28, _sum3); _mm256_storeu_ps(outptr0 + 24, _sum3); r0 += 2 * 32; r1 += 2 * 32; r2 += 2 * 32; outptr0 += 32; } for (; j + 1 < outw; j += 2) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k22, _r22, _sum0); __m256 _sum1 = _bias0; __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r23 = _mm256_loadu_ps(r2 + 24); __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _r24 = _mm256_loadu_ps(r2 + 32); _mm256_storeu_ps(outptr0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_k00, _r02, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k01, _r03, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k02, _r04, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k10, _r12, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k11, _r13, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k12, _r14, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k20, _r22, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k21, _r23, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k22, _r24, _sum1); _mm256_storeu_ps(outptr0 + 8, _sum1); r0 += 2 * 16; r1 += 2 * 16; r2 += 2 * 16; outptr0 += 16; } for (; j < outw; j++) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k22, _r22, _sum0); _mm256_storeu_ps(outptr0, _sum0); r0 += 2 * 8; r1 += 2 * 8; r2 += 2 * 8; outptr0 += 8; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } }
GB_binop__isne_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isne_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__isne_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__isne_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__isne_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isne_uint8) // A*D function (colscale): GB (_AxD__isne_uint8) // D*A function (rowscale): GB (_DxB__isne_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__isne_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__isne_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isne_uint8) // C=scalar+B GB (_bind1st__isne_uint8) // C=scalar+B' GB (_bind1st_tran__isne_uint8) // C=A+scalar GB (_bind2nd__isne_uint8) // C=A'+scalar GB (_bind2nd_tran__isne_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint8_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x != y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISNE || GxB_NO_UINT8 || GxB_NO_ISNE_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isne_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isne_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isne_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isne_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isne_uint8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isne_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isne_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isne_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__isne_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isne_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isne_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isne_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = (aij != y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__isne_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__isne_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
SectionsEndLink.c
int main() { #pragma omp sections { } #pragma omp sections { #pragma omp section { int x; } } #pragma omp sections { #pragma omp section { } #pragma omp section { } } #pragma omp sections { #pragma omp section { } } #pragma omp sections { #pragma omp section { int x; } #pragma omp section { } #pragma omp section { int x; } } #pragma omp sections { #pragma omp section { int x; } #pragma omp section { int x; } } }
mxv_col_omp.c
/* !----------------------------------------------------------------------- ! Author: Ruud van der Pas, Sun Microsystems ! ! Copyright: Sun Microsystems, All rights reserved, Un-authorized ! distribution not permitted !----------------------------------------------------------------------- */ #include "labs.h" #ifdef _OPENMP #include <omp.h> #endif void mxv_col(int m, int n, double *a, double *b, double *c) { int i, j; // threshold_col = 375; # pragma omp parallel if (m > threshold_col) default (none) \ private (i,j) shared(a, b, c, n, m) { #pragma omp for schedule (dynamic) for (i=0; i<m; i++) a[i] = b[i*n]*c[0]; for (j=1; j<n; j++) { #pragma omp for schedule (dynamic) for (i=0; i<m; i++) a[i] += b[i*n+j]*c[j]; } } /* -- End of parallel region --*/ }
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 16; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+2,4)); ubp=min(floord(4*Nt+Nz-9,16),floord(8*t1+Nz+2,16)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-1,2)),ceild(16*t2-Nz-3,16));t3<=min(min(min(floord(4*Nt+Ny-9,16),floord(8*t1+Ny+7,16)),floord(16*t2+Ny+3,16)),floord(16*t1-16*t2+Nz+Ny+5,16));t3++) { for (t4=max(max(max(0,ceild(t1-127,128)),ceild(16*t2-Nz-1011,1024)),ceild(16*t3-Ny-1011,1024));t4<=min(min(min(min(floord(4*Nt+Nx-9,1024),floord(8*t1+Nx+7,1024)),floord(16*t2+Nx+3,1024)),floord(16*t3+Nx+3,1024)),floord(16*t1-16*t2+Nz+Nx+5,1024));t4++) { for (t5=max(max(max(max(max(0,ceild(16*t2-Nz+5,4)),ceild(16*t3-Ny+5,4)),ceild(1024*t4-Nx+5,4)),2*t1),4*t1-4*t2+1);t5<=min(min(min(min(min(floord(16*t1-16*t2+Nz+10,4),Nt-1),2*t1+3),4*t2+2),4*t3+2),256*t4+254);t5++) { for (t6=max(max(16*t2,4*t5+4),-16*t1+16*t2+8*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(16*t3,4*t5+4);t7<=min(16*t3+15,4*t5+Ny-5);t7++) { lbv=max(1024*t4,4*t5+4); ubv=min(1024*t4+1023,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
sweep.c
/*********************************************************************** * Module: sweep.c * * This module contains all the subroutines related to the mesh sweep. ***********************************************************************/ #include "snap.h" void sweep_data_init ( sweep_data *sweep_vars ) { MTAG = 0; YP_SND = 0; YP_RCV = 0; ZP_SND = 0; ZP_RCV = 0; INCOMINGY = false; INCOMINGZ = false; OUTGOINGY = false; OUTGOINGZ = false; } /*********************************************************************** * Driver for the mesh sweeps. Manages the loops over octant pairs. ***********************************************************************/ void sweep ( input_data *input_vars, para_data *para_vars, geom_data *geom_vars, sn_data *sn_vars, data_data *data_vars, control_data *control_vars, solvar_data *solvar_vars, sweep_data *sweep_vars, dim_sweep_data *dim_sweep_vars, int *ierr ) { /*********************************************************************** * Local variables ***********************************************************************/ int jd, kd, jlo, jhi, jst, klo, khi, kst, iop; int g, k, j, i, g_indx; int *gnext; bool use_lock = false, cont_dogrp_loop = true; int grp_act[NG], dogrp[NUM_GRTH]; /*********************************************************************** * Set up OpenMP lock if necessary. ***********************************************************************/ use_lock = (NPROC>1) && (NTHREADS>1) && (THREAD_LEVEL!=THREAD_MULTIPLE); if ( use_lock ) { plock_omp ( "init", &LOCK ); } /*********************************************************************** * Start OpenMP parallel region for entire sweep subroutine. Then clear * leakage arrays with threaded do loop. ***********************************************************************/ //#pragma omp parallel default(shared) { #pragma omp for schedule(dynamic, 1) private(g, k, j, i) for ( g = 1; g <= NG; g++ ) { if ( !INRDONE_1D(g-1) ) { for ( k = 0; k < NZ; k++ ) { for ( j = 0; j < NY; j++ ) { for ( i = 0; i < NX+1; i++ ) { FLKX_4D(i,j,k,(g-1)) = 0; } } } for ( k = 0; k < NZ; k++ ) { for ( j = 0; j < NY+1; j++ ) { for ( i = 0; i < NX; i++ ) { FLKY_4D(i,j,k,(g-1)) = 0; } } } for ( k = 0; k < NZ+1; k++ ) { for ( j = 0; j < NY; j++ ) { for ( i = 0; i < NX; i++ ) { FLKZ_4D(i,j,k,(g-1)) = 0; } } } } } /*********************************************************************** * Loop over octant pairs, according to ndimen. Set up the sweep order. * Place a barrier at start of new octant to make sure all threads have * same kd and jd. Only one thread needs to set shared values of loop * bounds, strides, and communication parameters. ***********************************************************************/ // kd_loop for ( kd = 1; kd <= MAX((NDIMEN-1),1); kd++ ) { // jd_loop for ( jd = 1; jd <= MIN(NDIMEN, 2); jd++) { //#pragma omp barrier //#pragma omp single { if ( jd == 1 ) { jlo = NY; jhi = 1; jst = -1; YP_SND = YLOP; YP_RCV = YHIP; } else { jlo = 1; jhi = NY; jst = 1; YP_SND = YHIP; YP_RCV = YLOP; } if ( kd == 1 ) { klo = NZ; khi = 1; kst = -1; ZP_SND = ZLOP; ZP_RCV = ZHIP; } else { klo = 1; khi = NZ; kst = 1; ZP_SND = ZHIP; ZP_RCV = ZLOP; } INCOMINGY = !( (jd==1 && LASTY) || (jd==2 && FIRSTY) ); INCOMINGZ = !( (kd==1 && LASTZ) || (kd==2 && FIRSTZ) ); OUTGOINGY = !( (jd==1 && FIRSTY) || (jd==2 && LASTY) ); OUTGOINGZ = !( (kd==1 && FIRSTZ) || (kd==2 && LASTZ) ); MTAG = 2*NC * (jd-1 + 2*(kd-1)); /*********************************************************************** * Set up groups to be swept. Only num_grth can be swept at a time * due to communications. ***********************************************************************/ for (g_indx = 0; g_indx < NG; g_indx++ ) { grp_act[g_indx] = 1; if ( INRDONE_1D(g_indx) ) grp_act[g_indx] = 0; } for ( j = 1; j <= NUM_GRTH; j++ ) { dogrp[j-1] = 0; } for ( i = 1; i <= NUM_GRTH; i++ ) { g = 1; gnext = grp_act; *gnext = *grp_act; for ( j = 1; j < NG; j++ ) { if ( *(grp_act + j) > *gnext ) { gnext = (grp_act + j); g = j + 1; } } if ( grp_act[g-1] == 0 ) break; grp_act[g-1] = 0; dogrp[i-1] = g; } } /*********************************************************************** * Loop as long as groups that are not converged still need to be * done. Set an operation as looping over a chunk of i-cells. ***********************************************************************/ // dogrp_loop while (true) { //iop_loop for ( iop = 1; iop <= 2*NC; iop++ ) { /*********************************************************************** * If supported, thread_multiple allows all threads over groups * to handle independent MPI communications. Loop over groups. ***********************************************************************/ if ( THREAD_LEVEL == THREAD_MULTIPLE ) { //#pragma omp for schedule(static, 1) private(i) nowait for ( i = 1; i <= NUM_GRTH; i++ ) { if ( dogrp[i-1] != 0 ) { sweep_recv_bdry (input_vars, para_vars, solvar_vars, sweep_vars, dogrp[i-1], iop ); octsweep ( input_vars, para_vars, geom_vars, sn_vars, data_vars, control_vars, solvar_vars, dim_sweep_vars, dogrp[i-1], iop, jd, kd, jlo, jhi, jst, klo, khi, kst, ierr ); sweep_send_bdry (input_vars, para_vars, solvar_vars, sweep_vars, dogrp[i-1], iop ); } } } else { /*********************************************************************** * Otherwise, thread_serialized makes sure only one thread calls * for MPI communications at a time. Use locks to make sure all * sends/receives are done before next receives/sends. Use * ordered loops to match threads' receives with sends. ***********************************************************************/ if ( INCOMINGY || INCOMINGZ ) { //#pragma omp for schedule(static, 1) ordered private(i) nowait for ( i = 1; i <= NUM_GRTH; i++ ) { if ( i == 1 && use_lock ) plock_omp( "set", &LOCK ); //#pragma omp ordered { if ( dogrp[i-1] != 0 ) { sweep_recv_bdry( input_vars, para_vars, solvar_vars, sweep_vars, dogrp[i-1], iop ); } } if ( i == NUM_GRTH && use_lock ) plock_omp( "unset", &LOCK ); } } //#pragma omp for schedule(static, 1) private(i) nowait for ( i = 1; i <= NUM_GRTH; i++ ) { if ( dogrp[i-1] != 0 ) { octsweep ( input_vars, para_vars, geom_vars, sn_vars, data_vars, control_vars, solvar_vars, dim_sweep_vars, dogrp[i-1], iop, jd, kd, jlo, jhi, jst, klo, khi, kst, ierr ); } } if ( OUTGOINGY || OUTGOINGZ ) { //#pragma omp for schedule(static, 1) ordered private(i) nowait for ( i = 1; i <= NUM_GRTH; i++ ) { if ( i == 1 && use_lock ) plock_omp( "set", &LOCK ); //#pragma omp ordered { if ( dogrp[i-1] != 0 ) { sweep_send_bdry( input_vars, para_vars, solvar_vars, sweep_vars, dogrp[i-1], iop ); } } if ( i == NUM_GRTH && use_lock ) plock_omp( "unset", &LOCK ); } } } } // end iop_loop /*********************************************************************** * End sweep for octant pair. Use barrier statement to sync threads * and use single block to assign next set of groups, if any left ***********************************************************************/ //#pragma omp barrier //#pragma omp single // { for ( j = 1; j <= NUM_GRTH; j++ ) { dogrp[j-1] = 0; } for ( j = 1; j <= NUM_GRTH; j++ ) { g = 1; gnext = grp_act; *gnext = *grp_act; for ( i = 1; i < NG; i++ ) { if ( *(grp_act + i) > *gnext ) { gnext = (grp_act + i); g = i + 1; } } if ( grp_act[g-1] == 0 ) break; grp_act[g-1] = 0; dogrp[j-1] = g; } for ( i = 1; i <= NUM_GRTH; i++ ) { if ( dogrp[i-1] > 0 ) { cont_dogrp_loop = true; break; } else { cont_dogrp_loop = false; } } if ( !cont_dogrp_loop ) { break; } //} } // end dogrp_loop } // end jd_loop } // end kd_loop //} // end parallel /*********************************************************************** * Destroy the lock ***********************************************************************/ if (use_lock) { plock_omp ( "destroy", &LOCK ); } } /*********************************************************************** * Receive flux from upstream boundaries ***********************************************************************/ void sweep_recv_bdry ( input_data *input_vars, para_data *para_vars, solvar_data *solvar_vars, sweep_data *sweep_vars, int g, int iop ) { /*********************************************************************** * Local variables ***********************************************************************/ int i; int ierr = 0; /***********************************************************************/ i = iop + g*G_OFF + MTAG; precv_d_3d( &JB_IN_4D(0,0,0,(g-1)), NANG, ICHUNK, NZ, YCOMM, YP_RCV, YPROC, i ); precv_d_3d( &KB_IN_4D(0,0,0,(g-1)), NANG, ICHUNK, NY, ZCOMM, ZP_RCV, ZPROC, i ); } /*********************************************************************** * Send flux from upstream boundaries ***********************************************************************/ void sweep_send_bdry ( input_data *input_vars, para_data *para_vars, solvar_data *solvar_vars, sweep_data *sweep_vars, int g, int iop ) { /*********************************************************************** * Local variables ***********************************************************************/ int i; int ierr = 0; /***********************************************************************/ i = iop + g*G_OFF + MTAG; psend_d_3d( &JB_OUT_4D(0,0,0,(g-1)), NANG, ICHUNK, NZ, YCOMM, YP_SND, YPROC, i ); psend_d_3d( &KB_OUT_4D(0,0,0,(g-1)), NANG, ICHUNK, NY, ZCOMM, ZP_SND, ZPROC, i ); }
GB_unop__asin_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__asin_fc64_fc64) // op(A') function: GB (_unop_tran__asin_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = casin (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = casin (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = casin (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ASIN || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__asin_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = casin (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = casin (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__asin_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
prelu_kernel_arm.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: bhu@openailab.com */ #include "prelu_kernel_arm.h" #include <arm_neon.h> #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) int prelu_kernel_run(float* input, float* output, int dim0, int dim1, int dim2, int dim3, float* slope, int layout, int num_thread) { int channel_size = dim1 * dim2 * dim3; float32x4_t _zero = vdupq_n_f32(0.f); if (layout == 0) { int size = dim2 * dim3; for (int n = 0; n < dim0; n++) { #pragma omp parallel for num_threads(num_thread) for (int c = 0; c < dim1; c++) { float* cur_input = input + n * channel_size + c * size; float* cur_output = output + n * channel_size + c * size; float32x4_t _slope = vdupq_n_f32(slope[c]); for (int k = 0; k < (size & -4); k += 4) { float32x4_t _p = vld1q_f32(cur_input); // ri = ai <= bi ? 1...1:0...0 uint32x4_t _lemask = vcleq_f32(_p, _zero); float32x4_t _ps = vmulq_f32(_p, _slope); // bitwise select _p = vbslq_f32(_lemask, _ps, _p); vst1q_f32(cur_output, _p); cur_input += 4; cur_output += 4; } for (int k = size & ~3; k < size; k++) { *cur_output = MAX(cur_input[0], 0.f) + slope[c] * MIN(cur_input[0], 0.f); cur_input++; cur_output++; } } } } else { return -1; } return 0; }
GB_binop__gt_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__gt_int8 // A.*B function (eWiseMult): GB_AemultB__gt_int8 // A*D function (colscale): GB_AxD__gt_int8 // D*A function (rowscale): GB_DxB__gt_int8 // C+=B function (dense accum): GB_Cdense_accumB__gt_int8 // C+=b function (dense accum): GB_Cdense_accumb__gt_int8 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__gt_int8 // C=scalar+B GB_bind1st__gt_int8 // C=scalar+B' GB_bind1st_tran__gt_int8 // C=A+scalar GB_bind2nd__gt_int8 // C=A'+scalar GB_bind2nd_tran__gt_int8 // C type: bool // A type: int8_t // B,b type: int8_t // BinaryOp: cij = (aij > bij) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int8_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x > y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_GT || GxB_NO_INT8 || GxB_NO_GT_INT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__gt_int8 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__gt_int8 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__gt_int8 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__gt_int8 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__gt_int8 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__gt_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__gt_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__gt_int8 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t bij = Bx [p] ; Cx [p] = (x > bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__gt_int8 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t aij = Ax [p] ; Cx [p] = (aij > y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = Ax [pA] ; \ Cx [pC] = (x > aij) ; \ } GrB_Info GB_bind1st_tran__gt_int8 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = Ax [pA] ; \ Cx [pC] = (aij > y) ; \ } GrB_Info GB_bind2nd_tran__gt_int8 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
parallel_for.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file parallel_for.h * \brief An implementation to run loop in parallel. */ #ifndef TVM_SUPPORT_PARALLEL_FOR_H_ #define TVM_SUPPORT_PARALLEL_FOR_H_ #include <tvm/runtime/c_runtime_api.h> #include <functional> #include <vector> namespace tvm { namespace support { using PartitionerFuncType = std::function<std::vector<std::vector<int>>(int, int, int, int)>; /*! * \brief A partitioner to split the task to each thread in Round-robin manner. * \param begin The start index of this parallel loop(inclusive). * \param end The end index of this parallel loop(exclusive). * \param step The traversal step to the index. * \param num_threads The number of threads(the number of tasks to be partitioned to). * \return A list with `num_threads` elements, and each is a list of integers indicating the loop * indexes for the corresponding thread to process. */ TVM_DLL std::vector<std::vector<int>> rr_partitioner(int begin, int end, int step, int num_threads); /*! * \brief A runtime api provided to run the task function in parallel. * e.g. A for loop: * for (int i = 0; i < 10; i++) { * a[i] = i; * } * should work the same as: * parallel_for(0, 10, [&a](int index) { * a[i] = i; * }); * \param begin The start index of this parallel loop(inclusive). * \param end The end index of this parallel loop(exclusive). * \param f The task function to be executed. Assert to take an int index as input with no output. * \param step The traversal step to the index. * \param partitioner A partition function to split tasks to different threads. Use Round-robin * partitioner by default. * \note 1. Currently do not support nested parallel_for; 2. The order of execution in each thread * is not guaranteed, the for loop task should be thread independent and thread safe. */ TVM_DLL void parallel_for(int begin, int end, const std::function<void(int)>& f, int step = 1, const PartitionerFuncType partitioner = rr_partitioner); /*! * \brief An API to launch fix amount of threads to run the specific functor in parallel. * Different from `parallel_for`, the partition is determined dynamically on the fly, * i.e. any time when a thread is idle, it fetches the next task to run. * The behavior is similar to dynamic scheduling in OpenMP: * * \#pragma omp parallel for schedule(dynamic) num_threads(num_threads) * for (int i = 0; i < 10; i++) { * a[i] = i; * } * * \param begin The start index of this parallel loop (inclusive). * \param end The end index of this parallel loop (exclusive). * \param num_threads The number of threads to be used. * \param f The task function to be executed. Takes the thread index and the task index as * input with no output. * \note `step` support is left for future work. */ TVM_DLL void parallel_for_dynamic(int begin, int end, int num_threads, const std::function<void(int thread_id, int task_id)>& f); } // namespace support } // namespace tvm #endif // TVM_SUPPORT_PARALLEL_FOR_H_
tinyexr.h
/* Copyright (c) 2014 - 2018, Syoyo Fujita and many contributors. 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 Syoyo Fujita 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 <COPYRIGHT HOLDER> 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. */ // TinyEXR contains some OpenEXR code, which is licensed under ------------ /////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// // End of OpenEXR license ------------------------------------------------- #ifndef TINYEXR_H_ #define TINYEXR_H_ // // // Do this: // #define TINYEXR_IMPLEMENTATION // before you include this file in *one* C or C++ file to create the // implementation. // // // i.e. it should look like this: // #include ... // #include ... // #include ... // #define TINYEXR_IMPLEMENTATION // #include "tinyexr.h" // // #include <stddef.h> // for size_t #include <stdint.h> // guess stdint.h is available(C99) #ifdef __cplusplus extern "C" { #endif // Use embedded miniz or not to decode ZIP format pixel. Linking with zlib // required if this flas is 0. #ifndef TINYEXR_USE_MINIZ #define TINYEXR_USE_MINIZ (1) #endif // Disable PIZ comporession when applying cpplint. #ifndef TINYEXR_USE_PIZ #define TINYEXR_USE_PIZ (1) #endif #ifndef TINYEXR_USE_ZFP #define TINYEXR_USE_ZFP (0) // TinyEXR extension. // http://computation.llnl.gov/projects/floating-point-compression #endif #define TINYEXR_SUCCESS (0) #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1) #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2) #define TINYEXR_ERROR_INVALID_ARGUMENT (-3) #define TINYEXR_ERROR_INVALID_DATA (-4) #define TINYEXR_ERROR_INVALID_FILE (-5) #define TINYEXR_ERROR_INVALID_PARAMETER (-5) #define TINYEXR_ERROR_CANT_OPEN_FILE (-6) #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-7) #define TINYEXR_ERROR_INVALID_HEADER (-8) #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-9) #define TINYEXR_ERROR_CANT_WRITE_FILE (-10) #define TINYEXR_ERROR_SERIALZATION_FAILED (-11) // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf } // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2 #define TINYEXR_PIXELTYPE_UINT (0) #define TINYEXR_PIXELTYPE_HALF (1) #define TINYEXR_PIXELTYPE_FLOAT (2) #define TINYEXR_MAX_HEADER_ATTRIBUTES (1024) #define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128) #define TINYEXR_COMPRESSIONTYPE_NONE (0) #define TINYEXR_COMPRESSIONTYPE_RLE (1) #define TINYEXR_COMPRESSIONTYPE_ZIPS (2) #define TINYEXR_COMPRESSIONTYPE_ZIP (3) #define TINYEXR_COMPRESSIONTYPE_PIZ (4) #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0) #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1) #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2) #define TINYEXR_TILE_ONE_LEVEL (0) #define TINYEXR_TILE_MIPMAP_LEVELS (1) #define TINYEXR_TILE_RIPMAP_LEVELS (2) #define TINYEXR_TILE_ROUND_DOWN (0) #define TINYEXR_TILE_ROUND_UP (1) typedef struct _EXRVersion { int version; // this must be 2 int tiled; // tile format image int long_name; // long name attribute int non_image; // deep image(EXR 2.0) int multipart; // multi-part(EXR 2.0) } EXRVersion; typedef struct _EXRAttribute { char name[256]; // name and type are up to 255 chars long. char type[256]; unsigned char *value; // uint8_t* int size; int pad0; } EXRAttribute; typedef struct _EXRChannelInfo { char name[256]; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } EXRChannelInfo; typedef struct _EXRTile { int offset_x; int offset_y; int level_x; int level_y; int width; // actual width in a tile. int height; // actual height int a tile. unsigned char **images; // image[channels][pixels] } EXRTile; typedef struct _EXRHeader { float pixel_aspect_ratio; int line_order; int data_window[4]; int display_window[4]; float screen_window_center[2]; float screen_window_width; int chunk_count; // Properties for tiled format(`tiledesc`). int tiled; int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; int long_name; int non_image; int multipart; unsigned int header_len; // Custom attributes(exludes required attributes(e.g. `channels`, // `compression`, etc) int num_custom_attributes; EXRAttribute *custom_attributes; // array of EXRAttribute. size = // `num_custom_attributes`. EXRChannelInfo *channels; // [num_channels] int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for // each channel. This is overwritten with `requested_pixel_types` when // loading. int num_channels; int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*) int *requested_pixel_types; // Filled initially by // ParseEXRHeaderFrom(Meomory|File), then users // can edit it(only valid for HALF pixel type // channel) } EXRHeader; typedef struct _EXRMultiPartHeader { int num_headers; EXRHeader *headers; } EXRMultiPartHeader; typedef struct _EXRImage { EXRTile *tiles; // Tiled pixel data. The application must reconstruct image // from tiles manually. NULL if scanline format. unsigned char **images; // image[channels][pixels]. NULL if tiled format. int width; int height; int num_channels; // Properties for tile format. int num_tiles; } EXRImage; typedef struct _EXRMultiPartImage { int num_images; EXRImage *images; } EXRMultiPartImage; typedef struct _DeepImage { const char **channel_names; float ***image; // image[channels][scanlines][samples] int **offset_table; // offset_table[scanline][offsets] int num_channels; int width; int height; int pad0; } DeepImage; // @deprecated { to be removed. } // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel // alpha) or RGB(A) channels. // Application must free image data as returned by `out_rgba` // Result image format is: float x RGBA x width x hight // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err); // @deprecated { to be removed. } // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels. // components must be 1(Grayscale), 3(RGB) or 4(RGBA). // Input image format is: `float x width x height`, or `float x RGB(A) x width x // hight` // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero // value. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0. // Use ZIP compression by default. // Returns negative value and may set error string in `err` when there's an // error extern int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename, const char **err); // Initialize EXRHeader struct extern void InitEXRHeader(EXRHeader *exr_header); // Initialize EXRImage struct extern void InitEXRImage(EXRImage *exr_image); // Free's internal data of EXRHeader struct extern int FreeEXRHeader(EXRHeader *exr_header); // Free's internal data of EXRImage struct extern int FreeEXRImage(EXRImage *exr_image); // Free's error message extern void FreeEXRErrorMessage(const char *msg); // Parse EXR version header of a file. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename); // Parse EXR version header from memory-mapped EXR data. extern int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size); // Parse single-part OpenEXR header from a file and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version, const char *filename, const char **err); // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromMemory(EXRHeader *header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*` // array. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const char *filename, const char **err); // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*` // array // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Loads single-part OpenEXR image from a file. // Application must setup `ParseEXRHeaderFromFile` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header, const char *filename, const char **err); // Loads single-part OpenEXR image from a memory. // Application must setup `EXRHeader` with // `ParseEXRHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header, const unsigned char *memory, const size_t size, const char **err); // Loads multi-part OpenEXR image from a file. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this // function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromFile(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const char *filename, const char **err); // Loads multi-part OpenEXR image from a memory. // Application must setup `EXRHeader*` array with // `ParseEXRMultipartHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromMemory(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err); // Saves multi-channel, single-frame OpenEXR image to a file. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int SaveEXRImageToFile(const EXRImage *image, const EXRHeader *exr_header, const char *filename, const char **err); // Saves multi-channel, single-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // Return the number of bytes if success. // Return zero and will set error string in `err` when there's an // error. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern size_t SaveEXRImageToMemory(const EXRImage *image, const EXRHeader *exr_header, unsigned char **memory, const char **err); // Loads single-frame OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadDeepEXR(DeepImage *out_image, const char *filename, const char **err); // NOT YET IMPLEMENTED: // Saves single-frame OpenEXR deep image. // Returns negative value and may set error string in `err` when there's an // error // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename, // const char **err); // NOT YET IMPLEMENTED: // Loads multi-part OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const // char *filename, // const char **err); // For emscripten. // Loads single-frame OpenEXR image from memory. Assume EXR image contains // RGB(A) channels. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err); #ifdef __cplusplus } #endif #endif // TINYEXR_H_ #ifdef TINYEXR_IMPLEMENTATION #ifndef TINYEXR_IMPLEMENTATION_DEIFNED #define TINYEXR_IMPLEMENTATION_DEIFNED #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <limits> #include <string> #include <vector> #if __cplusplus > 199711L // C++11 #include <cstdint> #endif // __cplusplus > 199711L #ifdef _OPENMP #include <omp.h> #endif #if TINYEXR_USE_MINIZ #else // Issue #46. Please include your own zlib-compatible API header before // including `tinyexr.h` //#include "zlib.h" #endif #if TINYEXR_USE_ZFP #include "zfp.h" #endif namespace tinyexr { #if __cplusplus > 199711L // C++11 typedef uint64_t tinyexr_uint64; typedef int64_t tinyexr_int64; #else // Although `long long` is not a standard type pre C++11, assume it is defined // as a compiler's extension. #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #endif typedef unsigned long long tinyexr_uint64; typedef long long tinyexr_int64; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #if TINYEXR_USE_MINIZ namespace miniz { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #pragma clang diagnostic ignored "-Wundef" #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" #endif #if __has_warning("-Wmacro-redefined") #pragma clang diagnostic ignored "-Wmacro-redefined" #endif #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #if __has_warning("-Wtautological-constant-compare") #pragma clang diagnostic ignored "-Wtautological-constant-compare" #endif #endif /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED //#include <stdlib.h> // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be // CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on // stdio for file I/O. //#define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able // to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be // called. // The current downside is the times written to your archives will be from 1979. #define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. #define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive // API's. //#define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression // API's. //#define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent // conflicts against stock zlib. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom // user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's // which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and // tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc // on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) //#include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ defined(__i386) || defined(__i486__) || defined(__i486) || \ defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient // integer loads and stores from unaligned addresses. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \ 0 // disable to suppress compiler warnings #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are // reasonably fast (and don't involve compiler generated calls to helper // functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() // unless you've modified the MZ_MALLOC macro) to release a block allocated from // the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with // ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with // ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: // items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The // other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best // possible compression (not zlib compatible, and may be very slow), // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been // optimized purely for performance, not ratio. // (This special func. is currently only enabled when // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no // header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input // and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or // MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not // available, and/or there's more output to be written but the output buffer // is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been // written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or // output buffers are empty. (Fill up the input buffer or free up some output // space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of // data that could be generated by deflate(), assuming flush is set to only // MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on // failure. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of // data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that // controls the window size and whether or not the stream has been wrapped with // a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or // -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the // input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output // buffers are both sized large enough to decompress the entire stream in a // single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside // what's already in the input buffer, and that the output buffer is large // enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or // there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes // have been written. For zlib streams, the adler-32 of the decompressed data // has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is // empty but the inflater needs more input to continue, or if the output // buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when // using single call decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on // failure. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the // error code is invalid. const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used // as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you // use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional // expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is // 0 this function returns the number of bytes needed to fully store the // filename. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and // modified times. // This function only extracts files, not archive directory records. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive // file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient // in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the // archive's filename so it can be reopened for writing. If the file can't be // reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be // growable using the realloc callback (which defaults to realloc unless you've // overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's // user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what // you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record // the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a // forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records // the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no // recompression), along with its full filename, extra data, and comment fields. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by // the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive // struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be // valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if // mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) // appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the // input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available // beyond the end of the supplied input buffer. If clear, the input buffer // contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large // enough to hold the entire decompressed stream. If clear, the output buffer is // at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the // decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data // to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer // needed. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block // in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes // written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an // internal 32KB buffer, and a user provided callback function will be called to // flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) \ do { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function // actually needed for decompression. All the other functions are just // high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any // desired higher level decompression API. In the limit case, it can be called // once per every byte input or output. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly // slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 // tdefl_init() compression flags logically OR'd together (low 12 bits contain // the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap // compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before // the deflate data, and the Adler-32 of the source data at the end. Otherwise, // you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even // when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more // efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's // initialization time to the minimum, but the output may vary from run to run // given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per // dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against // the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in // memory. // Returns 0 on failure. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be // 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost // pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL // apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be // larger than *pLen_out) when it's no longer needed. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The // above helpers use this function internally. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed // output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper // functions aren't flexible enough. The low-level functions don't make any heap // allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1 } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not // dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified // callback. In this case, the user should call the tdefl_compress_buffer() API // for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() // API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, // etc.) tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer // as possible, and writing as much compressed data to the specified output // buffer as possible. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a // non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't // defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be // much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, // MZ_RLE, or MZ_FIXED mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want // the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; //#include <assert.h> //#include <string.h> #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C // implementation that balances processor cache usage against speed": // http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c}; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } // static void *def_realloc_func(void *opaque, void *address, size_t items, // size_t size) { // (void)opaque, (void)address, (void)items, (void)size; // return MZ_REALLOC(address, items * size); //} const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty // tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are // large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; // Stream is corrupted (there could be some // uncompressed data left in the output dictionary - // oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; // Signal caller that we can't make forward progress // without supplying more input or by setting flush // to MZ_FINISH. else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data // when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's // at least 1 more byte on the way. If there's no more room left in the // output buffer then something is wrong. else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = {{MZ_OK, ""}, {MZ_STREAM_END, "stream end"}, {MZ_NEED_DICT, "need dictionary"}, {MZ_ERRNO, "file error"}, {MZ_STREAM_ERROR, "stream error"}, {MZ_DATA_ERROR, "data error"}, {MZ_MEM_ERROR, "out of memory"}, {MZ_BUF_ERROR, "buf error"}, {MZ_VERSION_ERROR, "version error"}, {MZ_PARAM_ERROR, "parameter error"}}; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif // MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all // compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ switch (r->m_state) { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ do { \ status = result; \ r->m_state = state_index; \ goto common_exit; \ case state_index:; \ } \ MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do { \ for (;;) { \ TINFL_CR_RETURN(state_index, result); \ } \ } \ MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt // to read beyond the input buf, then something is wrong with the input because // the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of // the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) \ do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for (;;) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else \ c = *pIn_buf_cur++; \ } \ MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) \ do { \ mz_uint c; \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ b = bit_buf & ((1 << (n)) - 1); \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes // remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode // the next Huffman code (and absolutely no more). It works by trying to fully // decode a // Huffman code by using whatever bits are currently present in the bit buffer. // If this fails, it reads another byte, and tries again until it succeeds or // until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); \ if (temp >= 0) break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex // than you would initially expect because the zlib API expects the decompressor // to never read // beyond the final byte of the deflate stream. (In other words, when this macro // wants to read another byte from the input, it REALLY needs another byte in // order to fully // decode the next Huffman code.) Handling this properly is particularly // important on raw deflate (non-zlib) streams, which aren't followed by a byte // aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ do { \ int temp; \ mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ pIn_buf_cur += 2; \ num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while (temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ num_bits -= code_len; \ } \ MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static const int s_min_table_sizes[3] = {257, 1, 4}; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer // is large enough to hold the entire output file (in which case it doesn't // matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (;;) { mz_uint8 *pSrc; for (;;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for (;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression // API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285}; static const mz_uint8 s_tdefl_len_extra[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0}; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17}; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted // values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq *t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, // alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n == 0) return; else if (n == 1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next = 1; next < n - 1; next++) { if (leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n - 2].m_key = 0; for (next = n - 3; next >= 0; next--) A[next].m_key = A[A[next].m_key].m_key + 1; avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; while (avbl > 0) { while (root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } while (avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2 * used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) \ do { \ mz_uint bits = b; \ mz_uint len = l; \ MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); \ d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } \ MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() \ { \ if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)( \ d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) \ packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 16; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_repeat_count - 3); \ } \ rle_repeat_count = 0; \ } \ } #define TDEFL_RLE_ZERO_CODE_SIZE() \ { \ if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = \ (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 17; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 18; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 11); \ } \ rle_z_count = 0; \ } \ } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) \ { \ bit_buffer |= (((mz_uint64)(b)) << bits_in); \ bits_in += (l); \ } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && // MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output // buffer and send a raw block instead. if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS( d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed // block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN( (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const mz_uint16 *)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && \ (d->m_dict[probe_pos + match_len - 1] == c1)) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better // register utilization. Intended for applications where raw throughput is // valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to // TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output // buffer. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; // level may actually range from [0,10] (10 is a "hidden" max level, where we // want a bit more compression and it's fine if throughput to fall off a cliff // on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #endif // MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public // domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files // generated by this function pass pngcheck. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was // defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data tdefl_init( pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41, 0x54}; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); for (i = 0; i < 4; ++i, c <<= 8) ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter( "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); for (i = 0; i < 4; ++i, c <<= 8) (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's // where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #error "No arvhive APIs" #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE *pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler // alignment and platform endian issues, miniz.c doesn't use structs for any of // this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) \ do { \ mz_uint32 t = a; \ a = b; \ b = t; \ } \ MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), // but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename( mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for (;;) { if ((child = (root << 1) + 1) >= size) break; child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (;;) { if ((child = (root << 1) + 1) >= end) break; child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first // 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; // Find the end of central directory record by scanning the file from the end // towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE; pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another // heap block to hold the unsorted central dir file record offsets, and // another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return MZ_FALSE; // Now create an index into the central directory file records, do some // basic sanity checking on each record, and check for zip64 entries (which // are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return MZ_FALSE; n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh( mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } // Bugfix: This code was also checking if the internal attribute was non-zero, // which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the // low 16-bits, so check for the DOS directory flag and ignore the source OS // ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) return MZ_TRUE; return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) return MZ_FALSE; // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare( const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) l = m + 1; else h = m - 1; } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); name_len = strlen(pName); if (name_len > 0xFFFF) return -1; comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) return MZ_FALSE; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return MZ_FALSE; return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input // buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) return NULL; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; // Decompress the file either directly from memory or from a file input // buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32( file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; status = mz_zip_reader_extract_to_callback( pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc( pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; // No sense in trying to write to an archive that's already at the support max // size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is // NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can // resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the // user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; // Start writing new files at the archive's current central directory // location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir( mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_central_dir_header( pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start // with a forward slash, cannot contain a drive letter, and cannot use // DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment( mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return MZ_FALSE; // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) return MZ_FALSE; } // Try to do any allocations before writing to the archive, so if an // allocation fails the file remains unmodified. (A good idea if we're doing // an in-place modification.) if ((!mz_zip_array_ensure_room( pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) return MZ_FALSE; pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return MZ_FALSE; MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for (;;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; uncomp_crc32 = (mz_uint32)mz_crc32( uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer( pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) return MZ_FALSE; while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE; orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back( pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE; #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE; if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid // central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) return NULL; MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */ // ---------------------- end of miniz ---------------------------------------- #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace miniz #else // Reuse MINIZ_LITTE_ENDIAN macro #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #endif // TINYEXR_USE_MINIZ // static bool IsBigEndian(void) { // union { // unsigned int i; // char c[4]; // } bint = {0x01020304}; // // return bint.c[0] == 1; //} static void SetErrorMessage(const std::string &msg, const char **err) { if (err) { #ifdef _WIN32 (*err) = _strdup(msg.c_str()); #else (*err) = strdup(msg.c_str()); #endif } } static const int kEXRVersionSize = 8; static void cpy2(unsigned short *dst_val, const unsigned short *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; } static void swap2(unsigned short *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned short tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[1]; dst[1] = src[0]; #endif } static void cpy4(int *dst_val, const int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(unsigned int *dst_val, const unsigned int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(float *dst_val, const float *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void swap4(unsigned int *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } #if 0 static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; } #endif static void swap8(tinyexr::tinyexr_uint64 *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else tinyexr::tinyexr_uint64 tmp = (*val); unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; #endif } // https://gist.github.com/rygorous/2156668 // Reuse MINIZ_LITTLE_ENDIAN flag from miniz. union FP32 { unsigned int u; float f; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 23; unsigned int Exponent : 8; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 8; unsigned int Mantissa : 23; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif union FP16 { unsigned short u; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 10; unsigned int Exponent : 5; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 5; unsigned int Mantissa : 10; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic pop #endif static FP32 half_to_float(FP16 h) { static const FP32 magic = {113 << 23}; static const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift FP32 o; o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits unsigned int exp_ = shifted_exp & o.u; // just the exponent o.u += (127 - 15) << 23; // exponent adjust // handle exponent special cases if (exp_ == shifted_exp) // Inf/NaN? o.u += (128 - 16) << 23; // extra exp adjust else if (exp_ == 0) // Zero/Denormal? { o.u += 1 << 23; // extra exp adjust o.f -= magic.f; // renormalize } o.u |= (h.u & 0x8000U) << 16U; // sign bit return o; } static FP16 float_to_half_full(FP32 f) { FP16 o = {0}; // Based on ISPC reference code (with minor modifications) if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow) o.s.Exponent = 0; else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set) { o.s.Exponent = 31; o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf } else // Normalized number { // Exponent unbias the single, then bias the halfp int newexp = f.s.Exponent - 127 + 15; if (newexp >= 31) // Overflow, return signed infinity o.s.Exponent = 31; else if (newexp <= 0) // Underflow { if ((14 - newexp) <= 24) // Mantissa might be non-zero { unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit o.s.Mantissa = mant >> (14 - newexp); if ((mant >> (13 - newexp)) & 1) // Check for rounding o.u++; // Round, might overflow into exp bit, but this is OK } } else { o.s.Exponent = static_cast<unsigned int>(newexp); o.s.Mantissa = f.s.Mantissa >> 13; if (f.s.Mantissa & 0x1000) // Check for rounding o.u++; // Round, might overflow to inf, this is OK } } o.s.Sign = f.s.Sign; return o; } // NOTE: From OpenEXR code // #define IMF_INCREASING_Y 0 // #define IMF_DECREASING_Y 1 // #define IMF_RAMDOM_Y 2 // // #define IMF_NO_COMPRESSION 0 // #define IMF_RLE_COMPRESSION 1 // #define IMF_ZIPS_COMPRESSION 2 // #define IMF_ZIP_COMPRESSION 3 // #define IMF_PIZ_COMPRESSION 4 // #define IMF_PXR24_COMPRESSION 5 // #define IMF_B44_COMPRESSION 6 // #define IMF_B44A_COMPRESSION 7 #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #endif static const char *ReadString(std::string *s, const char *ptr, size_t len) { // Read untile NULL(\0). const char *p = ptr; const char *q = ptr; while ((size_t(q - ptr) < len) && (*q) != 0) { q++; } if (size_t(q - ptr) >= len) { (*s) = std::string(); return NULL; } (*s) = std::string(p, q); return q + 1; // skip '\0' } static bool ReadAttribute(std::string *name, std::string *type, std::vector<unsigned char> *data, size_t *marker_size, const char *marker, size_t size) { size_t name_len = strnlen(marker, size); if (name_len == size) { // String does not have a terminating character. return false; } *name = std::string(marker, name_len); marker += name_len + 1; size -= name_len + 1; size_t type_len = strnlen(marker, size); if (type_len == size) { return false; } *type = std::string(marker, type_len); marker += type_len + 1; size -= type_len + 1; if (size < sizeof(uint32_t)) { return false; } uint32_t data_len; memcpy(&data_len, marker, sizeof(uint32_t)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len == 0) { if ((*type).compare("string") == 0) { // Accept empty string attribute. marker += sizeof(uint32_t); size -= sizeof(uint32_t); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t); data->resize(1); (*data)[0] = '\0'; return true; } else { return false; } } marker += sizeof(uint32_t); size -= sizeof(uint32_t); if (size < data_len) { return false; } data->resize(static_cast<size_t>(data_len)); memcpy(&data->at(0), marker, static_cast<size_t>(data_len)); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len; return true; } static void WriteAttributeToMemory(std::vector<unsigned char> *out, const char *name, const char *type, const unsigned char *data, int len) { out->insert(out->end(), name, name + strlen(name) + 1); out->insert(out->end(), type, type + strlen(type) + 1); int outLen = len; tinyexr::swap4(reinterpret_cast<unsigned int *>(&outLen)); out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen), reinterpret_cast<unsigned char *>(&outLen) + sizeof(int)); out->insert(out->end(), data, data + len); } typedef struct { std::string name; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } ChannelInfo; typedef struct { std::vector<tinyexr::ChannelInfo> channels; std::vector<EXRAttribute> attributes; int data_window[4]; int line_order; int display_window[4]; float screen_window_center[2]; float screen_window_width; float pixel_aspect_ratio; int chunk_count; // Tiled format int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; unsigned int header_len; int compression_type; void clear() { channels.clear(); attributes.clear(); data_window[0] = 0; data_window[1] = 0; data_window[2] = 0; data_window[3] = 0; line_order = 0; display_window[0] = 0; display_window[1] = 0; display_window[2] = 0; display_window[3] = 0; screen_window_center[0] = 0.0f; screen_window_center[1] = 0.0f; screen_window_width = 0.0f; pixel_aspect_ratio = 0.0f; chunk_count = 0; // Tiled format tile_size_x = 0; tile_size_y = 0; tile_level_mode = 0; tile_rounding_mode = 0; header_len = 0; compression_type = 0; } } HeaderInfo; static bool ReadChannelInfo(std::vector<ChannelInfo> &channels, const std::vector<unsigned char> &data) { const char *p = reinterpret_cast<const char *>(&data.at(0)); for (;;) { if ((*p) == 0) { break; } ChannelInfo info; tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) - (p - reinterpret_cast<const char *>(data.data())); if (data_len < 0) { return false; } p = ReadString(&info.name, p, size_t(data_len)); if ((p == NULL) && (info.name.empty())) { // Buffer overrun. Issue #51. return false; } const unsigned char *data_end = reinterpret_cast<const unsigned char *>(p) + 16; if (data_end >= (data.data() + data.size())) { return false; } memcpy(&info.pixel_type, p, sizeof(int)); p += 4; info.p_linear = static_cast<unsigned char>(p[0]); // uchar p += 1 + 3; // reserved: uchar[3] memcpy(&info.x_sampling, p, sizeof(int)); // int p += 4; memcpy(&info.y_sampling, p, sizeof(int)); // int p += 4; tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.y_sampling)); channels.push_back(info); } return true; } static void WriteChannelInfo(std::vector<unsigned char> &data, const std::vector<ChannelInfo> &channels) { size_t sz = 0; // Calculate total size. for (size_t c = 0; c < channels.size(); c++) { sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0 sz += 16; // 4 * int } data.resize(sz + 1); unsigned char *p = &data.at(0); for (size_t c = 0; c < channels.size(); c++) { memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str())); p += strlen(channels[c].name.c_str()); (*p) = '\0'; p++; int pixel_type = channels[c].pixel_type; int x_sampling = channels[c].x_sampling; int y_sampling = channels[c].y_sampling; tinyexr::swap4(reinterpret_cast<unsigned int *>(&pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y_sampling)); memcpy(p, &pixel_type, sizeof(int)); p += sizeof(int); (*p) = channels[c].p_linear; p += 4; memcpy(p, &x_sampling, sizeof(int)); p += sizeof(int); memcpy(p, &y_sampling, sizeof(int)); p += sizeof(int); } (*p) = '\0'; } static void CompressZip(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } #if TINYEXR_USE_MINIZ // // Compress the data using miniz // miniz::mz_ulong outSize = miniz::mz_compressBound(src_size); int ret = miniz::mz_compress( dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)), src_size); assert(ret == miniz::MZ_OK); (void)ret; compressedSize = outSize; #else uLong outSize = compressBound(static_cast<uLong>(src_size)); int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)), src_size); assert(ret == Z_OK); compressedSize = outSize; #endif // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressZip(unsigned char *dst, unsigned long *uncompressed_size /* inout */, const unsigned char *src, unsigned long src_size) { if ((*uncompressed_size) == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } std::vector<unsigned char> tmpBuf(*uncompressed_size); #if TINYEXR_USE_MINIZ int ret = miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (miniz::MZ_OK != ret) { return false; } #else int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (Z_OK != ret) { return false; } #endif // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size); while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (*uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + (*uncompressed_size); for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } // RLE code from OpenEXR -------------------------------------- #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif const int MIN_RUN_LENGTH = 3; const int MAX_RUN_LENGTH = 127; // // Compress an array of bytes, using run-length encoding, // and return the length of the compressed data. // static int rleCompress(int inLength, const char in[], signed char out[]) { const char *inEnd = in + inLength; const char *runStart = in; const char *runEnd = in + 1; signed char *outWrite = out; while (runStart < inEnd) { while (runEnd < inEnd && *runStart == *runEnd && runEnd - runStart - 1 < MAX_RUN_LENGTH) { ++runEnd; } if (runEnd - runStart >= MIN_RUN_LENGTH) { // // Compressable run // *outWrite++ = static_cast<char>(runEnd - runStart) - 1; *outWrite++ = *(reinterpret_cast<const signed char *>(runStart)); runStart = runEnd; } else { // // Uncompressable run // while (runEnd < inEnd && ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) || (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) && runEnd - runStart < MAX_RUN_LENGTH) { ++runEnd; } *outWrite++ = static_cast<char>(runStart - runEnd); while (runStart < runEnd) { *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++)); } } ++runEnd; } return static_cast<int>(outWrite - out); } // // Uncompress an array of bytes compressed with rleCompress(). // Returns the length of the oncompressed data, or 0 if the // length of the uncompressed data would be more than maxLength. // static int rleUncompress(int inLength, int maxLength, const signed char in[], char out[]) { char *outStart = out; while (inLength > 0) { if (*in < 0) { int count = -(static_cast<int>(*in++)); inLength -= count + 1; if (0 > (maxLength -= count)) return 0; memcpy(out, in, count); out += count; in += count; } else { int count = *in++; inLength -= 2; if (0 > (maxLength -= count + 1)) return 0; memset(out, *reinterpret_cast<const char *>(in), count + 1); out += count + 1; in++; } } return static_cast<int>(out - outStart); } #ifdef __clang__ #pragma clang diagnostic pop #endif // End of RLE code from OpenEXR ----------------------------------- static void CompressRle(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } // outSize will be (srcSiz * 3) / 2 at max. int outSize = rleCompress(static_cast<int>(src_size), reinterpret_cast<const char *>(&tmpBuf.at(0)), reinterpret_cast<signed char *>(dst)); assert(outSize > 0); compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static void DecompressRle(unsigned char *dst, const unsigned long uncompressed_size, const unsigned char *src, unsigned long src_size) { if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return; } std::vector<unsigned char> tmpBuf(uncompressed_size); int ret = rleUncompress(static_cast<int>(src_size), static_cast<int>(uncompressed_size), reinterpret_cast<const signed char *>(src), reinterpret_cast<char *>(&tmpBuf.at(0))); assert(ret == static_cast<int>(uncompressed_size)); (void)ret; // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + uncompressed_size; while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + uncompressed_size; for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } } #if TINYEXR_USE_PIZ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #endif // // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp // // ----------------------------------------------------------------- // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC) // (3 clause BSD license) // struct PIZChannelData { unsigned short *start; unsigned short *end; int nx; int ny; int ys; int size; }; //----------------------------------------------------------------------------- // // 16-bit Haar Wavelet encoding and decoding // // The source code in this file is derived from the encoding // and decoding routines written by Christian Rouet for his // PIZ image file format. // //----------------------------------------------------------------------------- // // Wavelet basis functions without modulo arithmetic; they produce // the best compression ratios when the wavelet-transformed data are // Huffman-encoded, but the wavelet transform works only for 14-bit // data (untransformed data values must be less than (1 << 14)). // inline void wenc14(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { short as = static_cast<short>(a); short bs = static_cast<short>(b); short ms = (as + bs) >> 1; short ds = as - bs; l = static_cast<unsigned short>(ms); h = static_cast<unsigned short>(ds); } inline void wdec14(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { short ls = static_cast<short>(l); short hs = static_cast<short>(h); int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); short as = static_cast<short>(ai); short bs = static_cast<short>(ai - hi); a = static_cast<unsigned short>(as); b = static_cast<unsigned short>(bs); } // // Wavelet basis functions with modulo arithmetic; they work with full // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't // compress the data quite as well. // const int NBITS = 16; const int A_OFFSET = 1 << (NBITS - 1); const int M_OFFSET = 1 << (NBITS - 1); const int MOD_MASK = (1 << NBITS) - 1; inline void wenc16(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { int ao = (a + A_OFFSET) & MOD_MASK; int m = ((ao + b) >> 1); int d = ao - b; if (d < 0) m = (m + M_OFFSET) & MOD_MASK; d &= MOD_MASK; l = static_cast<unsigned short>(m); h = static_cast<unsigned short>(d); } inline void wdec16(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; b = static_cast<unsigned short>(bb); a = static_cast<unsigned short>(aa); } // // 2D Wavelet encoding: // static void wav2Encode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; // == 1 << level int p2 = 2; // == 1 << (level+1) // // Hierachical loop on smaller dimension n // while (p2 <= n) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet encoding // if (w14) { wenc14(*px, *p01, i00, i01); wenc14(*p10, *p11, i10, i11); wenc14(i00, i10, *px, *p10); wenc14(i01, i11, *p01, *p11); } else { wenc16(*px, *p01, i00, i01); wenc16(*p10, *p11, i10, i11); wenc16(i00, i10, *px, *p10); wenc16(i01, i11, *p01, *p11); } } // // Encode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wenc14(*px, *p10, i00, *p10); else wenc16(*px, *p10, i00, *p10); *px = i00; } } // // Encode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wenc14(*px, *p01, i00, *p01); else wenc16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p = p2; p2 <<= 1; } } // // 2D Wavelet decoding: // static void wav2Decode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; // // Search max level // while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; // // Hierarchical loop on smaller dimension n // while (p >= 1) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet decoding // if (w14) { wdec14(*px, *p10, i00, i10); wdec14(*p01, *p11, i01, i11); wdec14(i00, i01, *px, *p01); wdec14(i10, i11, *p10, *p11); } else { wdec16(*px, *p10, i00, i10); wdec16(*p01, *p11, i01, i11); wdec16(i00, i01, *px, *p01); wdec16(i10, i11, *p10, *p11); } } // // Decode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wdec14(*px, *p10, i00, *p10); else wdec16(*px, *p10, i00, *p10); *px = i00; } } // // Decode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wdec14(*px, *p01, i00, *p01); else wdec16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p2 = p; p >>= 1; } } //----------------------------------------------------------------------------- // // 16-bit Huffman compression and decompression. // // The source code in this file is derived from the 8-bit // Huffman compression and decompression routines written // by Christian Rouet for his PIZ image file format. // //----------------------------------------------------------------------------- // Adds some modification for tinyexr. const int HUF_ENCBITS = 16; // literal (value) bit length const int HUF_DECBITS = 14; // decoding bit size (>= 8) const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size const int HUF_DECMASK = HUF_DECSIZE - 1; struct HufDec { // short code long code //------------------------------- int len : 8; // code length 0 int lit : 24; // lit p size int *p; // 0 lits }; inline long long hufLength(long long code) { return code & 63; } inline long long hufCode(long long code) { return code >> 6; } inline void outputBits(int nBits, long long bits, long long &c, int &lc, char *&out) { c <<= nBits; lc += nBits; c |= bits; while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8))); } inline long long getBits(int nBits, long long &c, int &lc, const char *&in) { while (lc < nBits) { c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++)); lc += 8; } lc -= nBits; return (c >> lc) & ((1 << nBits) - 1); } // // ENCODING TABLE BUILDING & (UN)PACKING // // // Build a "canonical" Huffman code table: // - for each (uncompressed) symbol, hcode contains the length // of the corresponding code (in the compressed data) // - canonical codes are computed and stored in hcode // - the rules for constructing canonical codes are as follows: // * shorter codes (if filled with zeroes to the right) // have a numerically higher value than longer codes // * for codes with the same length, numerical values // increase with numerical symbol values // - because the canonical code table can be constructed from // symbol lengths alone, the code table can be transmitted // without sending the actual code values // - see http://www.compressconsult.com/huffman/ // static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) { long long n[59]; // // For each i from 0 through 58, count the // number of different codes of length i, and // store the count in n[i]. // for (int i = 0; i <= 58; ++i) n[i] = 0; for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; // // For each i from 58 through 1, compute the // numerically lowest code with length i, and // store that code in n[i]. // long long c = 0; for (int i = 58; i > 0; --i) { long long nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } // // hcode[i] contains the length, l, of the // code for symbol i. Assign the next available // code of length l to the symbol and store both // l and the code in hcode[i]. // for (int i = 0; i < HUF_ENCSIZE; ++i) { int l = static_cast<int>(hcode[i]); if (l > 0) hcode[i] = l | (n[l]++ << 6); } } // // Compute Huffman codes (based on frq input) and store them in frq: // - code structure is : [63:lsb - 6:msb] | [5-0: bit length]; // - max code length is 58 bits; // - codes outside the range [im-iM] have a null length (unused values); // - original frequencies are destroyed; // - encoding tables are used by hufEncode() and hufBuildDecTable(); // struct FHeapCompare { bool operator()(long long *a, long long *b) { return *a > *b; } }; static void hufBuildEncTable( long long *frq, // io: input frequencies [HUF_ENCSIZE], output table int *im, // o: min frq index int *iM) // o: max frq index { // // This function assumes that when it is called, array frq // indicates the frequency of all possible symbols in the data // that are to be Huffman-encoded. (frq[i] contains the number // of occurrences of symbol i in the data.) // // The loop below does three things: // // 1) Finds the minimum and maximum indices that point // to non-zero entries in frq: // // frq[im] != 0, and frq[i] == 0 for all i < im // frq[iM] != 0, and frq[i] == 0 for all i > iM // // 2) Fills array fHeap with pointers to all non-zero // entries in frq. // // 3) Initializes array hlink such that hlink[i] == i // for all array entries. // std::vector<int> hlink(HUF_ENCSIZE); std::vector<long long *> fHeap(HUF_ENCSIZE); *im = 0; while (!frq[*im]) (*im)++; int nf = 0; for (int i = *im; i < HUF_ENCSIZE; i++) { hlink[i] = i; if (frq[i]) { fHeap[nf] = &frq[i]; nf++; *iM = i; } } // // Add a pseudo-symbol, with a frequency count of 1, to frq; // adjust the fHeap and hlink array accordingly. Function // hufEncode() uses the pseudo-symbol for run-length encoding. // (*iM)++; frq[*iM] = 1; fHeap[nf] = &frq[*iM]; nf++; // // Build an array, scode, such that scode[i] contains the number // of bits assigned to symbol i. Conceptually this is done by // constructing a tree whose leaves are the symbols with non-zero // frequency: // // Make a heap that contains all symbols with a non-zero frequency, // with the least frequent symbol on top. // // Repeat until only one symbol is left on the heap: // // Take the two least frequent symbols off the top of the heap. // Create a new node that has first two nodes as children, and // whose frequency is the sum of the frequencies of the first // two nodes. Put the new node back into the heap. // // The last node left on the heap is the root of the tree. For each // leaf node, the distance between the root and the leaf is the length // of the code for the corresponding symbol. // // The loop below doesn't actually build the tree; instead we compute // the distances of the leaves from the root on the fly. When a new // node is added to the heap, then that node's descendants are linked // into a single linear list that starts at the new node, and the code // lengths of the descendants (that is, their distance from the root // of the tree) are incremented by one. // std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); std::vector<long long> scode(HUF_ENCSIZE); memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE); while (nf > 1) { // // Find the indices, mm and m, of the two smallest non-zero frq // values in fHeap, add the smallest frq to the second-smallest // frq, and remove the smallest frq value from fHeap. // int mm = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); --nf; int m = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); frq[m] += frq[mm]; std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); // // The entries in scode are linked into lists with the // entries in hlink serving as "next" pointers and with // the end of a list marked by hlink[j] == j. // // Traverse the lists that start at scode[m] and scode[mm]. // For each element visited, increment the length of the // corresponding code by one bit. (If we visit scode[j] // during the traversal, then the code for symbol j becomes // one bit longer.) // // Merge the lists that start at scode[m] and scode[mm] // into a single list that starts at scode[m]. // // // Add a bit to all codes in the first list. // for (int j = m;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) { // // Merge the two lists. // hlink[j] = mm; break; } } // // Add a bit to all codes in the second list // for (int j = mm;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) break; } } // // Build a canonical Huffman code table, replacing the code // lengths in scode with (code, code length) pairs. Copy the // code table from scode into frq. // hufCanonicalCodeTable(scode.data()); memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE); } // // Pack an encoding table: // - only code lengths, not actual codes, are stored // - runs of zeroes are compressed as follows: // // unpacked packed // -------------------------------- // 1 zero 0 (6 bits) // 2 zeroes 59 // 3 zeroes 60 // 4 zeroes 61 // 5 zeroes 62 // n zeroes (6 or more) 63 n-6 (6 + 8 bits) // const int SHORT_ZEROCODE_RUN = 59; const int LONG_ZEROCODE_RUN = 63; const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN; static void hufPackEncTable( const long long *hcode, // i : encoding table [HUF_ENCSIZE] int im, // i : min hcode index int iM, // i : max hcode index char **pcode) // o: ptr to packed table (updated) { char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { int l = hufLength(hcode[im]); if (l == 0) { int zerun = 1; while ((im < iM) && (zerun < LONGEST_LONG_RUN)) { if (hufLength(hcode[im + 1]) > 0) break; im++; zerun++; } if (zerun >= 2) { if (zerun >= SHORTEST_LONG_RUN) { outputBits(6, LONG_ZEROCODE_RUN, c, lc, p); outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p); } else { outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p); } continue; } } outputBits(6, l, c, lc, p); } if (lc > 0) *p++ = (unsigned char)(c << (8 - lc)); *pcode = p; } // // Unpack an encoding table packed by hufPackEncTable(): // static bool hufUnpackEncTable( const char **pcode, // io: ptr to packed table (updated) int ni, // i : input size (in bytes) int im, // i : min hcode index int iM, // i : max hcode index long long *hcode) // o: encoding table [HUF_ENCSIZE] { memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE); const char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { if (p - *pcode > ni) { return false; } long long l = hcode[im] = getBits(6, c, lc, p); // code length if (l == (long long)LONG_ZEROCODE_RUN) { if (p - *pcode > ni) { return false; } int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } else if (l >= (long long)SHORT_ZEROCODE_RUN) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } } *pcode = const_cast<char *>(p); hufCanonicalCodeTable(hcode); return true; } // // DECODING TABLE BUILDING // // // Clear a newly allocated decoding table so that it contains only zeroes. // static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller) // decoding table [HUF_DECSIZE] { for (int i = 0; i < HUF_DECSIZE; i++) { hdecod[i].len = 0; hdecod[i].lit = 0; hdecod[i].p = NULL; } // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE); } // // Build a decoding hash table based on the encoding table hcode: // - short codes (<= HUF_DECBITS) are resolved with a single table access; // - long code entry allocations are not optimized, because long codes are // unfrequent; // - decoding tables are used by hufDecode(); // static bool hufBuildDecTable(const long long *hcode, // i : encoding table int im, // i : min index in hcode int iM, // i : max index in hcode HufDec *hdecod) // o: (allocated by caller) // decoding table [HUF_DECSIZE] { // // Init hashtable & loop on all codes. // Assumes that hufClearDecTable(hdecod) has already been called. // for (; im <= iM; im++) { long long c = hufCode(hcode[im]); int l = hufLength(hcode[im]); if (c >> l) { // // Error: c is supposed to be an l-bit code, // but c contains a value that is greater // than the largest l-bit number. // // invalidTableEntry(); return false; } if (l > HUF_DECBITS) { // // Long code: add a secondary entry // HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) { // // Error: a short code has already // been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->lit++; if (pl->p) { int *p = pl->p; pl->p = new int[pl->lit]; for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i]; delete[] p; } else { pl->p = new int[1]; } pl->p[pl->lit - 1] = im; } else if (l) { // // Short code: init all primary entries // HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) { // // Error: a short code or a long code has // already been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->len = l; pl->lit = im; } } } return true; } // // Free the long code entries of a decoding table built by hufBuildDecTable() // static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table { for (int i = 0; i < HUF_DECSIZE; i++) { if (hdecod[i].p) { delete[] hdecod[i].p; hdecod[i].p = 0; } } } // // ENCODING // inline void outputCode(long long code, long long &c, int &lc, char *&out) { outputBits(hufLength(code), hufCode(code), c, lc, out); } inline void sendCode(long long sCode, int runCount, long long runCode, long long &c, int &lc, char *&out) { // // Output a run of runCount instances of the symbol sCount. // Output the symbols explicitly, or if that is shorter, output // the sCode symbol once followed by a runCode symbol and runCount // expressed as an 8-bit number. // if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) { outputCode(sCode, c, lc, out); outputCode(runCode, c, lc, out); outputBits(8, runCount, c, lc, out); } else { while (runCount-- >= 0) outputCode(sCode, c, lc, out); } } // // Encode (compress) ni values based on the Huffman encoding table hcode: // static int hufEncode // return: output size (in bits) (const long long *hcode, // i : encoding table const unsigned short *in, // i : uncompressed input buffer const int ni, // i : input buffer size (in bytes) int rlc, // i : rl code char *out) // o: compressed output buffer { char *outStart = out; long long c = 0; // bits not yet written to out int lc = 0; // number of valid bits in c (LSB) int s = in[0]; int cs = 0; // // Loop on input values // for (int i = 1; i < ni; i++) { // // Count same values or send code // if (s == in[i] && cs < 255) { cs++; } else { sendCode(hcode[s], cs, hcode[rlc], c, lc, out); cs = 0; } s = in[i]; } // // Send remaining code // sendCode(hcode[s], cs, hcode[rlc], c, lc, out); if (lc) *out = (c << (8 - lc)) & 0xff; return (out - outStart) * 8 + lc; } // // DECODING // // // In order to force the compiler to inline them, // getChar() and getCode() are implemented as macros // instead of "inline" functions. // #define getChar(c, lc, in) \ { \ c = (c << 8) | *(unsigned char *)(in++); \ lc += 8; \ } #if 0 #define getCode(po, rlc, c, lc, in, out, ob, oe) \ { \ if (po == rlc) { \ if (lc < 8) getChar(c, lc, in); \ \ lc -= 8; \ \ unsigned char cs = (c >> lc); \ \ if (out + cs > oe) return false; \ \ /* TinyEXR issue 78 */ \ unsigned short s = out[-1]; \ \ while (cs-- > 0) *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return false; \ } \ } #else static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in, const char *in_end, unsigned short *&out, const unsigned short *ob, const unsigned short *oe) { (void)ob; if (po == rlc) { if (lc < 8) { /* TinyEXR issue 78 */ if ((in + 1) >= in_end) { return false; } getChar(c, lc, in); } lc -= 8; unsigned char cs = (c >> lc); if (out + cs > oe) return false; // Bounds check for safety if ((out - 1) <= ob) return false; unsigned short s = out[-1]; while (cs-- > 0) *out++ = s; } else if (out < oe) { *out++ = po; } else { return false; } return true; } #endif // // Decode (uncompress) ni bits based on encoding & decoding tables: // static bool hufDecode(const long long *hcode, // i : encoding table const HufDec *hdecod, // i : decoding table const char *in, // i : compressed input buffer int ni, // i : input size (in bits) int rlc, // i : run-length code int no, // i : expected output size (in bytes) unsigned short *out) // o: uncompressed output buffer { long long c = 0; int lc = 0; unsigned short *outb = out; // begin unsigned short *oe = out + no; // end const char *ie = in + (ni + 7) / 8; // input byte size // // Loop on input bytes // while (in < ie) { getChar(c, lc, in); // // Access decoding table // while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { // // Get short code // lc -= pl.len; // std::cout << "lit = " << pl.lit << std::endl; // std::cout << "rlc = " << rlc << std::endl; // std::cout << "c = " << c << std::endl; // std::cout << "lc = " << lc << std::endl; // std::cout << "in = " << in << std::endl; // std::cout << "out = " << out << std::endl; // std::cout << "oe = " << oe << std::endl; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { if (!pl.p) { return false; } // invalidCode(); // wrong code // // Search long code // int j; for (j = 0; j < pl.lit; j++) { int l = hufLength(hcode[pl.p[j]]); while (lc < l && in < ie) // get more bits getChar(c, lc, in); if (lc >= l) { if (hufCode(hcode[pl.p[j]]) == ((c >> (lc - l)) & (((long long)(1) << l) - 1))) { // // Found : get long code // lc -= l; if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) { return false; } break; } } } if (j == pl.lit) { return false; // invalidCode(); // Not found } } } } // // Get remaining (short) codes // int i = (8 - ni) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { return false; // invalidCode(); // wrong (long) code } } if (out - outb != no) { return false; } // notEnoughData (); return true; } static void countFrequencies(std::vector<long long> &freq, const unsigned short data[/*n*/], int n) { for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0; for (int i = 0; i < n; ++i) ++freq[data[i]]; } static void writeUInt(char buf[4], unsigned int i) { unsigned char *b = (unsigned char *)buf; b[0] = i; b[1] = i >> 8; b[2] = i >> 16; b[3] = i >> 24; } static unsigned int readUInt(const char buf[4]) { const unsigned char *b = (const unsigned char *)buf; return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) | ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000); } // // EXTERNAL INTERFACE // static int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) { if (nRaw == 0) return 0; std::vector<long long> freq(HUF_ENCSIZE); countFrequencies(freq, raw, nRaw); int im = 0; int iM = 0; hufBuildEncTable(freq.data(), &im, &iM); char *tableStart = compressed + 20; char *tableEnd = tableStart; hufPackEncTable(freq.data(), im, iM, &tableEnd); int tableLength = tableEnd - tableStart; char *dataStart = tableEnd; int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart); int data_length = (nBits + 7) / 8; writeUInt(compressed, im); writeUInt(compressed + 4, iM); writeUInt(compressed + 8, tableLength); writeUInt(compressed + 12, nBits); writeUInt(compressed + 16, 0); // room for future extensions return dataStart + data_length - compressed; } static bool hufUncompress(const char compressed[], int nCompressed, std::vector<unsigned short> *raw) { if (nCompressed == 0) { if (raw->size() != 0) return false; return false; } int im = readUInt(compressed); int iM = readUInt(compressed + 4); // int tableLength = readUInt (compressed + 8); int nBits = readUInt(compressed + 12); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false; const char *ptr = compressed + 20; // // Fast decoder needs at least 2x64-bits of compressed data, and // needs to be run-able on this platform. Otherwise, fall back // to the original decoder // // if (FastHufDecoder::enabled() && nBits > 128) //{ // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); //} // else { std::vector<long long> freq(HUF_ENCSIZE); std::vector<HufDec> hdec(HUF_DECSIZE); hufClearDecTable(&hdec.at(0)); hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM, &freq.at(0)); { if (nBits > 8 * (nCompressed - (ptr - compressed))) { return false; } hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0)); hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(), raw->data()); } // catch (...) //{ // hufFreeDecTable (hdec); // throw; //} hufFreeDecTable(&hdec.at(0)); } return true; } // // Functions to compress the range of values in the pixel data // const int USHORT_RANGE = (1 << 16); const int BITMAP_SIZE = (USHORT_RANGE >> 3); static void bitmapFromData(const unsigned short data[/*nData*/], int nData, unsigned char bitmap[BITMAP_SIZE], unsigned short &minNonZero, unsigned short &maxNonZero) { for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0; for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7)); bitmap[0] &= ~1; // zero is not explicitly stored in // the bitmap; we assume that the // data always contain zeroes minNonZero = BITMAP_SIZE - 1; maxNonZero = 0; for (int i = 0; i < BITMAP_SIZE; ++i) { if (bitmap[i]) { if (minNonZero > i) minNonZero = i; if (maxNonZero < i) maxNonZero = i; } } } static unsigned short forwardLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[i] = k++; else lut[i] = 0; } return k - 1; // maximum value stored in lut[], } // i.e. number of ones in bitmap minus 1 static unsigned short reverseLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; } int n = k - 1; while (k < USHORT_RANGE) lut[k++] = 0; return n; // maximum k where lut[k] is non-zero, } // i.e. number of ones in bitmap minus 1 static void applyLut(const unsigned short lut[USHORT_RANGE], unsigned short data[/*nData*/], int nData) { for (int i = 0; i < nData; ++i) data[i] = lut[data[i]]; } #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #ifdef _MSC_VER #pragma warning(pop) #endif static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize, const unsigned char *inPtr, size_t inSize, const std::vector<ChannelInfo> &channelInfo, int data_width, int num_lines) { std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif // Assume `inSize` is multiple of 2 or 4. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short)); std::vector<PIZChannelData> channelData(channelInfo.size()); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t c = 0; c < channelData.size(); c++) { PIZChannelData &cd = channelData[c]; cd.start = tmpBufferEnd; cd.end = cd.start; cd.nx = data_width; cd.ny = num_lines; // cd.ys = c.channel().ySampling; size_t pixelSize = sizeof(int); // UINT and FLOAT if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } cd.size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += cd.nx * cd.ny * cd.size; } const unsigned char *ptr = inPtr; for (int y = 0; y < num_lines; ++y) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(cd.end, ptr, n * sizeof(unsigned short)); ptr += n * sizeof(unsigned short); cd.end += n; } } bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), bitmap.data(), minNonZero, maxNonZero); std::vector<unsigned short> lut(USHORT_RANGE); unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data()); applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size())); // // Store range compression info in _outBuffer // char *buf = reinterpret_cast<char *>(outPtr); memcpy(buf, &minNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); memcpy(buf, &maxNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); if (minNonZero <= maxNonZero) { memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero), maxNonZero - minNonZero + 1); buf += maxNonZero - minNonZero + 1; } // // Apply wavelet encoding // for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Apply Huffman encoding; append the result to _outBuffer // // length header(4byte), then huff data. Initialize length header with zero, // then later fill it by `length`. char *lengthPtr = buf; int zero = 0; memcpy(buf, &zero, sizeof(int)); buf += sizeof(int); int length = hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf); memcpy(lengthPtr, &length, sizeof(int)); (*outSize) = static_cast<unsigned int>( (reinterpret_cast<unsigned char *>(buf) - outPtr) + static_cast<unsigned int>(length)); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if ((*outSize) >= inSize) { (*outSize) = static_cast<unsigned int>(inSize); memcpy(outPtr, inPtr, inSize); } return true; } static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr, size_t tmpBufSize, size_t inLen, int num_channels, const EXRChannelInfo *channels, int data_width, int num_lines) { if (inLen == tmpBufSize) { // Data is not compressed(Issue 40). memcpy(outPtr, inPtr, inLen); return true; } std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif memset(bitmap.data(), 0, BITMAP_SIZE); const unsigned char *ptr = inPtr; // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr)); tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr)); // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2)); tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2)); ptr += 4; if (maxNonZero >= BITMAP_SIZE) { return false; } if (minNonZero <= maxNonZero) { memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr, maxNonZero - minNonZero + 1); ptr += maxNonZero - minNonZero + 1; } std::vector<unsigned short> lut(USHORT_RANGE); memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE); unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data()); // // Huffman decoding // int length; // length = *(reinterpret_cast<const int *>(ptr)); tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr)); ptr += sizeof(int); std::vector<unsigned short> tmpBuffer(tmpBufSize); hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer); // // Wavelet decoding // std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels)); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) { const EXRChannelInfo &chan = channels[i]; size_t pixelSize = sizeof(int); // UINT and FLOAT if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } channelData[i].start = tmpBufferEnd; channelData[i].end = channelData[i].start; channelData[i].nx = data_width; channelData[i].ny = num_lines; // channelData[i].ys = 1; channelData[i].size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size; } for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Expand the pixel data to their original range // applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize)); for (int y = 0; y < num_lines; y++) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short))); outPtr += n * sizeof(unsigned short); cd.end += n; } } return true; } #endif // TINYEXR_USE_PIZ #if TINYEXR_USE_ZFP struct ZFPCompressionParam { double rate; int precision; double tolerance; int type; // TINYEXR_ZFP_COMPRESSIONTYPE_* ZFPCompressionParam() { type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE; rate = 2.0; precision = 0; tolerance = 0.0f; } }; bool FindZFPCompressionParam(ZFPCompressionParam *param, const EXRAttribute *attributes, int num_attributes) { bool foundType = false; for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionType") == 0) && (attributes[i].size == 1)) { param->type = static_cast<int>(attributes[i].value[0]); foundType = true; } } if (!foundType) { return false; } if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) && (attributes[i].size == 8)) { param->rate = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) && (attributes[i].size == 4)) { param->rate = *(reinterpret_cast<int *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) && (attributes[i].size == 8)) { param->tolerance = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else { assert(0); } return false; } // Assume pixel format is FLOAT for all channels. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines, int num_channels, const unsigned char *src, unsigned long src_size, const ZFPCompressionParam &param) { size_t uncompressed_size = dst_width * dst_num_lines * num_channels; if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); } zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((dst_width % 4) == 0); assert((dst_num_lines % 4) == 0); if ((dst_width & 3U) || (dst_num_lines & 3U)) { return false; } field = zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)), zfp_type_float, dst_width, dst_num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimention */ 2, /* write random access */ 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); std::vector<unsigned char> buf(buf_size); memcpy(&buf.at(0), src, src_size); bitstream *stream = stream_open(&buf.at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); size_t image_size = dst_width * dst_num_lines; for (int c = 0; c < num_channels; c++) { // decompress 4x4 pixel block. for (int y = 0; y < dst_num_lines; y += 4) { for (int x = 0; x < dst_width; x += 4) { float fblock[16]; zfp_decode_block_float_2(zfp, fblock); for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { dst[c * image_size + ((y + j) * dst_width + (x + i))] = fblock[j * 4 + i]; } } } } } zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); return true; } // Assume pixel format is FLOAT for all channels. bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize, const float *inPtr, int width, int num_lines, int num_channels, const ZFPCompressionParam &param) { zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((width % 4) == 0); assert((num_lines % 4) == 0); if ((width & 3U) || (num_lines & 3U)) { return false; } // create input array. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)), zfp_type_float, width, num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); outBuf->resize(buf_size); bitstream *stream = stream_open(&outBuf->at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_field_free(field); size_t image_size = width * num_lines; for (int c = 0; c < num_channels; c++) { // compress 4x4 pixel block. for (int y = 0; y < num_lines; y += 4) { for (int x = 0; x < width; x += 4) { float fblock[16]; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { fblock[j * 4 + i] = inPtr[c * image_size + ((y + j) * width + (x + i))]; } } zfp_encode_block_float_2(zfp, fblock); } } } zfp_stream_flush(zfp); (*outSize) = zfp_stream_compressed_size(zfp); zfp_stream_close(zfp); return true; } #endif // // ----------------------------------------------------------------- // // TODO(syoyo): Refactor function arguments. static bool DecodePixelData(/* out */ unsigned char **out_images, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int width, int height, int x_stride, int y, int line_no, int num_lines, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ #if TINYEXR_USE_PIZ if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) { // Invalid input #90 return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>( static_cast<size_t>(width * num_lines) * pixel_data_size)); size_t tmpBufLen = outBuf.size(); bool ret = tinyexr::DecompressPiz( reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen, data_len, static_cast<int>(num_channels), channels, width, num_lines); assert(ret); (void)ret; // For PIZ_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { FP16 hf; // hf.u = line_ptr[u]; // use `cpy` to avoid unaligned memory access when compiler's // optimization is on. tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>(&outBuf.at( v * pixel_data_size * static_cast<size_t>(x_stride) + channel_offset_list[c] * static_cast<size_t>(x_stride))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); } } #else assert(0 && "PIZ is enabled in this build"); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS || compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For ZIP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); tinyexr::DecompressRle(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr, static_cast<unsigned long>(data_len)); // For RLE_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; if (!FindZFPCompressionParam(&zfp_compression_param, attributes, num_attributes)) { assert(0); return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = outBuf.size(); assert(dstLen > 0); tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width, num_lines, num_channels, data_ptr, static_cast<unsigned long>(data_len), zfp_compression_param); // For ZFP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } #else (void)attributes; (void)num_attributes; (void)num_channels; assert(0); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { for (size_t c = 0; c < num_channels; c++) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { const unsigned short *line_ptr = reinterpret_cast<const unsigned short *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *outLine = reinterpret_cast<unsigned short *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); outLine[u] = hf.u; } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // address may not be aliged. use byte-wise copy for safety.#76 // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); tinyexr::FP32 f32 = half_to_float(hf); outLine[u] = f32.f; } } else { assert(0); return false; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { const float *line_ptr = reinterpret_cast<const float *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); unsigned int *outLine = reinterpret_cast<unsigned int *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { if (reinterpret_cast<const unsigned char *>(line_ptr + u) >= (data_ptr + data_len)) { // Corrupsed data? return false; } unsigned int val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } } } } return true; } static void DecodeTiledPixelData( unsigned char **out_images, int *width, int *height, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int data_width, int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x, int tile_size_y, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { assert(tile_offset_x * tile_size_x < data_width); assert(tile_offset_y * tile_size_y < data_height); // Compute actual image size in a tile. if ((tile_offset_x + 1) * tile_size_x >= data_width) { (*width) = data_width - (tile_offset_x * tile_size_x); } else { (*width) = tile_size_x; } if ((tile_offset_y + 1) * tile_size_y >= data_height) { (*height) = data_height - (tile_offset_y * tile_size_y); } else { (*height) = tile_size_y; } // Image size = tile size. DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len, compression_type, line_order, (*width), tile_size_y, /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0, (*height), pixel_data_size, num_attributes, attributes, num_channels, channels, channel_offset_list); } static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list, int *pixel_data_size, size_t *channel_offset, int num_channels, const EXRChannelInfo *channels) { channel_offset_list->resize(static_cast<size_t>(num_channels)); (*pixel_data_size) = 0; (*channel_offset) = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { (*channel_offset_list)[c] = (*channel_offset); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { (*pixel_data_size) += sizeof(unsigned short); (*channel_offset) += sizeof(unsigned short); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { (*pixel_data_size) += sizeof(float); (*channel_offset) += sizeof(float); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { (*pixel_data_size) += sizeof(unsigned int); (*channel_offset) += sizeof(unsigned int); } else { // ??? return false; } } return true; } static unsigned char **AllocateImage(int num_channels, const EXRChannelInfo *channels, const int *requested_pixel_types, int data_width, int data_height) { unsigned char **images = reinterpret_cast<unsigned char **>(static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(num_channels)))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { size_t data_len = static_cast<size_t>(data_width) * static_cast<size_t>(data_height); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { // pixel_data_size += sizeof(unsigned short); // channel_offset += sizeof(unsigned short); // Alloc internal image for half type. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { images[c] = reinterpret_cast<unsigned char *>(static_cast<unsigned short *>( malloc(sizeof(unsigned short) * data_len))); } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // pixel_data_size += sizeof(float); // channel_offset += sizeof(float); images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { // pixel_data_size += sizeof(unsigned int); // channel_offset += sizeof(unsigned int); images[c] = reinterpret_cast<unsigned char *>( static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len))); } else { assert(0); } } return images; } static int ParseEXRHeader(HeaderInfo *info, bool *empty_header, const EXRVersion *version, std::string *err, const unsigned char *buf, size_t size) { const char *marker = reinterpret_cast<const char *>(&buf[0]); if (empty_header) { (*empty_header) = false; } if (version->multipart) { if (size > 0 && marker[0] == '\0') { // End of header list. if (empty_header) { (*empty_header) = true; } return TINYEXR_SUCCESS; } } // According to the spec, the header of every OpenEXR file must contain at // least the following attributes: // // channels chlist // compression compression // dataWindow box2i // displayWindow box2i // lineOrder lineOrder // pixelAspectRatio float // screenWindowCenter v2f // screenWindowWidth float bool has_channels = false; bool has_compression = false; bool has_data_window = false; bool has_display_window = false; bool has_line_order = false; bool has_pixel_aspect_ratio = false; bool has_screen_window_center = false; bool has_screen_window_width = false; info->data_window[0] = 0; info->data_window[1] = 0; info->data_window[2] = 0; info->data_window[3] = 0; info->line_order = 0; // @fixme info->display_window[0] = 0; info->display_window[1] = 0; info->display_window[2] = 0; info->display_window[3] = 0; info->screen_window_center[0] = 0.0f; info->screen_window_center[1] = 0.0f; info->screen_window_width = -1.0f; info->pixel_aspect_ratio = -1.0f; info->tile_size_x = -1; info->tile_size_y = -1; info->tile_level_mode = -1; info->tile_rounding_mode = -1; info->attributes.clear(); // Read attributes size_t orig_size = size; for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) { if (0 == size) { if (err) { (*err) += "Insufficient data size for attributes.\n"; } return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { if (err) { (*err) += "Failed to read attribute.\n"; } return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (version->tiled && attr_name.compare("tiles") == 0) { unsigned int x_size, y_size; unsigned char tile_mode; assert(data.size() == 9); memcpy(&x_size, &data.at(0), sizeof(int)); memcpy(&y_size, &data.at(4), sizeof(int)); tile_mode = data[8]; tinyexr::swap4(&x_size); tinyexr::swap4(&y_size); info->tile_size_x = static_cast<int>(x_size); info->tile_size_y = static_cast<int>(y_size); // mode = levelMode + roundingMode * 16 info->tile_level_mode = tile_mode & 0x3; info->tile_rounding_mode = (tile_mode >> 4) & 0x1; } else if (attr_name.compare("compression") == 0) { bool ok = false; if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) { ok = true; } if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ ok = true; #else if (err) { (*err) = "PIZ compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP ok = true; #else if (err) { (*err) = "ZFP compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (!ok) { if (err) { (*err) = "Unknown compression type."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->compression_type = static_cast<int>(data[0]); has_compression = true; } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!ReadChannelInfo(info->channels, data)) { if (err) { (*err) += "Failed to parse channel info.\n"; } return TINYEXR_ERROR_INVALID_DATA; } if (info->channels.size() < 1) { if (err) { (*err) += "# of channels is zero.\n"; } return TINYEXR_ERROR_INVALID_DATA; } has_channels = true; } else if (attr_name.compare("dataWindow") == 0) { if (data.size() >= 16) { memcpy(&info->data_window[0], &data.at(0), sizeof(int)); memcpy(&info->data_window[1], &data.at(4), sizeof(int)); memcpy(&info->data_window[2], &data.at(8), sizeof(int)); memcpy(&info->data_window[3], &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3])); has_data_window = true; } } else if (attr_name.compare("displayWindow") == 0) { if (data.size() >= 16) { memcpy(&info->display_window[0], &data.at(0), sizeof(int)); memcpy(&info->display_window[1], &data.at(4), sizeof(int)); memcpy(&info->display_window[2], &data.at(8), sizeof(int)); memcpy(&info->display_window[3], &data.at(12), sizeof(int)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[3])); has_display_window = true; } } else if (attr_name.compare("lineOrder") == 0) { if (data.size() >= 1) { info->line_order = static_cast<int>(data[0]); has_line_order = true; } } else if (attr_name.compare("pixelAspectRatio") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->pixel_aspect_ratio)); has_pixel_aspect_ratio = true; } } else if (attr_name.compare("screenWindowCenter") == 0) { if (data.size() >= 8) { memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float)); memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[1])); has_screen_window_center = true; } } else if (attr_name.compare("screenWindowWidth") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->screen_window_width, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_width)); has_screen_window_width = true; } } else if (attr_name.compare("chunkCount") == 0) { if (data.size() >= sizeof(int)) { memcpy(&info->chunk_count, &data.at(0), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->chunk_count)); } } else { // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES) if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) { EXRAttribute attrib; #ifdef _MSC_VER strncpy_s(attrib.name, attr_name.c_str(), 255); strncpy_s(attrib.type, attr_type.c_str(), 255); #else strncpy(attrib.name, attr_name.c_str(), 255); strncpy(attrib.type, attr_type.c_str(), 255); #endif attrib.name[255] = '\0'; attrib.type[255] = '\0'; attrib.size = static_cast<int>(data.size()); attrib.value = static_cast<unsigned char *>(malloc(data.size())); memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0), data.size()); info->attributes.push_back(attrib); } } } // Check if required attributes exist { std::stringstream ss_err; if (!has_compression) { ss_err << "\"compression\" attribute not found in the header." << std::endl; } if (!has_channels) { ss_err << "\"channels\" attribute not found in the header." << std::endl; } if (!has_line_order) { ss_err << "\"lineOrder\" attribute not found in the header." << std::endl; } if (!has_display_window) { ss_err << "\"displayWindow\" attribute not found in the header." << std::endl; } if (!has_data_window) { ss_err << "\"dataWindow\" attribute not found in the header or invalid." << std::endl; } if (!has_pixel_aspect_ratio) { ss_err << "\"pixelAspectRatio\" attribute not found in the header." << std::endl; } if (!has_screen_window_width) { ss_err << "\"screenWindowWidth\" attribute not found in the header." << std::endl; } if (!has_screen_window_center) { ss_err << "\"screenWindowCenter\" attribute not found in the header." << std::endl; } if (!(ss_err.str().empty())) { if (err) { (*err) += ss_err.str(); } return TINYEXR_ERROR_INVALID_HEADER; } } info->header_len = static_cast<unsigned int>(orig_size - size); return TINYEXR_SUCCESS; } // C++ HeaderInfo to C EXRHeader conversion. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) { exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio; exr_header->screen_window_center[0] = info.screen_window_center[0]; exr_header->screen_window_center[1] = info.screen_window_center[1]; exr_header->screen_window_width = info.screen_window_width; exr_header->chunk_count = info.chunk_count; exr_header->display_window[0] = info.display_window[0]; exr_header->display_window[1] = info.display_window[1]; exr_header->display_window[2] = info.display_window[2]; exr_header->display_window[3] = info.display_window[3]; exr_header->data_window[0] = info.data_window[0]; exr_header->data_window[1] = info.data_window[1]; exr_header->data_window[2] = info.data_window[2]; exr_header->data_window[3] = info.data_window[3]; exr_header->line_order = info.line_order; exr_header->compression_type = info.compression_type; exr_header->tile_size_x = info.tile_size_x; exr_header->tile_size_y = info.tile_size_y; exr_header->tile_level_mode = info.tile_level_mode; exr_header->tile_rounding_mode = info.tile_rounding_mode; exr_header->num_channels = static_cast<int>(info.channels.size()); exr_header->channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { #ifdef _MSC_VER strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #else strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #endif // manually add '\0' for safety. exr_header->channels[c].name[255] = '\0'; exr_header->channels[c].pixel_type = info.channels[c].pixel_type; exr_header->channels[c].p_linear = info.channels[c].p_linear; exr_header->channels[c].x_sampling = info.channels[c].x_sampling; exr_header->channels[c].y_sampling = info.channels[c].y_sampling; } exr_header->pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->pixel_types[c] = info.channels[c].pixel_type; } // Initially fill with values of `pixel_types` exr_header->requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->requested_pixel_types[c] = info.channels[c].pixel_type; } exr_header->num_custom_attributes = static_cast<int>(info.attributes.size()); if (exr_header->num_custom_attributes > 0) { // TODO(syoyo): Report warning when # of attributes exceeds // `TINYEXR_MAX_CUSTOM_ATTRIBUTES` if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) { exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES; } exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc( sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes))); for (size_t i = 0; i < info.attributes.size(); i++) { memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name, 256); memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type, 256); exr_header->custom_attributes[i].size = info.attributes[i].size; // Just copy poiner exr_header->custom_attributes[i].value = info.attributes[i].value; } } else { exr_header->custom_attributes = NULL; } exr_header->header_len = info.header_len; } static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header, const std::vector<tinyexr::tinyexr_uint64> &offsets, const unsigned char *head, const size_t size, std::string *err) { int num_channels = exr_header->num_channels; int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1; int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1; size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels)) { if (err) { (*err) += "Failed to compute channel layout.\n"; } return TINYEXR_ERROR_INVALID_DATA; } bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety. if (exr_header->tiled) { size_t num_tiles = offsets.size(); // = # of blocks exr_image->tiles = static_cast<EXRTile *>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) { // Allocate memory for each tile. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, exr_header->tile_size_x, exr_header->tile_size_y); // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) if (offsets[tile_idx] + sizeof(int) * 5 > size) { if (err) { (*err) += "Insufficient data size.\n"; } return TINYEXR_ERROR_INVALID_DATA; } size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]); int tile_coordinates[4]; memcpy(tile_coordinates, data_ptr, sizeof(int) * 4); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[3])); // @todo{ LoD } if (tile_coordinates[2] != 0) { return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } if (tile_coordinates[3] != 0) { return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } int data_len; memcpy(&data_len, data_ptr + 16, sizeof(int)); // 16 = sizeof(tile_coordinates) tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len < 4 || size_t(data_len) > data_size) { if (err) { (*err) += "Insufficient data length.\n"; } return TINYEXR_ERROR_INVALID_DATA; } // Move to data addr: 20 = 16 + 4; data_ptr += 20; tinyexr::DecodeTiledPixelData( exr_image->tiles[tile_idx].images, &(exr_image->tiles[tile_idx].width), &(exr_image->tiles[tile_idx].height), exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list); exr_image->tiles[tile_idx].offset_x = tile_coordinates[0]; exr_image->tiles[tile_idx].offset_y = tile_coordinates[1]; exr_image->tiles[tile_idx].level_x = tile_coordinates[2]; exr_image->tiles[tile_idx].level_y = tile_coordinates[3]; exr_image->num_tiles = static_cast<int>(num_tiles); } } else { // scanline format exr_image->images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); #ifdef _OPENMP #pragma omp parallel for #endif for (int y = 0; y < static_cast<int>(num_blocks); y++) { size_t y_idx = static_cast<size_t>(y); if (offsets[y_idx] + sizeof(int) * 2 > size) { invalid_data = true; } else { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed or compressed) size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y_idx]); int line_no; memcpy(&line_no, data_ptr, sizeof(int)); int data_len; memcpy(&data_len, data_ptr + 4, sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (size_t(data_len) > data_size) { invalid_data = true; } else { int end_line_no = (std::min)(line_no + num_scanline_blocks, (exr_header->data_window[3] + 1)); int num_lines = end_line_no - line_no; // assert(num_lines > 0); if (num_lines <= 0) { invalid_data = true; } else { // Move to data addr: 8 = 4 + 4; data_ptr += 8; // Adjust line_no with data_window.bmin.y line_no -= exr_header->data_window[1]; if (line_no < 0) { invalid_data = true; } else { if (!tinyexr::DecodePixelData( exr_image->images, exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, data_width, y, line_no, num_lines, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list)) { invalid_data = true; } } } } } } // omp parallel } if (invalid_data) { return TINYEXR_ERROR_INVALID_DATA; } // Overwrite `pixel_type` with `requested_pixel_type`. { for (int c = 0; c < exr_header->num_channels; c++) { exr_header->pixel_types[c] = exr_header->requested_pixel_types[c]; } } { exr_image->num_channels = num_channels; exr_image->width = data_width; exr_image->height = data_height; } return TINYEXR_SUCCESS; } static bool ReconstructLineOffsets( std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n, const unsigned char *head, const unsigned char *marker, const size_t size) { assert(head < marker); assert(offsets->size() == n); for (size_t i = 0; i < n; i++) { size_t offset = static_cast<size_t>(marker - head); // Offset should not exceed whole EXR file/data size. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) { return false; } int y; unsigned int data_len; memcpy(&y, marker, sizeof(int)); memcpy(&data_len, marker + 4, sizeof(unsigned int)); if (data_len >= size) { return false; } tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); (*offsets)[i] = offset; marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len) } return true; } static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *head, const unsigned char *marker, const size_t size, const char **err) { if (exr_image == NULL || exr_header == NULL || head == NULL || marker == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0]; if (data_width >= std::numeric_limits<int>::max()) { // Issue 63 tinyexr::SetErrorMessage("Invalid data window value", err); return TINYEXR_ERROR_INVALID_DATA; } data_width++; int data_height = exr_header->data_window[3] - exr_header->data_window[1]; if (data_height >= std::numeric_limits<int>::max()) { tinyexr::SetErrorMessage("Invalid data height value", err); return TINYEXR_ERROR_INVALID_DATA; } data_height++; if ((data_width < 0) || (data_height < 0)) { tinyexr::SetErrorMessage("data window or data height is negative.", err); return TINYEXR_ERROR_INVALID_DATA; } // Read offset tables. size_t num_blocks = 0; if (exr_header->chunk_count > 0) { // Use `chunkCount` attribute. num_blocks = static_cast<size_t>(exr_header->chunk_count); } else if (exr_header->tiled) { // @todo { LoD } size_t num_x_tiles = static_cast<size_t>(data_width) / static_cast<size_t>(exr_header->tile_size_x); if (num_x_tiles * static_cast<size_t>(exr_header->tile_size_x) < static_cast<size_t>(data_width)) { num_x_tiles++; } size_t num_y_tiles = static_cast<size_t>(data_height) / static_cast<size_t>(exr_header->tile_size_y); if (num_y_tiles * static_cast<size_t>(exr_header->tile_size_y) < static_cast<size_t>(data_height)) { num_y_tiles++; } num_blocks = num_x_tiles * num_y_tiles; } else { num_blocks = static_cast<size_t>(data_height) / static_cast<size_t>(num_scanline_blocks); if (num_blocks * static_cast<size_t>(num_scanline_blocks) < static_cast<size_t>(data_height)) { num_blocks++; } } std::vector<tinyexr::tinyexr_uint64> offsets(num_blocks); for (size_t y = 0; y < num_blocks; y++) { tinyexr::tinyexr_uint64 offset; // Issue #81 if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) { tinyexr::SetErrorMessage("Insufficient data size in offset table.", err); return TINYEXR_ERROR_INVALID_DATA; } memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } marker += sizeof(tinyexr::tinyexr_uint64); // = 8 offsets[y] = offset; } // If line offsets are invalid, we try to reconstruct it. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details. for (size_t y = 0; y < num_blocks; y++) { if (offsets[y] <= 0) { // TODO(syoyo) Report as warning? // if (err) { // stringstream ss; // ss << "Incomplete lineOffsets." << std::endl; // (*err) += ss.str(); //} bool ret = ReconstructLineOffsets(&offsets, num_blocks, head, marker, size); if (ret) { // OK break; } else { tinyexr::SetErrorMessage( "Cannot reconstruct lineOffset table in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } } } { std::string e; int ret = DecodeChunk(exr_image, exr_header, offsets, head, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } // release memory(if exists) if ((exr_header->num_channels > 0) && exr_image && exr_image->images) { for (size_t c = 0; c < size_t(exr_header->num_channels); c++) { if (exr_image->images[c]) { free(exr_image->images[c]); exr_image->images[c] = NULL; } } free(exr_image->images); exr_image->images = NULL; } } return ret; } } } // namespace tinyexr int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err) { if (out_rgba == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); InitEXRImage(&exr_image); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage("Invalid EXR header.", err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } { int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } { int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } if ((idxA == 0) && (idxR == -1) && (idxG == -1) && (idxB == -1)) { // Alpha channel only. if (exr_header.tiled) { // todo.implement this } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } else { // Assume RGB(A) if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } FreeEXRHeader(&exr_header); return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } FreeEXRHeader(&exr_header); return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @todo { free exr_image } FreeEXRHeader(&exr_header); return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_header == NULL) { tinyexr::SetErrorMessage( "Invalid argument. `memory` or `exr_header` argument is null in " "ParseEXRHeaderFromMemory()", err); // Invalid argument return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Insufficient header/data size.\n", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; tinyexr::HeaderInfo info; info.clear(); std::string err_str; int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { if (err && !err_str.empty()) { tinyexr::SetErrorMessage(err_str, err); } } ConvertHeader(exr_header, info); // transfoer `tiled` from version. exr_header->tiled = version->tiled; return ret; } int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err) { if (out_rgba == NULL || memory == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); int ret = ParseEXRVersionFromMemory(&exr_version, memory, size); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage("Failed to parse EXR version", err); return ret; } ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } InitEXRImage(&exr_image); ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize < 16) { tinyexr::SetErrorMessage("File size too short " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize, err); } int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *memory, const size_t size, const char **err) { if (exr_image == NULL || memory == NULL || (size < tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } const unsigned char *head = memory; const unsigned char *marker = reinterpret_cast<const unsigned char *>( memory + exr_header->header_len + 8); // +8 for magic number + version header. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size, err); } size_t SaveEXRImageToMemory(const EXRImage *exr_image, const EXRHeader *exr_header, unsigned char **memory_out, const char **err) { if (exr_image == NULL || memory_out == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToMemory", err); return 0; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return 0; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return 0; } #endif #if TINYEXR_USE_ZFP for (size_t i = 0; i < static_cast<size_t>(exr_header->num_channels); i++) { if (exr_header->requested_pixel_types[i] != TINYEXR_PIXELTYPE_FLOAT) { tinyexr::SetErrorMessage("Pixel type must be FLOAT for ZFP compression", err); return 0; } } #endif std::vector<unsigned char> memory; // Header { const char header[] = {0x76, 0x2f, 0x31, 0x01}; memory.insert(memory.end(), header, header + 4); } // Version, scanline. { char marker[] = {2, 0, 0, 0}; /* @todo if (exr_header->tiled) { marker[1] |= 0x2; } if (exr_header->long_name) { marker[1] |= 0x4; } if (exr_header->non_image) { marker[1] |= 0x8; } if (exr_header->multipart) { marker[1] |= 0x10; } */ memory.insert(memory.end(), marker, marker + 4); } int num_scanlines = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanlines = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanlines = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanlines = 16; } // Write attributes. std::vector<tinyexr::ChannelInfo> channels; { std::vector<unsigned char> data; for (int c = 0; c < exr_header->num_channels; c++) { tinyexr::ChannelInfo info; info.p_linear = 0; info.pixel_type = exr_header->requested_pixel_types[c]; info.x_sampling = 1; info.y_sampling = 1; info.name = std::string(exr_header->channels[c].name); channels.push_back(info); } tinyexr::WriteChannelInfo(data, channels); tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0), static_cast<int>(data.size())); } { int comp = exr_header->compression_type; tinyexr::swap4(reinterpret_cast<unsigned int *>(&comp)); tinyexr::WriteAttributeToMemory( &memory, "compression", "compression", reinterpret_cast<const unsigned char *>(&comp), 1); } { int data[4] = {0, 0, exr_image->width - 1, exr_image->height - 1}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[3])); tinyexr::WriteAttributeToMemory( &memory, "dataWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); tinyexr::WriteAttributeToMemory( &memory, "displayWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); } { unsigned char line_order = 0; // @fixme { read line_order from EXRHeader } tinyexr::WriteAttributeToMemory(&memory, "lineOrder", "lineOrder", &line_order, 1); } { float aspectRatio = 1.0f; tinyexr::swap4(reinterpret_cast<unsigned int *>(&aspectRatio)); tinyexr::WriteAttributeToMemory( &memory, "pixelAspectRatio", "float", reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float)); } { float center[2] = {0.0f, 0.0f}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[1])); tinyexr::WriteAttributeToMemory( &memory, "screenWindowCenter", "v2f", reinterpret_cast<const unsigned char *>(center), 2 * sizeof(float)); } { float w = static_cast<float>(exr_image->width); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::WriteAttributeToMemory(&memory, "screenWindowWidth", "float", reinterpret_cast<const unsigned char *>(&w), sizeof(float)); } // Custom attributes if (exr_header->num_custom_attributes > 0) { for (int i = 0; i < exr_header->num_custom_attributes; i++) { tinyexr::WriteAttributeToMemory( &memory, exr_header->custom_attributes[i].name, exr_header->custom_attributes[i].type, reinterpret_cast<const unsigned char *>( exr_header->custom_attributes[i].value), exr_header->custom_attributes[i].size); } } { // end of header unsigned char e = 0; memory.push_back(e); } int num_blocks = exr_image->height / num_scanlines; if (num_blocks * num_scanlines < exr_image->height) { num_blocks++; } std::vector<tinyexr::tinyexr_uint64> offsets(static_cast<size_t>(num_blocks)); size_t headerSize = memory.size(); tinyexr::tinyexr_uint64 offset = headerSize + static_cast<size_t>(num_blocks) * sizeof( tinyexr::tinyexr_int64); // sizeof(header) + sizeof(offsetTable) std::vector<std::vector<unsigned char> > data_list( static_cast<size_t>(num_blocks)); std::vector<size_t> channel_offset_list( static_cast<size_t>(exr_header->num_channels)); int pixel_data_size = 0; size_t channel_offset = 0; for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { channel_offset_list[c] = channel_offset; if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { pixel_data_size += sizeof(unsigned short); channel_offset += sizeof(unsigned short); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { pixel_data_size += sizeof(float); channel_offset += sizeof(float); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { pixel_data_size += sizeof(unsigned int); channel_offset += sizeof(unsigned int); } else { assert(0); } } #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; // Use ZFP compression parameter from custom attributes(if such a parameter // exists) { bool ret = tinyexr::FindZFPCompressionParam( &zfp_compression_param, exr_header->custom_attributes, exr_header->num_custom_attributes); if (!ret) { // Use predefined compression parameter. zfp_compression_param.type = 0; zfp_compression_param.rate = 2; } } #endif // Use signed int since some OpenMP compiler doesn't allow unsigned type for // `parallel for` #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_blocks; i++) { size_t ii = static_cast<size_t>(i); int start_y = num_scanlines * i; int endY = (std::min)(num_scanlines * (i + 1), exr_image->height); int h = endY - start_y; std::vector<unsigned char> buf( static_cast<size_t>(exr_image->width * h * pixel_data_size)); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP16 h16; h16.u = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP32 f32 = half_to_float(h16); tinyexr::swap4(reinterpret_cast<unsigned int *>(&f32.f)); // line_ptr[x] = f32.f; tinyexr::cpy4(line_ptr + x, &(f32.f)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned short val = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap2(&val); // line_ptr[x] = val; tinyexr::cpy2(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP32 f32; f32.f = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP16 h16; h16 = float_to_half_full(f32); tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u)); // line_ptr[x] = h16.u; tinyexr::cpy2(line_ptr + x, &(h16.u)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { float val = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned int val = reinterpret_cast<unsigned int **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(&val); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } } if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(buf.size()); memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), buf.begin(), buf.begin() + data_len); } else if ((exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #if TINYEXR_USE_MINIZ std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound( static_cast<unsigned long>(buf.size()))); #else std::vector<unsigned char> block( compressBound(static_cast<uLong>(buf.size()))); #endif tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressZip(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // (buf.size() * 3) / 2 would be enough. std::vector<unsigned char> block((buf.size() * 3) / 2); tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressRle(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ unsigned int bufLen = 8192 + static_cast<unsigned int>( 2 * static_cast<unsigned int>( buf.size())); // @fixme { compute good bound. } std::vector<unsigned char> block(bufLen); unsigned int outSize = static_cast<unsigned int>(block.size()); CompressPiz(&block.at(0), &outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), buf.size(), channels, exr_image->width, h); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP std::vector<unsigned char> block; unsigned int outSize; tinyexr::CompressZfp( &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)), exr_image->width, h, exr_header->num_channels, zfp_compression_param); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else { assert(0); } } // omp parallel for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { offsets[i] = offset; tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i])); offset += data_list[i].size(); } size_t totalSize = static_cast<size_t>(offset); { memory.insert( memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)), reinterpret_cast<unsigned char *>(&offsets.at(0)) + sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks)); } if ( memory.size() == 0 ) { tinyexr::SetErrorMessage("Output memory size is zero", err); return 0; } (*memory_out) = static_cast<unsigned char *>(malloc(totalSize)); memcpy((*memory_out), &memory.at(0), memory.size()); unsigned char *memory_ptr = *memory_out + memory.size(); for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { memcpy(memory_ptr, &data_list[i].at(0), data_list[i].size()); memory_ptr += data_list[i].size(); } return totalSize; // OK } int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL || filename == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "wb"); #else FILE *fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err); if (mem_size == 0) { return TINYEXR_ERROR_SERIALZATION_FAILED; } size_t written_size = 0; if ((mem_size > 0) && mem) { written_size = fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); if (written_size != mem_size) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } return TINYEXR_SUCCESS; } int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) { if (deep_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _MSC_VER FILE *fp = NULL; errno_t errcode = fopen_s(&fp, filename, "rb"); if ((0 != errcode) || (!fp)) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else FILE *fp = fopen(filename, "rb"); if (!fp) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #endif size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize == 0) { fclose(fp); tinyexr::SetErrorMessage("File size is zero : " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); (void)ret; } fclose(fp); const char *head = &buf[0]; const char *marker = &buf[0]; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { tinyexr::SetErrorMessage("Invalid magic number", err); return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } // Version, scanline. { // ver 2.0, scanline, deep bit on(0x800) // must be [2, 0, 0, 0] if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) { tinyexr::SetErrorMessage("Unsupported version or scanline", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } marker += 4; } int dx = -1; int dy = -1; int dw = -1; int dh = -1; int num_scanline_blocks = 1; // 16 for ZIP compression. int compression_type = -1; int num_channels = -1; std::vector<tinyexr::ChannelInfo> channels; // Read attributes size_t size = filesize - tinyexr::kEXRVersionSize; for (;;) { if (0 == size) { return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { marker++; size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (attr_name.compare("compression") == 0) { compression_type = data[0]; if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) { std::stringstream ss; ss << "Unsupported compression type : " << compression_type; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!tinyexr::ReadChannelInfo(channels, data)) { tinyexr::SetErrorMessage("Failed to parse channel info", err); return TINYEXR_ERROR_INVALID_DATA; } num_channels = static_cast<int>(channels.size()); if (num_channels < 1) { tinyexr::SetErrorMessage("Invalid channels format", err); return TINYEXR_ERROR_INVALID_DATA; } } else if (attr_name.compare("dataWindow") == 0) { memcpy(&dx, &data.at(0), sizeof(int)); memcpy(&dy, &data.at(4), sizeof(int)); memcpy(&dw, &data.at(8), sizeof(int)); memcpy(&dh, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dx)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dy)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dw)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dh)); } else if (attr_name.compare("displayWindow") == 0) { int x; int y; int w; int h; memcpy(&x, &data.at(0), sizeof(int)); memcpy(&y, &data.at(4), sizeof(int)); memcpy(&w, &data.at(8), sizeof(int)); memcpy(&h, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&h)); } } assert(dx >= 0); assert(dy >= 0); assert(dw >= 0); assert(dh >= 0); assert(num_channels >= 1); int data_width = dw - dx + 1; int data_height = dh - dy + 1; std::vector<float> image( static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA // Read offset tables. int num_blocks = data_height / num_scanline_blocks; if (num_blocks * num_scanline_blocks < data_height) { num_blocks++; } std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks)); for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { tinyexr::tinyexr_int64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset)); marker += sizeof(tinyexr::tinyexr_int64); // = 8 offsets[y] = offset; } #if TINYEXR_USE_PIZ if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) || (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) { #else if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #endif // OK } else { tinyexr::SetErrorMessage("Unsupported compression format", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } deep_image->image = static_cast<float ***>( malloc(sizeof(float **) * static_cast<size_t>(num_channels))); for (int c = 0; c < num_channels; c++) { deep_image->image[c] = static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { } } deep_image->offset_table = static_cast<int **>( malloc(sizeof(int *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { deep_image->offset_table[y] = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(data_width))); } for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y]); // int: y coordinate // int64: packed size of pixel offset table // int64: packed size of sample data // int64: unpacked size of sample data // compressed pixel offset table // compressed sample data int line_no; tinyexr::tinyexr_int64 packedOffsetTableSize; tinyexr::tinyexr_int64 packedSampleDataSize; tinyexr::tinyexr_int64 unpackedSampleDataSize; memcpy(&line_no, data_ptr, sizeof(int)); memcpy(&packedOffsetTableSize, data_ptr + 4, sizeof(tinyexr::tinyexr_int64)); memcpy(&packedSampleDataSize, data_ptr + 12, sizeof(tinyexr::tinyexr_int64)); memcpy(&unpackedSampleDataSize, data_ptr + 20, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize)); std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width)); // decode pixel offset table. { unsigned long dstLen = static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int)); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)), &dstLen, data_ptr + 28, static_cast<unsigned long>(packedOffsetTableSize))) { return false; } assert(dstLen == pixelOffsetTable.size() * sizeof(int)); for (size_t i = 0; i < static_cast<size_t>(data_width); i++) { deep_image->offset_table[y][i] = pixelOffsetTable[i]; } } std::vector<unsigned char> sample_data( static_cast<size_t>(unpackedSampleDataSize)); // decode sample data. { unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize); if (dstLen) { if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen, data_ptr + 28 + packedOffsetTableSize, static_cast<unsigned long>(packedSampleDataSize))) { return false; } assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize)); } } // decode sample int sampleSize = -1; std::vector<int> channel_offset_list(static_cast<size_t>(num_channels)); { int channel_offset = 0; for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) { channel_offset_list[i] = channel_offset; if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT channel_offset += 4; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half channel_offset += 2; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // float channel_offset += 4; } else { assert(0); } } sampleSize = channel_offset; } assert(sampleSize >= 2); assert(static_cast<size_t>( pixelOffsetTable[static_cast<size_t>(data_width - 1)] * sampleSize) == sample_data.size()); int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize; // // Alloc memory // // // pixel data is stored as image[channels][pixel_samples] // { tinyexr::tinyexr_uint64 data_offset = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { deep_image->image[c][y] = static_cast<float *>( malloc(sizeof(float) * static_cast<size_t>(samples_per_line))); if (channels[c].pixel_type == 0) { // UINT for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { unsigned int ui; unsigned int *src_ptr = reinterpret_cast<unsigned int *>( &sample_data.at(size_t(data_offset) + x * sizeof(int))); tinyexr::cpy4(&ui, src_ptr); deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme } data_offset += sizeof(unsigned int) * static_cast<size_t>(samples_per_line); } else if (channels[c].pixel_type == 1) { // half for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { tinyexr::FP16 f16; const unsigned short *src_ptr = reinterpret_cast<unsigned short *>( &sample_data.at(size_t(data_offset) + x * sizeof(short))); tinyexr::cpy2(&(f16.u), src_ptr); tinyexr::FP32 f32 = half_to_float(f16); deep_image->image[c][y][x] = f32.f; } data_offset += sizeof(short) * static_cast<size_t>(samples_per_line); } else { // float for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { float f; const float *src_ptr = reinterpret_cast<float *>( &sample_data.at(size_t(data_offset) + x * sizeof(float))); tinyexr::cpy4(&f, src_ptr); deep_image->image[c][y][x] = f; } data_offset += sizeof(float) * static_cast<size_t>(samples_per_line); } } } } // y deep_image->width = data_width; deep_image->height = data_height; deep_image->channel_names = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(num_channels))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { #ifdef _WIN32 deep_image->channel_names[c] = _strdup(channels[c].name.c_str()); #else deep_image->channel_names[c] = strdup(channels[c].name.c_str()); #endif } deep_image->num_channels = num_channels; return TINYEXR_SUCCESS; } void InitEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return; } exr_image->width = 0; exr_image->height = 0; exr_image->num_channels = 0; exr_image->images = NULL; exr_image->tiles = NULL; exr_image->num_tiles = 0; } void FreeEXRErrorMessage(const char *msg) { if (msg) { free(reinterpret_cast<void *>(const_cast<char *>(msg))); } return; } void InitEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return; } memset(exr_header, 0, sizeof(EXRHeader)); } int FreeEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->channels) { free(exr_header->channels); } if (exr_header->pixel_types) { free(exr_header->pixel_types); } if (exr_header->requested_pixel_types) { free(exr_header->requested_pixel_types); } for (int i = 0; i < exr_header->num_custom_attributes; i++) { if (exr_header->custom_attributes[i].value) { free(exr_header->custom_attributes[i].value); } } if (exr_header->custom_attributes) { free(exr_header->custom_attributes); } return TINYEXR_SUCCESS; } int FreeEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->images && exr_image->images[i]) { free(exr_image->images[i]); } } if (exr_image->images) { free(exr_image->images); } if (exr_image->tiles) { for (int tid = 0; tid < exr_image->num_tiles; tid++) { for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) { free(exr_image->tiles[tid].images[i]); } } if (exr_image->tiles[tid].images) { free(exr_image->tiles[tid].images); } } free(exr_image->tiles); } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_header == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("fread() error on " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize, err); } int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_headers == NULL || num_headers == NULL || exr_version == NULL) { // Invalid argument tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Data size too short", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; std::vector<tinyexr::HeaderInfo> infos; for (;;) { tinyexr::HeaderInfo info; info.clear(); std::string err_str; bool empty_header = false; int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage(err_str, err); return ret; } if (empty_header) { marker += 1; // skip '\0' break; } // `chunkCount` must exist in the header. if (info.chunk_count == 0) { tinyexr::SetErrorMessage( "`chunkCount' attribute is not found in the header.", err); return TINYEXR_ERROR_INVALID_DATA; } infos.push_back(info); // move to next header. marker += info.header_len; size -= info.header_len; } // allocate memory for EXRHeader and create array of EXRHeader pointers. (*exr_headers) = static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size())); for (size_t i = 0; i < infos.size(); i++) { EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader))); ConvertHeader(exr_header, infos[i]); // transfoer `tiled` from version. exr_header->tiled = exr_version->tiled; (*exr_headers)[i] = exr_header; } (*num_headers) = static_cast<int>(infos.size()); return TINYEXR_SUCCESS; } int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_headers == NULL || num_headers == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromFile()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRMultipartHeaderFromMemory( exr_headers, num_headers, exr_version, &buf.at(0), filesize, err); } int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size) { if (version == NULL || memory == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } version->tiled = false; version->long_name = false; version->non_image = false; version->multipart = false; // Parse version header. { // must be 2 if (marker[0] != 2) { return TINYEXR_ERROR_INVALID_EXR_VERSION; } if (version == NULL) { return TINYEXR_SUCCESS; // May OK } version->version = 2; if (marker[1] & 0x2) { // 9th bit version->tiled = true; } if (marker[1] & 0x4) { // 10th bit version->long_name = true; } if (marker[1] & 0x8) { // 11th bit version->non_image = true; // (deep image) } if (marker[1] & 0x10) { // 12th bit version->multipart = true; } } return TINYEXR_SUCCESS; } int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) { if (filename == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t file_size; // Compute size fseek(fp, 0, SEEK_END); file_size = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (file_size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } unsigned char buf[tinyexr::kEXRVersionSize]; size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp); fclose(fp); if (ret != tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize); } int LoadEXRMultipartImageFromMemory(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromMemory()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } // compute total header size. size_t total_header_size = 0; for (unsigned int i = 0; i < num_parts; i++) { if (exr_headers[i]->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } total_header_size += exr_headers[i]->header_len; } const char *marker = reinterpret_cast<const char *>( memory + total_header_size + 4 + 4); // +8 for magic number and version header. marker += 1; // Skip empty header. // NOTE 1: // In multipart image, There is 'part number' before chunk data. // 4 byte : part number // 4+ : chunk // // NOTE 2: // EXR spec says 'part number' is 'unsigned long' but actually this is // 'unsigned int(4 bytes)' in OpenEXR implementation... // http://www.openexr.com/openexrfilelayout.pdf // Load chunk offset table. std::vector<std::vector<tinyexr::tinyexr_uint64> > chunk_offset_table_list; for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> offset_table( static_cast<size_t>(exr_headers[i]->chunk_count)); for (size_t c = 0; c < offset_table.size(); c++) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, 8); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } offset_table[c] = offset + 4; // +4 to skip 'part number' marker += 8; } chunk_offset_table_list.push_back(offset_table); } // Decode image. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> &offset_table = chunk_offset_table_list[i]; // First check 'part number' is identitical to 'i' for (size_t c = 0; c < offset_table.size(); c++) { const unsigned char *part_number_addr = memory + offset_table[c] - 4; // -4 to move to 'part number' field. unsigned int part_no; memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4 tinyexr::swap4(&part_no); if (part_no != i) { tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } } std::string e; int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table, memory, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } return ret; } } return TINYEXR_SUCCESS; } int LoadEXRMultipartImageFromFile(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts, &buf.at(0), filesize, err); } int SaveEXR(const float *data, int width, int height, int components, const int save_as_fp16, const char *outfilename, const char **err) { if ((components == 1) || components == 3 || components == 4) { // OK } else { std::stringstream ss; ss << "Unsupported component value : " << components << std::endl; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRHeader header; InitEXRHeader(&header); if ((width < 16) && (height < 16)) { // No compression for small image. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE; } else { header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP; } EXRImage image; InitEXRImage(&image); image.num_channels = components; std::vector<float> images[4]; if (components == 1) { images[0].resize(static_cast<size_t>(width * height)); memcpy(images[0].data(), data, sizeof(float) * size_t(width * height)); } else { images[0].resize(static_cast<size_t>(width * height)); images[1].resize(static_cast<size_t>(width * height)); images[2].resize(static_cast<size_t>(width * height)); images[3].resize(static_cast<size_t>(width * height)); // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers for (size_t i = 0; i < static_cast<size_t>(width * height); i++) { images[0][i] = data[static_cast<size_t>(components) * i + 0]; images[1][i] = data[static_cast<size_t>(components) * i + 1]; images[2][i] = data[static_cast<size_t>(components) * i + 2]; if (components == 4) { images[3][i] = data[static_cast<size_t>(components) * i + 3]; } } } float *image_ptr[4] = {0, 0, 0, 0}; if (components == 4) { image_ptr[0] = &(images[3].at(0)); // A image_ptr[1] = &(images[2].at(0)); // B image_ptr[2] = &(images[1].at(0)); // G image_ptr[3] = &(images[0].at(0)); // R } else if (components == 3) { image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R } else if (components == 1) { image_ptr[0] = &(images[0].at(0)); // A } image.images = reinterpret_cast<unsigned char **>(image_ptr); image.width = width; image.height = height; header.num_channels = components; header.channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels))); // Must be (A)BGR order, since most of EXR viewers expect this channel order. if (components == 4) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); strncpy_s(header.channels[1].name, "B", 255); strncpy_s(header.channels[2].name, "G", 255); strncpy_s(header.channels[3].name, "R", 255); #else strncpy(header.channels[0].name, "A", 255); strncpy(header.channels[1].name, "B", 255); strncpy(header.channels[2].name, "G", 255); strncpy(header.channels[3].name, "R", 255); #endif header.channels[0].name[strlen("A")] = '\0'; header.channels[1].name[strlen("B")] = '\0'; header.channels[2].name[strlen("G")] = '\0'; header.channels[3].name[strlen("R")] = '\0'; } else if (components == 3) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "B", 255); strncpy_s(header.channels[1].name, "G", 255); strncpy_s(header.channels[2].name, "R", 255); #else strncpy(header.channels[0].name, "B", 255); strncpy(header.channels[1].name, "G", 255); strncpy(header.channels[2].name, "R", 255); #endif header.channels[0].name[strlen("B")] = '\0'; header.channels[1].name[strlen("G")] = '\0'; header.channels[2].name[strlen("R")] = '\0'; } else { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); #else strncpy(header.channels[0].name, "A", 255); #endif header.channels[0].name[strlen("A")] = '\0'; } header.pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); header.requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image if (save_as_fp16 > 0) { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format } else { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e. // no precision reduction) } } int ret = SaveEXRImageToFile(&image, &header, outfilename, err); if (ret != TINYEXR_SUCCESS) { return ret; } free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); return ret; } #ifdef __clang__ // zero-as-null-ppinter-constant #pragma clang diagnostic pop #endif #endif // TINYEXR_IMPLEMENTATION_DEIFNED #endif // TINYEXR_IMPLEMENTATION
integrator.h
#ifndef _INTEGRATOR_H #define _INTEGRATOR_H #include <omp.h> #include <optional> #include "camera.h" #include "core.h" #include "image.h" #include "scene.h" class Integrator { protected: const std::shared_ptr<Camera> camera; public: Integrator(const std::shared_ptr<Camera>& camera) : camera(camera) {} // render scene virtual void render(const Scene& scene, Sampler& sampler, Image& image) = 0; // compute cosine term // NOTE: need to account for the asymmetry of BSDF when photon tracing // https://pbr-book.org/3ed-2018/Light_Transport_III_Bidirectional_Methods/The_Path-Space_Measurement_Equation#x3-Non-symmetryDuetoShadingNormals // Veach, Eric. Robust Monte Carlo methods for light transport simulation. // Stanford University, 1998. Section 5.3 static float cosTerm(const Vec3f& wo, const Vec3f& wi, const SurfaceInfo& surfaceInfo, const TransportDirection& transport_dir) { const float wi_ns = dot(wi, surfaceInfo.shadingNormal); const float wi_ng = dot(wi, surfaceInfo.geometricNormal); const float wo_ns = dot(wo, surfaceInfo.shadingNormal); const float wo_ng = dot(wo, surfaceInfo.geometricNormal); // prevent light leaks if (wi_ng * wi_ns <= 0 || wo_ng * wo_ns <= 0) { return 0; } if (transport_dir == TransportDirection::FROM_CAMERA) { return std::abs(wi_ns); } else if (transport_dir == TransportDirection::FROM_LIGHT) { return std::abs(wo_ns) * std::abs(wi_ng) / std::abs(wo_ng); } else { spdlog::error("[Integrator] invalid transport direction"); std::exit(EXIT_FAILURE); } } static bool isTransmitted(const Vec3f& wo, const Vec3f& wi, const Vec3f& n) { return (dot(wo, n) < 0) != (dot(wi, n) < 0); } static bool isEntered(const Vec3f& wi, const Vec3f& n) { return dot(wi, n) < 0; } // push or pop medium static void updateMedium(Ray& ray, const Vec3f& wi, const IntersectInfo& info) { if (isTransmitted(-ray.direction, wi, info.surfaceInfo.shadingNormal)) { if (isEntered(wi, info.surfaceInfo.shadingNormal)) { if (info.hitPrimitive->hasMedium()) { ray.pushMedium(info.hitPrimitive->getMedium()); } } else { ray.popMedium(); } } } static Vec3f sampleDirectionToLight(const Scene& scene, const Vec3f& pos, Sampler& sampler, Vec3f& dir, float& dist_to_light, float& pdf) { // sample light float light_choose_prob; const std::shared_ptr<Light> light = scene.sampleLight(sampler, light_choose_prob); // sample point on light float light_pos_pdf; const SurfaceInfo light_surf = light->samplePoint(sampler, light_pos_pdf); dir = normalize(light_surf.position - pos); dist_to_light = length(light_surf.position - pos); // convert point pdf to directional pdf const float cos = std::abs(dot(-dir, light_surf.shadingNormal)); pdf = light_choose_prob * (dist_to_light * dist_to_light / cos * light_pos_pdf); return light->Le(light_surf, -dir); } }; // abstraction of path based integrator class PathIntegrator : public Integrator { private: // number of samples in each pixel const uint32_t n_samples; public: // compute radiance coming from the given ray virtual Vec3f integrate(const Ray& ray, const Scene& scene, Sampler& sampler) const = 0; PathIntegrator(const std::shared_ptr<Camera>& camera, uint32_t n_samples) : Integrator(camera), n_samples(n_samples) {} void render(const Scene& scene, Sampler& sampler, Image& image) override final { const uint32_t width = image.getWidth(); const uint32_t height = image.getHeight(); spdlog::info("[PathIntegrator] rendering..."); #pragma omp parallel for collapse(2) schedule(dynamic, 1) for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { // init sampler for each pixel const std::unique_ptr<Sampler> sampler_per_pixel = sampler.clone(); sampler_per_pixel->setSeed((sampler.getSeed() + 1) * (j + width * i)); // warmup sampler for (uint32_t k = 0; k < 100; ++k) { sampler_per_pixel->getNext1D(); } // iteration for (uint32_t k = 0; k < n_samples; ++k) { // SSAA const float u = (2.0f * (j + sampler_per_pixel->getNext1D()) - width) / height; const float v = (2.0f * (i + sampler_per_pixel->getNext1D()) - height) / height; Ray ray; float pdf; if (camera->sampleRay(Vec2f(u, v), *sampler_per_pixel, ray, pdf)) { // compute incoming radiance const Vec3f radiance = integrate(ray, scene, *sampler_per_pixel) / pdf; // invalid radiance check if (std::isnan(radiance[0]) || std::isnan(radiance[1]) || std::isnan(radiance[2])) { spdlog::error("[PathIntegrator] radiance is NaN: ({}, {}, {})", radiance[0], radiance[1], radiance[2]); continue; } else if (std::isinf(radiance[0]) || std::isinf(radiance[1]) || std::isinf(radiance[2])) { spdlog::error("[PathIntegrator] radiance is inf: ({}, {}, {})", radiance[0], radiance[1], radiance[2]); continue; } else if (radiance[0] < 0 || radiance[1] < 0 || radiance[2] < 0) { spdlog::error("[PathIntegrator] radiance is minus: ({}, {}, {})", radiance[0], radiance[1], radiance[2]); continue; } image.addPixel(i, j, radiance); } else { image.setPixel(i, j, Vec3f(0)); } } } } spdlog::info("[PathIntegrator] done"); // take average image /= Vec3f(n_samples); } }; // render shading normal class NormalIntegrator : public PathIntegrator { public: NormalIntegrator(const std::shared_ptr<Camera>& camera) : PathIntegrator(camera, 1) {} Vec3f integrate(const Ray& ray_in, const Scene& scene, Sampler& sampler) const override { IntersectInfo info; if (scene.intersect(ray_in, info)) { // return 0.5f * (ray_in.direction + 1.0f); // spdlog::info("{}, {}, {}", info.surfaceInfo.shadingNormal[0], // info.surfaceInfo.shadingNormal[1], // info.surfaceInfo.shadingNormal[2]); return 0.5f * (info.surfaceInfo.shadingNormal + 1.0f); } else { return Vec3f(0); } } }; // implementation of unidirectional path tracing class PathTracing : public PathIntegrator { private: const uint32_t maxDepth; public: PathTracing(const std::shared_ptr<Camera>& camera, uint32_t n_samples, uint32_t maxDepth = 100) : PathIntegrator(camera, n_samples), maxDepth(maxDepth) {} Vec3f integrate(const Ray& ray_in, const Scene& scene, Sampler& sampler) const override { Vec3f radiance(0); Ray ray = ray_in; ray.throughput = Vec3f(1, 1, 1); uint32_t depth = 0; while (depth < maxDepth) { IntersectInfo info; if (scene.intersect(ray, info)) { // russian roulette if (depth > 0) { const float russian_roulette_prob = std::min( (ray.throughput[0] + ray.throughput[1] + ray.throughput[2]) / 3.0f, 1.0f); if (sampler.getNext1D() >= russian_roulette_prob) { break; } ray.throughput /= russian_roulette_prob; } // sample medium bool is_scattered = false; if (ray.hasMedium()) { const Medium* medium = ray.getCurrentMedium(); Vec3f pos; Vec3f dir; Vec3f throughput_medium; is_scattered = medium->sampleMedium(ray, info.t, sampler, pos, dir, throughput_medium); // advance ray ray.origin = pos; ray.direction = dir; // update throughput ray.throughput *= throughput_medium; } bool is_reflected_or_refracted = false; if (!is_scattered) { // Le if (info.hitPrimitive->hasAreaLight()) { radiance += ray.throughput * info.hitPrimitive->Le(info.surfaceInfo, -ray.direction); break; } // sample direction by BxDF Vec3f dir = ray.direction; if (info.hitPrimitive->hasSurface()) { float pdf_dir; const Vec3f f = info.hitPrimitive->sampleBxDF( -ray.direction, info.surfaceInfo, TransportDirection::FROM_CAMERA, sampler, dir, pdf_dir); // update throughput ray.throughput *= f * cosTerm(-ray.direction, dir, info.surfaceInfo, TransportDirection::FROM_CAMERA) / pdf_dir; is_reflected_or_refracted = true; } // update ray's medium updateMedium(ray, dir, info); // update ray ray.origin = info.surfaceInfo.position; ray.direction = dir; } // update depth if (is_scattered || is_reflected_or_refracted) { depth++; } } else { // ray goes out to the sky break; } } return radiance; } }; // implementation of path tracing with next event estimation class PathTracingNEE : public PathIntegrator { private: const uint32_t maxDepth; static bool isVisible(const Scene& scene, const Vec3f& origin, const Vec3f& dir, float dist_to_light, std::stack<const Medium*>& current_mediums, Sampler& sampler, Vec3f& transmittance) { // create shadow ray Ray shadow_ray; shadow_ray.origin = origin; shadow_ray.direction = dir; shadow_ray.tmax = dist_to_light - RAY_EPS; shadow_ray.mediums = current_mediums; // trace shadow ray transmittance = Vec3f(1); while (true) { IntersectInfo shadow_info; if (scene.intersect(shadow_ray, shadow_info)) { // occuluded if (shadow_info.hitPrimitive->hasSurface()) { return false; } // update transmittance if (shadow_ray.hasMedium()) { const Medium* medium = shadow_ray.getCurrentMedium(); transmittance *= medium->transmittance( shadow_ray.origin, shadow_info.surfaceInfo.position, sampler); } // update shadow ray's medium updateMedium(shadow_ray, shadow_ray.direction, shadow_info); // advance shadow ray shadow_ray.origin = shadow_info.surfaceInfo.position; shadow_ray.tmax -= shadow_info.t; } else { // update transmittance if (shadow_ray.hasMedium()) { const Medium* medium = shadow_ray.getCurrentMedium(); transmittance *= medium->transmittance( shadow_ray.origin, shadow_ray(shadow_ray.tmax), sampler); } break; } } return true; } public: PathTracingNEE(const std::shared_ptr<Camera>& camera, uint32_t n_samples, uint32_t maxDepth = 100) : PathIntegrator(camera, n_samples), maxDepth(maxDepth) {} Vec3f integrate(const Ray& ray_in, const Scene& scene, Sampler& sampler) const override { Vec3f radiance(0); Ray ray = ray_in; ray.throughput = Vec3f(1, 1, 1); uint32_t depth = 0; while (depth < maxDepth) { IntersectInfo info; if (scene.intersect(ray, info)) { // russian roulette if (depth > 0) { const float russian_roulette_prob = std::min( (ray.throughput[0] + ray.throughput[1] + ray.throughput[2]) / 3.0f, 1.0f); if (sampler.getNext1D() >= russian_roulette_prob) { break; } ray.throughput /= russian_roulette_prob; } // sample medium bool is_scattered = false; if (ray.hasMedium()) { const Medium* medium = ray.getCurrentMedium(); // sample collision position, in-scattering direction Vec3f pos; Vec3f dir; Vec3f throughput_medium; is_scattered = medium->sampleMedium(ray, info.t, sampler, pos, dir, throughput_medium); // next event estimation if (is_scattered) { // sample direction to the light Vec3f dir; float dist_to_light; float pdf_dir; const Vec3f Le = sampleDirectionToLight(scene, pos, sampler, dir, dist_to_light, pdf_dir); // test visibility Vec3f transmittance; if (isVisible(scene, pos, dir, dist_to_light, ray.mediums, sampler, transmittance)) { // add contribution const Medium* medium = ray.getCurrentMedium(); const Vec3f f = medium->evalPhaseFunction(-ray.direction, dir); const Vec3f Ls = transmittance * f * Le / pdf_dir; // if (length(Ls) > 1.0f) { // spdlog::info("firefly"); // spdlog::info("Ls: ({}, {}, {})", Ls[0], Ls[1], Ls[2]); // spdlog::info("transmittance: ({}, {}, {})", transmittance[0], // transmittance[1], transmittance[2]); // spdlog::info("f: ({}, {}, {})", f[0], f[1], f[2]); // spdlog::info("pdf_dir: {}", pdf_dir); // } radiance += ray.throughput * throughput_medium * Ls; } } // advance ray ray.origin = pos; ray.direction = dir; // update throughput ray.throughput *= throughput_medium; } bool is_reflected_or_refracted = false; if (!is_scattered) { // direct hit to the light if (info.hitPrimitive->hasAreaLight()) { if (depth == 0) { radiance += ray.throughput * info.hitPrimitive->Le(info.surfaceInfo, -ray.direction); } break; } // next event estimation if (info.hitPrimitive->hasSurface()) { // sample direction to the light Vec3f dir; float dist_to_light; float pdf_dir; const Vec3f Le = sampleDirectionToLight(scene, info.surfaceInfo.position, sampler, dir, dist_to_light, pdf_dir); // test visibility Vec3f transmittance; if (isVisible(scene, info.surfaceInfo.position, dir, dist_to_light, ray.mediums, sampler, transmittance)) { // add contribution const Vec3f f = info.hitPrimitive->evaluateBxDF( -ray.direction, dir, info.surfaceInfo, TransportDirection::FROM_CAMERA); radiance += ray.throughput * transmittance * f * cosTerm(-ray.direction, dir, info.surfaceInfo, TransportDirection::FROM_CAMERA) * Le / pdf_dir; } } // sample direction by BxDF Vec3f dir = ray.direction; if (info.hitPrimitive->hasSurface()) { float pdf_dir; const Vec3f f = info.hitPrimitive->sampleBxDF( -ray.direction, info.surfaceInfo, TransportDirection::FROM_CAMERA, sampler, dir, pdf_dir); // update throughput ray.throughput *= f * cosTerm(-ray.direction, dir, info.surfaceInfo, TransportDirection::FROM_CAMERA) / pdf_dir; is_reflected_or_refracted = true; } // update ray's medium updateMedium(ray, dir, info); // update ray ray.origin = info.surfaceInfo.position; ray.direction = dir; } // update depth if (is_scattered || is_reflected_or_refracted) { depth++; } } else { // ray goes out to the sky break; } } return radiance; } }; #endif
convolution_sgemm_pack8to1_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void im2col_sgemm_pack8to1_fp16sa_neon(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { // Mat bottom_im2col(size, maxk, inch, 16u, 8, opt.workspace_allocator); const int size = bottom_im2col.w; const int maxk = bottom_im2col.h; const int inch = bottom_im2col.c; const int outch = top_blob.c; const __fp16* bias = _bias; // permute Mat tmp; if (size >= 8) tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + size % 4, 16u, 8, opt.workspace_allocator); else if (size >= 4) tmp.create(4 * maxk, inch, size / 4 + size % 4, 16u, 8, opt.workspace_allocator); else tmp.create(maxk, inch, size, 16u, 8, opt.workspace_allocator); { int nn_size = size / 8; int remain_size_start = 0; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 8; __fp16* tmpptr = tmp.channel(i / 8); for (int q = 0; q < inch; q++) { const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { // transpose 8x8 asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0], #64 \n" "ld4 {v4.8h, v5.8h, v6.8h, v7.8h}, [%0] \n" "sub %0, %0, #64 \n" "uzp1 v16.8h, v0.8h, v4.8h \n" "uzp2 v20.8h, v0.8h, v4.8h \n" "uzp1 v17.8h, v1.8h, v5.8h \n" "uzp2 v21.8h, v1.8h, v5.8h \n" "uzp1 v18.8h, v2.8h, v6.8h \n" "uzp2 v22.8h, v2.8h, v6.8h \n" "uzp1 v19.8h, v3.8h, v7.8h \n" "uzp2 v23.8h, v3.8h, v7.8h \n" "st1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%1], #64 \n" "st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); img0 += size * 8; } } } remain_size_start += nn_size << 3; nn_size = (size - remain_size_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 4; __fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); for (int q = 0; q < inch; q++) { const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { // transpose 8x4 asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0] \n" "st4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%1], #64 \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "v0", "v1", "v2", "v3"); img0 += size * 8; } } } remain_size_start += nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { __fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); for (int q = 0; q < inch; q++) { const __fp16* img0 = (const __fp16*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v0.8h}, [%0] \n" "st1 {v0.8h}, [%1], #16 \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "v0"); img0 += size * 8; } } } } int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; __fp16* outptr0 = top_blob.channel(p); __fp16* outptr1 = top_blob.channel(p + 1); __fp16* outptr2 = top_blob.channel(p + 2); __fp16* outptr3 = top_blob.channel(p + 3); __fp16* outptr4 = top_blob.channel(p + 4); __fp16* outptr5 = top_blob.channel(p + 5); __fp16* outptr6 = top_blob.channel(p + 6); __fp16* outptr7 = top_blob.channel(p + 7); const __fp16 zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; const __fp16* biasptr = bias ? bias + p : zeros; float16x8_t _bias0 = vld1q_f16(biasptr); int i = 0; for (; i + 7 < size; i += 8) { __fp16* tmpptr = tmp.channel(i / 8); const __fp16* kptr = kernel.channel(p / 8); int nn = inch * maxk; // inch always > 0 asm volatile( "dup v24.8h, %22.h[0] \n" "dup v25.8h, %22.h[1] \n" "dup v26.8h, %22.h[2] \n" "dup v27.8h, %22.h[3] \n" "dup v28.8h, %22.h[4] \n" "dup v29.8h, %22.h[5] \n" "dup v30.8h, %22.h[6] \n" "dup v31.8h, %22.h[7] \n" "0: \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%9], #64 \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%10], #64 \n" "fmla v24.8h, v16.8h, v0.h[0] \n" "fmla v25.8h, v16.8h, v0.h[1] \n" "fmla v26.8h, v16.8h, v0.h[2] \n" "fmla v27.8h, v16.8h, v0.h[3] \n" "fmla v28.8h, v16.8h, v0.h[4] \n" "fmla v29.8h, v16.8h, v0.h[5] \n" "fmla v30.8h, v16.8h, v0.h[6] \n" "fmla v31.8h, v16.8h, v0.h[7] \n" "fmla v24.8h, v17.8h, v1.h[0] \n" "fmla v25.8h, v17.8h, v1.h[1] \n" "fmla v26.8h, v17.8h, v1.h[2] \n" "fmla v27.8h, v17.8h, v1.h[3] \n" "fmla v28.8h, v17.8h, v1.h[4] \n" "fmla v29.8h, v17.8h, v1.h[5] \n" "fmla v30.8h, v17.8h, v1.h[6] \n" "fmla v31.8h, v17.8h, v1.h[7] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%9], #64 \n" "fmla v24.8h, v18.8h, v2.h[0] \n" "fmla v25.8h, v18.8h, v2.h[1] \n" "fmla v26.8h, v18.8h, v2.h[2] \n" "fmla v27.8h, v18.8h, v2.h[3] \n" "fmla v28.8h, v18.8h, v2.h[4] \n" "fmla v29.8h, v18.8h, v2.h[5] \n" "fmla v30.8h, v18.8h, v2.h[6] \n" "fmla v31.8h, v18.8h, v2.h[7] \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v4.8h, v5.8h, v6.8h, v7.8h}, [%10], #64 \n" "fmla v24.8h, v19.8h, v3.h[0] \n" "fmla v25.8h, v19.8h, v3.h[1] \n" "fmla v26.8h, v19.8h, v3.h[2] \n" "fmla v27.8h, v19.8h, v3.h[3] \n" "fmla v28.8h, v19.8h, v3.h[4] \n" "fmla v29.8h, v19.8h, v3.h[5] \n" "fmla v30.8h, v19.8h, v3.h[6] \n" "fmla v31.8h, v19.8h, v3.h[7] \n" "fmla v24.8h, v20.8h, v4.h[0] \n" "fmla v25.8h, v20.8h, v4.h[1] \n" "fmla v26.8h, v20.8h, v4.h[2] \n" "fmla v27.8h, v20.8h, v4.h[3] \n" "fmla v28.8h, v20.8h, v4.h[4] \n" "fmla v29.8h, v20.8h, v4.h[5] \n" "fmla v30.8h, v20.8h, v4.h[6] \n" "fmla v31.8h, v20.8h, v4.h[7] \n" "fmla v24.8h, v21.8h, v5.h[0] \n" "fmla v25.8h, v21.8h, v5.h[1] \n" "fmla v26.8h, v21.8h, v5.h[2] \n" "fmla v27.8h, v21.8h, v5.h[3] \n" "fmla v28.8h, v21.8h, v5.h[4] \n" "fmla v29.8h, v21.8h, v5.h[5] \n" "fmla v30.8h, v21.8h, v5.h[6] \n" "fmla v31.8h, v21.8h, v5.h[7] \n" "fmla v24.8h, v22.8h, v6.h[0] \n" "fmla v25.8h, v22.8h, v6.h[1] \n" "fmla v26.8h, v22.8h, v6.h[2] \n" "fmla v27.8h, v22.8h, v6.h[3] \n" "fmla v28.8h, v22.8h, v6.h[4] \n" "fmla v29.8h, v22.8h, v6.h[5] \n" "fmla v30.8h, v22.8h, v6.h[6] \n" "fmla v31.8h, v22.8h, v6.h[7] \n" "subs %w0, %w0, #1 \n" "fmla v24.8h, v23.8h, v7.h[0] \n" "fmla v25.8h, v23.8h, v7.h[1] \n" "fmla v26.8h, v23.8h, v7.h[2] \n" "fmla v27.8h, v23.8h, v7.h[3] \n" "fmla v28.8h, v23.8h, v7.h[4] \n" "fmla v29.8h, v23.8h, v7.h[5] \n" "fmla v30.8h, v23.8h, v7.h[6] \n" "fmla v31.8h, v23.8h, v7.h[7] \n" "bne 0b \n" "st1 {v24.8h}, [%1], #16 \n" "st1 {v25.8h}, [%2], #16 \n" "st1 {v26.8h}, [%3], #16 \n" "st1 {v27.8h}, [%4], #16 \n" "st1 {v28.8h}, [%5], #16 \n" "st1 {v29.8h}, [%6], #16 \n" "st1 {v30.8h}, [%7], #16 \n" "st1 {v31.8h}, [%8], #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(outptr6), // %7 "=r"(outptr7), // %8 "=r"(tmpptr), // %9 "=r"(kptr) // %10 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(outptr6), "8"(outptr7), "9"(tmpptr), "10"(kptr), "w"(_bias0) // %22 : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 3 < size; i += 4) { __fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); const __fp16* kptr = kernel.channel(p / 8); int nn = inch * maxk; // inch always > 0 asm volatile( "dup v24.4h, %22.h[0] \n" "dup v25.4h, %22.h[1] \n" "dup v26.4h, %22.h[2] \n" "dup v27.4h, %22.h[3] \n" "dup v28.4h, %22.h[4] \n" "dup v29.4h, %22.h[5] \n" "dup v30.4h, %22.h[6] \n" "dup v31.4h, %22.h[7] \n" "0: \n" "prfm pldl1keep, [%9, #256] \n" "ld1 {v16.4h, v17.4h, v18.4h, v19.4h}, [%9], #32 \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%10], #64 \n" "fmla v24.4h, v16.4h, v0.h[0] \n" "fmla v25.4h, v16.4h, v0.h[1] \n" "fmla v26.4h, v16.4h, v0.h[2] \n" "fmla v27.4h, v16.4h, v0.h[3] \n" "fmla v28.4h, v16.4h, v0.h[4] \n" "fmla v29.4h, v16.4h, v0.h[5] \n" "fmla v30.4h, v16.4h, v0.h[6] \n" "fmla v31.4h, v16.4h, v0.h[7] \n" "fmla v24.4h, v17.4h, v1.h[0] \n" "fmla v25.4h, v17.4h, v1.h[1] \n" "fmla v26.4h, v17.4h, v1.h[2] \n" "fmla v27.4h, v17.4h, v1.h[3] \n" "fmla v28.4h, v17.4h, v1.h[4] \n" "fmla v29.4h, v17.4h, v1.h[5] \n" "fmla v30.4h, v17.4h, v1.h[6] \n" "fmla v31.4h, v17.4h, v1.h[7] \n" "prfm pldl1keep, [%9, #256] \n" "ld1 {v20.4h, v21.4h, v22.4h, v23.4h}, [%9], #32 \n" "fmla v24.4h, v18.4h, v2.h[0] \n" "fmla v25.4h, v18.4h, v2.h[1] \n" "fmla v26.4h, v18.4h, v2.h[2] \n" "fmla v27.4h, v18.4h, v2.h[3] \n" "fmla v28.4h, v18.4h, v2.h[4] \n" "fmla v29.4h, v18.4h, v2.h[5] \n" "fmla v30.4h, v18.4h, v2.h[6] \n" "fmla v31.4h, v18.4h, v2.h[7] \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v4.8h, v5.8h, v6.8h, v7.8h}, [%10], #64 \n" "fmla v24.4h, v19.4h, v3.h[0] \n" "fmla v25.4h, v19.4h, v3.h[1] \n" "fmla v26.4h, v19.4h, v3.h[2] \n" "fmla v27.4h, v19.4h, v3.h[3] \n" "fmla v28.4h, v19.4h, v3.h[4] \n" "fmla v29.4h, v19.4h, v3.h[5] \n" "fmla v30.4h, v19.4h, v3.h[6] \n" "fmla v31.4h, v19.4h, v3.h[7] \n" "fmla v24.4h, v20.4h, v4.h[0] \n" "fmla v25.4h, v20.4h, v4.h[1] \n" "fmla v26.4h, v20.4h, v4.h[2] \n" "fmla v27.4h, v20.4h, v4.h[3] \n" "fmla v28.4h, v20.4h, v4.h[4] \n" "fmla v29.4h, v20.4h, v4.h[5] \n" "fmla v30.4h, v20.4h, v4.h[6] \n" "fmla v31.4h, v20.4h, v4.h[7] \n" "fmla v24.4h, v21.4h, v5.h[0] \n" "fmla v25.4h, v21.4h, v5.h[1] \n" "fmla v26.4h, v21.4h, v5.h[2] \n" "fmla v27.4h, v21.4h, v5.h[3] \n" "fmla v28.4h, v21.4h, v5.h[4] \n" "fmla v29.4h, v21.4h, v5.h[5] \n" "fmla v30.4h, v21.4h, v5.h[6] \n" "fmla v31.4h, v21.4h, v5.h[7] \n" "fmla v24.4h, v22.4h, v6.h[0] \n" "fmla v25.4h, v22.4h, v6.h[1] \n" "fmla v26.4h, v22.4h, v6.h[2] \n" "fmla v27.4h, v22.4h, v6.h[3] \n" "fmla v28.4h, v22.4h, v6.h[4] \n" "fmla v29.4h, v22.4h, v6.h[5] \n" "fmla v30.4h, v22.4h, v6.h[6] \n" "fmla v31.4h, v22.4h, v6.h[7] \n" "subs %w0, %w0, #1 \n" "fmla v24.4h, v23.4h, v7.h[0] \n" "fmla v25.4h, v23.4h, v7.h[1] \n" "fmla v26.4h, v23.4h, v7.h[2] \n" "fmla v27.4h, v23.4h, v7.h[3] \n" "fmla v28.4h, v23.4h, v7.h[4] \n" "fmla v29.4h, v23.4h, v7.h[5] \n" "fmla v30.4h, v23.4h, v7.h[6] \n" "fmla v31.4h, v23.4h, v7.h[7] \n" "bne 0b \n" "st1 {v24.4h}, [%1], #8 \n" "st1 {v25.4h}, [%2], #8 \n" "st1 {v26.4h}, [%3], #8 \n" "st1 {v27.4h}, [%4], #8 \n" "st1 {v28.4h}, [%5], #8 \n" "st1 {v29.4h}, [%6], #8 \n" "st1 {v30.4h}, [%7], #8 \n" "st1 {v31.4h}, [%8], #8 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(outptr6), // %7 "=r"(outptr7), // %8 "=r"(tmpptr), // %9 "=r"(kptr) // %10 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(outptr6), "8"(outptr7), "9"(tmpptr), "10"(kptr), "w"(_bias0) // %22 : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i < size; i++) { __fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); const __fp16* kptr = kernel.channel(p / 8); int nn = inch * maxk; // inch always > 0 asm volatile( "mov v30.16b, %22.16b \n" "0: \n" "prfm pldl1keep, [%9, #128] \n" "ld1 {v0.8h}, [%9], #16 \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%10], #64 \n" "fmla v30.8h, v16.8h, v0.h[0] \n" "fmla v30.8h, v17.8h, v0.h[1] \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%10], #64 \n" "fmla v30.8h, v18.8h, v0.h[2] \n" "fmla v30.8h, v19.8h, v0.h[3] \n" "subs %w0, %w0, #1 \n" "fmla v30.8h, v20.8h, v0.h[4] \n" "fmla v30.8h, v21.8h, v0.h[5] \n" "fmla v30.8h, v22.8h, v0.h[6] \n" "fmla v30.8h, v23.8h, v0.h[7] \n" "bne 0b \n" "st1 {v30.h}[0], [%1], #2 \n" "st1 {v30.h}[1], [%2], #2 \n" "st1 {v30.h}[2], [%3], #2 \n" "st1 {v30.h}[3], [%4], #2 \n" "st1 {v30.h}[4], [%5], #2 \n" "st1 {v30.h}[5], [%6], #2 \n" "st1 {v30.h}[6], [%7], #2 \n" "st1 {v30.h}[7], [%8], #2 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(outptr6), // %7 "=r"(outptr7), // %8 "=r"(tmpptr), // %9 "=r"(kptr) // %10 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(outptr6), "8"(outptr7), "9"(tmpptr), "10"(kptr), "w"(_bias0) // %22 : "cc", "memory", "v0", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v30"); } } remain_outch_start += nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { __fp16* outptr0 = top_blob.channel(p); const __fp16 bias0 = bias ? bias[p] : 0.f; float16x8_t _bias0 = vdupq_n_f16(bias0); int i = 0; for (; i + 7 < size; i += 8) { __fp16* tmpptr = tmp.channel(i / 8); const __fp16* kptr = kernel.channel(p / 8 + p % 8); int nn = inch * maxk; // inch always > 0 asm volatile( "mov v30.16b, %8.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%2], #64 \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v0.8h}, [%3], #16 \n" "fmla v30.8h, v16.8h, v0.h[0] \n" "fmla v30.8h, v17.8h, v0.h[1] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%2], #64 \n" "fmla v30.8h, v18.8h, v0.h[2] \n" "fmla v30.8h, v19.8h, v0.h[3] \n" "subs %w0, %w0, #1 \n" "fmla v30.8h, v20.8h, v0.h[4] \n" "fmla v30.8h, v21.8h, v0.h[5] \n" "fmla v30.8h, v22.8h, v0.h[6] \n" "fmla v30.8h, v23.8h, v0.h[7] \n" "bne 0b \n" "st1 {v30.8h}, [%1], #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(tmpptr), // %2 "=r"(kptr) // %3 : "0"(nn), "1"(outptr0), "2"(tmpptr), "3"(kptr), "w"(_bias0) // %8 : "cc", "memory", "v0", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v30"); } for (; i + 3 < size; i += 4) { __fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4); const __fp16* kptr = kernel.channel(p / 8 + p % 8); int nn = inch * maxk; // inch always > 0 asm volatile( "mov v30.16b, %8.16b \n" "0: \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v16.4h, v17.4h, v18.4h, v19.4h}, [%2], #32 \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v0.8h}, [%3], #16 \n" "fmla v30.4h, v16.4h, v0.h[0] \n" "fmla v30.4h, v17.4h, v0.h[1] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v20.4h, v21.4h, v22.4h, v23.4h}, [%2], #32 \n" "fmla v30.4h, v18.4h, v0.h[2] \n" "fmla v30.4h, v19.4h, v0.h[3] \n" "subs %w0, %w0, #1 \n" "fmla v30.4h, v20.4h, v0.h[4] \n" "fmla v30.4h, v21.4h, v0.h[5] \n" "fmla v30.4h, v22.4h, v0.h[6] \n" "fmla v30.4h, v23.4h, v0.h[7] \n" "bne 0b \n" "st1 {v30.4h}, [%1], #8 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(tmpptr), // %2 "=r"(kptr) // %3 : "0"(nn), "1"(outptr0), "2"(tmpptr), "3"(kptr), "w"(_bias0) // %8 : "cc", "memory", "v0", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v30"); } for (; i < size; i++) { __fp16* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4); const __fp16* kptr = kernel.channel(p / 8 + p % 8); int nn = inch * maxk; // inch always > 0 float16x8_t _sum0 = vdupq_n_f16((__fp16)0.f); for (int q = 0; q < nn; q++) { float16x8_t _r0 = vld1q_f16(tmpptr); float16x8_t _k0 = vld1q_f16(kptr); _sum0 = vfmaq_f16(_sum0, _r0, _k0); kptr += 8; tmpptr += 8; } __fp16 sum0 = bias0 + vaddvq_f32(vcvt_f32_f16(vadd_f16(vget_low_f16(_sum0), vget_high_f16(_sum0)))); outptr0[0] = sum0; outptr0++; } } } static void convolution_im2col_sgemm_transform_kernel_pack8to1_fp16sa_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h) { const int maxk = kernel_w * kernel_h; // interleave // src = maxk-inch-outch // dst = 8b-8a-maxk-inch/8a-outch/8b Mat kernel = _kernel.reshape(maxk, inch, outch); kernel_tm.create(64 * maxk, inch / 8, outch / 8 + outch % 8, (size_t)2u); int q = 0; for (; q + 7 < outch; q += 8) { Mat g0 = kernel_tm.channel(q / 8); for (int p = 0; p + 7 < inch; p += 8) { __fp16* g00 = g0.row<__fp16>(p / 8); for (int k = 0; k < maxk; k++) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { const float* k00 = kernel.channel(q + j).row(p + i); g00[0] = (__fp16)k00[k]; g00++; } } } } } for (; q < outch; q++) { Mat g0 = kernel_tm.channel(q / 8 + q % 8); for (int p = 0; p + 7 < inch; p += 8) { __fp16* g00 = g0.row<__fp16>(p / 8); for (int k = 0; k < maxk; k++) { for (int i = 0; i < 8; i++) { const float* k00 = kernel.channel(q).row(p + i); g00[0] = (__fp16)k00[k]; g00++; } } } } } static void convolution_im2col_sgemm_pack8to1_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int size = outw * outh; const int maxk = kernel_w * kernel_h; // im2col Mat bottom_im2col(size, maxk, inch, 16u, 8, opt.workspace_allocator); { const int gap = (w * stride_h - outw * stride_w) * 8; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < inch; p++) { const Mat img = bottom_blob.channel(p); __fp16* ptr = bottom_im2col.channel(p); for (int u = 0; u < kernel_h; u++) { for (int v = 0; v < kernel_w; v++) { const __fp16* sptr = img.row<const __fp16>(dilation_h * u) + dilation_w * v * 8; for (int i = 0; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { float16x8_t _val0 = vld1q_f16(sptr); float16x8_t _val1 = vld1q_f16(sptr + stride_w * 8); float16x8_t _val2 = vld1q_f16(sptr + stride_w * 16); float16x8_t _val3 = vld1q_f16(sptr + stride_w * 24); vst1q_f16(ptr, _val0); vst1q_f16(ptr + 8, _val1); vst1q_f16(ptr + 16, _val2); vst1q_f16(ptr + 24, _val3); sptr += stride_w * 32; ptr += 32; } for (; j + 1 < outw; j += 2) { float16x8_t _val0 = vld1q_f16(sptr); float16x8_t _val1 = vld1q_f16(sptr + stride_w * 8); vst1q_f16(ptr, _val0); vst1q_f16(ptr + 8, _val1); sptr += stride_w * 16; ptr += 16; } for (; j < outw; j++) { float16x8_t _val = vld1q_f16(sptr); vst1q_f16(ptr, _val); sptr += stride_w * 8; ptr += 8; } sptr += gap; } } } } } im2col_sgemm_pack8to1_fp16sa_neon(bottom_im2col, top_blob, kernel, _bias, opt); }
main.c
#include <omp.h> #include <stdio.h> __attribute__ ((constructor)) void a_constructor() { #pragma omp parallel printf("hello from thread %d\n", omp_get_num_threads()); } int main(int argc, char **argv) { printf("hello from main\n"); return 0; }
quantize.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE % % Q Q U U A A NN N T I ZZ E % % Q Q U U AAAAA N N N T I ZZZ EEEEE % % Q QQ U U A A N NN T I ZZ E % % QQQQ UUU A A N N T IIIII ZZZZZ EEEEE % % % % % % MagickCore Methods to Reduce the Number of Unique Colors in an Image % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Realism in computer graphics typically requires using 24 bits/pixel to % generate an image. Yet many graphic display devices do not contain the % amount of memory necessary to match the spatial and color resolution of % the human eye. The Quantize methods takes a 24 bit image and reduces % the number of colors so it can be displayed on raster device with less % bits per pixel. In most instances, the quantized image closely % resembles the original reference image. % % A reduction of colors in an image is also desirable for image % transmission and real-time animation. % % QuantizeImage() takes a standard RGB or monochrome images and quantizes % them down to some fixed number of colors. % % For purposes of color allocation, an image is a set of n pixels, where % each pixel is a point in RGB space. RGB space is a 3-dimensional % vector space, and each pixel, Pi, is defined by an ordered triple of % red, green, and blue coordinates, (Ri, Gi, Bi). % % Each primary color component (red, green, or blue) represents an % intensity which varies linearly from 0 to a maximum value, Cmax, which % corresponds to full saturation of that color. Color allocation is % defined over a domain consisting of the cube in RGB space with opposite % vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax = % 255. % % The algorithm maps this domain onto a tree in which each node % represents a cube within that domain. In the following discussion % these cubes are defined by the coordinate of two opposite vertices (vertex % nearest the origin in RGB space and the vertex farthest from the origin). % % The tree's root node represents the entire domain, (0,0,0) through % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by % subdividing one node's cube into eight smaller cubes of equal size. % This corresponds to bisecting the parent cube with planes passing % through the midpoints of each edge. % % The basic algorithm operates in three phases: Classification, % Reduction, and Assignment. Classification builds a color description % tree for the image. Reduction collapses the tree until the number it % represents, at most, the number of colors desired in the output image. % Assignment defines the output image's color map and sets each pixel's % color by restorage_class in the reduced tree. Our goal is to minimize % the numerical discrepancies between the original colors and quantized % colors (quantization error). % % Classification begins by initializing a color description tree of % sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color description % tree in the storage_class phase for realistic values of Cmax. If % colors components in the input image are quantized to k-bit precision, % so that Cmax= 2k-1, the tree would need k levels below the root node to % allow representing each possible input color in a leaf. This becomes % prohibitive because the tree's total number of nodes is 1 + % sum(i=1, k, 8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing the pixel's color. It updates the following data for each % such node: % % n1: Number of pixels whose color is contained in the RGB cube which % this node represents; % % n2: Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb: Sums of the red, green, and blue component values for all % pixels not classified at a lower depth. The combination of these sums % and n2 will ultimately characterize the mean color of a set of pixels % represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the % quantization error for a node. % % Reduction repeatedly prunes the tree until the number of nodes with n2 % > 0 is less than or equal to the maximum number of colors allowed in % the output image. On any given iteration over the tree, it selects % those nodes whose E count is minimal for pruning and merges their color % statistics upward. It uses a pruning threshold, Ep, to govern node % selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors within % the cubic volume which the node represents. This includes n1 - n2 % pixels whose colors should be defined by nodes at a lower level in the % tree. % % Assignment generates the output image from the pruned tree. The output % image consists of two parts: (1) A color map, which is an array of % color descriptions (RGB triples) for each color present in the output % image; (2) A pixel array, which represents each pixel as an index % into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % This method is based on a similar algorithm written by Paul Raveling. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" /* Define declarations. */ #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE) #define CacheShift 2 #else #define CacheShift 3 #endif #define ErrorQueueLength 16 #define MaxNodes 266817 #define MaxTreeDepth 8 #define NodesInAList 1920 /* Typdef declarations. */ typedef struct _DoublePixelPacket { double red, green, blue, alpha; } DoublePixelPacket; typedef struct _NodeInfo { struct _NodeInfo *parent, *child[16]; MagickSizeType number_unique; DoublePixelPacket total_color; double quantize_error; size_t color_number, id, level; } NodeInfo; typedef struct _Nodes { NodeInfo *nodes; struct _Nodes *next; } Nodes; typedef struct _CubeInfo { NodeInfo *root; size_t colors, maximum_colors; ssize_t transparent_index; MagickSizeType transparent_pixels; DoublePixelPacket target; double distance, pruning_threshold, next_threshold; size_t nodes, free_nodes, color_number; NodeInfo *next_node; Nodes *node_queue; MemoryInfo *memory_info; ssize_t *cache; DoublePixelPacket error[ErrorQueueLength]; double weights[ErrorQueueLength]; QuantizeInfo *quantize_info; MagickBooleanType associate_alpha; ssize_t x, y; size_t depth; MagickOffsetType offset; MagickSizeType span; } CubeInfo; /* Method prototypes. */ static CubeInfo *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t); static NodeInfo *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *); static MagickBooleanType AssignImageColors(Image *,CubeInfo *,ExceptionInfo *), ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *), DitherImage(Image *,CubeInfo *,ExceptionInfo *), SetGrayscaleImage(Image *,ExceptionInfo *); static size_t DefineImageColormap(Image *,CubeInfo *,NodeInfo *); static void ClosestColor(const Image *,CubeInfo *,const NodeInfo *), DestroyCubeInfo(CubeInfo *), PruneLevel(CubeInfo *,const NodeInfo *), PruneToCubeDepth(CubeInfo *,const NodeInfo *), ReduceImageColors(const Image *,CubeInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantizeInfo() allocates the QuantizeInfo structure. % % The format of the AcquireQuantizeInfo method is: % % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) { QuantizeInfo *quantize_info; quantize_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*quantize_info)); GetQuantizeInfo(quantize_info); if (image_info != (ImageInfo *) NULL) { const char *option; quantize_info->dither_method=image_info->dither == MagickFalse ? NoDitherMethod : RiemersmaDitherMethod; option=GetImageOption(image_info,"dither"); if (option != (const char *) NULL) quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,option); quantize_info->measure_error=image_info->verbose; } return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A s s i g n I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AssignImageColors() generates the output image from the pruned tree. The % output image consists of two parts: (1) A color map, which is an array % of color descriptions (RGB triples) for each color present in the % output image; (2) A pixel array, which represents each pixel as an % index into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % The format of the AssignImageColors() method is: % % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static inline void AssociateAlphaPixel(const Image *image, const CubeInfo *cube_info,const Quantum *pixel,DoublePixelPacket *alpha_pixel) { double alpha; if ((cube_info->associate_alpha == MagickFalse) || (GetPixelAlpha(image,pixel) == OpaqueAlpha)) { alpha_pixel->red=(double) GetPixelRed(image,pixel); alpha_pixel->green=(double) GetPixelGreen(image,pixel); alpha_pixel->blue=(double) GetPixelBlue(image,pixel); alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel); return; } alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel)); alpha_pixel->red=alpha*GetPixelRed(image,pixel); alpha_pixel->green=alpha*GetPixelGreen(image,pixel); alpha_pixel->blue=alpha*GetPixelBlue(image,pixel); alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel); } static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info, const PixelInfo *pixel,DoublePixelPacket *alpha_pixel) { double alpha; if ((cube_info->associate_alpha == MagickFalse) || (pixel->alpha == OpaqueAlpha)) { alpha_pixel->red=(double) pixel->red; alpha_pixel->green=(double) pixel->green; alpha_pixel->blue=(double) pixel->blue; alpha_pixel->alpha=(double) pixel->alpha; return; } alpha=(double) (QuantumScale*pixel->alpha); alpha_pixel->red=alpha*pixel->red; alpha_pixel->green=alpha*pixel->green; alpha_pixel->blue=alpha*pixel->blue; alpha_pixel->alpha=(double) pixel->alpha; } static inline size_t ColorToNodeId(const CubeInfo *cube_info, const DoublePixelPacket *pixel,size_t index) { size_t id; id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) | ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 | ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2); if (cube_info->associate_alpha != MagickFalse) id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3; return(id); } static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info, ExceptionInfo *exception) { #define AssignImageTag "Assign/Image" ColorspaceType colorspace; ssize_t y; /* Allocate image colormap. */ colorspace=image->colorspace; if (cube_info->quantize_info->colorspace != UndefinedColorspace) (void) TransformImageColorspace(image,cube_info->quantize_info->colorspace, exception); if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); image->colors=0; cube_info->transparent_pixels=0; cube_info->transparent_index=(-1); (void) DefineImageColormap(image,cube_info,cube_info->root); /* Create a reduced color image. */ if (cube_info->quantize_info->dither_method != NoDitherMethod) (void) DitherImage(image,cube_info,exception); else { CacheView *image_view; MagickBooleanType status; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CubeInfo cube; register Quantum *magick_restrict q; register ssize_t x; ssize_t count; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } cube=(*cube_info); for (x=0; x < (ssize_t) image->columns; x+=count) { DoublePixelPacket pixel; register const NodeInfo *node_info; register ssize_t i; size_t id, index; /* Identify the deepest node containing the pixel's color. */ for (count=1; (x+count) < (ssize_t) image->columns; count++) { PixelInfo packet; GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet); if (IsPixelEquivalent(image,q,&packet) == MagickFalse) break; } AssociateAlphaPixel(image,&cube,q,&pixel); node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+ 1.0); ClosestColor(image,&cube,node_info->parent); index=cube.color_number; for (i=0; i < (ssize_t) count; i++) { if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) index,q); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRed(image,ClampToQuantum( image->colormap[index].red),q); SetPixelGreen(image,ClampToQuantum( image->colormap[index].green),q); SetPixelBlue(image,ClampToQuantum( image->colormap[index].blue),q); if (cube.associate_alpha != MagickFalse) SetPixelAlpha(image,ClampToQuantum( image->colormap[index].alpha),q); } q+=GetPixelChannels(image); } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } if (cube_info->quantize_info->measure_error != MagickFalse) (void) GetImageQuantizeError(image,exception); if ((cube_info->quantize_info->number_colors == 2) && ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) || (cube_info->quantize_info->colorspace == GRAYColorspace))) { double intensity; /* Monochrome image. */ intensity=0.0; if ((image->colors > 1) && (GetPixelInfoLuma(image->colormap+0) > GetPixelInfoLuma(image->colormap+1))) intensity=(double) QuantumRange; image->colormap[0].red=intensity; image->colormap[0].green=intensity; image->colormap[0].blue=intensity; if (image->colors > 1) { image->colormap[1].red=(double) QuantumRange-intensity; image->colormap[1].green=(double) QuantumRange-intensity; image->colormap[1].blue=(double) QuantumRange-intensity; } } (void) SyncImage(image,exception); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (IssRGBCompatibleColorspace(colorspace) == MagickFalse)) (void) TransformImageColorspace(image,colorspace,exception); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l a s s i f y I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClassifyImageColors() begins by initializing a color description tree % of sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color % description tree in the storage_class phase for realistic values of % Cmax. If colors components in the input image are quantized to k-bit % precision, so that Cmax= 2k-1, the tree would need k levels below the % root node to allow representing each possible input color in a leaf. % This becomes prohibitive because the tree's total number of nodes is % 1 + sum(i=1,k,8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing It updates the following data for each such node: % % n1 : Number of pixels whose color is contained in the RGB cube % which this node represents; % % n2 : Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb : Sums of the red, green, and blue component values for % all pixels not classified at a lower depth. The combination of % these sums and n2 will ultimately characterize the mean color of a % set of pixels represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the quantization % error for a node. % % The format of the ClassifyImageColors() method is: % % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, % const Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o image: the image. % */ static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info) { MagickBooleanType associate_alpha; associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue : MagickFalse; if ((cube_info->quantize_info->number_colors == 2) && ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) || (cube_info->quantize_info->colorspace == GRAYColorspace))) associate_alpha=MagickFalse; cube_info->associate_alpha=associate_alpha; } static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, const Image *image,ExceptionInfo *exception) { #define ClassifyImageTag "Classify/Image" CacheView *image_view; DoublePixelPacket error, mid, midpoint, pixel; MagickBooleanType proceed; double bisect; NodeInfo *node_info; size_t count, id, index, level; ssize_t y; /* Classify the first cube_info->maximum_colors colors to a tree depth of 8. */ SetAssociatedAlpha(image,cube_info); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image, cube_info->quantize_info->colorspace,exception); else if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception); midpoint.red=(double) QuantumRange/2.0; midpoint.green=(double) QuantumRange/2.0; midpoint.blue=(double) QuantumRange/2.0; midpoint.alpha=(double) QuantumRange/2.0; error.alpha=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) { PixelInfo packet; GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet); if (IsPixelEquivalent(image,p,&packet) == MagickFalse) break; } AssociateAlphaPixel(image,cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((double) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= MaxTreeDepth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.alpha+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); continue; } if (level == MaxTreeDepth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.alpha=QuantumScale*(pixel.alpha-mid.alpha); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.alpha*error.alpha); if (IsNaN(distance)) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.alpha+=count*QuantumScale* ClampPixel(pixel.alpha); else node_info->total_color.alpha+=count*QuantumScale* ClampPixel((MagickRealType) OpaqueAlpha); p+=count*GetPixelChannels(image); } if (cube_info->colors > cube_info->maximum_colors) { PruneToCubeDepth(cube_info,cube_info->root); break; } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } for (y++; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) { PixelInfo packet; GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet); if (IsPixelEquivalent(image,p,&packet) == MagickFalse) break; } AssociateAlphaPixel(image,cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((double) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= cube_info->depth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.alpha+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","%s", image->filename); continue; } if (level == cube_info->depth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.alpha=QuantumScale*(pixel.alpha-mid.alpha); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.alpha*error.alpha); if (IsNaN(distance) != MagickFalse) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.alpha+=count*QuantumScale* ClampPixel(pixel.alpha); else node_info->total_color.alpha+=count*QuantumScale* ClampPixel((MagickRealType) OpaqueAlpha); p+=count*GetPixelChannels(image); } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } image_view=DestroyCacheView(image_view); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneQuantizeInfo() makes a duplicate of the given quantize info structure, % or if quantize info is NULL, a new one. % % The format of the CloneQuantizeInfo method is: % % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given % quantize info, or if image info is NULL a new one. % % o quantize_info: a structure of type info. % */ MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) { QuantizeInfo *clone_info; clone_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*clone_info)); GetQuantizeInfo(clone_info); if (quantize_info == (QuantizeInfo *) NULL) return(clone_info); clone_info->number_colors=quantize_info->number_colors; clone_info->tree_depth=quantize_info->tree_depth; clone_info->dither_method=quantize_info->dither_method; clone_info->colorspace=quantize_info->colorspace; clone_info->measure_error=quantize_info->measure_error; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o s e s t C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClosestColor() traverses the color cube tree at a particular node and % determines which colormap entry best represents the input color. % % The format of the ClosestColor method is: % % void ClosestColor(const Image *image,CubeInfo *cube_info, % const NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static void ClosestColor(const Image *image,CubeInfo *cube_info, const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) ClosestColor(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { double pixel; register double alpha, beta, distance; register DoublePixelPacket *magick_restrict q; register PixelInfo *magick_restrict p; /* Determine if this color is "closest". */ p=image->colormap+node_info->color_number; q=(&cube_info->target); alpha=1.0; beta=1.0; if (cube_info->associate_alpha != MagickFalse) { alpha=(double) (QuantumScale*p->alpha); beta=(double) (QuantumScale*q->alpha); } pixel=alpha*p->red-beta*q->red; distance=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*p->green-beta*q->green; distance+=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*p->blue-beta*q->blue; distance+=pixel*pixel; if (distance <= cube_info->distance) { if (cube_info->associate_alpha != MagickFalse) { pixel=p->alpha-q->alpha; distance+=pixel*pixel; } if (distance <= cube_info->distance) { cube_info->distance=distance; cube_info->color_number=node_info->color_number; } } } } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p r e s s I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompressImageColormap() compresses an image colormap by removing any % duplicate or unused color entries. % % The format of the CompressImageColormap method is: % % MagickBooleanType CompressImageColormap(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType CompressImageColormap(Image *image, ExceptionInfo *exception) { QuantizeInfo quantize_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsPaletteImage(image) == MagickFalse) return(MagickFalse); GetQuantizeInfo(&quantize_info); quantize_info.number_colors=image->colors; quantize_info.tree_depth=MaxTreeDepth; return(QuantizeImage(&quantize_info,image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e f i n e I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineImageColormap() traverses the color cube tree and notes each colormap % entry. A colormap entry is any node in the color cube tree where the % of unique colors is not zero. DefineImageColormap() returns the number of % colors in the image colormap. % % The format of the DefineImageColormap method is: % % size_t DefineImageColormap(Image *image,CubeInfo *cube_info, % NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static size_t DefineImageColormap(Image *image,CubeInfo *cube_info, NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) (void) DefineImageColormap(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { register double alpha; register PixelInfo *magick_restrict q; /* Colormap entry is defined by the mean color in this cube. */ q=image->colormap+image->colors; alpha=(double) ((MagickOffsetType) node_info->number_unique); alpha=PerceptibleReciprocal(alpha); if (cube_info->associate_alpha == MagickFalse) { q->red=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.red); q->green=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.green); q->blue=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.blue); q->alpha=(double) OpaqueAlpha; } else { double opacity; opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha); q->alpha=(double) ClampToQuantum(opacity); if (q->alpha == OpaqueAlpha) { q->red=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.red); q->green=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.green); q->blue=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.blue); } else { double gamma; gamma=(double) (QuantumScale*q->alpha); gamma=PerceptibleReciprocal(gamma); q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange* node_info->total_color.red); q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange* node_info->total_color.green); q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange* node_info->total_color.blue); if (node_info->number_unique > cube_info->transparent_pixels) { cube_info->transparent_pixels=node_info->number_unique; cube_info->transparent_index=(ssize_t) image->colors; } } } node_info->color_number=image->colors++; } return(image->colors); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyCubeInfo() deallocates memory associated with an image. % % The format of the DestroyCubeInfo method is: % % DestroyCubeInfo(CubeInfo *cube_info) % % A description of each parameter follows: % % o cube_info: the address of a structure of type CubeInfo. % */ static void DestroyCubeInfo(CubeInfo *cube_info) { register Nodes *nodes; /* Release color cube tree storage. */ do { nodes=cube_info->node_queue->next; cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory( cube_info->node_queue->nodes); cube_info->node_queue=(Nodes *) RelinquishMagickMemory( cube_info->node_queue); cube_info->node_queue=nodes; } while (cube_info->node_queue != (Nodes *) NULL); if (cube_info->memory_info != (MemoryInfo *) NULL) cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info); cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info); cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo % structure. % % The format of the DestroyQuantizeInfo method is: % % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % */ MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); assert(quantize_info->signature == MagickCoreSignature); quantize_info->signature=(~MagickCoreSignature); quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info); return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DitherImage() distributes the difference between an original image and % the corresponding color reduced algorithm to neighboring pixels using % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns % MagickTrue if the image is dithered otherwise MagickFalse. % % The format of the DitherImage method is: % % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o exception: return any errors or warnings in this structure. % */ static DoublePixelPacket **DestroyPixelThreadSet(DoublePixelPacket **pixels) { register ssize_t i; assert(pixels != (DoublePixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (DoublePixelPacket *) NULL) pixels[i]=(DoublePixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(DoublePixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static DoublePixelPacket **AcquirePixelThreadSet(const size_t count) { DoublePixelPacket **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(DoublePixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (DoublePixelPacket **) NULL) return((DoublePixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(DoublePixelPacket *) AcquireQuantumMemory(count,2* sizeof(**pixels)); if (pixels[i] == (DoublePixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static inline ssize_t CacheOffset(CubeInfo *cube_info, const DoublePixelPacket *pixel) { #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift))) #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift))) #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift))) #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift))) ssize_t offset; offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) | GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) | BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue)))); if (cube_info->associate_alpha != MagickFalse) offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha))); return(offset); } static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info, ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; const char *artifact; double amount; DoublePixelPacket **pixels; MagickBooleanType status; ssize_t y; /* Distribute quantization error using Floyd-Steinberg. */ pixels=AcquirePixelThreadSet(image->columns); if (pixels == (DoublePixelPacket **) NULL) return(MagickFalse); status=MagickTrue; amount=1.0; artifact=GetImageArtifact(image,"dither:diffusion-amount"); if (artifact != (const char *) NULL) amount=StringToDoubleInterval(artifact,1.0); image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); CubeInfo cube; DoublePixelPacket *current, *previous; register Quantum *magick_restrict q; register ssize_t x; size_t index; ssize_t v; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } cube=(*cube_info); current=pixels[id]+(y & 0x01)*image->columns; previous=pixels[id]+((y+1) & 0x01)*image->columns; v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1); for (x=0; x < (ssize_t) image->columns; x++) { DoublePixelPacket color, pixel; register ssize_t i; ssize_t u; u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x; AssociateAlphaPixel(image,&cube,q+u*GetPixelChannels(image),&pixel); if (x > 0) { pixel.red+=7.0*amount*current[u-v].red/16; pixel.green+=7.0*amount*current[u-v].green/16; pixel.blue+=7.0*amount*current[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.alpha+=7.0*amount*current[u-v].alpha/16; } if (y > 0) { if (x < (ssize_t) (image->columns-1)) { pixel.red+=previous[u+v].red/16; pixel.green+=previous[u+v].green/16; pixel.blue+=previous[u+v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.alpha+=previous[u+v].alpha/16; } pixel.red+=5.0*amount*previous[u].red/16; pixel.green+=5.0*amount*previous[u].green/16; pixel.blue+=5.0*amount*previous[u].blue/16; if (cube.associate_alpha != MagickFalse) pixel.alpha+=5.0*amount*previous[u].alpha/16; if (x > 0) { pixel.red+=3.0*amount*previous[u-v].red/16; pixel.green+=3.0*amount*previous[u-v].green/16; pixel.blue+=3.0*amount*previous[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.alpha+=3.0*amount*previous[u-v].alpha/16; } } pixel.red=(double) ClampPixel(pixel.red); pixel.green=(double) ClampPixel(pixel.green); pixel.blue=(double) ClampPixel(pixel.blue); if (cube.associate_alpha != MagickFalse) pixel.alpha=(double) ClampPixel(pixel.alpha); i=CacheOffset(&cube,&pixel); if (cube.cache[i] < 0) { register NodeInfo *node_info; register size_t node_id; /* Identify the deepest node containing the pixel's color. */ node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { node_id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[node_id] == (NodeInfo *) NULL) break; node_info=node_info->child[node_id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+ 1.0); ClosestColor(image,&cube,node_info->parent); cube.cache[i]=(ssize_t) cube.color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) cube.cache[i]; if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) index,q+u*GetPixelChannels(image)); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRed(image,ClampToQuantum(image->colormap[index].red), q+u*GetPixelChannels(image)); SetPixelGreen(image,ClampToQuantum(image->colormap[index].green), q+u*GetPixelChannels(image)); SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue), q+u*GetPixelChannels(image)); if (cube.associate_alpha != MagickFalse) SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha), q+u*GetPixelChannels(image)); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; /* Store the error. */ AssociateAlphaPixelInfo(&cube,image->colormap+index,&color); current[u].red=pixel.red-color.red; current[u].green=pixel.green-color.green; current[u].blue=pixel.blue-color.blue; if (cube.associate_alpha != MagickFalse) current[u].alpha=pixel.alpha-color.alpha; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } image_view=DestroyCacheView(image_view); pixels=DestroyPixelThreadSet(pixels); return(MagickTrue); } static MagickBooleanType RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int, ExceptionInfo *); static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info, const size_t level,const unsigned int direction,ExceptionInfo *exception) { if (level == 1) switch (direction) { case WestGravity: { (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); break; } case EastGravity: { (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); break; } case NorthGravity: { (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); break; } case SouthGravity: { (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); break; } default: break; } else switch (direction) { case WestGravity: { Riemersma(image,image_view,cube_info,level-1,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); Riemersma(image,image_view,cube_info,level-1,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); Riemersma(image,image_view,cube_info,level-1,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); Riemersma(image,image_view,cube_info,level-1,SouthGravity, exception); break; } case EastGravity: { Riemersma(image,image_view,cube_info,level-1,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); Riemersma(image,image_view,cube_info,level-1,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); Riemersma(image,image_view,cube_info,level-1,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); Riemersma(image,image_view,cube_info,level-1,NorthGravity, exception); break; } case NorthGravity: { Riemersma(image,image_view,cube_info,level-1,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); Riemersma(image,image_view,cube_info,level-1,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); Riemersma(image,image_view,cube_info,level-1,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); Riemersma(image,image_view,cube_info,level-1,EastGravity, exception); break; } case SouthGravity: { Riemersma(image,image_view,cube_info,level-1,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); Riemersma(image,image_view,cube_info,level-1,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); Riemersma(image,image_view,cube_info,level-1,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); Riemersma(image,image_view,cube_info,level-1,WestGravity, exception); break; } default: break; } } static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view, CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" DoublePixelPacket color, pixel; MagickBooleanType proceed; register CubeInfo *p; size_t index; p=cube_info; if ((p->x >= 0) && (p->x < (ssize_t) image->columns) && (p->y >= 0) && (p->y < (ssize_t) image->rows)) { register Quantum *magick_restrict q; register ssize_t i; /* Distribute error. */ q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); AssociateAlphaPixel(image,cube_info,q,&pixel); for (i=0; i < ErrorQueueLength; i++) { pixel.red+=p->weights[i]*p->error[i].red; pixel.green+=p->weights[i]*p->error[i].green; pixel.blue+=p->weights[i]*p->error[i].blue; if (cube_info->associate_alpha != MagickFalse) pixel.alpha+=p->weights[i]*p->error[i].alpha; } pixel.red=(double) ClampPixel(pixel.red); pixel.green=(double) ClampPixel(pixel.green); pixel.blue=(double) ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) pixel.alpha=(double) ClampPixel(pixel.alpha); i=CacheOffset(cube_info,&pixel); if (p->cache[i] < 0) { register NodeInfo *node_info; register size_t id; /* Identify the deepest node containing the pixel's color. */ node_info=p->root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(cube_info,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ p->target=pixel; p->distance=(double) (4.0*(QuantumRange+1.0)*((double) QuantumRange+1.0)+1.0); ClosestColor(image,p,node_info->parent); p->cache[i]=(ssize_t) p->color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) p->cache[i]; if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) index,q); if (cube_info->quantize_info->measure_error == MagickFalse) { SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q); if (cube_info->associate_alpha != MagickFalse) SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) return(MagickFalse); /* Propagate the error as the last entry of the error queue. */ (void) memmove(p->error,p->error+1,(ErrorQueueLength-1)* sizeof(p->error[0])); AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color); p->error[ErrorQueueLength-1].red=pixel.red-color.red; p->error[ErrorQueueLength-1].green=pixel.green-color.green; p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue; if (cube_info->associate_alpha != MagickFalse) p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha; proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span); if (proceed == MagickFalse) return(MagickFalse); p->offset++; } switch (direction) { case WestGravity: p->x--; break; case EastGravity: p->x++; break; case NorthGravity: p->y--; break; case SouthGravity: p->y++; break; } return(MagickTrue); } static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; register ssize_t i; size_t depth; if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod) return(FloydSteinbergDither(image,cube_info,exception)); /* Distribute quantization error along a Hilbert curve. */ (void) memset(cube_info->error,0,ErrorQueueLength* sizeof(*cube_info->error)); cube_info->x=0; cube_info->y=0; i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows); for (depth=1; i != 0; depth++) i>>=1; if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows)) depth++; cube_info->offset=0; cube_info->span=(MagickSizeType) image->columns*image->rows; image_view=AcquireAuthenticCacheView(image,exception); if (depth > 1) Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception); status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCubeInfo() initialize the Cube data structure. % % The format of the GetCubeInfo method is: % % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info, % const size_t depth,const size_t maximum_colors) % % A description of each parameter follows. % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o depth: Normally, this integer value is zero or one. A zero or % one tells Quantize to choose a optimal tree depth of Log4(number_colors). % A tree of this depth generally allows the best representation of the % reference image with the least amount of memory and the fastest % computational speed. In some cases, such as an image with low color % dispersion (a few number of colors), a value other than % Log4(number_colors) is required. To expand the color tree completely, % use a value of 8. % % o maximum_colors: maximum colors. % */ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info, const size_t depth,const size_t maximum_colors) { CubeInfo *cube_info; double sum, weight; register ssize_t i; size_t length; /* Initialize tree to describe color cube_info. */ cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info)); if (cube_info == (CubeInfo *) NULL) return((CubeInfo *) NULL); (void) memset(cube_info,0,sizeof(*cube_info)); cube_info->depth=depth; if (cube_info->depth > MaxTreeDepth) cube_info->depth=MaxTreeDepth; if (cube_info->depth < 2) cube_info->depth=2; cube_info->maximum_colors=maximum_colors; /* Initialize root node. */ cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL); if (cube_info->root == (NodeInfo *) NULL) return((CubeInfo *) NULL); cube_info->root->parent=cube_info->root; cube_info->quantize_info=CloneQuantizeInfo(quantize_info); if (cube_info->quantize_info->dither_method == NoDitherMethod) return(cube_info); /* Initialize dither resources. */ length=(size_t) (1UL << (4*(8-CacheShift))); cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache)); if (cube_info->memory_info == (MemoryInfo *) NULL) return((CubeInfo *) NULL); cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info); /* Initialize color cache. */ (void) memset(cube_info->cache,(-1),sizeof(*cube_info->cache)* length); /* Distribute weights along a curve of exponential decay. */ weight=1.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight); weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0)); } /* Normalize the weighting factors. */ weight=0.0; for (i=0; i < ErrorQueueLength; i++) weight+=cube_info->weights[i]; sum=0.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[i]/=weight; sum+=cube_info->weights[i]; } cube_info->weights[0]+=1.0-sum; return(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t N o d e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNodeInfo() allocates memory for a new node in the color cube tree and % presets all fields to zero. % % The format of the GetNodeInfo method is: % % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, % const size_t level,NodeInfo *parent) % % A description of each parameter follows. % % o node: The GetNodeInfo method returns a pointer to a queue of nodes. % % o id: Specifies the child number of the node. % % o level: Specifies the level in the storage_class the node resides. % */ static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, const size_t level,NodeInfo *parent) { NodeInfo *node_info; if (cube_info->free_nodes == 0) { Nodes *nodes; /* Allocate a new queue of nodes. */ nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes)); if (nodes == (Nodes *) NULL) return((NodeInfo *) NULL); nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList, sizeof(*nodes->nodes)); if (nodes->nodes == (NodeInfo *) NULL) return((NodeInfo *) NULL); nodes->next=cube_info->node_queue; cube_info->node_queue=nodes; cube_info->next_node=nodes->nodes; cube_info->free_nodes=NodesInAList; } cube_info->nodes++; cube_info->free_nodes--; node_info=cube_info->next_node++; (void) memset(node_info,0,sizeof(*node_info)); node_info->parent=parent; node_info->id=id; node_info->level=level; return(node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e Q u a n t i z e E r r o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageQuantizeError() measures the difference between the original % and quantized images. This difference is the total quantization error. % The error is computed by summing over all pixels in an image the distance % squared in RGB space between each reference pixel value and its quantized % value. These values are computed: % % o mean_error_per_pixel: This value is the mean error for any single % pixel in the image. % % o normalized_mean_square_error: This value is the normalized mean % quantization error for any single pixel in the image. This distance % measure is normalized to a range between 0 and 1. It is independent % of the range of red, green, and blue values in the image. % % o normalized_maximum_square_error: Thsi value is the normalized % maximum quantization error for any single pixel in the image. This % distance measure is normalized to a range between 0 and 1. It is % independent of the range of red, green, and blue values in your image. % % The format of the GetImageQuantizeError method is: % % MagickBooleanType GetImageQuantizeError(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageQuantizeError(Image *image, ExceptionInfo *exception) { CacheView *image_view; double alpha, area, beta, distance, maximum_error, mean_error, mean_error_per_pixel; ssize_t index, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->total_colors=GetNumberColors(image,(FILE *) NULL,exception); (void) memset(&image->error,0,sizeof(image->error)); if (image->storage_class == DirectClass) return(MagickTrue); alpha=1.0; beta=1.0; area=3.0*image->columns*image->rows; maximum_error=0.0; mean_error_per_pixel=0.0; mean_error=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=(ssize_t) GetPixelIndex(image,p); if (image->alpha_trait == BlendPixelTrait) { alpha=(double) (QuantumScale*GetPixelAlpha(image,p)); beta=(double) (QuantumScale*image->colormap[index].alpha); } distance=fabs((double) (alpha*GetPixelRed(image,p)-beta* image->colormap[index].red)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelGreen(image,p)-beta* image->colormap[index].green)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelBlue(image,p)-beta* image->colormap[index].blue)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area; image->error.normalized_mean_error=(double) QuantumScale*QuantumScale* mean_error/area; image->error.normalized_maximum_error=(double) QuantumScale*maximum_error; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantizeInfo() initializes the QuantizeInfo structure. % % The format of the GetQuantizeInfo method is: % % GetQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to a QuantizeInfo structure. % */ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); (void) memset(quantize_info,0,sizeof(*quantize_info)); quantize_info->number_colors=256; quantize_info->dither_method=RiemersmaDitherMethod; quantize_info->colorspace=UndefinedColorspace; quantize_info->measure_error=MagickFalse; quantize_info->signature=MagickCoreSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PosterizeImage() reduces the image to a limited number of colors for a % "poster" effect. % % The format of the PosterizeImage method is: % % MagickBooleanType PosterizeImage(Image *image,const size_t levels, % const DitherMethod dither_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Specifies a pointer to an Image structure. % % o levels: Number of color levels allowed in each channel. Very low values % (2, 3, or 4) have the most visible effect. % % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod, % RiemersmaDitherMethod, FloydSteinbergDitherMethod. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels, const DitherMethod dither_method,ExceptionInfo *exception) { #define PosterizeImageTag "Posterize/Image" #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \ QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1)) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; QuantizeInfo *quantize_info; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (image->storage_class == PseudoClass) #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->colors,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { /* Posterize colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) PosterizePixel(image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) PosterizePixel(image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) PosterizePixel(image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) PosterizePixel(image->colormap[i].alpha); } /* Posterize image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q); if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q); if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait == BlendPixelTrait)) SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,PosterizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL); quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels* levels,MaxColormapSize+1); quantize_info->dither_method=dither_method; quantize_info->tree_depth=MaxTreeDepth; status=QuantizeImage(quantize_info,image,exception); quantize_info=DestroyQuantizeInfo(quantize_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e C h i l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneChild() deletes the given node and merges its statistics into its % parent. % % The format of the PruneSubtree method is: % % PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) { NodeInfo *parent; register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneChild(cube_info,node_info->child[i]); /* Merge color statistics into parent. */ parent=node_info->parent; parent->number_unique+=node_info->number_unique; parent->total_color.red+=node_info->total_color.red; parent->total_color.green+=node_info->total_color.green; parent->total_color.blue+=node_info->total_color.blue; parent->total_color.alpha+=node_info->total_color.alpha; parent->child[node_info->id]=(NodeInfo *) NULL; cube_info->nodes--; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e L e v e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneLevel() deletes all nodes at the bottom level of the color tree merging % their color statistics into their parent node. % % The format of the PruneLevel method is: % % PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneLevel(cube_info,node_info->child[i]); if (node_info->level == cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e T o C u b e D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneToCubeDepth() deletes any nodes at a depth greater than % cube_info->depth while merging their color statistics into their parent % node. % % The format of the PruneToCubeDepth method is: % % PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneToCubeDepth(cube_info,node_info->child[i]); if (node_info->level > cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImage() analyzes the colors within a reference image and chooses a % fixed number of colors to represent the image. The goal of the algorithm % is to minimize the color difference between the input and output image while % minimizing the processing time. % % The format of the QuantizeImage method is: % % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, Image *image,ExceptionInfo *exception) { CubeInfo *cube_info; MagickBooleanType status; size_t depth, maximum_colors; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; if (image->alpha_trait != BlendPixelTrait) { if (SetImageGray(image,exception) != MagickFalse) (void) SetGrayscaleImage(image,exception); } if ((image->storage_class == PseudoClass) && (image->colors <= maximum_colors)) { if ((quantize_info->colorspace != UndefinedColorspace) && (quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace(image,quantize_info->colorspace, exception); return(MagickTrue); } depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2)) depth--; if ((image->alpha_trait == BlendPixelTrait) && (depth > 5)) depth--; if (SetImageGray(image,exception) != MagickFalse) depth=MaxTreeDepth; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,image,exception); if (status != MagickFalse) { /* Reduce the number of colors in the image if it contains more than the maximum, otherwise we can disable dithering to improve the performance. */ if (cube_info->colors > cube_info->maximum_colors) ReduceImageColors(image,cube_info); else cube_info->quantize_info->dither_method=NoDitherMethod; status=AssignImageColors(image,cube_info,exception); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImages() analyzes the colors within a set of reference images and % chooses a fixed number of colors to represent the set. The goal of the % algorithm is to minimize the color difference between the input and output % images while minimizing the processing time. % % The format of the QuantizeImages method is: % % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, % Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: Specifies a pointer to a list of Image structures. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, Image *images,ExceptionInfo *exception) { CubeInfo *cube_info; Image *image; MagickBooleanType proceed, status; MagickProgressMonitor progress_monitor; register ssize_t i; size_t depth, maximum_colors, number_images; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (GetNextImageInList(images) == (Image *) NULL) { /* Handle a single image with QuantizeImage. */ status=QuantizeImage(quantize_info,images,exception); return(status); } status=MagickFalse; maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if (quantize_info->dither_method != NoDitherMethod) depth--; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return(MagickFalse); } number_images=GetImageListLength(images); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL, image->client_data); status=ClassifyImageColors(cube_info,image,exception); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } if (status != MagickFalse) { /* Reduce the number of colors in an image sequence. */ ReduceImageColors(images,cube_info); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,image->client_data); status=AssignImageColors(image,cube_info,exception); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u a n t i z e E r r o r F l a t t e n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeErrorFlatten() traverses the color cube and flattens the quantization % error into a sorted 1D array. This accelerates the color reduction process. % % Contributed by Yoya. % % The format of the QuantizeErrorFlatten method is: % % size_t QuantizeErrorFlatten(const CubeInfo *cube_info, % const NodeInfo *node_info,const ssize_t offset, % double *quantize_error) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is current pointer. % % o offset: quantize error offset. % % o quantize_error: the quantization error vector. % */ static size_t QuantizeErrorFlatten(const CubeInfo *cube_info, const NodeInfo *node_info,const ssize_t offset,double *quantize_error) { register ssize_t i; size_t n, number_children; if (offset >= (ssize_t) cube_info->nodes) return(0); quantize_error[offset]=node_info->quantize_error; n=1; number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children ; i++) if (node_info->child[i] != (NodeInfo *) NULL) n+=QuantizeErrorFlatten(cube_info,node_info->child[i],offset+n, quantize_error); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Reduce() traverses the color cube tree and prunes any node whose % quantization error falls below a particular threshold. % % The format of the Reduce method is: % % Reduce(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void Reduce(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) Reduce(cube_info,node_info->child[i]); if (node_info->quantize_error <= cube_info->pruning_threshold) PruneChild(cube_info,node_info); else { /* Find minimum pruning threshold. */ if (node_info->number_unique > 0) cube_info->colors++; if (node_info->quantize_error < cube_info->next_threshold) cube_info->next_threshold=node_info->quantize_error; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReduceImageColors() repeatedly prunes the tree until the number of nodes % with n2 > 0 is less than or equal to the maximum number of colors allowed % in the output image. On any given iteration over the tree, it selects % those nodes whose E value is minimal for pruning and merges their % color statistics upward. It uses a pruning threshold, Ep, to govern % node selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors % within the cubic volume which the node represents. This includes n1 - % n2 pixels whose colors should be defined by nodes at a lower level in % the tree. % % The format of the ReduceImageColors method is: % % ReduceImageColors(const Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static int QuantizeErrorCompare(const void *error_p,const void *error_q) { double *p, *q; p=(double *) error_p; q=(double *) error_q; if (*p > *q) return(1); if (fabs(*q-*p) <= MagickEpsilon) return(0); return(-1); } static void ReduceImageColors(const Image *image,CubeInfo *cube_info) { #define ReduceImageTag "Reduce/Image" MagickBooleanType proceed; MagickOffsetType offset; size_t span; cube_info->next_threshold=0.0; if (cube_info->colors > cube_info->maximum_colors) { double *quantize_error; /* Enable rapid reduction of the number of unique colors. */ quantize_error=(double *) AcquireQuantumMemory(cube_info->nodes, sizeof(*quantize_error)); if (quantize_error != (double *) NULL) { (void) QuantizeErrorFlatten(cube_info,cube_info->root,0, quantize_error); qsort(quantize_error,cube_info->nodes,sizeof(double), QuantizeErrorCompare); if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100)) cube_info->next_threshold=quantize_error[cube_info->nodes-110* (cube_info->maximum_colors+1)/100]; quantize_error=(double *) RelinquishMagickMemory(quantize_error); } } for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; ) { cube_info->pruning_threshold=cube_info->next_threshold; cube_info->next_threshold=cube_info->root->quantize_error-1; cube_info->colors=0; Reduce(cube_info,cube_info->root); offset=(MagickOffsetType) span-cube_info->colors; proceed=SetImageProgress(image,ReduceImageTag,offset,span- cube_info->maximum_colors+1); if (proceed == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImage() replaces the colors of an image with the closest of the colors % from the reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, % Image *image,const Image *remap_image,ExceptionInfo *exception) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % % o remap_image: the reference image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, Image *image,const Image *remap_image,ExceptionInfo *exception) { CubeInfo *cube_info; MagickBooleanType status; /* Initialize color cube. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(remap_image != (Image *) NULL); assert(remap_image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; status=AssignImageColors(image,cube_info,exception); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImages() replaces the colors of a sequence of images with the % closest color from a reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, % Image *images,Image *remap_image,ExceptionInfo *exception) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: the image sequence. % % o remap_image: the reference image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, Image *images,const Image *remap_image,ExceptionInfo *exception) { CubeInfo *cube_info; Image *image; MagickBooleanType status; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=images; if (remap_image == (Image *) NULL) { /* Create a global colormap for an image sequence. */ status=QuantizeImages(quantize_info,images,exception); return(status); } /* Classify image colors from the reference image. */ cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) { status=AssignImageColors(image,cube_info,exception); if (status == MagickFalse) break; } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetGrayscaleImage() converts an image to a PseudoClass grayscale image. % % The format of the SetGrayscaleImage method is: % % MagickBooleanType SetGrayscaleImage(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { double intensity; PixelInfo *color_1, *color_2; color_1=(PixelInfo *) x; color_2=(PixelInfo *) y; intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)- GetPixelInfoIntensity((const Image *) NULL,color_2); return((int) intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType SetGrayscaleImage(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; PixelInfo *colormap; register ssize_t i; size_t extent; ssize_t *colormap_index, j, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->type != GrayscaleType) (void) TransformImageColorspace(image,GRAYColorspace,exception); extent=MagickMax(image->colors+1,MagickMax(MaxColormapSize,MaxMap+1)); colormap_index=(ssize_t *) AcquireQuantumMemory(extent, sizeof(*colormap_index)); if (colormap_index == (ssize_t *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); if (image->storage_class != PseudoClass) { (void) memset(colormap_index,(-1),extent*sizeof(*colormap_index)); if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } image->colors=0; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register size_t intensity; intensity=ScaleQuantumToMap(GetPixelRed(image,q)); if (colormap_index[intensity] < 0) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SetGrayscaleImage) #endif if (colormap_index[intensity] < 0) { colormap_index[intensity]=(ssize_t) image->colors; image->colormap[image->colors].red=(double) GetPixelRed(image,q); image->colormap[image->colors].green=(double) GetPixelGreen(image,q); image->colormap[image->colors].blue=(double) GetPixelBlue(image,q); image->colors++; } } SetPixelIndex(image,(Quantum) colormap_index[intensity],q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); } (void) memset(colormap_index,0,extent*sizeof(*colormap_index)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].alpha=(double) i; qsort((void *) image->colormap,image->colors,sizeof(PixelInfo), IntensityCompare); colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap)); if (colormap == (PixelInfo *) NULL) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } j=0; colormap[j]=image->colormap[0]; for (i=0; i < (ssize_t) image->colors; i++) { if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse) { j++; colormap[j]=image->colormap[i]; } colormap_index[(ssize_t) image->colormap[i].alpha]=j; } image->colors=(size_t) (j+1); image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap); image->colormap=colormap; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap( GetPixelIndex(image,q))],q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); image->type=GrayscaleType; if (SetImageMonochrome(image,exception) != MagickFalse) image->type=BilevelType; return(status); }
fft.c
/**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* 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 */ /**********************************************************************************************/ /* * Original code from the Cilk project * * Copyright (c) 2000 Massachusetts Institute of Technology * Copyright (c) 2000 Matteo Frigo */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <sys/time.h> #include <omp.h> #include "../../common/BOTSCommonUtils.h" #include "fft.h" /* Definitions and operations for complex numbers */ /* * compute the W coefficients (that is, powers of the root of 1) * and store them into an array. */ int size = 32*1024*1024; void compute_w_coefficients(int n, int a, int b, COMPLEX * W) { register double twoPiOverN; register int k; register REAL s, c; if (b - a < 128) { twoPiOverN = 2.0 * 3.1415926535897932384626434 / n; for (k = a; k <= b; ++k) { c = cos(twoPiOverN * k); c_re(W[k]) = c_re(W[n - k]) = c; s = sin(twoPiOverN * k); c_im(W[k]) = -s; c_im(W[n - k]) = s; } } else { int ab = (a + b) / 2; #pragma omp task untied compute_w_coefficients(n, a, ab, W); #pragma omp task untied compute_w_coefficients(n, ab + 1, b, W); #pragma omp taskwait } } void compute_w_coefficients_seq(int n, int a, int b, COMPLEX * W) { register double twoPiOverN; register int k; register REAL s, c; if (b - a < 128) { twoPiOverN = 2.0 * 3.1415926535897932384626434 / n; for (k = a; k <= b; ++k) { c = cos(twoPiOverN * k); c_re(W[k]) = c_re(W[n - k]) = c; s = sin(twoPiOverN * k); c_im(W[k]) = -s; c_im(W[n - k]) = s; } } else { int ab = (a + b) / 2; compute_w_coefficients_seq(n, a, ab, W); compute_w_coefficients_seq(n, ab + 1, b, W); } } /* * Determine (in a stupid way) if n is divisible by eight, then by four, else * find the smallest prime factor of n. */ int factor(int n) { int r; if (n < 2) return 1; if (n == 64 || n == 128 || n == 256 || n == 1024 || n == 2048 || n == 4096) return 8; if ((n & 15) == 0) return 16; if ((n & 7) == 0) return 8; if ((n & 3) == 0) return 4; if ((n & 1) == 0) return 2; /* try odd numbers up to n (computing the sqrt may be slower) */ for (r = 3; r < n; r += 2) if (n % r == 0) return r; /* n is prime */ return n; } void unshuffle(int a, int b, COMPLEX * in, COMPLEX * out, int r, int m) { int i, j; int r4 = r & (~0x3); const COMPLEX *ip; COMPLEX *jp; if (b - a < 16) { ip = in + a * r; for (i = a; i < b; ++i) { jp = out + i; for (j = 0; j < r4; j += 4) { jp[0] = ip[0]; jp[m] = ip[1]; jp[2 * m] = ip[2]; jp[3 * m] = ip[3]; jp += 4 * m; ip += 4; } for (; j < r; ++j) { *jp = *ip; ip++; jp += m; } } } else { int ab = (a + b) / 2; #pragma omp task untied unshuffle(a, ab, in, out, r, m); #pragma omp task untied unshuffle(ab, b, in, out, r, m); #pragma omp taskwait } } void unshuffle_seq(int a, int b, COMPLEX * in, COMPLEX * out, int r, int m) { int i, j; int r4 = r & (~0x3); const COMPLEX *ip; COMPLEX *jp; if (b - a < 16) { ip = in + a * r; for (i = a; i < b; ++i) { jp = out + i; for (j = 0; j < r4; j += 4) { jp[0] = ip[0]; jp[m] = ip[1]; jp[2 * m] = ip[2]; jp[3 * m] = ip[3]; jp += 4 * m; ip += 4; } for (; j < r; ++j) { *jp = *ip; ip++; jp += m; } } } else { int ab = (a + b) / 2; unshuffle_seq(a, ab, in, out, r, m); unshuffle_seq(ab, b, in, out, r, m); } } void fft_twiddle_gen1(COMPLEX * in, COMPLEX * out, COMPLEX * W, int r, int m, int nW, int nWdnti, int nWdntm) { int j, k; COMPLEX *jp, *kp; for (k = 0, kp = out; k < r; ++k, kp += m) { REAL r0, i0, rt, it, rw, iw; int l1 = nWdnti + nWdntm * k; int l0; r0 = i0 = 0.0; for (j = 0, jp = in, l0 = 0; j < r; ++j, jp += m) { rw = c_re(W[l0]); iw = c_im(W[l0]); rt = c_re(*jp); it = c_im(*jp); r0 += rt * rw - it * iw; i0 += rt * iw + it * rw; l0 += l1; if (l0 > nW) l0 -= nW; } c_re(*kp) = r0; c_im(*kp) = i0; } } void fft_twiddle_gen(int i, int i1, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int r, int m) { if (i == i1 - 1) { #pragma omp task untied fft_twiddle_gen1(in + i, out + i, W, r, m, nW, nWdn * i, nWdn * m); } else { int i2 = (i + i1) / 2; #pragma omp task untied fft_twiddle_gen(i, i2, in, out, W, nW, nWdn, r, m); #pragma omp task untied fft_twiddle_gen(i2, i1, in, out, W, nW, nWdn, r, m); } #pragma omp taskwait } void fft_twiddle_gen_seq(int i, int i1, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int r, int m) { if (i == i1 - 1) { fft_twiddle_gen1(in + i, out + i, W, r, m, nW, nWdn * i, nWdn * m); } else { int i2 = (i + i1) / 2; fft_twiddle_gen_seq(i, i2, in, out, W, nW, nWdn, r, m); fft_twiddle_gen_seq(i2, i1, in, out, W, nW, nWdn, r, m); } } /* machine-generated code begins here */ void fft_base_2(COMPLEX * in, COMPLEX * out) { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(in[0]); i1_0 = c_im(in[0]); r1_1 = c_re(in[1]); i1_1 = c_im(in[1]); c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[1]) = (r1_0 - r1_1); c_im(out[1]) = (i1_0 - i1_1); } void fft_twiddle_2(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(jp[0 * m]); i1_0 = c_im(jp[0 * m]); wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r1_1 = ((wr * tmpr) - (wi * tmpi)); i1_1 = ((wi * tmpr) + (wr * tmpi)); c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[1 * m]) = (r1_0 - r1_1); c_im(kp[1 * m]) = (i1_0 - i1_1); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_2(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_2(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_2_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(jp[0 * m]); i1_0 = c_im(jp[0 * m]); wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r1_1 = ((wr * tmpr) - (wi * tmpi)); i1_1 = ((wi * tmpr) + (wr * tmpi)); c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[1 * m]) = (r1_0 - r1_1); c_im(kp[1 * m]) = (i1_0 - i1_1); } } } else { int ab = (a + b) / 2; fft_twiddle_2_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_2_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_2(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 2; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_2(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_2(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_2_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 2; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_2_seq(a, ab, in, out, m); fft_unshuffle_2_seq(ab, b, in, out, m); } } void fft_base_4(COMPLEX * in, COMPLEX * out) { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(in[0]); i2_0 = c_im(in[0]); r2_2 = c_re(in[2]); i2_2 = c_im(in[2]); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; r2_1 = c_re(in[1]); i2_1 = c_im(in[1]); r2_3 = c_re(in[3]); i2_3 = c_im(in[3]); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[2]) = (r1_0 - r1_1); c_im(out[2]) = (i1_0 - i1_1); c_re(out[1]) = (r1_2 + i1_3); c_im(out[1]) = (i1_2 - r1_3); c_re(out[3]) = (r1_2 - i1_3); c_im(out[3]) = (i1_2 + r1_3); } void fft_twiddle_4(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(jp[0 * m]); i2_0 = c_im(jp[0 * m]); wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r2_2 = ((wr * tmpr) - (wi * tmpi)); i2_2 = ((wi * tmpr) + (wr * tmpi)); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r2_1 = ((wr * tmpr) - (wi * tmpi)); i2_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r2_3 = ((wr * tmpr) - (wi * tmpi)); i2_3 = ((wi * tmpr) + (wr * tmpi)); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[2 * m]) = (r1_0 - r1_1); c_im(kp[2 * m]) = (i1_0 - i1_1); c_re(kp[1 * m]) = (r1_2 + i1_3); c_im(kp[1 * m]) = (i1_2 - r1_3); c_re(kp[3 * m]) = (r1_2 - i1_3); c_im(kp[3 * m]) = (i1_2 + r1_3); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_4(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_4(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_4_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(jp[0 * m]); i2_0 = c_im(jp[0 * m]); wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r2_2 = ((wr * tmpr) - (wi * tmpi)); i2_2 = ((wi * tmpr) + (wr * tmpi)); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r2_1 = ((wr * tmpr) - (wi * tmpi)); i2_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r2_3 = ((wr * tmpr) - (wi * tmpi)); i2_3 = ((wi * tmpr) + (wr * tmpi)); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[2 * m]) = (r1_0 - r1_1); c_im(kp[2 * m]) = (i1_0 - i1_1); c_re(kp[1 * m]) = (r1_2 + i1_3); c_im(kp[1 * m]) = (i1_2 - r1_3); c_re(kp[3 * m]) = (r1_2 - i1_3); c_im(kp[3 * m]) = (i1_2 + r1_3); } } } else { int ab = (a + b) / 2; fft_twiddle_4_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_4_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_4(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 4; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_4(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_4(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_4_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 4; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_4_seq(a, ab, in, out, m); fft_unshuffle_4_seq(ab, b, in, out, m); } } void fft_base_8(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(in[0]); i3_0 = c_im(in[0]); r3_4 = c_re(in[4]); i3_4 = c_im(in[4]); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; r3_2 = c_re(in[2]); i3_2 = c_im(in[2]); r3_6 = c_re(in[6]); i3_6 = c_im(in[6]); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; r3_1 = c_re(in[1]); i3_1 = c_im(in[1]); r3_5 = c_re(in[5]); i3_5 = c_im(in[5]); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; r3_3 = c_re(in[3]); i3_3 = c_im(in[3]); r3_7 = c_re(in[7]); i3_7 = c_im(in[7]); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[4]) = (r1_0 - r1_1); c_im(out[4]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[5]) = (r1_2 - tmpr); c_im(out[5]) = (i1_2 - tmpi); c_re(out[2]) = (r1_4 + i1_5); c_im(out[2]) = (i1_4 - r1_5); c_re(out[6]) = (r1_4 - i1_5); c_im(out[6]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 - tmpi); c_re(out[7]) = (r1_6 - tmpr); c_im(out[7]) = (i1_6 + tmpi); } } void fft_twiddle_8(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(jp[0 * m]); i3_0 = c_im(jp[0 * m]); wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r3_4 = ((wr * tmpr) - (wi * tmpi)); i3_4 = ((wi * tmpr) + (wr * tmpi)); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r3_2 = ((wr * tmpr) - (wi * tmpi)); i3_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r3_6 = ((wr * tmpr) - (wi * tmpi)); i3_6 = ((wi * tmpr) + (wr * tmpi)); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r3_1 = ((wr * tmpr) - (wi * tmpi)); i3_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r3_5 = ((wr * tmpr) - (wi * tmpi)); i3_5 = ((wi * tmpr) + (wr * tmpi)); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r3_3 = ((wr * tmpr) - (wi * tmpi)); i3_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r3_7 = ((wr * tmpr) - (wi * tmpi)); i3_7 = ((wi * tmpr) + (wr * tmpi)); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[4 * m]) = (r1_0 - r1_1); c_im(kp[4 * m]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[5 * m]) = (r1_2 - tmpr); c_im(kp[5 * m]) = (i1_2 - tmpi); c_re(kp[2 * m]) = (r1_4 + i1_5); c_im(kp[2 * m]) = (i1_4 - r1_5); c_re(kp[6 * m]) = (r1_4 - i1_5); c_im(kp[6 * m]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 - tmpi); c_re(kp[7 * m]) = (r1_6 - tmpr); c_im(kp[7 * m]) = (i1_6 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_8(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_8(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_8_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(jp[0 * m]); i3_0 = c_im(jp[0 * m]); wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r3_4 = ((wr * tmpr) - (wi * tmpi)); i3_4 = ((wi * tmpr) + (wr * tmpi)); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r3_2 = ((wr * tmpr) - (wi * tmpi)); i3_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r3_6 = ((wr * tmpr) - (wi * tmpi)); i3_6 = ((wi * tmpr) + (wr * tmpi)); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r3_1 = ((wr * tmpr) - (wi * tmpi)); i3_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r3_5 = ((wr * tmpr) - (wi * tmpi)); i3_5 = ((wi * tmpr) + (wr * tmpi)); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r3_3 = ((wr * tmpr) - (wi * tmpi)); i3_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r3_7 = ((wr * tmpr) - (wi * tmpi)); i3_7 = ((wi * tmpr) + (wr * tmpi)); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[4 * m]) = (r1_0 - r1_1); c_im(kp[4 * m]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[5 * m]) = (r1_2 - tmpr); c_im(kp[5 * m]) = (i1_2 - tmpi); c_re(kp[2 * m]) = (r1_4 + i1_5); c_im(kp[2 * m]) = (i1_4 - r1_5); c_re(kp[6 * m]) = (r1_4 - i1_5); c_im(kp[6 * m]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 - tmpi); c_re(kp[7 * m]) = (r1_6 - tmpr); c_im(kp[7 * m]) = (i1_6 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_8_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_8_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_8(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 8; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_8(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_8(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_8_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 8; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_8_seq(a, ab, in, out, m); fft_unshuffle_8_seq(ab, b, in, out, m); } } void fft_base_16(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(in[0]); i4_0 = c_im(in[0]); r4_8 = c_re(in[8]); i4_8 = c_im(in[8]); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; r4_4 = c_re(in[4]); i4_4 = c_im(in[4]); r4_12 = c_re(in[12]); i4_12 = c_im(in[12]); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; r4_2 = c_re(in[2]); i4_2 = c_im(in[2]); r4_10 = c_re(in[10]); i4_10 = c_im(in[10]); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; r4_6 = c_re(in[6]); i4_6 = c_im(in[6]); r4_14 = c_re(in[14]); i4_14 = c_im(in[14]); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; r4_1 = c_re(in[1]); i4_1 = c_im(in[1]); r4_9 = c_re(in[9]); i4_9 = c_im(in[9]); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; r4_5 = c_re(in[5]); i4_5 = c_im(in[5]); r4_13 = c_re(in[13]); i4_13 = c_im(in[13]); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; r4_3 = c_re(in[3]); i4_3 = c_im(in[3]); r4_11 = c_re(in[11]); i4_11 = c_im(in[11]); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; r4_7 = c_re(in[7]); i4_7 = c_im(in[7]); r4_15 = c_re(in[15]); i4_15 = c_im(in[15]); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[8]) = (r1_0 - r1_1); c_im(out[8]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[9]) = (r1_2 - tmpr); c_im(out[9]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(out[2]) = (r1_4 + tmpr); c_im(out[2]) = (i1_4 + tmpi); c_re(out[10]) = (r1_4 - tmpr); c_im(out[10]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 + tmpi); c_re(out[11]) = (r1_6 - tmpr); c_im(out[11]) = (i1_6 - tmpi); c_re(out[4]) = (r1_8 + i1_9); c_im(out[4]) = (i1_8 - r1_9); c_re(out[12]) = (r1_8 - i1_9); c_im(out[12]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(out[5]) = (r1_10 + tmpr); c_im(out[5]) = (i1_10 - tmpi); c_re(out[13]) = (r1_10 - tmpr); c_im(out[13]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(out[6]) = (r1_12 + tmpr); c_im(out[6]) = (i1_12 - tmpi); c_re(out[14]) = (r1_12 - tmpr); c_im(out[14]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(out[7]) = (r1_14 + tmpr); c_im(out[7]) = (i1_14 - tmpi); c_re(out[15]) = (r1_14 - tmpr); c_im(out[15]) = (i1_14 + tmpi); } } void fft_twiddle_16(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(jp[0 * m]); i4_0 = c_im(jp[0 * m]); wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r4_8 = ((wr * tmpr) - (wi * tmpi)); i4_8 = ((wi * tmpr) + (wr * tmpi)); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r4_4 = ((wr * tmpr) - (wi * tmpi)); i4_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r4_12 = ((wr * tmpr) - (wi * tmpi)); i4_12 = ((wi * tmpr) + (wr * tmpi)); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r4_2 = ((wr * tmpr) - (wi * tmpi)); i4_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r4_10 = ((wr * tmpr) - (wi * tmpi)); i4_10 = ((wi * tmpr) + (wr * tmpi)); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r4_6 = ((wr * tmpr) - (wi * tmpi)); i4_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r4_14 = ((wr * tmpr) - (wi * tmpi)); i4_14 = ((wi * tmpr) + (wr * tmpi)); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r4_1 = ((wr * tmpr) - (wi * tmpi)); i4_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r4_9 = ((wr * tmpr) - (wi * tmpi)); i4_9 = ((wi * tmpr) + (wr * tmpi)); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r4_5 = ((wr * tmpr) - (wi * tmpi)); i4_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r4_13 = ((wr * tmpr) - (wi * tmpi)); i4_13 = ((wi * tmpr) + (wr * tmpi)); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r4_3 = ((wr * tmpr) - (wi * tmpi)); i4_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r4_11 = ((wr * tmpr) - (wi * tmpi)); i4_11 = ((wi * tmpr) + (wr * tmpi)); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r4_7 = ((wr * tmpr) - (wi * tmpi)); i4_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r4_15 = ((wr * tmpr) - (wi * tmpi)); i4_15 = ((wi * tmpr) + (wr * tmpi)); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[8 * m]) = (r1_0 - r1_1); c_im(kp[8 * m]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[9 * m]) = (r1_2 - tmpr); c_im(kp[9 * m]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[10 * m]) = (r1_4 - tmpr); c_im(kp[10 * m]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[11 * m]) = (r1_6 - tmpr); c_im(kp[11 * m]) = (i1_6 - tmpi); c_re(kp[4 * m]) = (r1_8 + i1_9); c_im(kp[4 * m]) = (i1_8 - r1_9); c_re(kp[12 * m]) = (r1_8 - i1_9); c_im(kp[12 * m]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 - tmpi); c_re(kp[13 * m]) = (r1_10 - tmpr); c_im(kp[13 * m]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 - tmpi); c_re(kp[14 * m]) = (r1_12 - tmpr); c_im(kp[14 * m]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 - tmpi); c_re(kp[15 * m]) = (r1_14 - tmpr); c_im(kp[15 * m]) = (i1_14 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_16(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_16(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_16_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(jp[0 * m]); i4_0 = c_im(jp[0 * m]); wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r4_8 = ((wr * tmpr) - (wi * tmpi)); i4_8 = ((wi * tmpr) + (wr * tmpi)); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r4_4 = ((wr * tmpr) - (wi * tmpi)); i4_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r4_12 = ((wr * tmpr) - (wi * tmpi)); i4_12 = ((wi * tmpr) + (wr * tmpi)); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r4_2 = ((wr * tmpr) - (wi * tmpi)); i4_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r4_10 = ((wr * tmpr) - (wi * tmpi)); i4_10 = ((wi * tmpr) + (wr * tmpi)); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r4_6 = ((wr * tmpr) - (wi * tmpi)); i4_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r4_14 = ((wr * tmpr) - (wi * tmpi)); i4_14 = ((wi * tmpr) + (wr * tmpi)); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r4_1 = ((wr * tmpr) - (wi * tmpi)); i4_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r4_9 = ((wr * tmpr) - (wi * tmpi)); i4_9 = ((wi * tmpr) + (wr * tmpi)); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r4_5 = ((wr * tmpr) - (wi * tmpi)); i4_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r4_13 = ((wr * tmpr) - (wi * tmpi)); i4_13 = ((wi * tmpr) + (wr * tmpi)); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r4_3 = ((wr * tmpr) - (wi * tmpi)); i4_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r4_11 = ((wr * tmpr) - (wi * tmpi)); i4_11 = ((wi * tmpr) + (wr * tmpi)); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r4_7 = ((wr * tmpr) - (wi * tmpi)); i4_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r4_15 = ((wr * tmpr) - (wi * tmpi)); i4_15 = ((wi * tmpr) + (wr * tmpi)); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[8 * m]) = (r1_0 - r1_1); c_im(kp[8 * m]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[9 * m]) = (r1_2 - tmpr); c_im(kp[9 * m]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[10 * m]) = (r1_4 - tmpr); c_im(kp[10 * m]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[11 * m]) = (r1_6 - tmpr); c_im(kp[11 * m]) = (i1_6 - tmpi); c_re(kp[4 * m]) = (r1_8 + i1_9); c_im(kp[4 * m]) = (i1_8 - r1_9); c_re(kp[12 * m]) = (r1_8 - i1_9); c_im(kp[12 * m]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 - tmpi); c_re(kp[13 * m]) = (r1_10 - tmpr); c_im(kp[13 * m]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 - tmpi); c_re(kp[14 * m]) = (r1_12 - tmpr); c_im(kp[14 * m]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 - tmpi); c_re(kp[15 * m]) = (r1_14 - tmpr); c_im(kp[15 * m]) = (i1_14 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_16_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_16_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_16(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 16; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_16(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_16(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_16_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 16; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_16_seq(a, ab, in, out, m); fft_unshuffle_16_seq(ab, b, in, out, m); } } void fft_base_32(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(in[0]); i5_0 = c_im(in[0]); r5_16 = c_re(in[16]); i5_16 = c_im(in[16]); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; r5_8 = c_re(in[8]); i5_8 = c_im(in[8]); r5_24 = c_re(in[24]); i5_24 = c_im(in[24]); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; r5_4 = c_re(in[4]); i5_4 = c_im(in[4]); r5_20 = c_re(in[20]); i5_20 = c_im(in[20]); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; r5_12 = c_re(in[12]); i5_12 = c_im(in[12]); r5_28 = c_re(in[28]); i5_28 = c_im(in[28]); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; r5_2 = c_re(in[2]); i5_2 = c_im(in[2]); r5_18 = c_re(in[18]); i5_18 = c_im(in[18]); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; r5_10 = c_re(in[10]); i5_10 = c_im(in[10]); r5_26 = c_re(in[26]); i5_26 = c_im(in[26]); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; r5_6 = c_re(in[6]); i5_6 = c_im(in[6]); r5_22 = c_re(in[22]); i5_22 = c_im(in[22]); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; r5_14 = c_re(in[14]); i5_14 = c_im(in[14]); r5_30 = c_re(in[30]); i5_30 = c_im(in[30]); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; r5_1 = c_re(in[1]); i5_1 = c_im(in[1]); r5_17 = c_re(in[17]); i5_17 = c_im(in[17]); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; r5_9 = c_re(in[9]); i5_9 = c_im(in[9]); r5_25 = c_re(in[25]); i5_25 = c_im(in[25]); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; r5_5 = c_re(in[5]); i5_5 = c_im(in[5]); r5_21 = c_re(in[21]); i5_21 = c_im(in[21]); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; r5_13 = c_re(in[13]); i5_13 = c_im(in[13]); r5_29 = c_re(in[29]); i5_29 = c_im(in[29]); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; r5_3 = c_re(in[3]); i5_3 = c_im(in[3]); r5_19 = c_re(in[19]); i5_19 = c_im(in[19]); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; r5_11 = c_re(in[11]); i5_11 = c_im(in[11]); r5_27 = c_re(in[27]); i5_27 = c_im(in[27]); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; r5_7 = c_re(in[7]); i5_7 = c_im(in[7]); r5_23 = c_re(in[23]); i5_23 = c_im(in[23]); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; r5_15 = c_re(in[15]); i5_15 = c_im(in[15]); r5_31 = c_re(in[31]); i5_31 = c_im(in[31]); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[16]) = (r1_0 - r1_1); c_im(out[16]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[17]) = (r1_2 - tmpr); c_im(out[17]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(out[2]) = (r1_4 + tmpr); c_im(out[2]) = (i1_4 + tmpi); c_re(out[18]) = (r1_4 - tmpr); c_im(out[18]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 + tmpi); c_re(out[19]) = (r1_6 - tmpr); c_im(out[19]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(out[4]) = (r1_8 + tmpr); c_im(out[4]) = (i1_8 + tmpi); c_re(out[20]) = (r1_8 - tmpr); c_im(out[20]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(out[5]) = (r1_10 + tmpr); c_im(out[5]) = (i1_10 + tmpi); c_re(out[21]) = (r1_10 - tmpr); c_im(out[21]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(out[6]) = (r1_12 + tmpr); c_im(out[6]) = (i1_12 + tmpi); c_re(out[22]) = (r1_12 - tmpr); c_im(out[22]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(out[7]) = (r1_14 + tmpr); c_im(out[7]) = (i1_14 + tmpi); c_re(out[23]) = (r1_14 - tmpr); c_im(out[23]) = (i1_14 - tmpi); c_re(out[8]) = (r1_16 + i1_17); c_im(out[8]) = (i1_16 - r1_17); c_re(out[24]) = (r1_16 - i1_17); c_im(out[24]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(out[9]) = (r1_18 + tmpr); c_im(out[9]) = (i1_18 - tmpi); c_re(out[25]) = (r1_18 - tmpr); c_im(out[25]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(out[10]) = (r1_20 + tmpr); c_im(out[10]) = (i1_20 - tmpi); c_re(out[26]) = (r1_20 - tmpr); c_im(out[26]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(out[11]) = (r1_22 + tmpr); c_im(out[11]) = (i1_22 - tmpi); c_re(out[27]) = (r1_22 - tmpr); c_im(out[27]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(out[12]) = (r1_24 + tmpr); c_im(out[12]) = (i1_24 - tmpi); c_re(out[28]) = (r1_24 - tmpr); c_im(out[28]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(out[13]) = (r1_26 + tmpr); c_im(out[13]) = (i1_26 - tmpi); c_re(out[29]) = (r1_26 - tmpr); c_im(out[29]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(out[14]) = (r1_28 + tmpr); c_im(out[14]) = (i1_28 - tmpi); c_re(out[30]) = (r1_28 - tmpr); c_im(out[30]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(out[15]) = (r1_30 + tmpr); c_im(out[15]) = (i1_30 - tmpi); c_re(out[31]) = (r1_30 - tmpr); c_im(out[31]) = (i1_30 + tmpi); } } void fft_twiddle_32(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(jp[0 * m]); i5_0 = c_im(jp[0 * m]); wr = c_re(W[16 * l1]); wi = c_im(W[16 * l1]); tmpr = c_re(jp[16 * m]); tmpi = c_im(jp[16 * m]); r5_16 = ((wr * tmpr) - (wi * tmpi)); i5_16 = ((wi * tmpr) + (wr * tmpi)); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r5_8 = ((wr * tmpr) - (wi * tmpi)); i5_8 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[24 * l1]); wi = c_im(W[24 * l1]); tmpr = c_re(jp[24 * m]); tmpi = c_im(jp[24 * m]); r5_24 = ((wr * tmpr) - (wi * tmpi)); i5_24 = ((wi * tmpr) + (wr * tmpi)); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r5_4 = ((wr * tmpr) - (wi * tmpi)); i5_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[20 * l1]); wi = c_im(W[20 * l1]); tmpr = c_re(jp[20 * m]); tmpi = c_im(jp[20 * m]); r5_20 = ((wr * tmpr) - (wi * tmpi)); i5_20 = ((wi * tmpr) + (wr * tmpi)); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r5_12 = ((wr * tmpr) - (wi * tmpi)); i5_12 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[28 * l1]); wi = c_im(W[28 * l1]); tmpr = c_re(jp[28 * m]); tmpi = c_im(jp[28 * m]); r5_28 = ((wr * tmpr) - (wi * tmpi)); i5_28 = ((wi * tmpr) + (wr * tmpi)); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r5_2 = ((wr * tmpr) - (wi * tmpi)); i5_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[18 * l1]); wi = c_im(W[18 * l1]); tmpr = c_re(jp[18 * m]); tmpi = c_im(jp[18 * m]); r5_18 = ((wr * tmpr) - (wi * tmpi)); i5_18 = ((wi * tmpr) + (wr * tmpi)); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r5_10 = ((wr * tmpr) - (wi * tmpi)); i5_10 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[26 * l1]); wi = c_im(W[26 * l1]); tmpr = c_re(jp[26 * m]); tmpi = c_im(jp[26 * m]); r5_26 = ((wr * tmpr) - (wi * tmpi)); i5_26 = ((wi * tmpr) + (wr * tmpi)); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r5_6 = ((wr * tmpr) - (wi * tmpi)); i5_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[22 * l1]); wi = c_im(W[22 * l1]); tmpr = c_re(jp[22 * m]); tmpi = c_im(jp[22 * m]); r5_22 = ((wr * tmpr) - (wi * tmpi)); i5_22 = ((wi * tmpr) + (wr * tmpi)); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r5_14 = ((wr * tmpr) - (wi * tmpi)); i5_14 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[30 * l1]); wi = c_im(W[30 * l1]); tmpr = c_re(jp[30 * m]); tmpi = c_im(jp[30 * m]); r5_30 = ((wr * tmpr) - (wi * tmpi)); i5_30 = ((wi * tmpr) + (wr * tmpi)); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r5_1 = ((wr * tmpr) - (wi * tmpi)); i5_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[17 * l1]); wi = c_im(W[17 * l1]); tmpr = c_re(jp[17 * m]); tmpi = c_im(jp[17 * m]); r5_17 = ((wr * tmpr) - (wi * tmpi)); i5_17 = ((wi * tmpr) + (wr * tmpi)); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r5_9 = ((wr * tmpr) - (wi * tmpi)); i5_9 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[25 * l1]); wi = c_im(W[25 * l1]); tmpr = c_re(jp[25 * m]); tmpi = c_im(jp[25 * m]); r5_25 = ((wr * tmpr) - (wi * tmpi)); i5_25 = ((wi * tmpr) + (wr * tmpi)); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r5_5 = ((wr * tmpr) - (wi * tmpi)); i5_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[21 * l1]); wi = c_im(W[21 * l1]); tmpr = c_re(jp[21 * m]); tmpi = c_im(jp[21 * m]); r5_21 = ((wr * tmpr) - (wi * tmpi)); i5_21 = ((wi * tmpr) + (wr * tmpi)); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r5_13 = ((wr * tmpr) - (wi * tmpi)); i5_13 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[29 * l1]); wi = c_im(W[29 * l1]); tmpr = c_re(jp[29 * m]); tmpi = c_im(jp[29 * m]); r5_29 = ((wr * tmpr) - (wi * tmpi)); i5_29 = ((wi * tmpr) + (wr * tmpi)); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r5_3 = ((wr * tmpr) - (wi * tmpi)); i5_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[19 * l1]); wi = c_im(W[19 * l1]); tmpr = c_re(jp[19 * m]); tmpi = c_im(jp[19 * m]); r5_19 = ((wr * tmpr) - (wi * tmpi)); i5_19 = ((wi * tmpr) + (wr * tmpi)); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r5_11 = ((wr * tmpr) - (wi * tmpi)); i5_11 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[27 * l1]); wi = c_im(W[27 * l1]); tmpr = c_re(jp[27 * m]); tmpi = c_im(jp[27 * m]); r5_27 = ((wr * tmpr) - (wi * tmpi)); i5_27 = ((wi * tmpr) + (wr * tmpi)); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r5_7 = ((wr * tmpr) - (wi * tmpi)); i5_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[23 * l1]); wi = c_im(W[23 * l1]); tmpr = c_re(jp[23 * m]); tmpi = c_im(jp[23 * m]); r5_23 = ((wr * tmpr) - (wi * tmpi)); i5_23 = ((wi * tmpr) + (wr * tmpi)); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r5_15 = ((wr * tmpr) - (wi * tmpi)); i5_15 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[31 * l1]); wi = c_im(W[31 * l1]); tmpr = c_re(jp[31 * m]); tmpi = c_im(jp[31 * m]); r5_31 = ((wr * tmpr) - (wi * tmpi)); i5_31 = ((wi * tmpr) + (wr * tmpi)); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[16 * m]) = (r1_0 - r1_1); c_im(kp[16 * m]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[17 * m]) = (r1_2 - tmpr); c_im(kp[17 * m]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[18 * m]) = (r1_4 - tmpr); c_im(kp[18 * m]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[19 * m]) = (r1_6 - tmpr); c_im(kp[19 * m]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(kp[4 * m]) = (r1_8 + tmpr); c_im(kp[4 * m]) = (i1_8 + tmpi); c_re(kp[20 * m]) = (r1_8 - tmpr); c_im(kp[20 * m]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 + tmpi); c_re(kp[21 * m]) = (r1_10 - tmpr); c_im(kp[21 * m]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 + tmpi); c_re(kp[22 * m]) = (r1_12 - tmpr); c_im(kp[22 * m]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 + tmpi); c_re(kp[23 * m]) = (r1_14 - tmpr); c_im(kp[23 * m]) = (i1_14 - tmpi); c_re(kp[8 * m]) = (r1_16 + i1_17); c_im(kp[8 * m]) = (i1_16 - r1_17); c_re(kp[24 * m]) = (r1_16 - i1_17); c_im(kp[24 * m]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(kp[9 * m]) = (r1_18 + tmpr); c_im(kp[9 * m]) = (i1_18 - tmpi); c_re(kp[25 * m]) = (r1_18 - tmpr); c_im(kp[25 * m]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(kp[10 * m]) = (r1_20 + tmpr); c_im(kp[10 * m]) = (i1_20 - tmpi); c_re(kp[26 * m]) = (r1_20 - tmpr); c_im(kp[26 * m]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(kp[11 * m]) = (r1_22 + tmpr); c_im(kp[11 * m]) = (i1_22 - tmpi); c_re(kp[27 * m]) = (r1_22 - tmpr); c_im(kp[27 * m]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(kp[12 * m]) = (r1_24 + tmpr); c_im(kp[12 * m]) = (i1_24 - tmpi); c_re(kp[28 * m]) = (r1_24 - tmpr); c_im(kp[28 * m]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(kp[13 * m]) = (r1_26 + tmpr); c_im(kp[13 * m]) = (i1_26 - tmpi); c_re(kp[29 * m]) = (r1_26 - tmpr); c_im(kp[29 * m]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(kp[14 * m]) = (r1_28 + tmpr); c_im(kp[14 * m]) = (i1_28 - tmpi); c_re(kp[30 * m]) = (r1_28 - tmpr); c_im(kp[30 * m]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(kp[15 * m]) = (r1_30 + tmpr); c_im(kp[15 * m]) = (i1_30 - tmpi); c_re(kp[31 * m]) = (r1_30 - tmpr); c_im(kp[31 * m]) = (i1_30 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_32(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_32(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_32_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(jp[0 * m]); i5_0 = c_im(jp[0 * m]); wr = c_re(W[16 * l1]); wi = c_im(W[16 * l1]); tmpr = c_re(jp[16 * m]); tmpi = c_im(jp[16 * m]); r5_16 = ((wr * tmpr) - (wi * tmpi)); i5_16 = ((wi * tmpr) + (wr * tmpi)); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r5_8 = ((wr * tmpr) - (wi * tmpi)); i5_8 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[24 * l1]); wi = c_im(W[24 * l1]); tmpr = c_re(jp[24 * m]); tmpi = c_im(jp[24 * m]); r5_24 = ((wr * tmpr) - (wi * tmpi)); i5_24 = ((wi * tmpr) + (wr * tmpi)); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r5_4 = ((wr * tmpr) - (wi * tmpi)); i5_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[20 * l1]); wi = c_im(W[20 * l1]); tmpr = c_re(jp[20 * m]); tmpi = c_im(jp[20 * m]); r5_20 = ((wr * tmpr) - (wi * tmpi)); i5_20 = ((wi * tmpr) + (wr * tmpi)); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r5_12 = ((wr * tmpr) - (wi * tmpi)); i5_12 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[28 * l1]); wi = c_im(W[28 * l1]); tmpr = c_re(jp[28 * m]); tmpi = c_im(jp[28 * m]); r5_28 = ((wr * tmpr) - (wi * tmpi)); i5_28 = ((wi * tmpr) + (wr * tmpi)); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r5_2 = ((wr * tmpr) - (wi * tmpi)); i5_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[18 * l1]); wi = c_im(W[18 * l1]); tmpr = c_re(jp[18 * m]); tmpi = c_im(jp[18 * m]); r5_18 = ((wr * tmpr) - (wi * tmpi)); i5_18 = ((wi * tmpr) + (wr * tmpi)); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r5_10 = ((wr * tmpr) - (wi * tmpi)); i5_10 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[26 * l1]); wi = c_im(W[26 * l1]); tmpr = c_re(jp[26 * m]); tmpi = c_im(jp[26 * m]); r5_26 = ((wr * tmpr) - (wi * tmpi)); i5_26 = ((wi * tmpr) + (wr * tmpi)); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r5_6 = ((wr * tmpr) - (wi * tmpi)); i5_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[22 * l1]); wi = c_im(W[22 * l1]); tmpr = c_re(jp[22 * m]); tmpi = c_im(jp[22 * m]); r5_22 = ((wr * tmpr) - (wi * tmpi)); i5_22 = ((wi * tmpr) + (wr * tmpi)); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r5_14 = ((wr * tmpr) - (wi * tmpi)); i5_14 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[30 * l1]); wi = c_im(W[30 * l1]); tmpr = c_re(jp[30 * m]); tmpi = c_im(jp[30 * m]); r5_30 = ((wr * tmpr) - (wi * tmpi)); i5_30 = ((wi * tmpr) + (wr * tmpi)); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r5_1 = ((wr * tmpr) - (wi * tmpi)); i5_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[17 * l1]); wi = c_im(W[17 * l1]); tmpr = c_re(jp[17 * m]); tmpi = c_im(jp[17 * m]); r5_17 = ((wr * tmpr) - (wi * tmpi)); i5_17 = ((wi * tmpr) + (wr * tmpi)); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r5_9 = ((wr * tmpr) - (wi * tmpi)); i5_9 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[25 * l1]); wi = c_im(W[25 * l1]); tmpr = c_re(jp[25 * m]); tmpi = c_im(jp[25 * m]); r5_25 = ((wr * tmpr) - (wi * tmpi)); i5_25 = ((wi * tmpr) + (wr * tmpi)); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r5_5 = ((wr * tmpr) - (wi * tmpi)); i5_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[21 * l1]); wi = c_im(W[21 * l1]); tmpr = c_re(jp[21 * m]); tmpi = c_im(jp[21 * m]); r5_21 = ((wr * tmpr) - (wi * tmpi)); i5_21 = ((wi * tmpr) + (wr * tmpi)); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r5_13 = ((wr * tmpr) - (wi * tmpi)); i5_13 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[29 * l1]); wi = c_im(W[29 * l1]); tmpr = c_re(jp[29 * m]); tmpi = c_im(jp[29 * m]); r5_29 = ((wr * tmpr) - (wi * tmpi)); i5_29 = ((wi * tmpr) + (wr * tmpi)); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r5_3 = ((wr * tmpr) - (wi * tmpi)); i5_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[19 * l1]); wi = c_im(W[19 * l1]); tmpr = c_re(jp[19 * m]); tmpi = c_im(jp[19 * m]); r5_19 = ((wr * tmpr) - (wi * tmpi)); i5_19 = ((wi * tmpr) + (wr * tmpi)); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r5_11 = ((wr * tmpr) - (wi * tmpi)); i5_11 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[27 * l1]); wi = c_im(W[27 * l1]); tmpr = c_re(jp[27 * m]); tmpi = c_im(jp[27 * m]); r5_27 = ((wr * tmpr) - (wi * tmpi)); i5_27 = ((wi * tmpr) + (wr * tmpi)); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r5_7 = ((wr * tmpr) - (wi * tmpi)); i5_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[23 * l1]); wi = c_im(W[23 * l1]); tmpr = c_re(jp[23 * m]); tmpi = c_im(jp[23 * m]); r5_23 = ((wr * tmpr) - (wi * tmpi)); i5_23 = ((wi * tmpr) + (wr * tmpi)); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r5_15 = ((wr * tmpr) - (wi * tmpi)); i5_15 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[31 * l1]); wi = c_im(W[31 * l1]); tmpr = c_re(jp[31 * m]); tmpi = c_im(jp[31 * m]); r5_31 = ((wr * tmpr) - (wi * tmpi)); i5_31 = ((wi * tmpr) + (wr * tmpi)); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[16 * m]) = (r1_0 - r1_1); c_im(kp[16 * m]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[17 * m]) = (r1_2 - tmpr); c_im(kp[17 * m]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[18 * m]) = (r1_4 - tmpr); c_im(kp[18 * m]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[19 * m]) = (r1_6 - tmpr); c_im(kp[19 * m]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(kp[4 * m]) = (r1_8 + tmpr); c_im(kp[4 * m]) = (i1_8 + tmpi); c_re(kp[20 * m]) = (r1_8 - tmpr); c_im(kp[20 * m]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 + tmpi); c_re(kp[21 * m]) = (r1_10 - tmpr); c_im(kp[21 * m]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 + tmpi); c_re(kp[22 * m]) = (r1_12 - tmpr); c_im(kp[22 * m]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 + tmpi); c_re(kp[23 * m]) = (r1_14 - tmpr); c_im(kp[23 * m]) = (i1_14 - tmpi); c_re(kp[8 * m]) = (r1_16 + i1_17); c_im(kp[8 * m]) = (i1_16 - r1_17); c_re(kp[24 * m]) = (r1_16 - i1_17); c_im(kp[24 * m]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(kp[9 * m]) = (r1_18 + tmpr); c_im(kp[9 * m]) = (i1_18 - tmpi); c_re(kp[25 * m]) = (r1_18 - tmpr); c_im(kp[25 * m]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(kp[10 * m]) = (r1_20 + tmpr); c_im(kp[10 * m]) = (i1_20 - tmpi); c_re(kp[26 * m]) = (r1_20 - tmpr); c_im(kp[26 * m]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(kp[11 * m]) = (r1_22 + tmpr); c_im(kp[11 * m]) = (i1_22 - tmpi); c_re(kp[27 * m]) = (r1_22 - tmpr); c_im(kp[27 * m]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(kp[12 * m]) = (r1_24 + tmpr); c_im(kp[12 * m]) = (i1_24 - tmpi); c_re(kp[28 * m]) = (r1_24 - tmpr); c_im(kp[28 * m]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(kp[13 * m]) = (r1_26 + tmpr); c_im(kp[13 * m]) = (i1_26 - tmpi); c_re(kp[29 * m]) = (r1_26 - tmpr); c_im(kp[29 * m]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(kp[14 * m]) = (r1_28 + tmpr); c_im(kp[14 * m]) = (i1_28 - tmpi); c_re(kp[30 * m]) = (r1_28 - tmpr); c_im(kp[30 * m]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(kp[15 * m]) = (r1_30 + tmpr); c_im(kp[15 * m]) = (i1_30 - tmpi); c_re(kp[31 * m]) = (r1_30 - tmpr); c_im(kp[31 * m]) = (i1_30 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_32_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_32_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_32(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 32; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_32(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_32(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_32_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 32; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_32_seq(a, ab, in, out, m); fft_unshuffle_32_seq(ab, b, in, out, m); } } /* end of machine-generated code */ /* * Recursive complex FFT on the n complex components of the array in: * basic Cooley-Tukey algorithm, with some improvements for * n power of two. The result is placed in the array out. n is arbitrary. * The algorithm runs in time O(n*(r1 + ... + rk)) where r1, ..., rk * are prime numbers, and r1 * r2 * ... * rk = n. * * n: size of the input * in: pointer to input * out: pointer to output * factors: list of factors of n, precomputed * W: twiddle factors * nW: size of W, that is, size of the original transform * */ void fft_aux(int n, COMPLEX * in, COMPLEX * out, int *factors, COMPLEX * W, int nW) { int r, m; int k; /* special cases */ if (n == 32) { fft_base_32(in, out); return; } if (n == 16) { fft_base_16(in, out); return; } if (n == 8) { fft_base_8(in, out); return; } if (n == 4) { fft_base_4(in, out); return; } if (n == 2) { fft_base_2(in, out); return; } /* * the cases n == 3, n == 5, and maybe 7 should be implemented as well */ r = *factors; m = n / r; if (r < n) { /* * split the DFT of length n into r DFTs of length n/r, and * recurse */ if (r == 32) { #pragma omp task untied fft_unshuffle_32(0, m, in, out, m); } else if (r == 16) { #pragma omp task untied fft_unshuffle_16(0, m, in, out, m); } else if (r == 8) { #pragma omp task untied fft_unshuffle_8(0, m, in, out, m); } else if (r == 4) { #pragma omp task untied fft_unshuffle_4(0, m, in, out, m); } else if (r == 2) { #pragma omp task untied fft_unshuffle_2(0, m, in, out, m); } else unshuffle(0, m, in, out, r, m); #pragma omp taskwait for (k = 0; k < n; k += m) { #pragma omp task untied fft_aux(m, out + k, in + k, factors + 1, W, nW); } #pragma omp taskwait } /* * now multiply by the twiddle factors, and perform m FFTs * of length r */ if (r == 2) { #pragma omp task untied fft_twiddle_2(0, m, in, out, W, nW, nW / n, m); } else if (r == 4) { #pragma omp task untied fft_twiddle_4(0, m, in, out, W, nW, nW / n, m); } else if (r == 8) { #pragma omp task untied fft_twiddle_8(0, m, in, out, W, nW, nW / n, m); } else if (r == 16) { #pragma omp task untied fft_twiddle_16(0, m, in, out, W, nW, nW / n, m); } else if (r == 32) { #pragma omp task untied fft_twiddle_32(0, m, in, out, W, nW, nW / n, m); } else { #pragma omp task untied fft_twiddle_gen(0, m, in, out, W, nW, nW / n, r, m); } #pragma omp taskwait return; } void fft_aux_seq(int n, COMPLEX * in, COMPLEX * out, int *factors, COMPLEX * W, int nW) { int r, m; int k; /* special cases */ if (n == 32) { fft_base_32(in, out); return; } if (n == 16) { fft_base_16(in, out); return; } if (n == 8) { fft_base_8(in, out); return; } if (n == 4) { fft_base_4(in, out); return; } if (n == 2) { fft_base_2(in, out); return; } /* * the cases n == 3, n == 5, and maybe 7 should be implemented as well */ r = *factors; m = n / r; if (r < n) { /* * split the DFT of length n into r DFTs of length n/r, and * recurse */ if (r == 32) fft_unshuffle_32_seq(0, m, in, out, m); else if (r == 16) fft_unshuffle_16_seq(0, m, in, out, m); else if (r == 8) fft_unshuffle_8_seq(0, m, in, out, m); else if (r == 4) fft_unshuffle_4_seq(0, m, in, out, m); else if (r == 2) fft_unshuffle_2_seq(0, m, in, out, m); else unshuffle_seq(0, m, in, out, r, m); for (k = 0; k < n; k += m) { fft_aux_seq(m, out + k, in + k, factors + 1, W, nW); } } /* * now multiply by the twiddle factors, and perform m FFTs * of length r */ if (r == 2) fft_twiddle_2_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 4) fft_twiddle_4_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 8) fft_twiddle_8_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 16) fft_twiddle_16_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 32) fft_twiddle_32_seq(0, m, in, out, W, nW, nW / n, m); else fft_twiddle_gen_seq(0, m, in, out, W, nW, nW / n, r, m); return; } /* * user interface for fft_aux */ void fft(int n, COMPLEX * in, COMPLEX * out) { int factors[40]; /* allows FFTs up to at least 3^40 */ int *p = factors; int l = n; int r; COMPLEX *W; fprintf(stdout,"Computing coefficients "); W = (COMPLEX *) malloc((n + 1) * sizeof(COMPLEX)); #pragma omp parallel #pragma omp single #pragma omp task untied compute_w_coefficients(n, 0, n / 2, W); fprintf(stdout," completed!\n"); /* * find factors of n, first 8, then 4 and then primes in ascending * order */ do { r = factor(l); *p++ = r; l /= r; } while (l > 1); fprintf(stdout,"Computing FFT "); #pragma omp parallel #pragma omp single #pragma omp task untied fft_aux(n, in, out, factors, W, n); fprintf(stdout," completed!\n"); free(W); return; } void fft_seq(int n, COMPLEX * in, COMPLEX * out) { int factors[40]; /* allows FFTs up to at least 3^40 */ int *p = factors; int l = n; int r; COMPLEX *W; W = (COMPLEX *) malloc((n + 1) * sizeof(COMPLEX)); compute_w_coefficients_seq(n, 0, n / 2, W); /* * find factors of n, first 8, then 4 and then primes in ascending * order */ do { r = factor(l); *p++ = r; l /= r; } while (l > 1); fft_aux_seq(n, in, out, factors, W, n); free(W); return; } int test_correctness(int n, COMPLEX *out1, COMPLEX *out2) { int i; double a,d,error = 0.0; for (i = 0; i < n; ++i) { a = sqrt((c_re(out1[i]) - c_re(out2[i])) * (c_re(out1[i]) - c_re(out2[i])) + (c_im(out1[i]) - c_im(out2[i])) * (c_im(out1[i]) - c_im(out2[i]))); d = sqrt(c_re(out2[i]) * c_re(out2[i]) + c_im(out2[i]) * c_im(out2[i])); if (d < -1.0e-10 || d > 1.0e-10) a /= d; if (a > error) error = a; } fprintf(stdout,"relative error=%e\n", error); if (error > 1e-3) return 0; else return 1; } void print_usage() { fprintf(stderr, "\n"); fprintf(stderr, "Usage: %s -[options]\n", "FFT"); fprintf(stderr, "\n"); fprintf(stderr, "Where options are:\n"); fprintf(stderr, " -n <size> : Matrix Size (de\n"); fprintf(stderr, " -h : Print program's usage (this help).\n"); fprintf(stdout, "\n"); } int main(int argc, char* argv[]) { int i; for (i=1; i<argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 'n': /* read argument size 0 */ argv[i][1] = '*'; i++; if (argc == i) { "Erro\n"; exit(100); } size = atoi(argv[i]); break; case 'h': /* print usage */ argv[i][1] = '*'; print_usage(); exit (100); break; } } } COMPLEX *in, *out1=NULL, *out2=NULL; in = malloc(size * sizeof(COMPLEX)); out1 = malloc(size * sizeof(COMPLEX)); for (i = 0; i < size; ++i) { c_re(in[i]) = 1.0; c_im(in[i]) = 1.0; } double t_start, t_end; t_start = rtclock(); fft(size, in, out1); t_end = rtclock(); fprintf(stdout, "Parallel Runtime: %0.6lfs\n", t_end - t_start); out2 = malloc(size * sizeof(COMPLEX)); for (i = 0; i < size; ++i) { c_re(in[i]) = 1.0; c_im(in[i]) = 1.0; } t_start = rtclock(); fft_seq(size, in, out2); t_end = rtclock(); fprintf(stdout, "Sequential Runtime: %0.6lfs\n", t_end - t_start); if (test_correctness(size, out1, out2)) { fprintf(stdout, "Result: Successful\n"); } else { fprintf(stdout, "Result: Unsuccessful\n"); } }
completed-ex36.c
/* randomized quicksort */ #include <stdio.h> #include <stdlib.h> #include <tictoc.h> #include <omp.h> #if !defined(MINSIZE) #define MINSIZE 16384 #endif int minsize = MINSIZE; int * create_random_list(int N) { int *list = (int *) malloc(N * sizeof(int)); int i; #pragma omp parallel { unsigned int seed = omp_get_thread_num(); #pragma omp for for (i = 0; i < N; i++) { list[i] = (int) rand_r(&seed); } } return list; } int list_is_sorted(int N, const int *list) { int i; int ret = 1; #pragma omp parallel for for (i = 0; i < N - 1; i++) { if (list[i] > list[i + 1]) { ret = 0; } } return ret; } static inline void list_swap(int *list, int a, int b) { int temp = list[a]; list[a] = list[b]; list[b] = temp; } void sort_int_list(int N, int *list) { int idx, i, last, key; if (N <= 1) return; idx = (int) rand() % N; list_swap(list,0,idx); key = list[0]; last = N; for (i = 1; i < last;) { int test = list[i]; if (test >= key) { list_swap(list, i, --last); } else { i++; } } list_swap(list, 0, i - 1); if (N - i > minsize) { #pragma omp task sort_int_list(N - i,&list[i]); } else { sort_int_list(N - i,&list[i]); } sort_int_list(i - 1,list); } int main(int argc, char **argv) { int N = 10000000; int *list, sorted; TicTocTimer timer; double time; if (argc > 1) { N = atoi(argv[1]); } printf("Creating a list of %d random entries: ",N); timer = tic(); list = create_random_list(N); time = toc(&timer); printf("(%e secs)\n",time); printf(" done.\n"); printf("Checking list: "); timer = tic(); sorted = list_is_sorted(N, list); time = toc(&timer); printf("(%e secs)\n",time); if (sorted) { printf(" sorted, done.\n"); free(list); return 0; } printf(" not sorted, let's get to work.\n"); printf("Sorting list: "); timer = tic(); #pragma omp parallel { #pragma omp single nowait sort_int_list(N, list); } time = toc(&timer); printf("(%e secs)\n",time); printf(" done.\n"); printf("Checking list: "); timer = tic(); sorted = list_is_sorted(N, list); time = toc(&timer); printf("(%e secs)\n",time); if (sorted) { printf(" sorted, hooray!\n"); free(list); return 0; } printf(" not sorted, uh oh.\n"); return -1; }
IJVector_parcsr.c
/****************************************************************************** * Copyright (c) 1998 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * IJVector_Par interface * *****************************************************************************/ #include "_hypre_IJ_mv.h" #include "../HYPRE.h" /****************************************************************************** * * hypre_IJVectorCreatePar * * creates ParVector if necessary, and leaves a pointer to it as the * hypre_IJVector object * *****************************************************************************/ HYPRE_Int hypre_IJVectorCreatePar(hypre_IJVector *vector, HYPRE_BigInt *IJpartitioning) { MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_BigInt global_n, partitioning[2], jmin; HYPRE_Int j; jmin = hypre_IJVectorGlobalFirstRow(vector); global_n = hypre_IJVectorGlobalNumRows(vector); /* Shift to zero-based partitioning for ParVector object */ for (j = 0; j < 2; j++) { partitioning[j] = IJpartitioning[j] - jmin; } hypre_IJVectorObject(vector) = hypre_ParVectorCreate(comm, global_n, partitioning); return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorDestroyPar * * frees ParVector local storage of an IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorDestroyPar(hypre_IJVector *vector) { return hypre_ParVectorDestroy((hypre_ParVector*)hypre_IJVectorObject(vector)); } /****************************************************************************** * * hypre_IJVectorInitializePar * * initializes ParVector of IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorInitializePar(hypre_IJVector *vector) { return hypre_IJVectorInitializePar_v2(vector, hypre_IJVectorMemoryLocation(vector)); } HYPRE_Int hypre_IJVectorInitializePar_v2(hypre_IJVector *vector, HYPRE_MemoryLocation memory_location) { hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_AuxParVector *aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); HYPRE_BigInt *partitioning = hypre_ParVectorPartitioning(par_vector); hypre_Vector *local_vector = hypre_ParVectorLocalVector(par_vector); HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); HYPRE_Int my_id; MPI_Comm comm = hypre_IJVectorComm(vector); hypre_MPI_Comm_rank(comm, &my_id); HYPRE_MemoryLocation memory_location_aux = hypre_GetExecPolicy1(memory_location) == HYPRE_EXEC_HOST ? HYPRE_MEMORY_HOST : HYPRE_MEMORY_DEVICE; if (!partitioning) { if (print_level) { hypre_printf("No ParVector partitioning for initialization -- "); hypre_printf("hypre_IJVectorInitializePar\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_VectorSize(local_vector) = (HYPRE_Int)(partitioning[1] - partitioning[0]); hypre_ParVectorInitialize_v2(par_vector, memory_location); if (!aux_vector) { hypre_AuxParVectorCreate(&aux_vector); hypre_IJVectorTranslator(vector) = aux_vector; } hypre_AuxParVectorInitialize_v2(aux_vector, memory_location_aux); return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorSetMaxOffProcElmtsPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorSetMaxOffProcElmtsPar(hypre_IJVector *vector, HYPRE_Int max_off_proc_elmts) { hypre_AuxParVector *aux_vector; aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); if (!aux_vector) { hypre_AuxParVectorCreate(&aux_vector); hypre_IJVectorTranslator(vector) = aux_vector; } hypre_AuxParVectorMaxOffProcElmts(aux_vector) = max_off_proc_elmts; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_AuxParVectorUsrOffProcElmts(aux_vector) = max_off_proc_elmts; #endif return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorDistributePar * * takes an IJVector generated for one processor and distributes it * across many processors according to vec_starts, * if vec_starts is NULL, it distributes them evenly? * *****************************************************************************/ HYPRE_Int hypre_IJVectorDistributePar(hypre_IJVector *vector, const HYPRE_Int *vec_starts) { hypre_ParVector *old_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_ParVector *par_vector; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); if (!old_vector) { if (print_level) { hypre_printf("old_vector == NULL -- "); hypre_printf("hypre_IJVectorDistributePar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } par_vector = hypre_VectorToParVector(hypre_ParVectorComm(old_vector), hypre_ParVectorLocalVector(old_vector), (HYPRE_BigInt *)vec_starts); if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorDistributePar\n"); hypre_printf("**** Vector storage is unallocated ****\n"); } hypre_error_in_arg(1); } hypre_ParVectorDestroy(old_vector); hypre_IJVectorObject(vector) = par_vector; return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorZeroValuesPar * * zeroes all local components of an IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorZeroValuesPar(hypre_IJVector *vector) { HYPRE_Int my_id; HYPRE_BigInt vec_start, vec_stop; hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_BigInt *partitioning; hypre_Vector *local_vector; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } partitioning = hypre_ParVectorPartitioning(par_vector); local_vector = hypre_ParVectorLocalVector(par_vector); if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = partitioning[0]; vec_stop = partitioning[1]; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_assert(hypre_VectorSize(local_vector) == (HYPRE_Int)(vec_stop - vec_start)); hypre_SeqVectorSetConstantValues(local_vector, 0.0); return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorSetValuesPar * * sets a potentially noncontiguous set of components of an IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorSetValuesPar(hypre_IJVector *vector, HYPRE_Int num_values, const HYPRE_BigInt *indices, const HYPRE_Complex *values) { HYPRE_Int my_id; HYPRE_Int j, k; HYPRE_BigInt i, vec_start, vec_stop; HYPRE_Complex *data; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); MPI_Comm comm = hypre_IJVectorComm(vector); hypre_Vector *local_vector; /* If no components are to be set, perform no checking and return */ if (num_values < 1) { return 0; } hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } local_vector = hypre_ParVectorLocalVector(par_vector); if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = IJpartitioning[0]; vec_stop = IJpartitioning[1] - 1; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } /* Determine whether indices points to local indices only, and if not, store indices and values in auxiliary vector structure. If indices == NULL, assume that num_values components are to be set in a block starting at vec_start. NOTE: If indices == NULL off proc values are ignored!!! */ data = hypre_VectorData(local_vector); if (indices) { for (j = 0; j < num_values; j++) { i = indices[j]; if (i >= vec_start && i <= vec_stop) { k = (HYPRE_Int)( i - vec_start); data[k] = values[j]; } } } else { if (num_values > (HYPRE_Int)(vec_stop - vec_start) + 1) { if (print_level) { hypre_printf("Warning! Indices beyond local range not identified!\n "); hypre_printf("Off processor values have been ignored!\n"); } num_values = (HYPRE_Int)(vec_stop - vec_start) + 1; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_values; j++) { data[j] = values[j]; } } return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorAddToValuesPar * * adds to a potentially noncontiguous set of IJVectorPar components * *****************************************************************************/ HYPRE_Int hypre_IJVectorAddToValuesPar(hypre_IJVector *vector, HYPRE_Int num_values, const HYPRE_BigInt *indices, const HYPRE_Complex *values) { HYPRE_Int my_id; HYPRE_Int i, j, vec_start, vec_stop; HYPRE_Complex *data; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_AuxParVector *aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); MPI_Comm comm = hypre_IJVectorComm(vector); hypre_Vector *local_vector; /* If no components are to be retrieved, perform no checking and return */ if (num_values < 1) { return 0; } hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } local_vector = hypre_ParVectorLocalVector(par_vector); if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = IJpartitioning[0]; vec_stop = IJpartitioning[1] - 1; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } data = hypre_VectorData(local_vector); if (indices) { HYPRE_Int current_num_elmts = hypre_AuxParVectorCurrentOffProcElmts(aux_vector); HYPRE_Int max_off_proc_elmts = hypre_AuxParVectorMaxOffProcElmts(aux_vector); HYPRE_BigInt *off_proc_i = hypre_AuxParVectorOffProcI(aux_vector); HYPRE_Complex *off_proc_data = hypre_AuxParVectorOffProcData(aux_vector); HYPRE_Int k; for (j = 0; j < num_values; j++) { i = indices[j]; if (i < vec_start || i > vec_stop) { /* if elements outside processor boundaries, store in off processor stash */ if (!max_off_proc_elmts) { max_off_proc_elmts = 100; hypre_AuxParVectorMaxOffProcElmts(aux_vector) = max_off_proc_elmts; hypre_AuxParVectorOffProcI(aux_vector) = hypre_CTAlloc(HYPRE_BigInt, max_off_proc_elmts, HYPRE_MEMORY_HOST); hypre_AuxParVectorOffProcData(aux_vector) = hypre_CTAlloc(HYPRE_Complex, max_off_proc_elmts, HYPRE_MEMORY_HOST); off_proc_i = hypre_AuxParVectorOffProcI(aux_vector); off_proc_data = hypre_AuxParVectorOffProcData(aux_vector); } else if (current_num_elmts + 1 > max_off_proc_elmts) { max_off_proc_elmts += 10; off_proc_i = hypre_TReAlloc(off_proc_i, HYPRE_BigInt, max_off_proc_elmts, HYPRE_MEMORY_HOST); off_proc_data = hypre_TReAlloc(off_proc_data, HYPRE_Complex, max_off_proc_elmts, HYPRE_MEMORY_HOST); hypre_AuxParVectorMaxOffProcElmts(aux_vector) = max_off_proc_elmts; hypre_AuxParVectorOffProcI(aux_vector) = off_proc_i; hypre_AuxParVectorOffProcData(aux_vector) = off_proc_data; } off_proc_i[current_num_elmts] = i; off_proc_data[current_num_elmts++] = values[j]; hypre_AuxParVectorCurrentOffProcElmts(aux_vector) = current_num_elmts; } else /* local values are added to the vector */ { k = (HYPRE_Int)(i - vec_start); data[k] += values[j]; } } } else { if (num_values > (HYPRE_Int)(vec_stop - vec_start) + 1) { if (print_level) { hypre_printf("Warning! Indices beyond local range not identified!\n "); hypre_printf("Off processor values have been ignored!\n"); } num_values = (HYPRE_Int)(vec_stop - vec_start) + 1; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_values; j++) { data[j] += values[j]; } } return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorAssemblePar * * currently tests existence of of ParVector object and its partitioning * *****************************************************************************/ HYPRE_Int hypre_IJVectorAssemblePar(hypre_IJVector *vector) { hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_AuxParVector *aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorAssemblePar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); } if (aux_vector) { HYPRE_Int off_proc_elmts, current_num_elmts; HYPRE_Int max_off_proc_elmts; HYPRE_BigInt *off_proc_i; HYPRE_Complex *off_proc_data; current_num_elmts = hypre_AuxParVectorCurrentOffProcElmts(aux_vector); hypre_MPI_Allreduce(&current_num_elmts, &off_proc_elmts, 1, HYPRE_MPI_INT, hypre_MPI_SUM, comm); if (off_proc_elmts) { max_off_proc_elmts = hypre_AuxParVectorMaxOffProcElmts(aux_vector); off_proc_i = hypre_AuxParVectorOffProcI(aux_vector); off_proc_data = hypre_AuxParVectorOffProcData(aux_vector); hypre_IJVectorAssembleOffProcValsPar(vector, max_off_proc_elmts, current_num_elmts, HYPRE_MEMORY_HOST, off_proc_i, off_proc_data); hypre_TFree(hypre_AuxParVectorOffProcI(aux_vector), HYPRE_MEMORY_HOST); hypre_TFree(hypre_AuxParVectorOffProcData(aux_vector), HYPRE_MEMORY_HOST); hypre_AuxParVectorMaxOffProcElmts(aux_vector) = 0; hypre_AuxParVectorCurrentOffProcElmts(aux_vector) = 0; } } return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorGetValuesPar * * get a potentially noncontiguous set of IJVectorPar components * *****************************************************************************/ HYPRE_Int hypre_IJVectorGetValuesPar(hypre_IJVector *vector, HYPRE_Int num_values, const HYPRE_BigInt *indices, HYPRE_Complex *values) { HYPRE_Int my_id; MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); HYPRE_BigInt vec_start; HYPRE_BigInt vec_stop; HYPRE_BigInt jmin = hypre_IJVectorGlobalFirstRow(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); /* If no components are to be retrieved, perform no checking and return */ if (num_values < 1) { return 0; } hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_Vector *local_vector = hypre_ParVectorLocalVector(par_vector); if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = IJpartitioning[0]; vec_stop = IJpartitioning[1]; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParVectorGetValues2(par_vector, num_values, (HYPRE_BigInt *) indices, jmin, values); return hypre_error_flag; } /****************************************************************************** * hypre_IJVectorAssembleOffProcValsPar * * This is for handling set and get values calls to off-proc. entries - it is * called from assemble. There is an alternate version for when the assumed * partition is being used. *****************************************************************************/ HYPRE_Int hypre_IJVectorAssembleOffProcValsPar( hypre_IJVector *vector, HYPRE_Int max_off_proc_elmts, HYPRE_Int current_num_elmts, HYPRE_MemoryLocation memory_location, HYPRE_BigInt *off_proc_i, HYPRE_Complex *off_proc_data) { HYPRE_Int myid; HYPRE_BigInt global_first_row, global_num_rows; HYPRE_Int i, j, in, k; HYPRE_Int proc_id, last_proc, prev_id, tmp_id; HYPRE_Int max_response_size; HYPRE_Int ex_num_contacts = 0; HYPRE_BigInt range_start, range_end; HYPRE_Int storage; HYPRE_Int indx; HYPRE_BigInt row; HYPRE_Int num_ranges, row_count; HYPRE_Int num_recvs; HYPRE_Int counter; HYPRE_BigInt upper_bound; HYPRE_Int num_real_procs; HYPRE_BigInt *row_list = NULL; HYPRE_Int *a_proc_id = NULL, *orig_order = NULL; HYPRE_Int *real_proc_id = NULL, *us_real_proc_id = NULL; HYPRE_Int *ex_contact_procs = NULL, *ex_contact_vec_starts = NULL; HYPRE_Int *recv_starts = NULL; HYPRE_BigInt *response_buf = NULL; HYPRE_Int *response_buf_starts = NULL; HYPRE_Int *num_rows_per_proc = NULL; HYPRE_Int tmp_int; HYPRE_Int obj_size_bytes, big_int_size, complex_size; HYPRE_Int first_index; void *void_contact_buf = NULL; void *index_ptr; void *recv_data_ptr; HYPRE_Complex tmp_complex; HYPRE_BigInt *ex_contact_buf = NULL; HYPRE_Complex *vector_data; HYPRE_Complex value; hypre_DataExchangeResponse response_obj1, response_obj2; hypre_ProcListElements send_proc_obj; MPI_Comm comm = hypre_IJVectorComm(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_IJAssumedPart *apart; hypre_MPI_Comm_rank(comm, &myid); global_num_rows = hypre_IJVectorGlobalNumRows(vector); global_first_row = hypre_IJVectorGlobalFirstRow(vector); if (memory_location == HYPRE_MEMORY_DEVICE) { HYPRE_BigInt *off_proc_i_h = hypre_TAlloc(HYPRE_BigInt, current_num_elmts, HYPRE_MEMORY_HOST); HYPRE_Complex *off_proc_data_h = hypre_TAlloc(HYPRE_Complex, current_num_elmts, HYPRE_MEMORY_HOST); hypre_TMemcpy(off_proc_i_h, off_proc_i, HYPRE_BigInt, current_num_elmts, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(off_proc_data_h, off_proc_data, HYPRE_Complex, current_num_elmts, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); off_proc_i = off_proc_i_h; off_proc_data = off_proc_data_h; } /* call hypre_IJVectorAddToValuesParCSR directly inside this function * with one chunk of data */ HYPRE_Int off_proc_nelm_recv_cur = 0; HYPRE_Int off_proc_nelm_recv_max = 0; HYPRE_BigInt *off_proc_i_recv = NULL; HYPRE_Complex *off_proc_data_recv = NULL; HYPRE_BigInt *off_proc_i_recv_d = NULL; HYPRE_Complex *off_proc_data_recv_d = NULL; /* verify that we have created the assumed partition */ if (hypre_IJVectorAssumedPart(vector) == NULL) { hypre_IJVectorCreateAssumedPartition(vector); } apart = (hypre_IJAssumedPart*) hypre_IJVectorAssumedPart(vector); /* get the assumed processor id for each row */ a_proc_id = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); orig_order = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); real_proc_id = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); row_list = hypre_CTAlloc(HYPRE_BigInt, current_num_elmts, HYPRE_MEMORY_HOST); if (current_num_elmts > 0) { for (i = 0; i < current_num_elmts; i++) { row = off_proc_i[i]; row_list[i] = row; hypre_GetAssumedPartitionProcFromRow(comm, row, global_first_row, global_num_rows, &proc_id); a_proc_id[i] = proc_id; orig_order[i] = i; } /* now we need to find the actual order of each row - sort on row - this will result in proc ids sorted also...*/ hypre_BigQsortb2i(row_list, a_proc_id, orig_order, 0, current_num_elmts - 1); /* calculate the number of contacts */ ex_num_contacts = 1; last_proc = a_proc_id[0]; for (i = 1; i < current_num_elmts; i++) { if (a_proc_id[i] > last_proc) { ex_num_contacts++; last_proc = a_proc_id[i]; } } } /* now we will go through a create a contact list - need to contact assumed processors and find out who the actual row owner is - we will contact with a range (2 numbers) */ ex_contact_procs = hypre_CTAlloc(HYPRE_Int, ex_num_contacts, HYPRE_MEMORY_HOST); ex_contact_vec_starts = hypre_CTAlloc(HYPRE_Int, ex_num_contacts + 1, HYPRE_MEMORY_HOST); ex_contact_buf = hypre_CTAlloc(HYPRE_BigInt, ex_num_contacts * 2, HYPRE_MEMORY_HOST); counter = 0; range_end = -1; for (i = 0; i < current_num_elmts; i++) { if (row_list[i] > range_end) { /* assumed proc */ proc_id = a_proc_id[i]; /* end of prev. range */ if (counter > 0) { ex_contact_buf[counter * 2 - 1] = row_list[i - 1]; } /*start new range*/ ex_contact_procs[counter] = proc_id; ex_contact_vec_starts[counter] = counter * 2; ex_contact_buf[counter * 2] = row_list[i]; counter++; hypre_GetAssumedPartitionRowRange(comm, proc_id, global_first_row, global_num_rows, &range_start, &range_end); } } /*finish the starts*/ ex_contact_vec_starts[counter] = counter * 2; /*finish the last range*/ if (counter > 0) { ex_contact_buf[counter * 2 - 1] = row_list[current_num_elmts - 1]; } /* create response object - can use same fill response as used in the commpkg routine */ response_obj1.fill_response = hypre_RangeFillResponseIJDetermineRecvProcs; response_obj1.data1 = apart; /* this is necessary so we can fill responses*/ response_obj1.data2 = NULL; max_response_size = 6; /* 6 means we can fit 3 ranges*/ hypre_DataExchangeList(ex_num_contacts, ex_contact_procs, ex_contact_buf, ex_contact_vec_starts, sizeof(HYPRE_BigInt), sizeof(HYPRE_BigInt), &response_obj1, max_response_size, 4, comm, (void**) &response_buf, &response_buf_starts); /* now response_buf contains a proc_id followed by an upper bound for the range. */ hypre_TFree(ex_contact_procs, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_buf, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_vec_starts, HYPRE_MEMORY_HOST); hypre_TFree(a_proc_id, HYPRE_MEMORY_HOST); a_proc_id = NULL; /*how many ranges were returned?*/ num_ranges = response_buf_starts[ex_num_contacts]; num_ranges = num_ranges / 2; prev_id = -1; j = 0; counter = 0; num_real_procs = 0; /* loop through ranges - create a list of actual processor ids*/ for (i = 0; i < num_ranges; i++) { upper_bound = response_buf[i * 2 + 1]; counter = 0; tmp_id = (HYPRE_Int)response_buf[i * 2]; /* loop through row_list entries - counting how many are in the range */ while (j < current_num_elmts && row_list[j] <= upper_bound) { real_proc_id[j] = tmp_id; j++; counter++; } if (counter > 0 && tmp_id != prev_id) { num_real_procs++; } prev_id = tmp_id; } /* now we have the list of real procesors ids (real_proc_id) - and the number of distinct ones - so now we can set up data to be sent - we have HYPRE_Int and HYPRE_Complex data. (row number and value) - we will send everything as a void since we may not know the rel sizes of ints and doubles */ /* first find out how many elements to send per proc - so we can do storage */ complex_size = sizeof(HYPRE_Complex); big_int_size = sizeof(HYPRE_BigInt); obj_size_bytes = hypre_max(big_int_size, complex_size); ex_contact_procs = hypre_CTAlloc(HYPRE_Int, num_real_procs, HYPRE_MEMORY_HOST); num_rows_per_proc = hypre_CTAlloc(HYPRE_Int, num_real_procs, HYPRE_MEMORY_HOST); counter = 0; if (num_real_procs > 0 ) { ex_contact_procs[0] = real_proc_id[0]; num_rows_per_proc[0] = 1; /* loop through real procs - these are sorted (row_list is sorted also)*/ for (i = 1; i < current_num_elmts; i++) { if (real_proc_id[i] == ex_contact_procs[counter]) /* same processor */ { num_rows_per_proc[counter] += 1; /*another row */ } else /* new processor */ { counter++; ex_contact_procs[counter] = real_proc_id[i]; num_rows_per_proc[counter] = 1; } } } /* calculate total storage and make vec_starts arrays */ storage = 0; ex_contact_vec_starts = hypre_CTAlloc(HYPRE_Int, num_real_procs + 1, HYPRE_MEMORY_HOST); ex_contact_vec_starts[0] = -1; for (i = 0; i < num_real_procs; i++) { storage += 1 + 2 * num_rows_per_proc[i]; ex_contact_vec_starts[i + 1] = -storage - 1; /* need negative for next loop */ } /*void_contact_buf = hypre_MAlloc(storage*obj_size_bytes);*/ void_contact_buf = hypre_CTAlloc(char, storage * obj_size_bytes, HYPRE_MEMORY_HOST); index_ptr = void_contact_buf; /* step through with this index */ /* set up data to be sent to send procs */ /* for each proc, ex_contact_buf_d contains #rows, row #, data, etc. */ /* un-sort real_proc_id - we want to access data arrays in order */ us_real_proc_id = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); for (i = 0; i < current_num_elmts; i++) { us_real_proc_id[orig_order[i]] = real_proc_id[i]; } hypre_TFree(real_proc_id, HYPRE_MEMORY_HOST); prev_id = -1; for (i = 0; i < current_num_elmts; i++) { proc_id = us_real_proc_id[i]; /* can't use row list[i] - you loose the negative signs that differentiate add/set values */ row = off_proc_i[i]; /* find position of this processor */ indx = hypre_BinarySearch(ex_contact_procs, proc_id, num_real_procs); in = ex_contact_vec_starts[indx]; index_ptr = (void *) ((char *) void_contact_buf + in * obj_size_bytes); /* first time for this processor - add the number of rows to the buffer */ if (in < 0) { in = -in - 1; /* re-calc. index_ptr since in_i was negative */ index_ptr = (void *) ((char *) void_contact_buf + in * obj_size_bytes); tmp_int = num_rows_per_proc[indx]; hypre_TMemcpy( index_ptr, &tmp_int, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); index_ptr = (void *) ((char *) index_ptr + obj_size_bytes); in++; } /* add row # */ hypre_TMemcpy( index_ptr, &row, HYPRE_BigInt, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); index_ptr = (void *) ((char *) index_ptr + obj_size_bytes); in++; /* add value */ tmp_complex = off_proc_data[i]; hypre_TMemcpy( index_ptr, &tmp_complex, HYPRE_Complex, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); index_ptr = (void *) ((char *) index_ptr + obj_size_bytes); in++; /* increment the indexes to keep track of where we are - fix later */ ex_contact_vec_starts[indx] = in; } /* some clean up */ hypre_TFree(response_buf, HYPRE_MEMORY_HOST); hypre_TFree(response_buf_starts, HYPRE_MEMORY_HOST); hypre_TFree(us_real_proc_id, HYPRE_MEMORY_HOST); hypre_TFree(orig_order, HYPRE_MEMORY_HOST); hypre_TFree(row_list, HYPRE_MEMORY_HOST); hypre_TFree(num_rows_per_proc, HYPRE_MEMORY_HOST); for (i = num_real_procs; i > 0; i--) { ex_contact_vec_starts[i] = ex_contact_vec_starts[i - 1]; } ex_contact_vec_starts[0] = 0; /* now send the data */ /***********************************/ /* now get the info in send_proc_obj_d */ /* the response we expect is just a confirmation*/ response_buf = NULL; response_buf_starts = NULL; /*build the response object*/ /* use the send_proc_obj for the info kept from contacts */ /*estimate inital storage allocation */ send_proc_obj.length = 0; send_proc_obj.storage_length = num_real_procs + 5; send_proc_obj.id = NULL; /* don't care who sent it to us */ send_proc_obj.vec_starts = hypre_CTAlloc(HYPRE_Int, send_proc_obj.storage_length + 1, HYPRE_MEMORY_HOST); send_proc_obj.vec_starts[0] = 0; send_proc_obj.element_storage_length = storage + 20; send_proc_obj.v_elements = hypre_TAlloc(char, obj_size_bytes * send_proc_obj.element_storage_length, HYPRE_MEMORY_HOST); response_obj2.fill_response = hypre_FillResponseIJOffProcVals; response_obj2.data1 = NULL; response_obj2.data2 = &send_proc_obj; max_response_size = 0; hypre_DataExchangeList(num_real_procs, ex_contact_procs, void_contact_buf, ex_contact_vec_starts, obj_size_bytes, 0, &response_obj2, max_response_size, 5, comm, (void **) &response_buf, &response_buf_starts); /***********************************/ hypre_TFree(response_buf, HYPRE_MEMORY_HOST); hypre_TFree(response_buf_starts, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_procs, HYPRE_MEMORY_HOST); hypre_TFree(void_contact_buf, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_vec_starts, HYPRE_MEMORY_HOST); /* Now we can unpack the send_proc_objects and either set or add to the vector data */ num_recvs = send_proc_obj.length; /* alias */ recv_data_ptr = send_proc_obj.v_elements; recv_starts = send_proc_obj.vec_starts; vector_data = hypre_VectorData(hypre_ParVectorLocalVector(par_vector)); first_index = hypre_ParVectorFirstIndex(par_vector); for (i = 0; i < num_recvs; i++) { indx = recv_starts[i]; /* get the number of rows for this recv */ hypre_TMemcpy( &row_count, recv_data_ptr, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); recv_data_ptr = (void *) ((char *)recv_data_ptr + obj_size_bytes); indx++; for (j = 0; j < row_count; j++) /* for each row: unpack info */ { /* row # */ hypre_TMemcpy( &row, recv_data_ptr, HYPRE_BigInt, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); recv_data_ptr = (void *) ((char *)recv_data_ptr + obj_size_bytes); indx++; /* value */ hypre_TMemcpy( &value, recv_data_ptr, HYPRE_Complex, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); recv_data_ptr = (void *) ((char *)recv_data_ptr + obj_size_bytes); indx++; if (memory_location == HYPRE_MEMORY_HOST) { k = (HYPRE_Int)(row - first_index - global_first_row); vector_data[k] += value; } else { if (off_proc_nelm_recv_cur >= off_proc_nelm_recv_max) { off_proc_nelm_recv_max = 2 * (off_proc_nelm_recv_cur + 1); off_proc_i_recv = hypre_TReAlloc(off_proc_i_recv, HYPRE_BigInt, off_proc_nelm_recv_max, HYPRE_MEMORY_HOST); off_proc_data_recv = hypre_TReAlloc(off_proc_data_recv, HYPRE_Complex, off_proc_nelm_recv_max, HYPRE_MEMORY_HOST); } off_proc_i_recv[off_proc_nelm_recv_cur] = row; off_proc_data_recv[off_proc_nelm_recv_cur] = value; off_proc_nelm_recv_cur ++; } } } if (memory_location == HYPRE_MEMORY_DEVICE) { off_proc_i_recv_d = hypre_TAlloc(HYPRE_BigInt, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE); off_proc_data_recv_d = hypre_TAlloc(HYPRE_Complex, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(off_proc_i_recv_d, off_proc_i_recv, HYPRE_BigInt, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_TMemcpy(off_proc_data_recv_d, off_proc_data_recv, HYPRE_Complex, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_IJVectorSetAddValuesParDevice(vector, off_proc_nelm_recv_cur, off_proc_i_recv_d, off_proc_data_recv_d, "add"); #endif } hypre_TFree(send_proc_obj.v_elements, HYPRE_MEMORY_HOST); hypre_TFree(send_proc_obj.vec_starts, HYPRE_MEMORY_HOST); if (memory_location == HYPRE_MEMORY_DEVICE) { hypre_TFree(off_proc_i, HYPRE_MEMORY_HOST); hypre_TFree(off_proc_data, HYPRE_MEMORY_HOST); } hypre_TFree(off_proc_i_recv, HYPRE_MEMORY_HOST); hypre_TFree(off_proc_data_recv, HYPRE_MEMORY_HOST); hypre_TFree(off_proc_i_recv_d, HYPRE_MEMORY_DEVICE); hypre_TFree(off_proc_data_recv_d, HYPRE_MEMORY_DEVICE); return hypre_error_flag; }
2Dpfold.c
/* * minimum free energy * RNA secondary structure with * basepair distance d_1 to reference structure 1 and distance d_2 to reference structure 2 * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <string.h> #include <float.h> /* #defines FLT_MAX ... */ #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/params/default.h" #include "ViennaRNA/loops/all.h" #include "ViennaRNA/2Dpfold.h" /* ################################# # GLOBAL VARIABLES # ################################# */ /* ################################# # PRIVATE VARIABLES # ################################# */ /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ PRIVATE void crosslink(TwoDpfold_vars *vars); PRIVATE void pf2D_linear(vrna_fold_compound_t *vc); PRIVATE void pf2D_circ(vrna_fold_compound_t *vc); PRIVATE char * pbacktrack_circ(vrna_fold_compound_t *vc, int d1, int d2); PRIVATE void backtrack(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2, unsigned int i, unsigned int j); PRIVATE void backtrack_qm(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2, unsigned int i, unsigned int j); PRIVATE void backtrack_qm1(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2, unsigned int i, unsigned int j); PRIVATE void backtrack_qm2(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2, unsigned int k); PRIVATE void backtrack_qcH(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2); PRIVATE void backtrack_qcI(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2); PRIVATE void backtrack_qcM(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2); PRIVATE void adjustArrayBoundaries(FLT_OR_DBL ***array, int *k_min, int *k_max, int **l_min, int **l_max, int k_min_real, int k_max_real, int *l_min_real, int *l_max_real); INLINE PRIVATE void preparePosteriorBoundaries(int size, int shift, int *min_k, int *max_k, int **min_l, int **max_l); INLINE PRIVATE void updatePosteriorBoundaries(int d1, int d2, int *min_k, int *max_k, int **min_l, int **max_l); INLINE PRIVATE void prepareBoundaries(int min_k_pre, int max_k_pre, int min_l_pre, int max_l_pre, int bpdist, int *min_k, int *max_k, int **min_l, int **max_l); INLINE PRIVATE void prepareArray(FLT_OR_DBL ***array, int min_k, int max_k, int *min_l, int *max_l); /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ PUBLIC vrna_sol_TwoD_pf_t * vrna_pf_TwoD(vrna_fold_compound_t *vc, int distance1, int distance2) { unsigned int maxD1 = 0, maxD2 = 0, counter = 0; int cnt1, cnt2, k_min, k_max, l_min, l_max, ndx; FLT_OR_DBL q = 0.; vrna_sol_TwoD_pf_t *output; vrna_md_t *md; vrna_mx_pf_t *matrices; maxD1 = vc->maxD1; maxD2 = vc->maxD2; matrices = vc->exp_matrices; md = &(vc->exp_params->model_details); if (distance1 >= 0) { if ((unsigned int)distance1 > maxD1) vrna_message_warning("vrna_pf_TwoD@2Dpfold.c: limiting maximum basepair distance 1 to %u\n", maxD1); else maxD1 = (unsigned int)distance1; } if (distance2 >= 0) { if ((unsigned int)distance2 > maxD2) vrna_message_warning("vrna_pf_TwoD@2Dpfold.c: limiting maximum basepair distance 2 to %u\n", maxD2); else maxD2 = (unsigned int)distance2; } vc->maxD1 = maxD1; vc->maxD2 = maxD2; output = (vrna_sol_TwoD_pf_t *)vrna_alloc( (((maxD1 + 1) * (maxD2 + 2)) / 2 + 2) * sizeof(vrna_sol_TwoD_pf_t)); pf2D_linear(vc); if (md->circ) pf2D_circ(vc); ndx = vc->iindx[1] - vc->length; k_min = (md->circ) ? matrices->k_min_Q_c : matrices->k_min_Q[ndx]; k_max = (md->circ) ? matrices->k_max_Q_c : matrices->k_max_Q[ndx]; for (cnt1 = k_min; cnt1 <= k_max; cnt1++) { l_min = (md->circ) ? matrices->l_min_Q_c[cnt1] : matrices->l_min_Q[ndx][cnt1]; l_max = (md->circ) ? matrices->l_max_Q_c[cnt1] : matrices->l_max_Q[ndx][cnt1]; for (cnt2 = l_min; cnt2 <= l_max; cnt2 += 2) { q = (md->circ) ? matrices->Q_c[cnt1][cnt2 / 2] : matrices->Q[ndx][cnt1][cnt2 / 2]; if (q == 0.) continue; output[counter].k = cnt1; output[counter].l = cnt2; output[counter].q = q; counter++; } } /* store entry for remaining partition if it exists */ q = (md->circ) ? matrices->Q_c_rem : matrices->Q_rem[ndx]; if (q != 0.) { output[counter].k = -1; output[counter].l = -1; output[counter].q = q; counter++; } /* insert end-marker entry */ output[counter].k = output[counter].l = INF; counter++; /* resize to actual dataset amount */ output = (vrna_sol_TwoD_pf_t *)vrna_realloc(output, sizeof(vrna_sol_TwoD_pf_t) * counter); return output; } #if 0 PUBLIC FLT_OR_DBL ** TwoDpfold(TwoDpfold_vars *vars, int distance1, int distance2) { unsigned int i; unsigned int maxD1 = 0; unsigned int maxD2 = 0; unsigned int mm; int cnt1, cnt2; FLT_OR_DBL **output; initialize_TwoDpfold_vars(vars); vars->S = encode_sequence(vars->sequence, 0); vars->S1 = encode_sequence(vars->sequence, 1); make_ptypes2(vars); for (i = 1; i <= (unsigned int)vars->reference_pt1[0]; i++) if (i < (unsigned int)vars->reference_pt1[i]) maxD1++; for (i = 1; i <= (unsigned int)vars->reference_pt2[0]; i++) if (i < (unsigned int)vars->reference_pt2[i]) maxD2++; mm = maximumMatching(vars->sequence); maxD1 += mm; maxD2 += mm; if (distance1 >= 0) { if ((unsigned int)distance1 > maxD1) fprintf(stderr, "limiting maximum basepair distance 1 to %u\n", maxD1); maxD1 = (unsigned int)distance1; } if (distance2 >= 0) { if ((unsigned int)distance2 > maxD2) fprintf(stderr, "limiting maximum basepair distance 2 to %u\n", maxD2); maxD2 = (unsigned int)distance2; } vars->maxD1 = maxD1; vars->maxD2 = maxD2; output = (FLT_OR_DBL **)vrna_alloc(sizeof(FLT_OR_DBL *) * (maxD1 + 1)); pf2D_linear(vars); int ndx = vars->my_iindx[1] - vars->seq_length; for (cnt1 = vars->k_min_values[ndx]; cnt1 <= MIN2(vars->k_max_values[ndx], vars->maxD1); cnt1++) { output[cnt1] = (FLT_OR_DBL *)vrna_alloc((vars->maxD2 + 1) * sizeof(FLT_OR_DBL)); for (cnt2 = vars->l_min_values[ndx][cnt1]; cnt2 <= MIN2(vars->l_max_values[ndx][cnt1], vars->maxD2); cnt2 += 2) output[cnt1][cnt2] = vars->Q[ndx][cnt1][cnt2 / 2]; } return output; } PUBLIC FLT_OR_DBL ** TwoDpfold_circ(TwoDpfold_vars *vars, int distance1, int distance2) { unsigned int i; unsigned int maxD1 = 0; unsigned int maxD2 = 0; unsigned int mm; int cnt1, cnt2; FLT_OR_DBL **output; initialize_TwoDpfold_vars(vars); vars->S = encode_sequence(vars->sequence, 0); vars->S1 = encode_sequence(vars->sequence, 1); make_ptypes2(vars); for (i = 1; i <= (unsigned int)vars->reference_pt1[0]; i++) if (i < (unsigned int)vars->reference_pt1[i]) maxD1++; for (i = 1; i <= (unsigned int)vars->reference_pt2[0]; i++) if (i < (unsigned int)vars->reference_pt2[i]) maxD2++; mm = maximumMatching(vars->sequence); maxD1 += mm; maxD2 += mm; if (distance1 >= 0) { if ((unsigned int)distance1 > maxD1) fprintf(stderr, "limiting maximum basepair distance 1 to %u\n", maxD1); maxD1 = (unsigned int)distance1; } if (distance2 >= 0) { if ((unsigned int)distance2 > maxD2) fprintf(stderr, "limiting maximum basepair distance 2 to %u\n", maxD2); maxD2 = (unsigned int)distance2; } vars->maxD1 = maxD1; vars->maxD2 = maxD2; output = (FLT_OR_DBL **)vrna_alloc(sizeof(FLT_OR_DBL *) * (maxD1 + 1)); pf2D_linear(vars); pf2D_circ(vars); for (cnt1 = vars->k_min_values_qc; cnt1 <= MIN2(vars->k_max_values_qc, vars->maxD1); cnt1++) { output[cnt1] = (FLT_OR_DBL *)vrna_alloc((vars->maxD2 + 1) * sizeof(FLT_OR_DBL)); for (cnt2 = vars->l_min_values_qc[cnt1]; cnt2 <= MIN2(vars->l_max_values_qc[cnt1], vars->maxD2); cnt2 += 2) output[cnt1][cnt2] = vars->Q_c[cnt1][cnt2 / 2]; } return output; } #endif PRIVATE void pf2D_linear(vrna_fold_compound_t *vc) { char *sequence, *ptype; short *S1, *reference_pt1, *reference_pt2; unsigned int *referenceBPs1, *referenceBPs2, d, i, j, ij, seq_length, maxD1, maxD2, *mm1, *mm2, *bpdist; int *my_iindx, *jindx, circ, cnt1, cnt2, cnt3, cnt4, *rtype, turn; double max_real; FLT_OR_DBL *scale, Qmax; vrna_exp_param_t *pf_params; vrna_mx_pf_t *matrices; vrna_md_t *md; max_real = (sizeof(FLT_OR_DBL) == sizeof(float)) ? FLT_MAX : DBL_MAX; pf_params = vc->exp_params; md = &(pf_params->model_details); matrices = vc->exp_matrices; sequence = vc->sequence; seq_length = vc->length; maxD1 = vc->maxD1; maxD2 = vc->maxD2; S1 = vc->sequence_encoding; ptype = vc->ptype; rtype = &(md->rtype[0]); scale = matrices->scale; reference_pt1 = vc->reference_pt1; reference_pt2 = vc->reference_pt2; my_iindx = vc->iindx; jindx = vc->jindx; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; dangles = md->dangles; circ = md->circ; turn = md->min_loop_size; mm1 = vc->mm1; mm2 = vc->mm2; bpdist = vc->bpdist; Qmax = 0.; /*array initialization ; qb,qm,q * qb,qm,q (i,j) are stored as ((n+1-i)*(n-i) div 2 + n+1-j */ for (j = 1; j <= seq_length; j++) for (i = (j > turn ? (j - turn) : 1); i <= j; i++) { ij = my_iindx[i] - j; matrices->k_min_Q[ij] = 0; matrices->k_max_Q[ij] = 0; matrices->l_min_Q[ij] = (int *)vrna_alloc(sizeof(int)); matrices->l_max_Q[ij] = (int *)vrna_alloc(sizeof(int)); matrices->l_min_Q[ij][0] = 0; matrices->l_max_Q[ij][0] = 0; matrices->Q[ij] = (FLT_OR_DBL **)vrna_alloc(sizeof(FLT_OR_DBL *)); matrices->Q[ij][0] = (FLT_OR_DBL *)vrna_alloc(sizeof(FLT_OR_DBL)); matrices->Q[ij][0][0] = 1.0 * scale[j - i + 1]; } for (d = turn + 2; d <= seq_length; d++) { /* i,j in [1..seq_length] */ #ifdef _OPENMP #pragma omp parallel for private(i, j, ij, cnt1, cnt2, cnt3, cnt4) #endif for (j = d; j <= seq_length; j++) { unsigned int k, l, kl, u, ii, dij; int no_close, type, type_2, tt, da, db, base_da, base_db; FLT_OR_DBL temp2, aux_en; i = j - d + 1; ij = my_iindx[i] - j; dij = j - i - 1; type = ptype[jindx[j] + i]; no_close = (((type == 3) || (type == 4)) && no_closingGU); if (type) { /* we have a pair */ int k_min_Q_B, k_max_Q_B, l_min_Q_B, l_max_Q_B; int k_min_post_b, k_max_post_b, *l_min_post_b, *l_max_post_b; int update_b = 0; if (!matrices->Q_B[ij]) { update_b = 1; k_min_Q_B = l_min_Q_B = 0; k_max_Q_B = mm1[ij] + referenceBPs1[ij]; l_max_Q_B = mm2[ij] + referenceBPs2[ij]; prepareBoundaries(k_min_Q_B, k_max_Q_B, l_min_Q_B, l_max_Q_B, bpdist[ij], &matrices->k_min_Q_B[ij], &matrices->k_max_Q_B[ij], &matrices->l_min_Q_B[ij], &matrices->l_max_Q_B[ij] ); preparePosteriorBoundaries(matrices->k_max_Q_B[ij] - matrices->k_min_Q_B[ij] + 1, matrices->k_min_Q_B[ij], &k_min_post_b, &k_max_post_b, &l_min_post_b, &l_max_post_b ); prepareArray(&matrices->Q_B[ij], matrices->k_min_Q_B[ij], matrices->k_max_Q_B[ij], matrices->l_min_Q_B[ij], matrices->l_max_Q_B[ij] ); } /* hairpin ----------------------------------------------*/ /* get distance to reference if closing the hairpin * d1a = dbp(T1_{i,j}, {i,j}) */ base_da = ((unsigned int)reference_pt1[i] != j) ? 1 : -1; base_db = ((unsigned int)reference_pt2[i] != j) ? 1 : -1; da = base_da + referenceBPs1[ij]; db = base_db + referenceBPs2[ij]; if (!no_close) { if ((da >= 0) && (db >= 0)) { if (((unsigned int)da <= maxD1) && ((unsigned int)db <= maxD2)) { matrices->Q_B[ij][da][db / 2] = exp_E_Hairpin(dij, type, S1[i + 1], S1[j - 1], sequence + i - 1, pf_params) * scale[dij + 2]; if (update_b) { updatePosteriorBoundaries(da, db, &k_min_post_b, &k_max_post_b, &l_min_post_b, &l_max_post_b ); } } else { matrices->Q_B_rem[ij] = exp_E_Hairpin(dij, type, S1[i + 1], S1[j - 1], sequence + i - 1, pf_params) * scale[dij + 2]; } } } /*-------------------------------------------------------- * check for elementary structures involving more than one * closing pair. * --------------------------------------------------------*/ for (k = i + 1; k <= MIN2(j - 2 - turn, i + MAXLOOP + 1); k++) { unsigned int minl, ln_pre; minl = k + turn + 1; ln_pre = dij + k; if (ln_pre > minl + MAXLOOP) minl = ln_pre - MAXLOOP - 1; for (l = minl; l < j; l++) { kl = my_iindx[k] - l; type_2 = ptype[jindx[l] + k]; if (type_2 == 0) continue; type_2 = rtype[type_2]; aux_en = exp_E_IntLoop(k - i - 1, j - l - 1, type, type_2, S1[i + 1], S1[j - 1], S1[k - 1], S1[l + 1], pf_params) * scale[k - i + j - l]; /* get distance to reference if closing the interior loop * d2 = dbp(S_{i,j}, S_{k,l} + {i,j}) */ da = base_da + referenceBPs1[ij] - referenceBPs1[kl]; db = base_db + referenceBPs2[ij] - referenceBPs2[kl]; if (matrices->Q_B_rem[kl]) matrices->Q_B_rem[ij] += matrices->Q_B_rem[kl] * aux_en; if (!matrices->Q_B[kl]) continue; for (cnt1 = matrices->k_min_Q_B[kl]; cnt1 <= matrices->k_max_Q_B[kl]; cnt1++) for (cnt2 = matrices->l_min_Q_B[kl][cnt1]; cnt2 <= matrices->l_max_Q_B[kl][cnt1]; cnt2 += 2) { if (((cnt1 + da) <= maxD1) && ((cnt2 + db) <= maxD2)) { matrices->Q_B[ij][cnt1 + da][(cnt2 + db) / 2] += matrices->Q_B[kl][cnt1][cnt2 / 2] * aux_en; if (update_b) { updatePosteriorBoundaries(da + cnt1, db + cnt2, &k_min_post_b, &k_max_post_b, &l_min_post_b, &l_max_post_b ); } } else { matrices->Q_B_rem[ij] += matrices->Q_B[kl][cnt1][cnt2 / 2] * aux_en; } } } /* end l-loop */ } /* end k-loop */ /* multi-loop contribution ------------------------*/ if (!no_close) { for (u = i + turn + 2; u < j - turn - 2; u++) { tt = rtype[type]; temp2 = pf_params->expMLclosing * exp_E_MLstem(tt, S1[j - 1], S1[i + 1], pf_params) * scale[2]; if (matrices->Q_M_rem[my_iindx[i + 1] - u]) { if (matrices->Q_M1[jindx[j - 1] + u + 1]) { for (cnt1 = matrices->k_min_Q_M1[jindx[j - 1] + u + 1]; cnt1 <= matrices->k_max_Q_M1[jindx[j - 1] + u + 1]; cnt1++) for (cnt2 = matrices->l_min_Q_M1[jindx[j - 1] + u + 1][cnt1]; cnt2 <= matrices->l_max_Q_M1[jindx[j - 1] + u + 1][cnt1]; cnt2 += 2) matrices->Q_B_rem[ij] += matrices->Q_M_rem[my_iindx[i + 1] - u] * matrices->Q_M1[jindx[j - 1] + u + 1][cnt1][cnt2 / 2] * temp2; } if (matrices->Q_M1_rem[jindx[j - 1] + u + 1]) matrices->Q_B_rem[ij] += matrices->Q_M_rem[my_iindx[i + 1] - u] * matrices->Q_M1_rem[jindx[j - 1] + u + 1] * temp2; } if (matrices->Q_M1_rem[jindx[j - 1] + u + 1]) { if (matrices->Q_M[my_iindx[i + 1] - u]) { for (cnt1 = matrices->k_min_Q_M[my_iindx[i + 1] - u]; cnt1 <= matrices->k_max_Q_M[my_iindx[i + 1] - u]; cnt1++) for (cnt2 = matrices->l_min_Q_M[my_iindx[i + 1] - u][cnt1]; cnt2 <= matrices->l_max_Q_M[my_iindx[i + 1] - u][cnt1]; cnt2 += 2) matrices->Q_B_rem[ij] += matrices->Q_M[my_iindx[i + 1] - u][cnt1][cnt2 / 2] * matrices->Q_M1_rem[jindx[j - 1] + u + 1] * temp2; } } /* get distance to reference if closing the multiloop * dist3 = dbp(S_{i,j}, {i,j} + S_{i+1,u} + S_{u+1,j-1}) */ da = base_da + referenceBPs1[ij] - referenceBPs1[my_iindx[i + 1] - u] - referenceBPs1[my_iindx[u + 1] - j + 1]; db = base_db + referenceBPs2[ij] - referenceBPs2[my_iindx[i + 1] - u] - referenceBPs2[my_iindx[u + 1] - j + 1]; if (!matrices->Q_M[my_iindx[i + 1] - u]) continue; if (!matrices->Q_M1[jindx[j - 1] + u + 1]) continue; for (cnt1 = matrices->k_min_Q_M[my_iindx[i + 1] - u]; cnt1 <= matrices->k_max_Q_M[my_iindx[i + 1] - u]; cnt1++) for (cnt2 = matrices->l_min_Q_M[my_iindx[i + 1] - u][cnt1]; cnt2 <= matrices->l_max_Q_M[my_iindx[i + 1] - u][cnt1]; cnt2 += 2) { for (cnt3 = matrices->k_min_Q_M1[jindx[j - 1] + u + 1]; cnt3 <= matrices->k_max_Q_M1[jindx[j - 1] + u + 1]; cnt3++) for (cnt4 = matrices->l_min_Q_M1[jindx[j - 1] + u + 1][cnt3]; cnt4 <= matrices->l_max_Q_M1[jindx[j - 1] + u + 1][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) <= maxD1) && ((cnt2 + cnt4 + db) <= maxD2)) { matrices->Q_B[ij][cnt1 + cnt3 + da][(cnt2 + cnt4 + db) / 2] += matrices->Q_M[my_iindx[i + 1] - u][cnt1][cnt2 / 2] * matrices-> Q_M1[jindx[j - 1] + u + 1][cnt3][cnt4 / 2] * temp2; if (update_b) { updatePosteriorBoundaries(cnt1 + cnt3 + da, cnt2 + cnt4 + db, &k_min_post_b, &k_max_post_b, &l_min_post_b, &l_max_post_b ); } } else { matrices->Q_B_rem[ij] += matrices->Q_M[my_iindx[i + 1] - u][cnt1][cnt2 / 2] * matrices->Q_M1[jindx[j - 1] + u + 1][cnt3][cnt4 / 2] * temp2; } } } } } if (update_b) { adjustArrayBoundaries(&matrices->Q_B[ij], &matrices->k_min_Q_B[ij], &matrices->k_max_Q_B[ij], &matrices->l_min_Q_B[ij], &matrices->l_max_Q_B[ij], k_min_post_b, k_max_post_b, l_min_post_b, l_max_post_b ); } } /* end >> if (pair) << */ /* free ends ? -----------------------------------------*/ int k_min_Q_M, k_max_Q_M, l_min_Q_M, l_max_Q_M; int k_min_post_m, k_max_post_m, *l_min_post_m, *l_max_post_m; int update_m = 0; int k_min_Q_M1, k_max_Q_M1, l_min_Q_M1, l_max_Q_M1; int k_min_post_m1, k_max_post_m1, *l_min_post_m1, *l_max_post_m1; int update_m1 = 0; if (!matrices->Q_M[ij]) { update_m = 1; k_min_Q_M = l_min_Q_M = 0; k_max_Q_M = mm1[ij] + referenceBPs1[ij]; l_max_Q_M = mm2[ij] + referenceBPs2[ij]; prepareBoundaries(k_min_Q_M, k_max_Q_M, l_min_Q_M, l_max_Q_M, bpdist[ij], &matrices->k_min_Q_M[ij], &matrices->k_max_Q_M[ij], &matrices->l_min_Q_M[ij], &matrices->l_max_Q_M[ij] ); preparePosteriorBoundaries(matrices->k_max_Q_M[ij] - matrices->k_min_Q_M[ij] + 1, matrices->k_min_Q_M[ij], &k_min_post_m, &k_max_post_m, &l_min_post_m, &l_max_post_m ); prepareArray(&matrices->Q_M[ij], matrices->k_min_Q_M[ij], matrices->k_max_Q_M[ij], matrices->l_min_Q_M[ij], matrices->l_max_Q_M[ij] ); } if (!matrices->Q_M1[jindx[j] + i]) { update_m1 = 1; k_min_Q_M1 = l_min_Q_M1 = 0; k_max_Q_M1 = mm1[ij] + referenceBPs1[ij]; l_max_Q_M1 = mm2[ij] + referenceBPs2[ij]; prepareBoundaries(k_min_Q_M1, k_max_Q_M1, l_min_Q_M1, l_max_Q_M1, bpdist[ij], &matrices->k_min_Q_M1[jindx[j] + i], &matrices->k_max_Q_M1[jindx[j] + i], &matrices->l_min_Q_M1[jindx[j] + i], &matrices->l_max_Q_M1[jindx[j] + i] ); preparePosteriorBoundaries(matrices->k_max_Q_M1[jindx[j] + i] - matrices->k_min_Q_M1[jindx[j] + i] + 1, matrices->k_min_Q_M1[jindx[j] + i], &k_min_post_m1, &k_max_post_m1, &l_min_post_m1, &l_max_post_m1 ); prepareArray(&matrices->Q_M1[jindx[j] + i], matrices->k_min_Q_M1[jindx[j] + i], matrices->k_max_Q_M1[jindx[j] + i], matrices->l_min_Q_M1[jindx[j] + i], matrices->l_max_Q_M1[jindx[j] + i] ); } /* j is unpaired */ da = referenceBPs1[ij] - referenceBPs1[ij + 1]; db = referenceBPs2[ij] - referenceBPs2[ij + 1]; if (matrices->Q_M_rem[ij + 1]) matrices->Q_M_rem[ij] += matrices->Q_M_rem[ij + 1] * pf_params->expMLbase * scale[1]; if (matrices->Q_M[ij + 1]) { for (cnt1 = matrices->k_min_Q_M[ij + 1]; cnt1 <= matrices->k_max_Q_M[ij + 1]; cnt1++) { for (cnt2 = matrices->l_min_Q_M[ij + 1][cnt1]; cnt2 <= matrices->l_max_Q_M[ij + 1][cnt1]; cnt2 += 2) { if (((cnt1 + da) <= maxD1) && ((cnt2 + db) <= maxD2)) { matrices->Q_M[ij][cnt1 + da][(cnt2 + db) / 2] += matrices->Q_M[ij + 1][cnt1][cnt2 / 2] * pf_params->expMLbase * scale[1]; if (update_m) { updatePosteriorBoundaries(cnt1 + da, cnt2 + db, &k_min_post_m, &k_max_post_m, &l_min_post_m, &l_max_post_m ); } } else { matrices->Q_M_rem[ij] += matrices->Q_M[ij + 1][cnt1][cnt2 / 2] * pf_params->expMLbase * scale[1]; } } } } if (matrices->Q_M1_rem[jindx[j - 1] + i]) matrices->Q_M1_rem[jindx[j] + i] += matrices->Q_M1_rem[jindx[j - 1] + i] * pf_params->expMLbase * scale[1]; if (matrices->Q_M1[jindx[j - 1] + i]) { for (cnt1 = matrices->k_min_Q_M1[jindx[j - 1] + i]; cnt1 <= matrices->k_max_Q_M1[jindx[j - 1] + i]; cnt1++) for (cnt2 = matrices->l_min_Q_M1[jindx[j - 1] + i][cnt1]; cnt2 <= matrices->l_max_Q_M1[jindx[j - 1] + i][cnt1]; cnt2 += 2) { if (((cnt1 + da) <= maxD1) && ((cnt2 + db) <= maxD2)) { matrices->Q_M1[jindx[j] + i][cnt1 + da][(cnt2 + db) / 2] += matrices->Q_M1[jindx[j - 1] + i][cnt1][cnt2 / 2] * pf_params->expMLbase * scale[1]; if (update_m1) { updatePosteriorBoundaries(cnt1 + da, cnt2 + db, &k_min_post_m1, &k_max_post_m1, &l_min_post_m1, &l_max_post_m1 ); } } else { matrices->Q_M1_rem[jindx[j] + i] += matrices->Q_M1[jindx[j - 1] + i][cnt1][cnt2 / 2] * pf_params->expMLbase * scale[1]; } } } /* j pairs with i */ if ((!no_close) && type) { FLT_OR_DBL aux_en = exp_E_MLstem(type, (i > 1) || circ ? S1[i - 1] : -1, (j < seq_length) || circ ? S1[j + 1] : -1, pf_params); if (matrices->Q_B_rem[ij]) { matrices->Q_M_rem[ij] += matrices->Q_B_rem[ij] * aux_en; matrices->Q_M1_rem[jindx[j] + i] += matrices->Q_B_rem[ij] * aux_en; } if (matrices->Q_B[ij]) { for (cnt1 = matrices->k_min_Q_B[ij]; cnt1 <= matrices->k_max_Q_B[ij]; cnt1++) for (cnt2 = matrices->l_min_Q_B[ij][cnt1]; cnt2 <= matrices->l_max_Q_B[ij][cnt1]; cnt2 += 2) { matrices->Q_M[ij][cnt1][cnt2 / 2] += matrices->Q_B[ij][cnt1][cnt2 / 2] * aux_en; if (update_m) { updatePosteriorBoundaries(cnt1, cnt2, &k_min_post_m, &k_max_post_m, &l_min_post_m, &l_max_post_m ); } matrices->Q_M1[jindx[j] + i][cnt1][cnt2 / 2] += matrices->Q_B[ij][cnt1][cnt2 / 2] * aux_en; if (update_m1) { updatePosteriorBoundaries(cnt1, cnt2, &k_min_post_m1, &k_max_post_m1, &l_min_post_m1, &l_max_post_m1 ); } } } } /* j pairs with k: i<k<j */ ii = my_iindx[i]; for (k = i + 1; k <= j; k++) { tt = ptype[jindx[j] + k]; temp2 = exp_E_MLstem(tt, S1[k - 1], (j < seq_length) || circ ? S1[j + 1] : -1, pf_params); if (matrices->Q_B_rem[my_iindx[k] - j]) { matrices->Q_M_rem[ij] += matrices->Q_B_rem[my_iindx[k] - j] * pow(pf_params->expMLbase, (double)(k - i)) * scale[k - i] * temp2; if (matrices->Q_M[ii - k + 1]) { for (cnt1 = matrices->k_min_Q_M[ii - k + 1]; cnt1 <= matrices->k_max_Q_M[ii - k + 1]; cnt1++) for (cnt2 = matrices->l_min_Q_M[ii - k + 1][cnt1]; cnt2 <= matrices->l_max_Q_M[ii - k + 1][cnt1]; cnt2 += 2) matrices->Q_M_rem[ij] += matrices->Q_M[ii - k + 1][cnt1][cnt2 / 2] * matrices->Q_B_rem[my_iindx[k] - j] * temp2; } if (matrices->Q_M_rem[ii - k + 1]) matrices->Q_M_rem[ij] += matrices->Q_M_rem[ii - k + 1] * matrices->Q_B_rem[my_iindx[k] - j] * temp2; } if (matrices->Q_M_rem[ii - k + 1]) { if (matrices->Q_B[my_iindx[k] - j]) { for (cnt1 = matrices->k_min_Q_B[my_iindx[k] - j]; cnt1 <= matrices->k_max_Q_B[my_iindx[k] - j]; cnt1++) for (cnt2 = matrices->l_min_Q_B[my_iindx[k] - j][cnt1]; cnt2 <= matrices->l_max_Q_B[my_iindx[k] - j][cnt1]; cnt2 += 2) matrices->Q_M_rem[ij] += matrices->Q_M_rem[my_iindx[k] - j] * matrices->Q_B[my_iindx[k] - j][cnt1][cnt2 / 2] * temp2; } } /* add contributions of QM(i,k-1)*QB(k,j)*e^b and * e^((k-i) * c) * QB(k,j) * e^b * therefor we need d1a = dbp(T1_{i,j}, T1_{i,k-1} + T1_{k,j}), * d1b = dbp(T2_{i,j}, T2_{i,k-1} + T2_{k,j}) * d1c = dbp(T1_{i,j}, T1_{k,j})circ = 0; * d1d = dbp(T2_{i,j}, T2_{k,j}) */ da = referenceBPs1[ij] - referenceBPs1[my_iindx[k] - j]; db = referenceBPs2[ij] - referenceBPs2[my_iindx[k] - j]; if (!matrices->Q_B[my_iindx[k] - j]) continue; for (cnt1 = matrices->k_min_Q_B[my_iindx[k] - j]; cnt1 <= matrices->k_max_Q_B[my_iindx[k] - j]; cnt1++) for (cnt2 = matrices->l_min_Q_B[my_iindx[k] - j][cnt1]; cnt2 <= matrices->l_max_Q_B[my_iindx[k] - j][cnt1]; cnt2 += 2) { if (((cnt1 + da) <= maxD1) && ((cnt2 + db) <= maxD2)) { matrices->Q_M[ij][cnt1 + da][(cnt2 + db) / 2] += matrices->Q_B[my_iindx[k] - j][cnt1][cnt2 / 2] * pow(pf_params->expMLbase, (double)(k - i)) * scale[k - i] * temp2; if (update_m) { updatePosteriorBoundaries(cnt1 + da, cnt2 + db, &k_min_post_m, &k_max_post_m, &l_min_post_m, &l_max_post_m ); } } else { matrices->Q_M_rem[ij] += matrices->Q_B[my_iindx[k] - j][cnt1][cnt2 / 2] * pow( pf_params->expMLbase, (double)(k - i)) * scale[k - i] * temp2; } } if (!matrices->Q_M[ii - k + 1]) continue; da -= referenceBPs1[ii - k + 1]; db -= referenceBPs2[ii - k + 1]; for (cnt1 = matrices->k_min_Q_M[ii - k + 1]; cnt1 <= matrices->k_max_Q_M[ii - k + 1]; cnt1++) for (cnt2 = matrices->l_min_Q_M[ii - k + 1][cnt1]; cnt2 <= matrices->l_max_Q_M[ii - k + 1][cnt1]; cnt2 += 2) for (cnt3 = matrices->k_min_Q_B[my_iindx[k] - j]; cnt3 <= matrices->k_max_Q_B[my_iindx[k] - j]; cnt3++) for (cnt4 = matrices->l_min_Q_B[my_iindx[k] - j][cnt3]; cnt4 <= matrices->l_max_Q_B[my_iindx[k] - j][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) <= maxD1) && ((cnt2 + cnt4 + db) <= maxD2)) { matrices->Q_M[ij][cnt1 + cnt3 + da][(cnt2 + cnt4 + db) / 2] += matrices->Q_M[ii - k + 1][cnt1][cnt2 / 2] * matrices->Q_B[my_iindx[k] - j][cnt3][cnt4 / 2] * temp2; if (update_m) { updatePosteriorBoundaries(cnt1 + cnt3 + da, cnt2 + cnt4 + db, &k_min_post_m, &k_max_post_m, &l_min_post_m, &l_max_post_m ); } } else { matrices->Q_M_rem[ij] += matrices->Q_M[ii - k + 1][cnt1][cnt2 / 2] * matrices->Q_B[my_iindx[k] - j][cnt3][cnt4 / 2] * temp2; } } } if (update_m) { adjustArrayBoundaries(&matrices->Q_M[ij], &matrices->k_min_Q_M[ij], &matrices->k_max_Q_M[ij], &matrices->l_min_Q_M[ij], &matrices->l_max_Q_M[ij], k_min_post_m, k_max_post_m, l_min_post_m, l_max_post_m ); } if (update_m1) { adjustArrayBoundaries(&matrices->Q_M1[jindx[j] + i], &matrices->k_min_Q_M1[jindx[j] + i], &matrices->k_max_Q_M1[jindx[j] + i], &matrices->l_min_Q_M1[jindx[j] + i], &matrices->l_max_Q_M1[jindx[j] + i], k_min_post_m1, k_max_post_m1, l_min_post_m1, l_max_post_m1 ); } /* compute contributions for Q(i,j) */ int k_min, k_max, l_min, l_max; int k_min_post, k_max_post, *l_min_post, *l_max_post; int update_q = 0; if (!matrices->Q[ij]) { update_q = 1; k_min = l_min = 0; k_max = mm1[ij] + referenceBPs1[ij]; l_max = mm2[ij] + referenceBPs2[ij]; prepareBoundaries(k_min, k_max, l_min, l_max, bpdist[ij], &matrices->k_min_Q[ij], &matrices->k_max_Q[ij], &matrices->l_min_Q[ij], &matrices->l_max_Q[ij] ); preparePosteriorBoundaries(matrices->k_max_Q[ij] - matrices->k_min_Q[ij] + 1, matrices->k_min_Q[ij], &k_min_post, &k_max_post, &l_min_post, &l_max_post ); prepareArray(&matrices->Q[ij], matrices->k_min_Q[ij], matrices->k_max_Q[ij], matrices->l_min_Q[ij], matrices->l_max_Q[ij] ); } if (type) { aux_en = vrna_exp_E_ext_stem(type, (i > 1) || circ ? S1[i - 1] : -1, (j < seq_length) || circ ? S1[j + 1] : -1, pf_params); if (matrices->Q_B_rem[ij]) matrices->Q_rem[ij] += matrices->Q_B_rem[ij] * aux_en; if (matrices->Q_B[ij]) { for (cnt1 = matrices->k_min_Q_B[ij]; cnt1 <= matrices->k_max_Q_B[ij]; cnt1++) for (cnt2 = matrices->l_min_Q_B[ij][cnt1]; cnt2 <= matrices->l_max_Q_B[ij][cnt1]; cnt2 += 2) { matrices->Q[ij][cnt1][cnt2 / 2] += matrices->Q_B[ij][cnt1][cnt2 / 2] * aux_en; if (update_q) { updatePosteriorBoundaries(cnt1, cnt2, &k_min_post, &k_max_post, &l_min_post, &l_max_post ); } } } } /* j is unpaired */ if (matrices->Q_rem[ij + 1]) matrices->Q_rem[ij] += matrices->Q_rem[ij + 1] * scale[1]; /* da = dbp(T1_{i,j}, T1_{i,j-1}) * db = dbp(T2_{i,j}, T2_{i,j-1}) */ da = referenceBPs1[ij] - referenceBPs1[ij + 1]; db = referenceBPs2[ij] - referenceBPs2[ij + 1]; if (matrices->Q[ij + 1]) { for (cnt1 = matrices->k_min_Q[ij + 1]; cnt1 <= matrices->k_max_Q[ij + 1]; cnt1++) for (cnt2 = matrices->l_min_Q[ij + 1][cnt1]; cnt2 <= matrices->l_max_Q[ij + 1][cnt1]; cnt2 += 2) { if (((cnt1 + da) <= maxD1) && ((cnt2 + db) <= maxD2)) { matrices->Q[ij][cnt1 + da][(cnt2 + db) / 2] += matrices->Q[ij + 1][cnt1][cnt2 / 2] * scale[1]; if (update_q) { updatePosteriorBoundaries(cnt1 + da, cnt2 + db, &k_min_post, &k_max_post, &l_min_post, &l_max_post ); } } else { matrices->Q_rem[ij] += matrices->Q[ij + 1][cnt1][cnt2 / 2] * scale[1]; } } } for (k = j - turn - 1; k > i; k--) { tt = ptype[jindx[j] + k]; temp2 = vrna_exp_E_ext_stem(tt, S1[k - 1], (j < seq_length) || circ ? S1[j + 1] : -1, pf_params); if (matrices->Q_rem[my_iindx[i] - k + 1]) { if (matrices->Q_B[my_iindx[k] - j]) { for (cnt1 = matrices->k_min_Q_B[my_iindx[k] - j]; cnt1 <= matrices->k_max_Q_B[my_iindx[k] - j]; cnt1++) for (cnt2 = matrices->l_min_Q_B[my_iindx[k] - j][cnt1]; cnt2 <= matrices->l_max_Q_B[my_iindx[k] - j][cnt1]; cnt2 += 2) matrices->Q_rem[ij] += matrices->Q_rem[my_iindx[i] - k + 1] * matrices->Q_B[my_iindx[k] - j][cnt1][cnt2 / 2] * temp2; } if (matrices->Q_B_rem[my_iindx[k] - j]) matrices->Q_rem[ij] += matrices->Q_rem[my_iindx[i] - k + 1] * matrices->Q_B_rem[my_iindx[k] - j] * temp2; } if (matrices->Q_B_rem[my_iindx[k] - j]) { if (matrices->Q[my_iindx[i] - k + 1]) { for (cnt1 = matrices->k_min_Q[my_iindx[i] - k + 1]; cnt1 <= matrices->k_max_Q[my_iindx[i] - k + 1]; cnt1++) for (cnt2 = matrices->l_min_Q[my_iindx[i] - k + 1][cnt1]; cnt2 <= matrices->l_max_Q[my_iindx[i] - k + 1][cnt1]; cnt2 += 2) matrices->Q_rem[ij] += matrices->Q[my_iindx[i] - k + 1][cnt1][cnt2 / 2] * matrices->Q_B_rem[my_iindx[k] - j] * temp2; } } /* da = dbp{T1_{i,j}, T1_{k,j} * db = dbp{T2_{i,j}, T2_{k,j}} */ da = referenceBPs1[ij] - referenceBPs1[my_iindx[k] - j] - referenceBPs1[my_iindx[i] - k + 1]; db = referenceBPs2[ij] - referenceBPs2[my_iindx[k] - j] - referenceBPs2[my_iindx[i] - k + 1]; if (!matrices->Q[my_iindx[i] - k + 1]) continue; if (!matrices->Q_B[my_iindx[k] - j]) continue; for (cnt1 = matrices->k_min_Q[my_iindx[i] - k + 1]; cnt1 <= matrices->k_max_Q[my_iindx[i] - k + 1]; cnt1++) for (cnt2 = matrices->l_min_Q[my_iindx[i] - k + 1][cnt1]; cnt2 <= matrices->l_max_Q[my_iindx[i] - k + 1][cnt1]; cnt2 += 2) for (cnt3 = matrices->k_min_Q_B[my_iindx[k] - j]; cnt3 <= matrices->k_max_Q_B[my_iindx[k] - j]; cnt3++) for (cnt4 = matrices->l_min_Q_B[my_iindx[k] - j][cnt3]; cnt4 <= matrices->l_max_Q_B[my_iindx[k] - j][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) <= maxD1) && ((cnt2 + cnt4 + db) <= maxD2)) { matrices->Q[ij][cnt1 + cnt3 + da][(cnt2 + cnt4 + db) / 2] += matrices->Q[my_iindx[i] - k + 1][cnt1][cnt2 / 2] * matrices->Q_B[my_iindx[k] - j][cnt3][cnt4 / 2] * temp2; if (update_q) { updatePosteriorBoundaries(cnt1 + cnt3 + da, cnt2 + cnt4 + db, &k_min_post, &k_max_post, &l_min_post, &l_max_post ); } } else { matrices->Q_rem[ij] += matrices->Q[my_iindx[i] - k + 1][cnt1][cnt2 / 2] * matrices->Q_B[my_iindx[k] - j][cnt3][cnt4 / 2] * temp2; } } } if (update_q) { adjustArrayBoundaries(&matrices->Q[ij], &matrices->k_min_Q[ij], &matrices->k_max_Q[ij], &matrices->l_min_Q[ij], &matrices->l_max_Q[ij], k_min_post, k_max_post, l_min_post, l_max_post ); } #if 1 for (cnt1 = matrices->k_min_Q[ij]; cnt1 <= matrices->k_max_Q[ij]; cnt1++) { for (cnt2 = matrices->l_min_Q[ij][cnt1]; cnt2 <= matrices->l_max_Q[ij][cnt1]; cnt2 += 2) { if (matrices->Q[ij][cnt1][cnt2 / 2] > Qmax) { Qmax = matrices->Q[ij][cnt1][cnt2 / 2]; if (Qmax > max_real / 10.) vrna_message_warning("Q close to overflow: %u %u %g\n", i, j, matrices->Q[ij][cnt1][cnt2 / 2]); } if (matrices->Q[ij][cnt1][cnt2 / 2] >= max_real) vrna_message_error("overflow in pf_fold while calculating q[%u,%u]\n" "use larger pf_scale", i, j); } } #endif } /* end of j-loop */ } } /* * calculate partition function for circular case * NOTE: this is the postprocessing step ONLY * You have to call pf2D_linear first to calculate * complete circular case!!! */ PRIVATE void pf2D_circ(vrna_fold_compound_t *vc) { unsigned int d, p, q, pq, k, l, kl, u, da, db, seq_length, maxD1, maxD2, base_d1, base_d2, *mm1, *mm2, *bpdist; int *my_iindx, *jindx, type, cnt1, cnt2, cnt3, cnt4, *rtype, turn; short *S1; unsigned int *referenceBPs1, *referenceBPs2; char *sequence, *ptype; FLT_OR_DBL *scale; vrna_exp_param_t *pf_params; /* holds all [unscaled] pf parameters */ vrna_md_t *md; vrna_mx_pf_t *matrices; pf_params = vc->exp_params; md = &(pf_params->model_details); matrices = vc->exp_matrices; sequence = vc->sequence; seq_length = vc->length; maxD1 = vc->maxD1; maxD2 = vc->maxD2; S1 = vc->sequence_encoding; ptype = vc->ptype; rtype = &(md->rtype[0]); scale = matrices->scale; my_iindx = vc->iindx; jindx = vc->jindx; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; dangles = md->dangles; turn = md->min_loop_size; mm1 = vc->mm1; mm2 = vc->mm2; bpdist = vc->bpdist; FLT_OR_DBL ***Q_B, ***Q_M, ***Q_M1; FLT_OR_DBL *Q_B_rem, *Q_M_rem, *Q_M1_rem; int **l_min_Q_B, **l_max_Q_B, **l_min_Q_M, **l_max_Q_M, **l_min_Q_M1, **l_max_Q_M1; int *k_min_Q_B, *k_max_Q_B, *k_min_Q_M, *k_max_Q_M, *k_min_Q_M1, *k_max_Q_M1; Q_B = matrices->Q_B; l_min_Q_B = matrices->l_min_Q_B; l_max_Q_B = matrices->l_max_Q_B; k_min_Q_B = matrices->k_min_Q_B; k_max_Q_B = matrices->k_max_Q_B; Q_M = matrices->Q_M; l_min_Q_M = matrices->l_min_Q_M; l_max_Q_M = matrices->l_max_Q_M; k_min_Q_M = matrices->k_min_Q_M; k_max_Q_M = matrices->k_max_Q_M; Q_M1 = matrices->Q_M1; l_min_Q_M1 = matrices->l_min_Q_M1; l_max_Q_M1 = matrices->l_max_Q_M1; k_min_Q_M1 = matrices->k_min_Q_M1; k_max_Q_M1 = matrices->k_max_Q_M1; Q_B_rem = matrices->Q_B_rem; Q_M_rem = matrices->Q_M_rem; Q_M1_rem = matrices->Q_M1_rem; matrices->Q_c_rem = 0.; matrices->Q_cH_rem = 0.; matrices->Q_cI_rem = 0.; matrices->Q_cM_rem = 0.; /* construct qm2 matrix from qm1 entries */ #ifdef _OPENMP #pragma omp parallel for private(d, k, l, da, db, cnt1, cnt2, cnt3, cnt4) #endif for (k = 1; k < seq_length - turn - 1; k++) { int k_min_Q_M2, k_max_Q_M2, l_min_Q_M2, l_max_Q_M2; int k_min_post_m2, k_max_post_m2, *l_min_post_m2, *l_max_post_m2; int update_m2 = 0; l_min_post_m2 = l_max_post_m2 = NULL; if (!matrices->Q_M2[k]) { update_m2 = 1; k_min_Q_M2 = l_min_Q_M2 = 0; k_max_Q_M2 = mm1[my_iindx[k] - seq_length] + referenceBPs1[my_iindx[k] - seq_length]; l_max_Q_M2 = mm2[my_iindx[k] - seq_length] + referenceBPs2[my_iindx[k] - seq_length]; prepareBoundaries(k_min_Q_M2, k_max_Q_M2, l_min_Q_M2, l_max_Q_M2, bpdist[my_iindx[k] - seq_length], &matrices->k_min_Q_M2[k], &matrices->k_max_Q_M2[k], &matrices->l_min_Q_M2[k], &matrices->l_max_Q_M2[k] ); preparePosteriorBoundaries(matrices->k_max_Q_M2[k] - matrices->k_min_Q_M2[k] + 1, matrices->k_min_Q_M2[k], &k_min_post_m2, &k_max_post_m2, &l_min_post_m2, &l_max_post_m2 ); prepareArray(&matrices->Q_M2[k], matrices->k_min_Q_M2[k], matrices->k_max_Q_M2[k], matrices->l_min_Q_M2[k], matrices->l_max_Q_M2[k] ); } /* construct Q_M2 */ for (l = k + turn + 1; l < seq_length - turn - 1; l++) { if (Q_M1_rem[jindx[l] + k]) { if (Q_M1[jindx[seq_length] + l + 1]) { for (cnt1 = k_min_Q_M1[jindx[seq_length] + l + 1]; cnt1 <= k_max_Q_M1[jindx[seq_length] + l + 1]; cnt1++) for (cnt2 = l_min_Q_M1[jindx[seq_length] + l + 1][cnt1]; cnt2 <= l_max_Q_M1[jindx[seq_length] + l + 1][cnt1]; cnt2 += 2) matrices->Q_M2_rem[k] += Q_M1_rem[jindx[l] + k] * Q_M1[jindx[seq_length] + l + 1][cnt1][cnt2 / 2]; } if (Q_M1_rem[jindx[seq_length] + l + 1]) matrices->Q_M2_rem[k] += Q_M1_rem[jindx[l] + k] * Q_M1_rem[jindx[seq_length] + l + 1]; } if (Q_M1_rem[jindx[seq_length] + l + 1]) { if (Q_M1[jindx[l] + k]) { for (cnt1 = k_min_Q_M1[jindx[l] + k]; cnt1 <= k_max_Q_M1[jindx[l] + k]; cnt1++) for (cnt2 = l_min_Q_M1[jindx[l] + k][cnt1]; cnt2 <= l_max_Q_M1[jindx[l] + k][cnt1]; cnt2 += 2) matrices->Q_M2_rem[k] += Q_M1[jindx[l] + k][cnt1][cnt2 / 2] * Q_M1_rem[jindx[seq_length] + l + 1]; } } if (matrices->Q_M1[jindx[l] + k] && matrices->Q_M1[jindx[seq_length] + l + 1]) { da = referenceBPs1[my_iindx[k] - seq_length] - referenceBPs1[my_iindx[k] - l] - referenceBPs1[my_iindx[l + 1] - seq_length]; db = referenceBPs2[my_iindx[k] - seq_length] - referenceBPs2[my_iindx[k] - l] - referenceBPs2[my_iindx[l + 1] - seq_length]; for (cnt1 = k_min_Q_M1[jindx[l] + k]; cnt1 <= k_max_Q_M1[jindx[l] + k]; cnt1++) for (cnt2 = l_min_Q_M1[jindx[l] + k][cnt1]; cnt2 <= l_max_Q_M1[jindx[l] + k][cnt1]; cnt2 += 2) { for (cnt3 = k_min_Q_M1[jindx[seq_length] + l + 1]; cnt3 <= k_max_Q_M1[jindx[seq_length] + l + 1]; cnt3++) for (cnt4 = l_min_Q_M1[jindx[seq_length] + l + 1][cnt3]; cnt4 <= l_max_Q_M1[jindx[seq_length] + l + 1][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) <= maxD1) && ((cnt2 + cnt4 + db) <= maxD2)) { matrices->Q_M2[k][cnt1 + cnt3 + da][(cnt2 + cnt4 + db) / 2] += Q_M1[jindx[l] + k][cnt1][cnt2 / 2] * Q_M1[jindx[seq_length] + l + 1][cnt3][cnt4 / 2]; if (update_m2) { updatePosteriorBoundaries(cnt1 + cnt3 + da, cnt2 + cnt4 + db, &k_min_post_m2, &k_max_post_m2, &l_min_post_m2, &l_max_post_m2 ); } } else { matrices->Q_M2_rem[k] += Q_M1[jindx[l] + k][cnt1][cnt2 / 2] * Q_M1[jindx[seq_length] + l + 1][cnt3][cnt4 / 2]; } } } } } if (update_m2) { adjustArrayBoundaries(&matrices->Q_M2[k], &matrices->k_min_Q_M2[k], &matrices->k_max_Q_M2[k], &matrices->l_min_Q_M2[k], &matrices->l_max_Q_M2[k], k_min_post_m2, k_max_post_m2, l_min_post_m2, l_max_post_m2 ); } } base_d1 = referenceBPs1[my_iindx[1] - seq_length]; base_d2 = referenceBPs2[my_iindx[1] - seq_length]; int min_k, max_k, max_l, min_l; int min_k_real, max_k_real, min_k_real_qcH, max_k_real_qcH, min_k_real_qcI, max_k_real_qcI, min_k_real_qcM, max_k_real_qcM; int *min_l_real, *max_l_real, *min_l_real_qcH, *max_l_real_qcH, *min_l_real_qcI, *max_l_real_qcI, *min_l_real_qcM, *max_l_real_qcM; int update_c, update_cH, update_cI, update_cM; max_l_real_qcM = min_l_real_qcM = NULL; max_l_real_qcI = min_l_real_qcI = NULL; max_l_real_qcH = min_l_real_qcH = NULL; max_l_real = min_l_real = NULL; update_c = update_cH = update_cI = update_cM = 0; min_k = min_l = 0; max_k = mm1[my_iindx[1] - seq_length] + referenceBPs1[my_iindx[1] - seq_length]; max_l = mm2[my_iindx[1] - seq_length] + referenceBPs2[my_iindx[1] - seq_length]; #ifdef _OPENMP #pragma omp sections { #pragma omp section { #endif if (!matrices->Q_c) { update_c = 1; prepareBoundaries(min_k, max_k, min_l, max_l, bpdist[my_iindx[1] - seq_length], &matrices->k_min_Q_c, &matrices->k_max_Q_c, &matrices->l_min_Q_c, &matrices->l_max_Q_c ); prepareArray(&matrices->Q_c, matrices->k_min_Q_c, matrices->k_max_Q_c, matrices->l_min_Q_c, matrices->l_max_Q_c ); preparePosteriorBoundaries(max_k - min_k + 1, min_k, &min_k_real, &max_k_real, &min_l_real, &max_l_real ); } #ifdef _OPENMP } #pragma omp section { #endif if (!matrices->Q_cH) { update_cH = 1; prepareBoundaries(min_k, max_k, min_l, max_l, bpdist[my_iindx[1] - seq_length], &matrices->k_min_Q_cH, &matrices->k_max_Q_cH, &matrices->l_min_Q_cH, &matrices->l_max_Q_cH ); prepareArray(&matrices->Q_cH, matrices->k_min_Q_cH, matrices->k_max_Q_cH, matrices->l_min_Q_cH, matrices->l_max_Q_cH ); preparePosteriorBoundaries(max_k - min_k + 1, min_k, &min_k_real_qcH, &max_k_real_qcH, &min_l_real_qcH, &max_l_real_qcH ); } #ifdef _OPENMP } #pragma omp section { #endif if (!matrices->Q_cI) { update_cI = 1; prepareBoundaries(min_k, max_k, min_l, max_l, bpdist[my_iindx[1] - seq_length], &matrices->k_min_Q_cI, &matrices->k_max_Q_cI, &matrices->l_min_Q_cI, &matrices->l_max_Q_cI ); prepareArray(&matrices->Q_cI, matrices->k_min_Q_cI, matrices->k_max_Q_cI, matrices->l_min_Q_cI, matrices->l_max_Q_cI ); preparePosteriorBoundaries(max_k - min_k + 1, min_k, &min_k_real_qcI, &max_k_real_qcI, &min_l_real_qcI, &max_l_real_qcI ); } #ifdef _OPENMP } #pragma omp section { #endif if (!matrices->Q_cM) { update_cM = 1; prepareBoundaries(min_k, max_k, min_l, max_l, bpdist[my_iindx[1] - seq_length], &matrices->k_min_Q_cM, &matrices->k_max_Q_cM, &matrices->l_min_Q_cM, &matrices->l_max_Q_cM ); prepareArray(&matrices->Q_cM, matrices->k_min_Q_cM, matrices->k_max_Q_cM, matrices->l_min_Q_cM, matrices->l_max_Q_cM ); preparePosteriorBoundaries(max_k - min_k + 1, min_k, &min_k_real_qcM, &max_k_real_qcM, &min_l_real_qcM, &max_l_real_qcM ); } #ifdef _OPENMP } } #endif for (d = turn + 2; d <= seq_length; d++) /* i,j in [1..length] */ #ifdef _OPENMP #pragma omp parallel for private(p, q, pq, k, l, kl, u, da, db, type, cnt1, cnt2, cnt3, cnt4) #endif for (q = d; q <= seq_length; q++) { FLT_OR_DBL qot; char loopseq[10]; p = q - d + 1; pq = my_iindx[p] - q; /* 1. get exterior hairpin contribution */ u = seq_length - q + p - 1; if (u < turn) continue; type = ptype[jindx[q] + p]; if (!type) continue; if (((type == 3) || (type == 4)) && no_closingGU) continue; /* cause we want to calc the exterior loops, we need the reversed pair type from now on */ type = rtype[type]; if (u < 7) { strcpy(loopseq, sequence + q - 1); strncat(loopseq, sequence, p); } /* get distance to reference if closing the hairpin * da = dbp(T1_[1,n}, T1_{p,q}) * db = dbp(T2_{1,n}, T2_{p,q}) */ da = base_d1 - referenceBPs1[pq]; db = base_d2 - referenceBPs2[pq]; qot = exp_E_Hairpin(u, type, S1[q + 1], S1[p - 1], loopseq, pf_params) * scale[u]; if (Q_B_rem[pq]) matrices->Q_cH_rem += Q_B_rem[pq] * qot; if (Q_B[pq]) { for (cnt1 = k_min_Q_B[pq]; cnt1 <= k_max_Q_B[pq]; cnt1++) for (cnt2 = l_min_Q_B[pq][cnt1]; cnt2 <= l_max_Q_B[pq][cnt1]; cnt2 += 2) { if (((cnt1 + da) <= maxD1) && ((cnt2 + db) <= maxD2)) { matrices->Q_cH[cnt1 + da][(cnt2 + db) / 2] += Q_B[pq][cnt1][cnt2 / 2] * qot; if (update_cH) { updatePosteriorBoundaries(cnt1 + da, cnt2 + db, &min_k_real_qcH, &max_k_real_qcH, &min_l_real_qcH, &max_l_real_qcH ); } } else { matrices->Q_cH_rem += Q_B[pq][cnt1][cnt2 / 2] * qot; } } } /* * 2. exterior interior loops, i "define" the (k,l) pair as "outer pair" * so "outer type" is rtype[type[k,l]] and inner type is type[p,q] */ if (Q_B_rem[pq]) { for (k = q + 1; k < seq_length; k++) { unsigned int ln1, lstart, ln_pre; ln1 = k - q - 1; if (ln1 + p - 1 > MAXLOOP) break; lstart = k + turn + 1; ln_pre = ln1 + p + seq_length; if (ln_pre > lstart + MAXLOOP) lstart = ln_pre - MAXLOOP - 1; for (l = lstart; l <= seq_length; l++) { unsigned int ln2; int type2; kl = my_iindx[k] - l; ln2 = (p - 1) + (seq_length - l); if ((ln1 + ln2) > MAXLOOP) continue; type2 = ptype[jindx[l] + k]; if (!type2) continue; qot = exp_E_IntLoop(ln2, ln1, rtype[type2], type, S1[l + 1], S1[k - 1], S1[p - 1], S1[q + 1], pf_params) * scale[ln1 + ln2]; if (Q_B_rem[kl]) matrices->Q_cI_rem += Q_B_rem[pq] * Q_B_rem[kl] * qot; if (Q_B[kl]) { for (cnt1 = k_min_Q_B[kl]; cnt1 <= k_max_Q_B[kl]; cnt1++) for (cnt2 = l_min_Q_B[kl][cnt1]; cnt2 <= l_max_Q_B[kl][cnt1]; cnt2 += 2) matrices->Q_cI_rem += Q_B_rem[pq] * Q_B[kl][cnt1][cnt2 / 2] * qot; } } } } if (Q_B[pq]) { for (k = q + 1; k < seq_length; k++) { unsigned int ln1, lstart, ln_pre; ln1 = k - q - 1; if (ln1 + p - 1 > MAXLOOP) break; lstart = k + turn + 1; ln_pre = ln1 + p + seq_length; if (ln_pre > lstart + MAXLOOP) lstart = ln_pre - MAXLOOP - 1; for (l = lstart; l <= seq_length; l++) { unsigned int ln2; int type2; kl = my_iindx[k] - l; ln2 = (p - 1) + (seq_length - l); if ((ln1 + ln2) > MAXLOOP) continue; type2 = ptype[jindx[l] + k]; if (!type2) continue; qot = exp_E_IntLoop(ln2, ln1, rtype[type2], type, S1[l + 1], S1[k - 1], S1[p - 1], S1[q + 1], pf_params) * scale[ln1 + ln2]; if (Q_B_rem[kl]) { for (cnt1 = k_min_Q_B[pq]; cnt1 <= k_max_Q_B[pq]; cnt1++) for (cnt2 = l_min_Q_B[pq][cnt1]; cnt2 <= l_max_Q_B[pq][cnt1]; cnt2 += 2) matrices->Q_cI_rem += Q_B[pq][cnt1][cnt2 / 2] * Q_B_rem[kl] * qot; } if (!Q_B[kl]) continue; /* get distance to reference if closing the interior loop * d2a = dbp(T1_[1,n}, T1_{p,q} + T1_{k,l}) * d2b = dbp(T2_[1,n}, T2_{p,q} + T2_{k,l}) */ da = base_d1 - referenceBPs1[pq] - referenceBPs1[kl]; db = base_d2 - referenceBPs2[pq] - referenceBPs2[kl]; for (cnt1 = k_min_Q_B[pq]; cnt1 <= k_max_Q_B[pq]; cnt1++) for (cnt2 = l_min_Q_B[pq][cnt1]; cnt2 <= l_max_Q_B[pq][cnt1]; cnt2 += 2) for (cnt3 = k_min_Q_B[kl]; cnt3 <= k_max_Q_B[kl]; cnt3++) for (cnt4 = l_min_Q_B[kl][cnt3]; cnt4 <= l_max_Q_B[kl][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) <= maxD1) && ((cnt2 + cnt4 + db) <= maxD2)) { matrices->Q_cI[cnt1 + cnt3 + da][(cnt2 + cnt4 + db) / 2] += Q_B[pq][cnt1][cnt2 / 2] * Q_B[kl][cnt3][cnt4 / 2] * qot; if (update_cI) { updatePosteriorBoundaries(cnt1 + cnt3 + da, cnt2 + cnt4 + db, &min_k_real_qcI, &max_k_real_qcI, &min_l_real_qcI, &max_l_real_qcI ); } } else { matrices->Q_cI_rem += Q_B[pq][cnt1][cnt2 / 2] * Q_B[kl][cnt3][cnt4 / 2] * qot; } } } } } } if (update_cH) { adjustArrayBoundaries(&matrices->Q_cH, &matrices->k_min_Q_cH, &matrices->k_max_Q_cH, &matrices->l_min_Q_cH, &matrices->l_max_Q_cH, min_k_real_qcH, max_k_real_qcH, min_l_real_qcH, max_l_real_qcH ); } if (update_cI) { adjustArrayBoundaries(&matrices->Q_cI, &matrices->k_min_Q_cI, &matrices->k_max_Q_cI, &matrices->l_min_Q_cI, &matrices->l_max_Q_cI, min_k_real_qcI, max_k_real_qcI, min_l_real_qcI, max_l_real_qcI ); } /* 3. Multiloops */ if (seq_length > 2 * turn - 3) { #ifdef _OPENMP #pragma omp parallel for private(k, da, db, cnt1, cnt2, cnt3, cnt4) #endif for (k = turn + 2; k < seq_length - 2 * turn - 3; k++) { if (Q_M_rem[my_iindx[1] - k]) { if (matrices->Q_M2[k + 1]) { for (cnt1 = matrices->k_min_Q_M2[k + 1]; cnt1 <= matrices->k_max_Q_M2[k + 1]; cnt1++) for (cnt2 = matrices->l_min_Q_M2[k + 1][cnt1]; cnt2 <= matrices->l_max_Q_M2[k + 1][cnt1]; cnt2 += 2) matrices->Q_cM_rem += Q_M_rem[my_iindx[1] - k] * matrices->Q_M2[k + 1][cnt1][cnt2 / 2] * pf_params->expMLclosing; } if (matrices->Q_M2_rem[k + 1]) matrices->Q_cM_rem += Q_M_rem[my_iindx[1] - k] * matrices->Q_M2_rem[k + 1] * pf_params->expMLclosing; } if (matrices->Q_M2_rem[k + 1]) { if (Q_M[my_iindx[1] - k]) { for (cnt1 = k_min_Q_M[my_iindx[1] - k]; cnt1 <= k_max_Q_M[my_iindx[1] - k]; cnt1++) for (cnt2 = l_min_Q_M[my_iindx[1] - k][cnt1]; cnt2 <= l_max_Q_M[my_iindx[1] - k][cnt1]; cnt2 += 2) matrices->Q_cM_rem += Q_M[my_iindx[1] - k][cnt1][cnt2 / 2] * matrices->Q_M2_rem[k + 1] * pf_params->expMLclosing; } } /* get distancies to references * d3a = dbp(T1_[1,n}, T1_{1,k} + T1_{k+1, n}) * d3b = dbp(T2_[1,n}, T2_{1,k} + T2_{k+1, n}) */ da = base_d1 - referenceBPs1[my_iindx[1] - k] - referenceBPs1[my_iindx[k + 1] - seq_length]; db = base_d2 - referenceBPs2[my_iindx[1] - k] - referenceBPs2[my_iindx[k + 1] - seq_length]; if (Q_M[my_iindx[1] - k] && matrices->Q_M2[k + 1]) { for (cnt1 = k_min_Q_M[my_iindx[1] - k]; cnt1 <= k_max_Q_M[my_iindx[1] - k]; cnt1++) for (cnt2 = l_min_Q_M[my_iindx[1] - k][cnt1]; cnt2 <= l_max_Q_M[my_iindx[1] - k][cnt1]; cnt2 += 2) for (cnt3 = matrices->k_min_Q_M2[k + 1]; cnt3 <= matrices->k_max_Q_M2[k + 1]; cnt3++) for (cnt4 = matrices->l_min_Q_M2[k + 1][cnt3]; cnt4 <= matrices->l_max_Q_M2[k + 1][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) <= maxD1) && ((cnt2 + cnt4 + db) <= maxD2)) { matrices->Q_cM[cnt1 + cnt3 + da][(cnt2 + cnt4 + db) / 2] += Q_M[my_iindx[1] - k][cnt1][cnt2 / 2] * matrices->Q_M2[k + 1][cnt3][cnt4 / 2] * pf_params->expMLclosing; if (update_cM) { updatePosteriorBoundaries(cnt1 + cnt3 + da, cnt2 + cnt4 + db, &min_k_real_qcM, &max_k_real_qcM, &min_l_real_qcM, &max_l_real_qcM ); } } else { matrices->Q_cM_rem += Q_M[my_iindx[1] - k][cnt1][cnt2 / 2] * matrices->Q_M2[k + 1][cnt3][cnt4 / 2] * pf_params->expMLclosing; } } } } } if (update_cM) { adjustArrayBoundaries(&matrices->Q_cM, &matrices->k_min_Q_cM, &matrices->k_max_Q_cM, &matrices->l_min_Q_cM, &matrices->l_max_Q_cM, min_k_real_qcM, max_k_real_qcM, min_l_real_qcM, max_l_real_qcM ); } for (cnt1 = matrices->k_min_Q_cH; cnt1 <= matrices->k_max_Q_cH; cnt1++) for (cnt2 = matrices->l_min_Q_cH[cnt1]; cnt2 <= matrices->l_max_Q_cH[cnt1]; cnt2 += 2) { matrices->Q_c[cnt1][cnt2 / 2] += matrices->Q_cH[cnt1][cnt2 / 2]; if (update_c) { updatePosteriorBoundaries(cnt1, cnt2, &min_k_real, &max_k_real, &min_l_real, &max_l_real ); } } for (cnt1 = matrices->k_min_Q_cI; cnt1 <= matrices->k_max_Q_cI; cnt1++) for (cnt2 = matrices->l_min_Q_cI[cnt1]; cnt2 <= matrices->l_max_Q_cI[cnt1]; cnt2 += 2) { matrices->Q_c[cnt1][cnt2 / 2] += matrices->Q_cI[cnt1][cnt2 / 2]; if (update_c) { updatePosteriorBoundaries(cnt1, cnt2, &min_k_real, &max_k_real, &min_l_real, &max_l_real ); } } for (cnt1 = matrices->k_min_Q_cM; cnt1 <= matrices->k_max_Q_cM; cnt1++) for (cnt2 = matrices->l_min_Q_cM[cnt1]; cnt2 <= matrices->l_max_Q_cM[cnt1]; cnt2 += 2) { matrices->Q_c[cnt1][cnt2 / 2] += matrices->Q_cM[cnt1][cnt2 / 2]; if (update_c) { updatePosteriorBoundaries(cnt1, cnt2, &min_k_real, &max_k_real, &min_l_real, &max_l_real ); } } matrices->Q_c_rem = matrices->Q_cH_rem + matrices->Q_cI_rem + matrices->Q_cM_rem; /* add the case were structure is unfolded chain */ if ((referenceBPs1[my_iindx[1] - seq_length] <= maxD1) && (referenceBPs2[my_iindx[1] - seq_length] <= maxD2)) { matrices->Q_c[referenceBPs1[my_iindx[1] - seq_length]][referenceBPs2[my_iindx[1] - seq_length] / 2] += 1.0 * scale[seq_length]; if (update_c) { updatePosteriorBoundaries(referenceBPs1[my_iindx[1] - seq_length], referenceBPs2[my_iindx[1] - seq_length], &min_k_real, &max_k_real, &min_l_real, &max_l_real ); } } else { matrices->Q_c_rem += 1.0 * scale[seq_length]; } adjustArrayBoundaries(&matrices->Q_c, &matrices->k_min_Q_c, &matrices->k_max_Q_c, &matrices->l_min_Q_c, &matrices->l_max_Q_c, min_k_real, max_k_real, min_l_real, max_l_real ); } /* * ################################################### * stochastic backtracking * ################################################### */ PUBLIC char * vrna_pbacktrack_TwoD(vrna_fold_compound_t *vc, int d1, int d2) { return vrna_pbacktrack5_TwoD(vc, d1, d2, vc->length); } PUBLIC char * vrna_pbacktrack5_TwoD(vrna_fold_compound_t *vc, int d1, int d2, unsigned int length) { char *pstruc, *ptype; short *S1; unsigned int i, j, n, start, maxD1, maxD2, da, db, *referenceBPs1, *referenceBPs2; int *my_iindx, *jindx, ij, cnt1, cnt2, cnt3, cnt4, type, **l_min_Q, **l_max_Q, **l_min_Q_B, **l_max_Q_B, *k_min_Q, *k_max_Q, *k_min_Q_B, *k_max_Q_B, turn; FLT_OR_DBL r, qt, *scale, ***Q, ***Q_B, *Q_rem, *Q_B_rem; vrna_exp_param_t *pf_params; vrna_md_t *md; vrna_mx_pf_t *matrices; n = vc->length; pf_params = vc->exp_params; md = &(pf_params->model_details); matrices = vc->exp_matrices; maxD1 = vc->maxD1; maxD2 = vc->maxD2; my_iindx = vc->iindx; jindx = vc->jindx; scale = matrices->scale; ptype = vc->ptype; S1 = vc->sequence_encoding; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; turn = pf_params->model_details.min_loop_size; Q = matrices->Q; l_min_Q = matrices->l_min_Q; l_max_Q = matrices->l_max_Q; k_min_Q = matrices->k_min_Q; k_max_Q = matrices->k_max_Q; Q_B = matrices->Q_B; l_min_Q_B = matrices->l_min_Q_B; l_max_Q_B = matrices->l_max_Q_B; k_min_Q_B = matrices->k_min_Q_B; k_max_Q_B = matrices->k_max_Q_B; Q_rem = matrices->Q_rem; Q_B_rem = matrices->Q_B_rem; cnt1 = cnt2 = cnt3 = cnt4 = -1; if (md->circ) { if (n != length) vrna_message_error( "vrna_pbacktrack_TwoD@2Dfold.c: cotranscriptional backtracking for circular RNAs not supported!"); return pbacktrack_circ(vc, d1, d2); } if (length > n) vrna_message_error( "vrna_pbacktrack_TwoD@2Dpfold.c: requested transcript length exceeds sequence length!"); #if 0 if (d1 > maxD1) vrna_message_error("pbacktrack@2Dpfold.c: distance to 1st reference structure to high!"); if (d2 > maxD2) vrna_message_error("pbacktrack@2Dpfold.c: distance to 2nd reference structure to high!"); #endif /* check whether the chosen neighborhood exists at all */ int dumb = 1; ij = my_iindx[1] - length; if ((d1 == -1) && (Q_rem[ij] != 0.)) { dumb = 0; } else { if ((k_min_Q[ij] <= d1) && (k_max_Q[ij] >= d1)) { int l_min = l_min_Q[ij][d1]; if ((d2 % 2) == (l_min % 2)) if ((l_min <= d2) && (l_max_Q[ij][d1] >= d2)) dumb = 0; } } if (dumb) { vrna_message_error("neighborhood %d:%d is not in scope of calculated partition function!\n" "pbacktrack@2Dpfold.c: exiting...", d1, d2); } pstruc = vrna_alloc((length + 1) * sizeof(char)); for (i = 0; i < length; i++) pstruc[i] = '.'; pstruc[i] = '\0'; start = 1; while (start < length) { int sn = my_iindx[start] - length; /* find i position of first pair */ FLT_OR_DBL qln_i = 0, qln_i1 = 0; if (d1 == -1) { qln_i = Q_rem[sn]; /* open chain ? */ if ((maxD1 > referenceBPs1[sn]) && (maxD2 > referenceBPs2[sn])) { r = vrna_urn() * qln_i; if (scale[length - start + 1] > r) return pstruc; } /* lets see if we find a base pair with i involved */ for (i = start; i < length; i++) { r = vrna_urn() * qln_i; qln_i1 = Q_rem[my_iindx[i + 1] - length]; da = referenceBPs1[sn] - referenceBPs1[my_iindx[i + 1] - length]; db = referenceBPs2[sn] - referenceBPs2[my_iindx[i + 1] - length]; for (cnt1 = k_min_Q[my_iindx[i + 1] - length]; cnt1 <= k_max_Q[my_iindx[i + 1] - length]; cnt1++) for (cnt2 = l_min_Q[my_iindx[i + 1] - length][cnt1]; cnt2 <= l_max_Q[my_iindx[i + 1] - length][cnt1]; cnt2 += 2) if (((cnt1 + da) > maxD1) || ((cnt2 + db) > maxD2)) qln_i1 += Q[my_iindx[i + 1] - length][cnt1][cnt2 / 2]; if (r > qln_i1 * scale[1]) break; qln_i = qln_i1; } if (i >= length) break; /* no more pairs */ /* i is paired, find pairing partner j */ r = vrna_urn() * (qln_i - qln_i1 * scale[1]); for (qt = 0, j = i + turn + 1; j < length; j++) { ij = my_iindx[i] - j; type = ptype[jindx[j] + i]; if (type) { cnt1 = cnt2 = cnt3 = cnt4 = -1; double qkl = vrna_exp_E_ext_stem(type, (i > 1) ? S1[i - 1] : -1, S1[j + 1], pf_params); if (Q_B_rem[ij] != 0.) { if (Q_rem[my_iindx[j + 1] - length] != 0.) { qt += qkl * Q_B_rem[ij] * Q_rem[my_iindx[j + 1] - length]; if (qt >= r) goto pbacktrack_ext_loop_early_escape_rem; } if (Q[my_iindx[j + 1] - length]) { for (cnt3 = k_min_Q[my_iindx[j + 1] - length]; cnt3 <= k_max_Q[my_iindx[j + 1] - length]; cnt3++) for (cnt4 = l_min_Q[my_iindx[j + 1] - length][cnt3]; cnt4 <= l_max_Q[my_iindx[j + 1] - length][cnt3]; cnt4 += 2) { qt += qkl * Q_B_rem[ij] * Q[my_iindx[j + 1] - length][cnt3][cnt4 / 2]; if (qt >= r) goto pbacktrack_ext_loop_early_escape_rem; } } } if (Q_rem[my_iindx[j + 1] - length] != 0.) { cnt3 = cnt4 = -1; if (Q_B[ij]) { for (cnt1 = k_min_Q_B[ij]; cnt1 <= k_max_Q_B[ij]; cnt1++) for (cnt2 = l_min_Q_B[ij][cnt1]; cnt2 <= l_max_Q_B[ij][cnt1]; cnt2 += 2) { qt += qkl * Q_B[ij][cnt1][cnt2 / 2] * Q_rem[my_iindx[j + 1] - length]; if (qt >= r) goto pbacktrack_ext_loop_early_escape_rem; } } } /* if we still search for pairing partner j, we go on here... */ if (Q_B[ij] && Q[my_iindx[j + 1] - length]) { da = referenceBPs1[sn] - referenceBPs1[ij] - referenceBPs1[my_iindx[j + 1] - length]; db = referenceBPs2[sn] - referenceBPs2[ij] - referenceBPs2[my_iindx[j + 1] - length]; for (cnt1 = k_min_Q_B[ij]; cnt1 <= k_max_Q_B[ij]; cnt1++) for (cnt2 = l_min_Q_B[ij][cnt1]; cnt2 <= l_max_Q_B[ij][cnt1]; cnt2 += 2) for (cnt3 = k_min_Q[my_iindx[j + 1] - length]; cnt3 <= k_max_Q[my_iindx[j + 1] - length]; cnt3++) for (cnt4 = l_min_Q[my_iindx[j + 1] - length][cnt3]; cnt4 <= l_max_Q[my_iindx[j + 1] - length][cnt3]; cnt4 += 2) if (((cnt1 + cnt3 + da) > maxD1) || ((cnt2 + cnt4 + db) > maxD2)) { qt += qkl * Q_B[ij][cnt1][cnt2 / 2] * Q[my_iindx[j + 1] - length][cnt3][cnt4 / 2]; if (qt >= r) goto pbacktrack_ext_loop_early_escape_rem; } } } /* end if(type) */ } /* end for(j) */ cnt1 = cnt2 = cnt3 = cnt4 = -1; /* dont forget the case where i pairs with n */ j = length; ij = my_iindx[i] - j; type = ptype[jindx[j] + i]; if (type) { double qkl = vrna_exp_E_ext_stem(type, (i > 1) ? S1[i - 1] : -1, (j < n) ? S1[j + 1] : -1, pf_params); if (Q_B_rem[ij] != 0.) { qt += qkl * Q_B_rem[ij]; if (qt >= r) goto pbacktrack_ext_loop_early_escape_rem; } /* if we still search for pairing partner j, we go on here... */ if (Q_B[ij]) { da = referenceBPs1[sn] - referenceBPs1[ij]; db = referenceBPs2[sn] - referenceBPs2[ij]; for (cnt1 = k_min_Q_B[ij]; cnt1 <= k_max_Q_B[ij]; cnt1++) for (cnt2 = l_min_Q_B[ij][cnt1]; cnt2 <= l_max_Q_B[ij][cnt1]; cnt2 += 2) if (((cnt1 + da) > maxD1) || ((cnt2 + db) > maxD2)) { qt += qkl * Q_B[ij][cnt1][cnt2 / 2]; if (qt >= r) goto pbacktrack_ext_loop_early_escape_rem; } } } /* end if(type) */ j++; pbacktrack_ext_loop_early_escape_rem: if (j == length + 1) vrna_message_error("pbacktrack@2Dpfold.c: backtracking failed in ext loop (rem)"); /* finally start backtracking the first exterior stem */ backtrack(vc, pstruc, cnt1, cnt2, i, j); if (j == length) break; start = j + 1; d1 = cnt3; d2 = cnt4; } /* end if d1 ==-1 */ else { qln_i = Q[sn][d1][d2 / 2]; /* open chain ? */ if ((d1 == referenceBPs1[sn]) && (d2 == referenceBPs2[sn])) { r = vrna_urn() * qln_i; if (scale[length - start + 1] > r) return pstruc; } for (i = start; i < length; i++) { r = vrna_urn() * qln_i; da = referenceBPs1[sn] - referenceBPs1[my_iindx[i + 1] - length]; db = referenceBPs2[sn] - referenceBPs2[my_iindx[i + 1] - length]; qln_i1 = 0; if (d1 >= da && d2 >= db) { if ( (d1 - da >= k_min_Q[my_iindx[i + 1] - length]) && (d1 - da <= k_max_Q[my_iindx[i + 1] - length])) { if ( (d2 - db >= l_min_Q[my_iindx[i + 1] - length][d1 - da]) && (d2 - db <= l_max_Q[my_iindx[i + 1] - length][d1 - da])) qln_i1 += Q[my_iindx[i + 1] - length][d1 - da][(d2 - db) / 2]; } } if (r > qln_i1 * scale[1]) break; /* i is paired */ qln_i = qln_i1; } if (i >= length) break; /* no more pairs */ /* now find the pairing partner j */ r = vrna_urn() * (qln_i - qln_i1 * scale[1]); for (qt = 0, j = i + 1; j < length; j++) { int type; ij = my_iindx[i] - j; type = ptype[jindx[j] + i]; if (type) { double qkl = 1.0; qkl *= vrna_exp_E_ext_stem(type, (i > 1) ? S1[i - 1] : -1, S1[j + 1], pf_params); da = referenceBPs1[sn] - referenceBPs1[ij] - referenceBPs1[my_iindx[j + 1] - length]; db = referenceBPs2[sn] - referenceBPs2[ij] - referenceBPs2[my_iindx[j + 1] - length]; if ((d1 >= da) && (d2 >= db) && Q_B[ij] && Q[my_iindx[j + 1] - length]) { for (cnt1 = k_min_Q_B[ij]; cnt1 <= MIN2(k_max_Q_B[ij], d1 - da); cnt1++) for (cnt2 = l_min_Q_B[ij][cnt1]; cnt2 <= MIN2(l_max_Q_B[ij][cnt1], d2 - db); cnt2 += 2) if ((d1 - da - cnt1 >= k_min_Q[my_iindx[j + 1] - length]) && (d1 - da - cnt1 <= k_max_Q[my_iindx[j + 1] - length])) { if ((d2 - db - cnt2 >= l_min_Q[my_iindx[j + 1] - length][d1 - da - cnt1]) && (d2 - db - cnt2 <= l_max_Q[my_iindx[j + 1] - length][d1 - da - cnt1])) { qt += qkl * Q_B[ij][cnt1][cnt2 / 2] * Q[my_iindx[j + 1] - length][d1 - da - cnt1][(d2 - db - cnt2) / 2]; if (qt >= r) goto pbacktrack_ext_loop_early_escape; } } } } } /* now dont forget the case j==n */ j = length; ij = my_iindx[i] - j; int type = ptype[jindx[j] + i]; if (type) { double qkl = 1.0; qkl *= vrna_exp_E_ext_stem(type, (i > 1) ? S1[i - 1] : -1, (j < n) ? S1[j + 1] : -1, pf_params); da = referenceBPs1[sn] - referenceBPs1[ij]; db = referenceBPs2[sn] - referenceBPs2[ij]; if (d1 >= da && d2 >= db) { cnt1 = d1 - da; cnt2 = d2 - db; if ((cnt1 >= k_min_Q_B[ij]) && (cnt1 <= k_max_Q_B[ij])) { if ((cnt2 >= l_min_Q_B[ij][cnt1]) && (cnt2 <= l_max_Q_B[ij][cnt1])) { qt += qkl * Q_B[ij][cnt1][cnt2 / 2]; if (qt >= r) goto pbacktrack_ext_loop_early_escape; /* j is paired */ } } } } j++; pbacktrack_ext_loop_early_escape: if (j == length + 1) vrna_message_error("pbacktrack@2Dpfold.c: backtracking failed in ext loop"); backtrack(vc, pstruc, cnt1, cnt2, i, j); if (j == length) break; start = j + 1; d1 -= cnt1 + da; d2 -= cnt2 + db; } /* end if d1!=-1 */ } return pstruc; } PRIVATE char * pbacktrack_circ(vrna_fold_compound_t *vc, int d1, int d2) { char *pstruc; unsigned int i, n, maxD1, maxD2, *referenceBPs1, *referenceBPs2; int *my_iindx, k_min_Q_c, k_max_Q_c, k_min_Q_cH, k_max_Q_cH, k_min_Q_cI, k_max_Q_cI, k_min_Q_cM, k_max_Q_cM, *l_min_Q_c, *l_max_Q_c, *l_min_Q_cH, *l_max_Q_cH, *l_min_Q_cI, *l_max_Q_cI, *l_min_Q_cM, *l_max_Q_cM; FLT_OR_DBL r, *scale, qot, **Q_c, **Q_cH, **Q_cI, **Q_cM, Q_c_rem, Q_cH_rem, Q_cI_rem, Q_cM_rem; vrna_mx_pf_t *matrices; matrices = vc->exp_matrices; n = vc->length; maxD1 = vc->maxD1; maxD2 = vc->maxD2; my_iindx = vc->iindx; scale = matrices->scale; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; Q_c = matrices->Q_c; l_min_Q_c = matrices->l_min_Q_c; l_max_Q_c = matrices->l_max_Q_c; k_min_Q_c = matrices->k_min_Q_c; k_max_Q_c = matrices->k_max_Q_c; Q_cH = matrices->Q_cH; l_min_Q_cH = matrices->l_min_Q_cH; l_max_Q_cH = matrices->l_max_Q_cH; k_min_Q_cH = matrices->k_min_Q_cH; k_max_Q_cH = matrices->k_max_Q_cH; Q_cI = matrices->Q_cI; l_min_Q_cI = matrices->l_min_Q_cI; l_max_Q_cI = matrices->l_max_Q_cI; k_min_Q_cI = matrices->k_min_Q_cI; k_max_Q_cI = matrices->k_max_Q_cI; Q_cM = matrices->Q_cM; l_min_Q_cM = matrices->l_min_Q_cM; l_max_Q_cM = matrices->l_max_Q_cM; k_min_Q_cM = matrices->k_min_Q_cM; k_max_Q_cM = matrices->k_max_Q_cM; Q_c_rem = matrices->Q_c_rem; Q_cH_rem = matrices->Q_cH_rem; Q_cI_rem = matrices->Q_cI_rem; Q_cM_rem = matrices->Q_cM_rem; /* check whether the chosen neighborhood exists at all */ int dumb = 1; if ((d1 == -1) && (Q_c_rem != 0.)) { dumb = 0; } else { if ((k_min_Q_c <= d1) && (k_max_Q_c >= d1)) { int l_min = l_min_Q_c[d1]; if ((d2 % 2) == (l_min % 2)) if ((l_min <= d2) && (l_max_Q_c[d1] >= d2)) dumb = 0; } } if (dumb) { vrna_message_error("neighborhood %d:%d is not in scope of calculated partition function!\n" "pbacktrack_circ@2Dpfold.c: exiting cheerless...", d1, d2); } pstruc = vrna_alloc((n + 1) * sizeof(char)); for (i = 0; i < n; i++) pstruc[i] = '.'; pstruc[i] = '\0'; /* now we come to the actual backtracking process */ qot = 0.; /* backtrack in rest-partition */ if (d1 == -1) { r = vrna_urn() * Q_c_rem; /* open chain ? */ if ((referenceBPs1[my_iindx[1] - n] > maxD1) || (referenceBPs2[my_iindx[1] - n] > maxD2)) { qot = 1.0 * scale[n]; if (qot >= r) goto pbacktrack_circ_escape; } qot += Q_cH_rem; if (qot >= r) { backtrack_qcH(vc, pstruc, d1, d2); goto pbacktrack_circ_escape; } qot += Q_cI_rem; if (qot >= r) { backtrack_qcI(vc, pstruc, d1, d2); goto pbacktrack_circ_escape; } qot += Q_cM_rem; if (qot >= r) { backtrack_qcM(vc, pstruc, d1, d2); goto pbacktrack_circ_escape; } vrna_message_error( "pbacktrack_circ@2Dpfold.c: backtracking failed in exterior loop! Exiting cheerless..."); } /* normal backtracking */ else { r = vrna_urn() * Q_c[d1][d2 / 2]; /* open chain ? */ if ((referenceBPs1[my_iindx[1] - n] == d1) && (referenceBPs2[my_iindx[1] - n] == d2)) { qot += 1.0 * scale[n]; if (qot >= r) goto pbacktrack_circ_escape; } /* exterior hairpin loop ? */ if ((k_min_Q_cH <= d1) && (k_max_Q_cH >= d1)) { int l_min = l_min_Q_cH[d1]; if ((d2 % 2) == (l_min % 2)) { if ((l_min <= d2) && (l_max_Q_cH[d1] >= d2)) { qot += Q_cH[d1][d2 / 2]; if (qot >= r) { backtrack_qcH(vc, pstruc, d1, d2); goto pbacktrack_circ_escape; } } } } /* exterior interior loop ? */ if ((k_min_Q_cI <= d1) && (k_max_Q_cI >= d1)) { int l_min = l_min_Q_cI[d1]; if ((d2 % 2) == (l_min % 2)) { if ((l_min <= d2) && (l_max_Q_cI[d1] >= d2)) { qot += Q_cI[d1][d2 / 2]; if (qot >= r) { backtrack_qcI(vc, pstruc, d1, d2); goto pbacktrack_circ_escape; } } } } /* exterior multibranch loop ? */ if ((k_min_Q_cM <= d1) && (k_max_Q_cM >= d1)) { int l_min = l_min_Q_cM[d1]; if ((d2 % 2) == (l_min % 2)) { if ((l_min <= d2) && (l_max_Q_cM[d1] >= d2)) { qot += Q_cM[d1][d2 / 2]; if (qot >= r) { backtrack_qcM(vc, pstruc, d1, d2); goto pbacktrack_circ_escape; } } } } } pbacktrack_circ_escape: return pstruc; } PRIVATE void backtrack_qcH(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2) { char *ptype, *sequence; short *S1; unsigned int i, j, n, maxD1, maxD2, base_d1, base_d2, da, db, *referenceBPs1, *referenceBPs2; int u, *my_iindx, *jindx, ij, cnt1, cnt2, type, **l_min_Q_B, **l_max_Q_B, *k_min_Q_B, *k_max_Q_B, *rtype, turn; FLT_OR_DBL r, qt, *scale, qot, ***Q_B, **Q_cH, *Q_B_rem, Q_cH_rem; vrna_exp_param_t *pf_params; vrna_md_t *md; vrna_mx_pf_t *matrices; pf_params = vc->exp_params; md = &(pf_params->model_details); matrices = vc->exp_matrices; sequence = vc->sequence; n = vc->length; my_iindx = vc->iindx; jindx = vc->jindx; scale = matrices->scale; ptype = vc->ptype; rtype = &(md->rtype[0]); S1 = vc->sequence_encoding; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; maxD1 = vc->maxD1; maxD2 = vc->maxD2; turn = md->min_loop_size; Q_B_rem = matrices->Q_B_rem; Q_B = matrices->Q_B; l_min_Q_B = matrices->l_min_Q_B; l_max_Q_B = matrices->l_max_Q_B; k_min_Q_B = matrices->k_min_Q_B; k_max_Q_B = matrices->k_max_Q_B; Q_cH_rem = matrices->Q_cH_rem; Q_cH = matrices->Q_cH; qot = qt = 0.; base_d1 = referenceBPs1[my_iindx[1] - n]; base_d2 = referenceBPs2[my_iindx[1] - n]; if (d1 == -1) { r = vrna_urn() * Q_cH_rem; for (i = 1; i < n; i++) for (j = i + turn + 1; j <= n; j++) { char loopseq[10]; ij = my_iindx[i] - j; u = n - j + i - 1; if (u < turn) continue; type = ptype[jindx[j] + i]; if (!type) continue; if (((type == 3) || (type == 4)) && no_closingGU) continue; type = rtype[type]; if (u < 7) { strcpy(loopseq, sequence + j - 1); strncat(loopseq, sequence, i); } qt = exp_E_Hairpin(u, type, S1[j + 1], S1[i - 1], loopseq, pf_params) * scale[u]; if (Q_B_rem[ij]) { qot += Q_B_rem[ij] * qt; if (qot >= r) { backtrack(vc, pstruc, d1, d2, i, j); return; } } da = base_d1 - referenceBPs1[ij]; db = base_d2 - referenceBPs2[ij]; if (Q_B[ij]) { for (cnt1 = k_min_Q_B[ij]; cnt1 <= k_max_Q_B[ij]; cnt1++) for (cnt2 = l_min_Q_B[ij][cnt1]; cnt2 <= l_max_Q_B[ij][cnt1]; cnt2 += 2) { if (((cnt1 + da) > maxD1) || ((cnt2 + db) > maxD2)) { qot += Q_B[ij][cnt1][cnt2 / 2] * qt; if (qot >= r) { backtrack(vc, pstruc, cnt1, cnt2, i, j); return; } } } } } } else { r = vrna_urn() * Q_cH[d1][d2 / 2]; for (i = 1; i < n; i++) for (j = i + turn + 1; j <= n; j++) { char loopseq[10]; ij = my_iindx[i] - j; if (!Q_B[ij]) continue; u = n - j + i - 1; if (u < turn) continue; type = ptype[jindx[j] + i]; if (!type) continue; if (((type == 3) || (type == 4)) && no_closingGU) continue; type = rtype[type]; if (u < 7) { strcpy(loopseq, sequence + j - 1); strncat(loopseq, sequence, i); } qt = exp_E_Hairpin(u, type, S1[j + 1], S1[i - 1], loopseq, pf_params) * scale[u]; da = base_d1 - referenceBPs1[ij]; db = base_d2 - referenceBPs2[ij]; for (cnt1 = k_min_Q_B[ij]; cnt1 <= k_max_Q_B[ij]; cnt1++) for (cnt2 = l_min_Q_B[ij][cnt1]; cnt2 <= l_max_Q_B[ij][cnt1]; cnt2 += 2) { if (((cnt1 + da) == d1) && ((cnt2 + db) == d2)) { qot += Q_B[ij][cnt1][cnt2 / 2] * qt; if (qot >= r) { backtrack(vc, pstruc, cnt1, cnt2, i, j); return; } } } } } vrna_message_error("backtrack_qcH@2Dpfold.c: failed to find closing pair!"); } PRIVATE void backtrack_qcI(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2) { char *ptype; short *S1; unsigned int i, j, ij, p, q, pq, n, maxD1, maxD2, base_d1, base_d2, da, db, *referenceBPs1, *referenceBPs2; int *my_iindx, *jindx, cnt1, cnt2, cnt3, cnt4, type, **l_min_Q_B, **l_max_Q_B, *k_min_Q_B, *k_max_Q_B, *rtype, turn; FLT_OR_DBL r, qt, *scale, qot, ***Q_B, *Q_B_rem, **Q_cI, Q_cI_rem; vrna_exp_param_t *pf_params; vrna_md_t *md; vrna_mx_pf_t *matrices; pf_params = vc->exp_params; md = &(pf_params->model_details); matrices = vc->exp_matrices; n = vc->length; my_iindx = vc->iindx; jindx = vc->jindx; scale = matrices->scale; ptype = vc->ptype; rtype = &(md->rtype[0]); S1 = vc->sequence_encoding; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; maxD1 = vc->maxD1; maxD2 = vc->maxD2; turn = md->min_loop_size; Q_B = matrices->Q_B; l_min_Q_B = matrices->l_min_Q_B; l_max_Q_B = matrices->l_max_Q_B; k_min_Q_B = matrices->k_min_Q_B; k_max_Q_B = matrices->k_max_Q_B; Q_cI = matrices->Q_cI; Q_B_rem = matrices->Q_B_rem; Q_cI_rem = matrices->Q_cI_rem; qot = qt = 0.; base_d1 = referenceBPs1[my_iindx[1] - n]; base_d2 = referenceBPs2[my_iindx[1] - n]; if (d1 == -1) { r = vrna_urn() * Q_cI_rem; for (i = 1; i < n; i++) for (j = i + turn + 1; j <= n; j++) { ij = my_iindx[i] - j; type = rtype[(unsigned int)ptype[jindx[j] + i]]; if (!type) continue; if (Q_B_rem[ij]) { for (p = j + 1; p < n; p++) { unsigned int ln1, qstart, ln_pre; ln1 = p - j - 1; if (ln1 + i - 1 > MAXLOOP) break; qstart = p + turn + 1; ln_pre = ln1 + i + n; if (ln_pre > qstart + MAXLOOP) qstart = ln_pre - MAXLOOP - 1; for (q = qstart; q <= n; q++) { unsigned int ln2; int type2; pq = my_iindx[p] - q; ln2 = (i - 1) + (n - q); if ((ln1 + ln2) > MAXLOOP) continue; type2 = ptype[jindx[q] + p]; if (!type2) continue; qt = exp_E_IntLoop(ln2, ln1, rtype[type2], type, S1[q + 1], S1[p - 1], S1[i - 1], S1[j + 1], pf_params) * scale[ln1 + ln2]; if (Q_B_rem[pq]) { qot += Q_B_rem[ij] * Q_B_rem[pq] * qt; if (qot > r) { backtrack(vc, pstruc, d1, d2, i, j); backtrack(vc, pstruc, d1, d2, p, q); return; } } if (Q_B[pq]) { for (cnt1 = k_min_Q_B[pq]; cnt1 <= k_max_Q_B[pq]; cnt1++) for (cnt2 = l_min_Q_B[pq][cnt1]; cnt2 <= l_max_Q_B[pq][cnt1]; cnt2 += 2) { qot += Q_B_rem[ij] * Q_B[pq][cnt1][cnt2 / 2] * qt; if (qot > r) { backtrack(vc, pstruc, d1, d2, i, j); backtrack(vc, pstruc, cnt1, cnt2, p, q); return; } } } } } } if (Q_B[ij]) { for (p = j + 1; p < n; p++) { unsigned int ln1, qstart, ln_pre; ln1 = p - j - 1; if (ln1 + i - 1 > MAXLOOP) break; qstart = p + turn + 1; ln_pre = ln1 + i + n; if (ln_pre > qstart + MAXLOOP) qstart = ln_pre - MAXLOOP - 1; for (q = qstart; q <= n; q++) { unsigned int ln2; int type2; pq = my_iindx[p] - q; ln2 = (i - 1) + (n - q); if ((ln1 + ln2) > MAXLOOP) continue; type2 = ptype[jindx[q] + p]; if (!type2) continue; qt = exp_E_IntLoop(ln2, ln1, rtype[type2], type, S1[q + 1], S1[p - 1], S1[i - 1], S1[j + 1], pf_params) * scale[ln1 + ln2]; if (Q_B_rem[pq]) { for (cnt1 = k_min_Q_B[ij]; cnt1 <= k_max_Q_B[ij]; cnt1++) for (cnt2 = l_min_Q_B[ij][cnt1]; cnt2 <= l_max_Q_B[ij][cnt1]; cnt2 += 2) { qot += Q_B[ij][cnt1][cnt2 / 2] * Q_B_rem[pq] * qt; if (qot > r) { backtrack(vc, pstruc, cnt1, cnt2, i, j); backtrack(vc, pstruc, d1, d2, p, q); return; } } } if (Q_B[pq]) { da = base_d1 - referenceBPs1[ij] - referenceBPs1[pq]; db = base_d2 - referenceBPs2[ij] - referenceBPs2[pq]; for (cnt1 = k_min_Q_B[ij]; cnt1 <= k_max_Q_B[ij]; cnt1++) for (cnt2 = l_min_Q_B[ij][cnt1]; cnt2 <= l_max_Q_B[ij][cnt1]; cnt2 += 2) for (cnt3 = k_min_Q_B[pq]; cnt3 <= k_max_Q_B[pq]; cnt3++) for (cnt4 = l_min_Q_B[pq][cnt3]; cnt4 <= l_max_Q_B[pq][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) > maxD1) || ((cnt2 + cnt4 + db) > maxD2)) { qot += Q_B[ij][cnt1][cnt2 / 2] * Q_B[pq][cnt3][cnt4 / 2] * qt; if (qot > r) { backtrack(vc, pstruc, cnt1, cnt2, i, j); backtrack(vc, pstruc, cnt3, cnt4, p, q); return; } } } } } } } } } else { r = vrna_urn() * Q_cI[d1][d2 / 2]; for (i = 1; i < n; i++) for (j = i + turn + 1; j <= n; j++) { ij = my_iindx[i] - j; type = rtype[(unsigned int)ptype[jindx[j] + i]]; if (!type) continue; if (!Q_B[ij]) continue; for (p = j + 1; p < n; p++) { unsigned int ln1, qstart, ln_pre; ln1 = p - j - 1; if (ln1 + i - 1 > MAXLOOP) break; qstart = p + turn + 1; ln_pre = ln1 + i + n; if (ln_pre > qstart + MAXLOOP) qstart = ln_pre - MAXLOOP - 1; for (q = qstart; q <= n; q++) { unsigned int ln2; int type2; pq = my_iindx[p] - q; if (!Q_B[pq]) continue; ln2 = (i - 1) + (n - q); if ((ln1 + ln2) > MAXLOOP) continue; type2 = ptype[jindx[q] + p]; if (!type2) continue; qt = exp_E_IntLoop(ln2, ln1, rtype[type2], type, S1[q + 1], S1[p - 1], S1[i - 1], S1[j + 1], pf_params) * scale[ln1 + ln2]; da = base_d1 - referenceBPs1[ij] - referenceBPs1[pq]; db = base_d2 - referenceBPs2[ij] - referenceBPs2[pq]; for (cnt1 = k_min_Q_B[ij]; cnt1 <= k_max_Q_B[ij]; cnt1++) for (cnt2 = l_min_Q_B[ij][cnt1]; cnt2 <= l_max_Q_B[ij][cnt1]; cnt2 += 2) for (cnt3 = k_min_Q_B[pq]; cnt3 <= k_max_Q_B[pq]; cnt3++) for (cnt4 = l_min_Q_B[pq][cnt3]; cnt4 <= l_max_Q_B[pq][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) == d1) && ((cnt2 + cnt4 + db) == d2)) { qot += Q_B[ij][cnt1][cnt2 / 2] * Q_B[pq][cnt3][cnt4 / 2] * qt; if (qot > r) { backtrack(vc, pstruc, cnt1, cnt2, i, j); backtrack(vc, pstruc, cnt3, cnt4, p, q); return; } } } } } } } } PRIVATE void backtrack_qcM(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2) { unsigned int k, n, maxD1, maxD2, base_d1, base_d2, da, db, *referenceBPs1, *referenceBPs2; int *my_iindx, cnt1, cnt2, cnt3, cnt4, **l_min_Q_M, **l_max_Q_M, **l_min_Q_M2, **l_max_Q_M2, *k_min_Q_M, *k_max_Q_M, *k_min_Q_M2, *k_max_Q_M2, turn; FLT_OR_DBL r, qt, qot, ***Q_M, ***Q_M2, **Q_cM, *Q_M_rem, *Q_M2_rem, Q_cM_rem; vrna_exp_param_t *pf_params; vrna_mx_pf_t *matrices; pf_params = vc->exp_params; matrices = vc->exp_matrices; n = vc->length; my_iindx = vc->iindx; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; maxD1 = vc->maxD1; maxD2 = vc->maxD2; turn = pf_params->model_details.min_loop_size; Q_cM = matrices->Q_cM; Q_M = matrices->Q_M; l_min_Q_M = matrices->l_min_Q_M; l_max_Q_M = matrices->l_max_Q_M; k_min_Q_M = matrices->k_min_Q_M; k_max_Q_M = matrices->k_max_Q_M; Q_M2 = matrices->Q_M2; l_min_Q_M2 = matrices->l_min_Q_M2; l_max_Q_M2 = matrices->l_max_Q_M2; k_min_Q_M2 = matrices->k_min_Q_M2; k_max_Q_M2 = matrices->k_max_Q_M2; Q_cM_rem = matrices->Q_cM_rem; Q_M_rem = matrices->Q_M_rem; Q_M2_rem = matrices->Q_M2_rem; base_d1 = referenceBPs1[my_iindx[1] - n]; base_d2 = referenceBPs2[my_iindx[1] - n]; qot = qt = 0.; if (d1 == -1) { r = vrna_urn() * Q_cM_rem; for (k = turn + 2; k < n - 2 * turn - 3; k++) { if (Q_M_rem[my_iindx[1] - k]) { if (Q_M2[k + 1]) { for (cnt1 = k_min_Q_M2[k + 1]; cnt1 <= k_max_Q_M2[k + 1]; cnt1++) for (cnt2 = l_min_Q_M2[k + 1][cnt1]; cnt2 <= l_max_Q_M2[k + 1][cnt1]; cnt2 += 2) { qot += Q_M_rem[my_iindx[1] - k] * Q_M2[k + 1][cnt1][cnt2 / 2] * pf_params->expMLclosing; if (qot > r) { backtrack_qm(vc, pstruc, d1, d2, 1, k); backtrack_qm2(vc, pstruc, cnt1, cnt2, k + 1); return; } } } if (Q_M2_rem[k + 1]) { qot += Q_M_rem[my_iindx[1] - k] * Q_M2_rem[k + 1] * pf_params->expMLclosing; if (qot > r) { backtrack_qm(vc, pstruc, d1, d2, 1, k); backtrack_qm2(vc, pstruc, d1, d2, k + 1); return; } } } if (Q_M2_rem[k + 1]) { if (Q_M[my_iindx[1] - k]) { for (cnt1 = k_min_Q_M[my_iindx[1] - k]; cnt1 <= k_max_Q_M[my_iindx[1] - k]; cnt1++) for (cnt2 = l_min_Q_M[my_iindx[1] - k][cnt1]; cnt2 <= l_max_Q_M[my_iindx[1] - k][cnt1]; cnt2 += 2) { qot += Q_M[my_iindx[1] - k][cnt1][cnt2 / 2] * Q_M2_rem[k + 1] * pf_params->expMLclosing; if (qot > r) { backtrack_qm(vc, pstruc, cnt1, cnt2, 1, k); backtrack_qm2(vc, pstruc, d1, d2, k + 1); return; } } } } da = base_d1 - referenceBPs1[my_iindx[1] - k] - referenceBPs1[my_iindx[k + 1] - n]; db = base_d2 - referenceBPs2[my_iindx[1] - k] - referenceBPs2[my_iindx[k + 1] - n]; if (Q_M[my_iindx[1] - k] && Q_M2[k + 1]) { for (cnt1 = k_min_Q_M[my_iindx[1] - k]; cnt1 <= k_max_Q_M[my_iindx[1] - k]; cnt1++) for (cnt2 = l_min_Q_M[my_iindx[1] - k][cnt1]; cnt2 <= l_max_Q_M[my_iindx[1] - k][cnt1]; cnt2 += 2) for (cnt3 = k_min_Q_M2[k + 1]; cnt3 <= k_max_Q_M2[k + 1]; cnt3++) for (cnt4 = l_min_Q_M2[k + 1][cnt3]; cnt4 <= l_max_Q_M2[k + 1][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) > maxD1) || ((cnt2 + cnt4 + db) > maxD2)) { qot += Q_M[my_iindx[1] - k][cnt1][cnt2 / 2] * Q_M2[k + 1][cnt3][cnt4 / 2] * pf_params->expMLclosing; if (qot > r) { backtrack_qm(vc, pstruc, cnt1, cnt2, 1, k); backtrack_qm2(vc, pstruc, cnt3, cnt4, k + 1); return; } } } } } } else { r = vrna_urn() * Q_cM[d1][d2 / 2]; for (k = turn + 2; k < n - 2 * turn - 3; k++) { da = base_d1 - referenceBPs1[my_iindx[1] - k] - referenceBPs1[my_iindx[k + 1] - n]; db = base_d2 - referenceBPs2[my_iindx[1] - k] - referenceBPs2[my_iindx[k + 1] - n]; if (Q_M[my_iindx[1] - k] && Q_M2[k + 1]) { for (cnt1 = k_min_Q_M[my_iindx[1] - k]; cnt1 <= k_max_Q_M[my_iindx[1] - k]; cnt1++) for (cnt2 = l_min_Q_M[my_iindx[1] - k][cnt1]; cnt2 <= l_max_Q_M[my_iindx[1] - k][cnt1]; cnt2 += 2) for (cnt3 = k_min_Q_M2[k + 1]; cnt3 <= k_max_Q_M2[k + 1]; cnt3++) for (cnt4 = l_min_Q_M2[k + 1][cnt3]; cnt4 <= l_max_Q_M2[k + 1][cnt3]; cnt4 += 2) if (((cnt1 + cnt3 + da) == d1) && ((cnt2 + cnt4 + db) == d2)) { qot += Q_M[my_iindx[1] - k][cnt1][cnt2 / 2] * Q_M2[k + 1][cnt3][cnt4 / 2] * pf_params->expMLclosing; if (qot > r) { backtrack_qm(vc, pstruc, cnt1, cnt2, 1, k); backtrack_qm2(vc, pstruc, cnt3, cnt4, k + 1); return; } } } } } vrna_message_error("backtrack_qcM@2Dpfold.c: backtracking failed"); } PRIVATE void backtrack_qm2(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2, unsigned int k) { unsigned int l, n, maxD1, maxD2, da, db, *referenceBPs1, *referenceBPs2; int *my_iindx, *jindx, cnt1, cnt2, cnt3, cnt4, *k_min_Q_M1, *k_max_Q_M1, **l_min_Q_M1, **l_max_Q_M1, turn; FLT_OR_DBL r, qt, qot, ***Q_M2, ***Q_M1, *Q_M2_rem, *Q_M1_rem; vrna_mx_pf_t *matrices; matrices = vc->exp_matrices; n = vc->length; my_iindx = vc->iindx; jindx = vc->jindx; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; maxD1 = vc->maxD1; maxD2 = vc->maxD2; turn = vc->exp_params->model_details.min_loop_size; Q_M1_rem = matrices->Q_M1_rem; Q_M1 = matrices->Q_M1; l_min_Q_M1 = matrices->l_min_Q_M1; l_max_Q_M1 = matrices->l_max_Q_M1; k_min_Q_M1 = matrices->k_min_Q_M1; k_max_Q_M1 = matrices->k_max_Q_M1; Q_M2_rem = matrices->Q_M2_rem; Q_M2 = matrices->Q_M2; qot = qt = 0.; if (d1 == -1) { r = vrna_urn() * Q_M2_rem[k]; for (l = k + turn + 1; l < n - turn - 1; l++) { if (Q_M1_rem[jindx[l] + k]) { if (Q_M1[jindx[n] + l + 1]) { for (cnt1 = k_min_Q_M1[jindx[n] + l + 1]; cnt1 <= k_max_Q_M1[jindx[n] + l + 1]; cnt1++) for (cnt2 = l_min_Q_M1[jindx[n] + l + 1][cnt1]; cnt2 <= l_max_Q_M1[jindx[n] + l + 1][cnt1]; cnt2 += 2) { qot += Q_M1_rem[jindx[l] + k] * Q_M1[jindx[n] + l + 1][cnt1][cnt2 / 2]; if (qot > r) { backtrack_qm1(vc, pstruc, d1, d2, k, l); backtrack_qm1(vc, pstruc, cnt1, cnt2, l + 1, n); return; } } } if (Q_M1_rem[jindx[n] + l + 1]) { qot += Q_M1_rem[jindx[l] + k] * Q_M1_rem[jindx[n] + l + 1]; if (qot > r) { backtrack_qm1(vc, pstruc, d1, d2, k, l); backtrack_qm1(vc, pstruc, d1, d2, l + 1, n); return; } } } if (Q_M1_rem[jindx[n] + l + 1]) { if (Q_M1[jindx[l] + k]) { for (cnt1 = k_min_Q_M1[jindx[l] + k]; cnt1 <= k_max_Q_M1[jindx[l] + k]; cnt1++) for (cnt2 = l_min_Q_M1[jindx[l] + k][cnt1]; cnt2 <= l_max_Q_M1[jindx[l] + k][cnt1]; cnt2 += 2) { qot += Q_M1[jindx[l] + k][cnt1][cnt2 / 2] * Q_M1_rem[jindx[n] + l + 1]; if (qot > r) { backtrack_qm1(vc, pstruc, cnt1, cnt2, k, l); backtrack_qm1(vc, pstruc, d1, d2, l + 1, n); return; } } } } if (!Q_M1[jindx[l] + k]) continue; if (!Q_M1[jindx[n] + l + 1]) continue; da = referenceBPs1[my_iindx[k] - n] - referenceBPs1[my_iindx[k] - l] - referenceBPs1[my_iindx[l + 1] - n]; db = referenceBPs2[my_iindx[k] - n] - referenceBPs2[my_iindx[k] - l] - referenceBPs2[my_iindx[l + 1] - n]; for (cnt1 = k_min_Q_M1[jindx[l] + k]; cnt1 <= k_max_Q_M1[jindx[l] + k]; cnt1++) for (cnt2 = l_min_Q_M1[jindx[l] + k][cnt1]; cnt2 <= l_max_Q_M1[jindx[l] + k][cnt1]; cnt2 += 2) { for (cnt3 = k_min_Q_M1[jindx[n] + l + 1]; cnt3 <= k_max_Q_M1[jindx[n] + l + 1]; cnt3++) for (cnt4 = l_min_Q_M1[jindx[n] + l + 1][cnt3]; cnt4 <= l_max_Q_M1[jindx[n] + l + 1][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) > maxD1) || ((cnt2 + cnt4 + db) > maxD2)) { qot += Q_M1[jindx[l] + k][cnt1][cnt2 / 2] * Q_M1[jindx[n] + l + 1][cnt3][cnt4 / 2]; if (qot > r) { backtrack_qm1(vc, pstruc, cnt1, cnt2, k, l); backtrack_qm1(vc, pstruc, cnt3, cnt4, l + 1, n); return; } } } } } } else { r = vrna_urn() * Q_M2[k][d1][d2 / 2]; for (l = k + turn + 1; l < n - turn - 1; l++) { if (!Q_M1[jindx[l] + k]) continue; if (!Q_M1[jindx[n] + l + 1]) continue; da = referenceBPs1[my_iindx[k] - n] - referenceBPs1[my_iindx[k] - l] - referenceBPs1[my_iindx[l + 1] - n]; db = referenceBPs2[my_iindx[k] - n] - referenceBPs2[my_iindx[k] - l] - referenceBPs2[my_iindx[l + 1] - n]; for (cnt1 = k_min_Q_M1[jindx[l] + k]; cnt1 <= k_max_Q_M1[jindx[l] + k]; cnt1++) for (cnt2 = l_min_Q_M1[jindx[l] + k][cnt1]; cnt2 <= l_max_Q_M1[jindx[l] + k][cnt1]; cnt2 += 2) { for (cnt3 = k_min_Q_M1[jindx[n] + l + 1]; cnt3 <= k_max_Q_M1[jindx[n] + l + 1]; cnt3++) for (cnt4 = l_min_Q_M1[jindx[n] + l + 1][cnt3]; cnt4 <= l_max_Q_M1[jindx[n] + l + 1][cnt3]; cnt4 += 2) { if (((cnt1 + cnt3 + da) == d1) && ((cnt2 + cnt4 + db) == d2)) { qot += Q_M1[jindx[l] + k][cnt1][cnt2 / 2] * Q_M1[jindx[n] + l + 1][cnt3][cnt4 / 2]; if (qot > r) { backtrack_qm1(vc, pstruc, cnt1, cnt2, k, l); backtrack_qm1(vc, pstruc, cnt3, cnt4, l + 1, n); return; } } } } } } vrna_message_error("backtrack_qm2@2Dpfold.c: backtracking failed"); } PRIVATE void backtrack(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2, unsigned int i, unsigned int j) { FLT_OR_DBL *scale; unsigned int maxD1, maxD2, base_d1, base_d2, da, db; unsigned int *referenceBPs1, *referenceBPs2; char *ptype, *sequence; short *S1, *reference_pt1, *reference_pt2; int *my_iindx, *jindx, ij, cnt1, cnt2, cnt3, cnt4, *rtype, turn; vrna_exp_param_t *pf_params; /* holds all [unscaled] pf parameters */ vrna_md_t *md; vrna_mx_pf_t *matrices; pf_params = vc->exp_params; md = &(pf_params->model_details); matrices = vc->exp_matrices; sequence = vc->sequence; maxD1 = vc->maxD1; maxD2 = vc->maxD2; my_iindx = vc->iindx; jindx = vc->jindx; scale = matrices->scale; ptype = vc->ptype; rtype = &(md->rtype[0]); S1 = vc->sequence_encoding; reference_pt1 = vc->reference_pt1; reference_pt2 = vc->reference_pt2; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; turn = md->min_loop_size; FLT_OR_DBL ***Q_B, ***Q_M, ***Q_M1, *Q_B_rem, *Q_M_rem, *Q_M1_rem; int *k_min_Q_M, *k_max_Q_M, *k_min_Q_M1, *k_max_Q_M1, *k_min_Q_B, *k_max_Q_B; int **l_min_Q_M, **l_max_Q_M, **l_min_Q_M1, **l_max_Q_M1, **l_min_Q_B, **l_max_Q_B; Q_B = matrices->Q_B; k_min_Q_B = matrices->k_min_Q_B; k_max_Q_B = matrices->k_max_Q_B; l_min_Q_B = matrices->l_min_Q_B; l_max_Q_B = matrices->l_max_Q_B; Q_M = matrices->Q_M; k_min_Q_M = matrices->k_min_Q_M; k_max_Q_M = matrices->k_max_Q_M; l_min_Q_M = matrices->l_min_Q_M; l_max_Q_M = matrices->l_max_Q_M; Q_M1 = matrices->Q_M1; k_min_Q_M1 = matrices->k_min_Q_M1; k_max_Q_M1 = matrices->k_max_Q_M1; l_min_Q_M1 = matrices->l_min_Q_M1; l_max_Q_M1 = matrices->l_max_Q_M1; Q_B_rem = matrices->Q_B_rem; Q_M_rem = matrices->Q_M_rem; Q_M1_rem = matrices->Q_M1_rem; cnt1 = cnt2 = cnt3 = cnt4 = -1; do { double r, qbt1 = 0.; unsigned int k, l, u, u1; int type; pstruc[i - 1] = '('; pstruc[j - 1] = ')'; r = 0.; ij = my_iindx[i] - j; l = INF; if (d1 == -1) { r = vrna_urn() * Q_B_rem[ij]; if (r == 0.) vrna_message_error("backtrack@2Dpfold.c: backtracking failed\n"); type = ptype[jindx[j] + i]; u = j - i - 1; base_d1 = ((unsigned int)reference_pt1[i] != j) ? 1 : -1; base_d2 = ((unsigned int)reference_pt2[i] != j) ? 1 : -1; da = base_d1 + referenceBPs1[ij]; db = base_d2 + referenceBPs2[ij]; /* hairpin ? */ if ((da > maxD1) || (db > maxD2)) if (!(((type == 3) || (type == 4)) && no_closingGU)) qbt1 = exp_E_Hairpin(u, type, S1[i + 1], S1[j - 1], sequence + i - 1, pf_params) * scale[u + 2]; if (qbt1 >= r) return; /* found the hairpin we're done */ /* lets see if we form an interior loop */ for (k = i + 1; k <= MIN2(i + MAXLOOP + 1, j - turn - 2); k++) { unsigned int u_pre, lmin; u1 = k - i - 1; lmin = k + turn + 1; u_pre = u1 + j; /* lmin = MAX2(k + turn + 1, u1 + j - 1 - MAXLOOP) */ if (u_pre > lmin + MAXLOOP) lmin = u_pre - 1 - MAXLOOP; for (l = lmin; l < j; l++) { int type_2; type_2 = ptype[jindx[l] + k]; if (type_2) { cnt1 = cnt2 = -1; da = base_d1 + referenceBPs1[my_iindx[i] - j] - referenceBPs1[my_iindx[k] - l]; db = base_d2 + referenceBPs2[my_iindx[i] - j] - referenceBPs2[my_iindx[k] - l]; type_2 = rtype[type_2]; FLT_OR_DBL tmp_en = exp_E_IntLoop(u1, j - l - 1, type, type_2, S1[i + 1], S1[j - 1], S1[k - 1], S1[l + 1], pf_params) * scale[u1 + j - l + 1]; if (Q_B_rem[my_iindx[k] - l] != 0.) { qbt1 += Q_B_rem[my_iindx[k] - l] * tmp_en; if (qbt1 > r) goto backtrack_int_early_escape_rem; } if (Q_B[my_iindx[k] - l]) { for (cnt1 = k_min_Q_B[my_iindx[k] - l]; cnt1 <= k_max_Q_B[my_iindx[k] - l]; cnt1++) for (cnt2 = l_min_Q_B[my_iindx[k] - l][cnt1]; cnt2 <= l_max_Q_B[my_iindx[k] - l][cnt1]; cnt2 += 2) if (((cnt1 + da) > maxD1) || ((cnt2 + db) > maxD2)) { qbt1 += Q_B[my_iindx[k] - l][cnt1][cnt2 / 2] * tmp_en; if (qbt1 > r) goto backtrack_int_early_escape_rem; } } } } } backtrack_int_early_escape_rem: if (l < j) { i = k; j = l; d1 = cnt1; d2 = cnt2; } else { break; } } else { if ((d1 >= k_min_Q_B[ij]) && (d1 <= k_max_Q_B[ij])) if ((d2 >= l_min_Q_B[ij][d1]) && (d2 <= l_max_Q_B[ij][d1])) r = vrna_urn() * Q_B[ij][d1][d2 / 2]; if (r == 0.) vrna_message_error("backtrack@2Dpfold.c: backtracking failed\n"); type = ptype[jindx[j] + i]; u = j - i - 1; base_d1 = ((unsigned int)reference_pt1[i] != j) ? 1 : -1; base_d2 = ((unsigned int)reference_pt2[i] != j) ? 1 : -1; da = base_d1 + referenceBPs1[ij]; db = base_d2 + referenceBPs2[ij]; /*hairpin contribution*/ if ((da == d1) && (db == d2)) if (!(((type == 3) || (type == 4)) && no_closingGU)) qbt1 = exp_E_Hairpin(u, type, S1[i + 1], S1[j - 1], sequence + i - 1, pf_params) * scale[u + 2]; if (qbt1 >= r) return; /* found the hairpin we're done */ for (k = i + 1; k <= MIN2(i + MAXLOOP + 1, j - turn - 2); k++) { unsigned int u_pre, lmin; u1 = k - i - 1; lmin = k + turn + 1; u_pre = u1 + j; /* lmin = MAX2(k + turn + 1, u1 + j - 1 - MAXLOOP) */ if (u_pre > lmin + MAXLOOP) lmin = u_pre - 1 - MAXLOOP; for (l = lmin; l < j; l++) { int type_2; type_2 = ptype[jindx[l] + k]; if (type_2) { da = base_d1 + referenceBPs1[my_iindx[i] - j] - referenceBPs1[my_iindx[k] - l]; db = base_d2 + referenceBPs2[my_iindx[i] - j] - referenceBPs2[my_iindx[k] - l]; type_2 = rtype[type_2]; FLT_OR_DBL tmp_en = exp_E_IntLoop(u1, j - l - 1, type, type_2, S1[i + 1], S1[j - 1], S1[k - 1], S1[l + 1], pf_params) * scale[u1 + j - l + 1]; if (d1 >= da && d2 >= db) { if ((d1 - da >= k_min_Q_B[my_iindx[k] - l]) && (d1 - da <= k_max_Q_B[my_iindx[k] - l])) { if ((d2 - db >= l_min_Q_B[my_iindx[k] - l][d1 - da]) && (d2 - db <= l_max_Q_B[my_iindx[k] - l][d1 - da])) { cnt1 = d1 - da; cnt2 = d2 - db; qbt1 += Q_B[my_iindx[k] - l][cnt1][cnt2 / 2] * tmp_en; if (qbt1 > r) goto backtrack_int_early_escape; } } } } } } backtrack_int_early_escape: if (l < j) { i = k; j = l; d1 = cnt1; d2 = cnt2; } else { break; } } } while (1); /* backtrack in multi-loop */ { double r, qt; unsigned int k, ii, jj; base_d1 = ((unsigned int)reference_pt1[i] != j) ? 1 : -1; base_d2 = ((unsigned int)reference_pt2[i] != j) ? 1 : -1; base_d1 += referenceBPs1[my_iindx[i] - j]; base_d2 += referenceBPs2[my_iindx[i] - j]; i++; j--; /* find the first split index */ ii = my_iindx[i]; /* ii-j=[i,j] */ jj = jindx[j]; /* jj+i=[j,i] */ if (d1 == -1) { /* get total contribution for current part */ for (qt = 0., k = i + 1; k < j; k++) { if (Q_M_rem[ii - k + 1] != 0.) { if (Q_M1[jj + k]) { for (cnt1 = k_min_Q_M1[jj + k]; cnt1 <= k_max_Q_M1[jj + k]; cnt1++) for (cnt2 = l_min_Q_M1[jj + k][cnt1]; cnt2 <= l_max_Q_M1[jj + k][cnt1]; cnt2 += 2) qt += Q_M_rem[ii - k + 1] * Q_M1[jj + k][cnt1][cnt2 / 2]; } if (Q_M1_rem[jj + k] != 0.) qt += Q_M_rem[ii - k + 1] * Q_M1_rem[jj + k]; } if (Q_M1_rem[jj + k] != 0.) { if (Q_M[ii - k + 1]) { for (cnt1 = k_min_Q_M[ii - k + 1]; cnt1 <= k_max_Q_M[ii - k + 1]; cnt1++) for (cnt2 = l_min_Q_M[ii - k + 1][cnt1]; cnt2 <= l_max_Q_M[ii - k + 1][cnt1]; cnt2 += 2) qt += Q_M[ii - k + 1][cnt1][cnt2 / 2] * Q_M1_rem[jj + k]; } } /* calculate introduced distance to reference structures */ if (!Q_M[ii - k + 1]) continue; if (!Q_M1[jj + k]) continue; da = base_d1 - referenceBPs1[my_iindx[i] - k + 1] - referenceBPs1[my_iindx[k] - j]; db = base_d2 - referenceBPs2[my_iindx[i] - k + 1] - referenceBPs2[my_iindx[k] - j]; /* collect all contributing energies */ for (cnt1 = k_min_Q_M[ii - k + 1]; cnt1 <= k_max_Q_M[ii - k + 1]; cnt1++) for (cnt2 = l_min_Q_M[ii - k + 1][cnt1]; cnt2 <= l_max_Q_M[ii - k + 1][cnt1]; cnt2 += 2) for (cnt3 = k_min_Q_M1[jj + k]; cnt3 <= k_max_Q_M1[jj + k]; cnt3++) for (cnt4 = l_min_Q_M1[jj + k][cnt3]; cnt4 <= l_max_Q_M1[jj + k][cnt3]; cnt4 += 2) if (((cnt1 + cnt3 + da) > maxD1) || ((cnt2 + cnt4 + db) > maxD2)) qt += Q_M[ii - k + 1][cnt1][cnt2 / 2] * Q_M1[jj + k][cnt3][cnt4 / 2]; } /* throw the dice */ r = vrna_urn() * qt; for (qt = 0., k = i + 1; k < j; k++) { cnt1 = cnt2 = cnt3 = cnt4 = -1; if (Q_M_rem[ii - k + 1] != 0.) { if (Q_M1_rem[jj + k] != 0) { qt += Q_M_rem[ii - k + 1] * Q_M1_rem[jj + k]; if (qt >= r) goto backtrack_ml_early_escape; } if (Q_M1[jj + k]) { for (cnt3 = k_min_Q_M1[jj + k]; cnt3 <= k_max_Q_M1[jj + k]; cnt3++) for (cnt4 = l_min_Q_M1[jj + k][cnt3]; cnt4 <= l_max_Q_M1[jj + k][cnt3]; cnt4 += 2) { qt += Q_M_rem[ii - k + 1] * Q_M1[jj + k][cnt3][cnt4 / 2]; if (qt >= r) goto backtrack_ml_early_escape; } } } if (Q_M1_rem[jj + k] != 0.) { cnt3 = cnt4 = -1; if (Q_M[ii - k + 1]) { for (cnt1 = k_min_Q_M[ii - k + 1]; cnt1 <= k_max_Q_M[ii - k + 1]; cnt1++) for (cnt2 = l_min_Q_M[ii - k + 1][cnt1]; cnt2 <= l_max_Q_M[ii - k + 1][cnt1]; cnt2 += 2) { qt += Q_M[ii - k + 1][cnt1][cnt2 / 2] * Q_M1_rem[jj + k]; if (qt >= r) goto backtrack_ml_early_escape; } } } /* calculate introduced distance to reference structures */ da = base_d1 - referenceBPs1[my_iindx[i] - k + 1] - referenceBPs1[my_iindx[k] - j]; db = base_d2 - referenceBPs2[my_iindx[i] - k + 1] - referenceBPs2[my_iindx[k] - j]; /* collect all contributing energies */ if (!Q_M[ii - k + 1]) continue; if (!Q_M1[jj + k]) continue; for (cnt1 = k_min_Q_M[ii - k + 1]; cnt1 <= k_max_Q_M[ii - k + 1]; cnt1++) for (cnt2 = l_min_Q_M[ii - k + 1][cnt1]; cnt2 <= l_max_Q_M[ii - k + 1][cnt1]; cnt2 += 2) for (cnt3 = k_min_Q_M1[jj + k]; cnt3 <= k_max_Q_M1[jj + k]; cnt3++) for (cnt4 = l_min_Q_M1[jj + k][cnt3]; cnt4 <= l_max_Q_M1[jj + k][cnt3]; cnt4 += 2) if (((cnt1 + cnt3 + da) > maxD1) || ((cnt2 + cnt4 + db) > maxD2)) { qt += Q_M[ii - k + 1][cnt1][cnt2 / 2] * Q_M1[jj + k][cnt3][cnt4 / 2]; if (qt >= r) goto backtrack_ml_early_escape; } } } else { /* get total contribution */ for (qt = 0., k = i + 1; k < j; k++) { /* calculate introduced distance to reference structures */ da = base_d1 - referenceBPs1[my_iindx[i] - k + 1] - referenceBPs1[my_iindx[k] - j]; db = base_d2 - referenceBPs2[my_iindx[i] - k + 1] - referenceBPs2[my_iindx[k] - j]; /* collect all contributing energies */ if (d1 >= da && d2 >= db && Q_M[ii - k + 1] && Q_M1[jj + k]) { for (cnt1 = k_min_Q_M[ii - k + 1]; cnt1 <= MIN2(k_max_Q_M[ii - k + 1], d1 - da); cnt1++) for (cnt2 = l_min_Q_M[ii - k + 1][cnt1]; cnt2 <= MIN2(l_max_Q_M[ii - k + 1][cnt1], d2 - db); cnt2 += 2) if ((d1 - cnt1 - da >= k_min_Q_M1[jj + k]) && (d1 - cnt1 - da <= k_max_Q_M1[jj + k])) if ((d2 - cnt2 - db >= l_min_Q_M1[jj + k][d1 - da - cnt1]) && (d2 - cnt2 - db <= l_max_Q_M1[jj + k][d1 - cnt1 - da])) qt += Q_M[ii - k + 1][cnt1][cnt2 / 2] * Q_M1[jj + k][d1 - da - cnt1][(d2 - db - cnt2) / 2]; } } r = vrna_urn() * qt; for (qt = 0., k = i + 1; k < j; k++) { /* calculate introduced distance to reference structures */ da = base_d1 - referenceBPs1[my_iindx[i] - k + 1] - referenceBPs1[my_iindx[k] - j]; db = base_d2 - referenceBPs2[my_iindx[i] - k + 1] - referenceBPs2[my_iindx[k] - j]; /* collect all contributing energies */ if (d1 >= da && d2 >= db && Q_M[ii - k + 1] && Q_M1[jj + k]) { for (cnt1 = k_min_Q_M[ii - k + 1]; cnt1 <= MIN2(k_max_Q_M[ii - k + 1], d1 - da); cnt1++) for (cnt2 = l_min_Q_M[ii - k + 1][cnt1]; cnt2 <= MIN2(l_max_Q_M[ii - k + 1][cnt1], d2 - db); cnt2 += 2) if ((d1 - cnt1 - da >= k_min_Q_M1[jj + k]) && (d1 - cnt1 - da <= k_max_Q_M1[jj + k])) { if ((d2 - cnt2 - db >= l_min_Q_M1[jj + k][d1 - da - cnt1]) && (d2 - cnt2 - db <= l_max_Q_M1[jj + k][d1 - cnt1 - da])) { cnt3 = d1 - da - cnt1; cnt4 = d2 - db - cnt2; qt += Q_M[ii - k + 1][cnt1][cnt2 / 2] * Q_M1[jj + k][cnt3][cnt4 / 2]; if (qt >= r) goto backtrack_ml_early_escape; } } } } } if (k >= j) vrna_message_error("backtrack failed, can't find split index "); backtrack_ml_early_escape: backtrack_qm1(vc, pstruc, cnt3, cnt4, k, j); j = k - 1; backtrack_qm(vc, pstruc, cnt1, cnt2, i, j); } } PRIVATE void backtrack_qm1(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2, unsigned int i, unsigned int j) { /* i is paired to l, i<l<j; backtrack in qm1 to find l */ FLT_OR_DBL r, qt, *scale; unsigned int maxD1, maxD2, da, db; unsigned int *referenceBPs1, *referenceBPs2; char *ptype; short *S1; int *my_iindx, *jindx, cnt1, cnt2, turn; vrna_exp_param_t *pf_params; /* holds all [unscaled] pf parameters */ vrna_mx_pf_t *matrices; pf_params = vc->exp_params; matrices = vc->exp_matrices; maxD1 = vc->maxD1; maxD2 = vc->maxD2; my_iindx = vc->iindx; jindx = vc->jindx; scale = matrices->scale; ptype = vc->ptype; S1 = vc->sequence_encoding; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; turn = pf_params->model_details.min_loop_size; FLT_OR_DBL ***Q_B, ***Q_M1, *Q_B_rem, *Q_M1_rem; int *k_min_Q_M1, *k_max_Q_M1, *k_min_Q_B, *k_max_Q_B; int **l_min_Q_M1, **l_max_Q_M1, **l_min_Q_B, **l_max_Q_B; Q_B = matrices->Q_B; k_min_Q_B = matrices->k_min_Q_B; k_max_Q_B = matrices->k_max_Q_B; l_min_Q_B = matrices->l_min_Q_B; l_max_Q_B = matrices->l_max_Q_B; Q_M1 = matrices->Q_M1; k_min_Q_M1 = matrices->k_min_Q_M1; k_max_Q_M1 = matrices->k_max_Q_M1; l_min_Q_M1 = matrices->l_min_Q_M1; l_max_Q_M1 = matrices->l_max_Q_M1; Q_B_rem = matrices->Q_B_rem; Q_M1_rem = matrices->Q_M1_rem; unsigned int ii, l; int type; r = 0.; cnt1 = cnt2 = -1; /* find qm1 contribution */ if (d1 == -1) { r = vrna_urn() * Q_M1_rem[jindx[j] + i]; } else { if ((d1 >= k_min_Q_M1[jindx[j] + i]) && (d1 <= k_max_Q_M1[jindx[j] + i])) if ((d2 >= l_min_Q_M1[jindx[j] + i][d1]) && (d2 <= l_max_Q_M1[jindx[j] + i][d1])) r = vrna_urn() * Q_M1[jindx[j] + i][d1][d2 / 2]; } if (r == 0.) vrna_message_error("backtrack_qm1@2Dpfold.c: backtracking failed\n"); ii = my_iindx[i]; for (qt = 0., l = i + turn + 1; l <= j; l++) { type = ptype[jindx[l] + i]; if (type) { FLT_OR_DBL tmp = exp_E_MLstem(type, S1[i - 1], S1[l + 1], pf_params) * pow( pf_params->expMLbase, j - l) * scale[j - l]; /* compute the introduced distance to reference structures */ da = referenceBPs1[my_iindx[i] - j] - referenceBPs1[my_iindx[i] - l]; db = referenceBPs2[my_iindx[i] - j] - referenceBPs2[my_iindx[i] - l]; cnt1 = cnt2 = -1; if (d1 == -1) { if (Q_B_rem[ii - l] != 0.) { qt += Q_B_rem[ii - l] * tmp; if (qt >= r) goto backtrack_qm1_early_escape; } if (Q_B[ii - l]) { for (cnt1 = k_min_Q_B[ii - l]; cnt1 <= k_max_Q_B[ii - l]; cnt1++) for (cnt2 = l_min_Q_B[ii - l][cnt1]; cnt2 <= l_max_Q_B[ii - l][cnt1]; cnt2 += 2) if (((cnt1 + da) > maxD1) || ((cnt2 + db) > maxD2)) { qt += Q_B[ii - l][cnt1][cnt2 / 2] * tmp; if (qt >= r) goto backtrack_qm1_early_escape; } } } else { /* get energy contributions */ if (d1 >= da && d2 >= db) { if ((d1 - da >= k_min_Q_B[ii - l]) && (d1 - da <= k_max_Q_B[ii - l])) { if ((d2 - db >= l_min_Q_B[ii - l][d1 - da]) && (d2 - db <= l_max_Q_B[ii - l][d1 - da])) { cnt1 = d1 - da; cnt2 = d2 - db; qt += Q_B[ii - l][cnt1][cnt2 / 2] * tmp; if (qt >= r) goto backtrack_qm1_early_escape; } } } } } } if (l > j) vrna_message_error("backtrack failed in qm1"); backtrack_qm1_early_escape: backtrack(vc, pstruc, cnt1, cnt2, i, l); } PRIVATE void backtrack_qm(vrna_fold_compound_t *vc, char *pstruc, int d1, int d2, unsigned int i, unsigned int j) { /* divide multiloop into qm and qm1 */ FLT_OR_DBL r, *scale; unsigned int maxD1, maxD2, da, db, da2, db2; unsigned int *referenceBPs1, *referenceBPs2; int *my_iindx, *jindx, cnt1, cnt2, cnt3, cnt4, turn; vrna_exp_param_t *pf_params; /* holds all [unscaled] pf parameters */ vrna_mx_pf_t *matrices; pf_params = vc->exp_params; matrices = vc->exp_matrices; maxD1 = vc->maxD1; maxD2 = vc->maxD2; my_iindx = vc->iindx; jindx = vc->jindx; scale = matrices->scale; referenceBPs1 = vc->referenceBPs1; referenceBPs2 = vc->referenceBPs2; turn = pf_params->model_details.min_loop_size; FLT_OR_DBL ***Q_M, ***Q_M1, *Q_M_rem, *Q_M1_rem; int *k_min_Q_M, *k_max_Q_M, *k_min_Q_M1, *k_max_Q_M1; int **l_min_Q_M, **l_max_Q_M, **l_min_Q_M1, **l_max_Q_M1; Q_M = matrices->Q_M; k_min_Q_M = matrices->k_min_Q_M; k_max_Q_M = matrices->k_max_Q_M; l_min_Q_M = matrices->l_min_Q_M; l_max_Q_M = matrices->l_max_Q_M; Q_M1 = matrices->Q_M1; k_min_Q_M1 = matrices->k_min_Q_M1; k_max_Q_M1 = matrices->k_max_Q_M1; l_min_Q_M1 = matrices->l_min_Q_M1; l_max_Q_M1 = matrices->l_max_Q_M1; Q_M_rem = matrices->Q_M_rem; Q_M1_rem = matrices->Q_M1_rem; double qmt = 0; unsigned int k; cnt1 = cnt2 = cnt3 = cnt4 = -1; r = 0.; while (j > i) { /* now backtrack [i ... j] in qm[] */ /* find qm contribution */ if (d1 == -1) { r = vrna_urn() * Q_M_rem[my_iindx[i] - j]; } else { if (Q_M[my_iindx[i] - j]) if ((d1 >= k_min_Q_M[my_iindx[i] - j]) && (d1 <= k_max_Q_M[my_iindx[i] - j])) if ((d2 >= l_min_Q_M[my_iindx[i] - j][d1]) && (d2 <= l_max_Q_M[my_iindx[i] - j][d1])) r = vrna_urn() * Q_M[my_iindx[i] - j][d1][d2 / 2]; } if (r == 0.) vrna_message_error("backtrack_qm@2Dpfold.c: backtracking failed in finding qm contribution\n"); qmt = 0.; if (d1 == -1) { if (Q_M1_rem[jindx[j] + i] != 0.) { qmt += Q_M1_rem[jindx[j] + i]; if (qmt >= r) { backtrack_qm1(vc, pstruc, d1, d2, i, j); return; } } for (k = i + 1; k <= j; k++) { FLT_OR_DBL tmp = pow(pf_params->expMLbase, k - i) * scale[k - i]; if (Q_M1_rem[jindx[j] + k] != 0.) { qmt += Q_M1_rem[jindx[j] + k] * tmp; if (qmt >= r) { backtrack_qm1(vc, pstruc, d1, d2, k, j); return; } } da2 = referenceBPs1[my_iindx[i] - j] - referenceBPs1[my_iindx[k] - j]; db2 = referenceBPs2[my_iindx[i] - j] - referenceBPs2[my_iindx[k] - j]; if (Q_M1[jindx[j] + k]) { for (cnt1 = k_min_Q_M1[jindx[j] + k]; cnt1 <= k_max_Q_M1[jindx[j] + k]; cnt1++) for (cnt2 = l_min_Q_M1[jindx[j] + k][cnt1]; cnt2 <= l_max_Q_M1[jindx[j] + k][cnt1]; cnt2 += 2) if (((cnt1 + da2) > maxD1) || ((cnt2 + db2) > maxD2)) { qmt += Q_M1[jindx[j] + k][cnt1][cnt2 / 2] * tmp; if (qmt >= r) { backtrack_qm1(vc, pstruc, cnt1, cnt2, k, j); return; } } } da = da2 - referenceBPs1[my_iindx[i] - k + 1]; db = db2 - referenceBPs2[my_iindx[i] - k + 1]; cnt1 = cnt2 = cnt3 = cnt4 = -1; if (Q_M_rem[my_iindx[i] - k + 1] != 0.) { if (Q_M1_rem[jindx[j] + k] != 0.) { qmt += Q_M_rem[my_iindx[i] - k + 1] * Q_M1_rem[jindx[j] + k]; if (qmt >= r) goto backtrack_qm_early_escape; } if (Q_M1[jindx[j] + k]) { for (cnt3 = k_min_Q_M1[jindx[j] + k]; cnt3 <= k_max_Q_M1[jindx[j] + k]; cnt3++) for (cnt4 = l_min_Q_M1[jindx[j] + k][cnt3]; cnt4 <= l_max_Q_M1[jindx[j] + k][cnt3]; cnt4 += 2) { qmt += Q_M_rem[my_iindx[i] - k + 1] * Q_M1[jindx[j] + k][cnt3][cnt4 / 2]; if (qmt >= r) goto backtrack_qm_early_escape; } } } if (Q_M1_rem[jindx[j] + k] != 0.) { cnt3 = cnt4 = -1; if (Q_M[my_iindx[i] - k + 1]) { for (cnt1 = k_min_Q_M[my_iindx[i] - k + 1]; cnt1 <= k_max_Q_M[my_iindx[i] - k + 1]; cnt1++) for (cnt2 = l_min_Q_M[my_iindx[i] - k + 1][cnt1]; cnt2 <= l_max_Q_M[my_iindx[i] - k + 1][cnt1]; cnt2 += 2) { qmt += Q_M[my_iindx[i] - k + 1][cnt1][cnt2 / 2] * Q_M1_rem[jindx[j] + k]; if (qmt >= r) goto backtrack_qm_early_escape; } } } if (!Q_M[my_iindx[i] - k + 1]) continue; if (!Q_M1[jindx[j] + k]) continue; for (cnt1 = k_min_Q_M[my_iindx[i] - k + 1]; cnt1 <= k_max_Q_M[my_iindx[i] - k + 1]; cnt1++) for (cnt2 = l_min_Q_M[my_iindx[i] - k + 1][cnt1]; cnt2 <= l_max_Q_M[my_iindx[i] - k + 1][cnt1]; cnt2 += 2) for (cnt3 = k_min_Q_M1[jindx[j] + k]; cnt3 <= k_max_Q_M1[jindx[j] + k]; cnt3++) for (cnt4 = l_min_Q_M1[jindx[j] + k][cnt3]; cnt4 <= l_max_Q_M1[jindx[j] + k][cnt3]; cnt4 += 2) if (((cnt1 + cnt3 + da) > maxD1) || ((cnt2 + cnt4 + db) > maxD2)) { qmt += Q_M[my_iindx[i] - k + 1][cnt1][cnt2 / 2] * Q_M1[jindx[j] + k][cnt3][cnt4 / 2]; if (qmt >= r) goto backtrack_qm_early_escape; } } } else { /* find corresponding qm1 contribution */ if (Q_M1[jindx[j] + i]) { if ((d1 >= k_min_Q_M1[jindx[j] + i]) && (d1 <= k_max_Q_M1[jindx[j] + i])) if ((d2 >= l_min_Q_M1[jindx[j] + i][d1]) && (d2 <= l_max_Q_M1[jindx[j] + i][d1])) qmt = Q_M1[jindx[j] + i][d1][d2 / 2]; } k = i; if (qmt < r) { for (k = i + 1; k <= j; k++) { /* calculate introduced distancies to reference structures */ da2 = referenceBPs1[my_iindx[i] - j] - referenceBPs1[my_iindx[k] - j]; db2 = referenceBPs2[my_iindx[i] - j] - referenceBPs2[my_iindx[k] - j]; da = da2 - referenceBPs1[my_iindx[i] - k + 1]; db = db2 - referenceBPs2[my_iindx[i] - k + 1]; FLT_OR_DBL tmp = pow(pf_params->expMLbase, k - i) * scale[k - i]; /* collect unpaired + qm1 contributions */ if (d1 >= da2 && d2 >= db2) { if ((d1 - da2 >= k_min_Q_M1[jindx[j] + k]) && (d1 - da2 <= k_max_Q_M1[jindx[j] + k])) { if ((d2 - db2 >= l_min_Q_M1[jindx[j] + k][d1 - da2]) && (d2 - db2 <= l_max_Q_M1[jindx[j] + k][d1 - da2])) { cnt3 = d1 - da2; cnt4 = d2 - db2; qmt += Q_M1[jindx[j] + k][cnt3][cnt4 / 2] * tmp; if (qmt >= r) { backtrack_qm1(vc, pstruc, cnt3, cnt4, k, j); return; } } } } /* collect qm + qm1 contributions */ if (d1 >= da && d2 >= db && Q_M[my_iindx[i] - k + 1] && Q_M1[jindx[j] + k]) { for (cnt1 = k_min_Q_M[my_iindx[i] - k + 1]; cnt1 <= MIN2(k_max_Q_M[my_iindx[i] - k + 1], d1 - da); cnt1++) for (cnt2 = l_min_Q_M[my_iindx[i] - k + 1][cnt1]; cnt2 <= MIN2(l_max_Q_M[my_iindx[i] - k + 1][cnt1], d2 - db); cnt2 += 2) if ((d1 - da - cnt1 >= k_min_Q_M1[jindx[j] + k]) && (d1 - da - cnt1 <= k_max_Q_M1[jindx[j] + k])) { if ((d2 - db - cnt2 >= l_min_Q_M1[jindx[j] + k][d1 - da - cnt1]) && (d2 - db - cnt2 <= l_max_Q_M1[jindx[j] + k][d1 - da - cnt1])) { cnt3 = d1 - da - cnt1; cnt4 = d2 - db - cnt2; qmt += Q_M[my_iindx[i] - k + 1][cnt1][cnt2 / 2] * Q_M1[jindx[j] + k][cnt3][cnt4 / 2]; if (qmt >= r) goto backtrack_qm_early_escape; } } } } } else { backtrack_qm1(vc, pstruc, d1, d2, k, j); return; } } if (k > j) vrna_message_error("backtrack_qm@2Dpfold.c: backtrack failed in qm"); backtrack_qm_early_escape: backtrack_qm1(vc, pstruc, cnt3, cnt4, k, j); if (k < i + turn) break; /* no more pairs */ d1 = cnt1; d2 = cnt2; if (d1 == referenceBPs1[my_iindx[i] - k + 1] && d2 == referenceBPs2[my_iindx[i] - k + 1]) { /* is interval [i,k] totally unpaired? */ FLT_OR_DBL tmp = pow(pf_params->expMLbase, k - i) * scale[k - i]; r = vrna_urn() * (Q_M[my_iindx[i] - k + 1][d1][d2 / 2] + tmp); if (tmp >= r) return; /* no more pairs */ } j = k - 1; } } PRIVATE void adjustArrayBoundaries(FLT_OR_DBL ***array, int *k_min, int *k_max, int **l_min, int **l_max, int k_min_post, int k_max_post, int *l_min_post, int *l_max_post) { int cnt1; int k_diff_pre = k_min_post - *k_min; int mem_size = k_max_post - k_min_post + 1; if (k_min_post < INF) { /* free all the unused memory behind actual data */ for (cnt1 = k_max_post + 1; cnt1 <= *k_max; cnt1++) { (*array)[cnt1] += (*l_min)[cnt1] / 2; free((*array)[cnt1]); } /* free unused memory before actual data */ for (cnt1 = *k_min; cnt1 < k_min_post; cnt1++) { (*array)[cnt1] += (*l_min)[cnt1] / 2; free((*array)[cnt1]); } /* move data to front and thereby eliminating unused memory in front of actual data */ if (k_diff_pre > 0) { memmove((FLT_OR_DBL **)(*array), ((FLT_OR_DBL **)(*array)) + k_diff_pre, sizeof(FLT_OR_DBL *) * mem_size); memmove((int *)(*l_min), ((int *)(*l_min)) + k_diff_pre, sizeof(int) * mem_size); memmove((int *)(*l_max), ((int *)(*l_max)) + k_diff_pre, sizeof(int) * mem_size); } /* reallocating memory to actual size used */ *array += *k_min; *array = (FLT_OR_DBL **)realloc(*array, sizeof(FLT_OR_DBL *) * mem_size); *array -= k_min_post; *l_min += *k_min; *l_min = (int *)realloc(*l_min, sizeof(int) * mem_size); *l_min -= k_min_post; *l_max += *k_min; *l_max = (int *)realloc(*l_max, sizeof(int) * mem_size); *l_max -= k_min_post; for (cnt1 = k_min_post; cnt1 <= k_max_post; cnt1++) { if (l_min_post[cnt1] < INF) { /* new memsize */ mem_size = (l_max_post[cnt1] - l_min_post[cnt1] + 1) / 2 + 1; /* reshift the pointer */ (*array)[cnt1] += (*l_min)[cnt1] / 2; int shift = (l_min_post[cnt1] % 2 == (*l_min)[cnt1] % 2) ? 0 : 1; /* eliminate unused memory in front of actual data */ unsigned int start = (l_min_post[cnt1] - (*l_min)[cnt1]) / 2 + shift; if (start > 0) memmove((FLT_OR_DBL *)((*array)[cnt1]), (FLT_OR_DBL *)((*array)[cnt1]) + start, sizeof(FLT_OR_DBL) * mem_size); (*array)[cnt1] = (FLT_OR_DBL *)realloc((*array)[cnt1], sizeof(FLT_OR_DBL) * mem_size); (*array)[cnt1] -= l_min_post[cnt1] / 2; } else { /* free according memory */ (*array)[cnt1] += (*l_min)[cnt1] / 2; free((*array)[cnt1]); } (*l_min)[cnt1] = l_min_post[cnt1]; (*l_max)[cnt1] = l_max_post[cnt1]; } } else { /* we have to free all unused memory */ for (cnt1 = *k_min; cnt1 <= *k_max; cnt1++) { (*array)[cnt1] += (*l_min)[cnt1] / 2; free((*array)[cnt1]); } (*l_min) += *k_min; (*l_max) += *k_min; free(*l_min); free(*l_max); (*array) += *k_min; free(*array); *array = NULL; } l_min_post += *k_min; l_max_post += *k_min; *k_min = k_min_post; *k_max = k_max_post; free(l_min_post); free(l_max_post); } PRIVATE INLINE void preparePosteriorBoundaries(int size, int shift, int *min_k, int *max_k, int **min_l, int **max_l) { int i; *min_k = INF; *max_k = 0; *min_l = (int *)vrna_alloc(sizeof(int) * size); *max_l = (int *)vrna_alloc(sizeof(int) * size); for (i = 0; i < size; i++) { (*min_l)[i] = INF; (*max_l)[i] = 0; } *min_l -= shift; *max_l -= shift; } PRIVATE INLINE void updatePosteriorBoundaries(int d1, int d2, int *min_k, int *max_k, int **min_l, int **max_l) { (*min_l)[d1] = MIN2((*min_l)[d1], d2); (*max_l)[d1] = MAX2((*max_l)[d1], d2); *min_k = MIN2(*min_k, d1); *max_k = MAX2(*max_k, d1); } PRIVATE INLINE void prepareBoundaries(int min_k_pre, int max_k_pre, int min_l_pre, int max_l_pre, int bpdist, int *min_k, int *max_k, int **min_l, int **max_l) { int cnt; int mem = max_k_pre - min_k_pre + 1; *min_k = min_k_pre; *max_k = max_k_pre; *min_l = (int *)vrna_alloc(sizeof(int) * mem); *max_l = (int *)vrna_alloc(sizeof(int) * mem); *min_l -= min_k_pre; *max_l -= min_k_pre; /* for each k guess the according minimum l*/ for (cnt = min_k_pre; cnt <= max_k_pre; cnt++) { (*min_l)[cnt] = min_l_pre; (*max_l)[cnt] = max_l_pre; while ((*min_l)[cnt] + cnt < bpdist) (*min_l)[cnt]++; if ((bpdist % 2) != (((*min_l)[cnt] + cnt) % 2)) (*min_l)[cnt]++; } } PRIVATE INLINE void prepareArray(FLT_OR_DBL ***array, int min_k, int max_k, int *min_l, int *max_l) { int i, mem; *array = (FLT_OR_DBL **)vrna_alloc(sizeof(FLT_OR_DBL *) * (max_k - min_k + 1)); *array -= min_k; for (i = min_k; i <= max_k; i++) { mem = (max_l[i] - min_l[i] + 1) / 2 + 1; (*array)[i] = (FLT_OR_DBL *)vrna_alloc(sizeof(FLT_OR_DBL) * mem); (*array)[i] -= min_l[i] / 2; } } /* ################################# # DEPRECATED FUNCTIONS BELOW # ################################# */ PRIVATE void crosslink(TwoDpfold_vars *vars) { vrna_fold_compound_t *c; vrna_mx_pf_t *m; c = vars->compatibility; m = c->exp_matrices; vars->sequence = c->sequence; vars->seq_length = c->length; vars->reference_pt1 = c->reference_pt1; vars->reference_pt2 = c->reference_pt2; vars->referenceBPs1 = c->referenceBPs1; vars->referenceBPs2 = c->referenceBPs2; vars->mm1 = c->mm1; vars->mm2 = c->mm2; vars->bpdist = c->bpdist; vars->dangles = c->exp_params->model_details.dangles; vars->circ = c->exp_params->model_details.circ; vars->temperature = c->exp_params->model_details.temperature; vars->init_temp = c->exp_params->model_details.temperature; vars->pf_scale = c->exp_params->pf_scale; vars->pf_params = c->exp_params; vars->scale = m->scale; vars->ptype = c->ptype_pf_compat; vars->S = c->sequence_encoding2; vars->S1 = c->sequence_encoding; vars->jindx = c->jindx; vars->my_iindx = c->iindx; vars->maxD1 = c->maxD1; vars->maxD2 = c->maxD2; vars->Q = m->Q; vars->l_min_values = m->l_min_Q; vars->l_max_values = m->l_max_Q; vars->k_min_values = m->k_min_Q; vars->k_max_values = m->k_max_Q; vars->Q_B = m->Q_B; vars->l_min_values_b = m->l_min_Q_B; vars->l_max_values_b = m->l_max_Q_B; vars->k_min_values_b = m->k_min_Q_B; vars->k_max_values_b = m->k_max_Q_B; vars->Q_M = m->Q_M; vars->l_min_values_m = m->l_min_Q_M; vars->l_max_values_m = m->l_max_Q_M; vars->k_min_values_m = m->k_min_Q_M; vars->k_max_values_m = m->k_max_Q_M; vars->Q_M1 = m->Q_M1; vars->l_min_values_m1 = m->l_min_Q_M1; vars->l_max_values_m1 = m->l_max_Q_M1; vars->k_min_values_m1 = m->k_min_Q_M1; vars->k_max_values_m1 = m->k_max_Q_M1; vars->Q_M2_rem = m->Q_M2_rem; vars->Q_M2 = m->Q_M2; vars->l_min_values_m2 = m->l_min_Q_M2; vars->l_max_values_m2 = m->l_max_Q_M2; vars->k_min_values_m2 = m->k_min_Q_M2; vars->k_max_values_m2 = m->k_max_Q_M2; vars->Q_c = m->Q_c; vars->Q_cH = m->Q_cH; vars->Q_cI = m->Q_cI; vars->Q_cM = m->Q_cM; vars->Q_c_rem = m->Q_c_rem; vars->Q_cH_rem = m->Q_cH_rem; vars->Q_cI_rem = m->Q_cI_rem; vars->Q_cM_rem = m->Q_cM_rem; vars->Q_rem = m->Q_rem; vars->Q_B_rem = m->Q_B_rem; vars->Q_M_rem = m->Q_M_rem; vars->Q_M1_rem = m->Q_M1_rem; } PUBLIC char * TwoDpfold_pbacktrack(TwoDpfold_vars *vars, int d1, int d2) { return vrna_pbacktrack_TwoD(vars->compatibility, d1, d2); } PUBLIC char * TwoDpfold_pbacktrack5(TwoDpfold_vars *vars, int d1, int d2, unsigned int length) { return vrna_pbacktrack5_TwoD(vars->compatibility, d1, d2, length); } PUBLIC TwoDpfold_vars * get_TwoDpfold_variables(const char *seq, const char *structure1, char *structure2, int circ) { vrna_md_t md; TwoDpfold_vars *vars; set_model_details(&md); md.circ = circ; vars = (TwoDpfold_vars *)malloc(sizeof(TwoDpfold_vars)); vars->compatibility = vrna_fold_compound_TwoD(seq, structure1, structure2, &md, VRNA_OPTION_PF); crosslink(vars); return vars; } PUBLIC void destroy_TwoDpfold_variables(TwoDpfold_vars *vars) { if (vars == NULL) return; vrna_fold_compound_free(vars->compatibility); free(vars); } vrna_sol_TwoD_pf_t * TwoDpfoldList(TwoDpfold_vars *vars, int distance1, int distance2) { vrna_sol_TwoD_pf_t *sol; sol = vrna_pf_TwoD(vars->compatibility, distance1, distance2); crosslink(vars); return sol; }
pi_nonreentrant.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #endif /* * This program approximates pi by computing the area of a quarter circle and * compare that to a square that circumscribes it. It generateds random x and * y coordinates and checks whether these are in the quarter circle or not. * * For performance tests, the application can optionally be called with an * integer value to control the size of the for-loop. */ int main(int argc, char *argv[]) { long nr_tries = 10000; if (argc > 1) nr_tries = atol(argv[1]); long nr_success = 0; #pragma omp parallel { #pragma omp single { int num_threads = 1; #ifdef _OPENMP num_threads = omp_get_num_threads(); #endif printf("running with %d threads\n", num_threads); } #pragma omp for reduction(+:nr_success) for (int try_nr = 0; try_nr < nr_tries; try_nr++) { double x = ((double) rand())/((double) RAND_MAX); double y = ((double) rand())/((double) RAND_MAX); if (x*x + y*y < 1.0) nr_success++; } } double pi = 4.0*((double) nr_success)/((double) nr_tries); printf("pi = %lf\n", pi); return 0; }
main.c
/*-----------------------------------------------------------------------*/ /* Program: STREAM */ /* Revision: $Id: stream.c,v 5.10 2013/01/17 16:01:06 mccalpin Exp mccalpin $ */ /* Original code developed by John D. McCalpin */ /* Programmers: John D. McCalpin */ /* Joe R. Zagar */ /* */ /* This program measures memory transfer rates in MB/s for simple */ /* computational kernels coded in C. */ /*-----------------------------------------------------------------------*/ /* Copyright 1991-2013: John D. McCalpin */ /*-----------------------------------------------------------------------*/ /* License: */ /* 1. You are free to use this program and/or to redistribute */ /* this program. */ /* 2. You are free to modify this program for your own use, */ /* including commercial use, subject to the publication */ /* restrictions in item 3. */ /* 3. You are free to publish results obtained from running this */ /* program, or from works that you derive from this program, */ /* with the following limitations: */ /* 3a. In order to be referred to as "STREAM benchmark results", */ /* published results must be in conformance to the STREAM */ /* Run Rules, (briefly reviewed below) published at */ /* http://www.cs.virginia.edu/stream/ref.html */ /* and incorporated herein by reference. */ /* As the copyright holder, John McCalpin retains the */ /* right to determine conformity with the Run Rules. */ /* 3b. Results based on modified source code or on runs not in */ /* accordance with the STREAM Run Rules must be clearly */ /* labelled whenever they are published. Examples of */ /* proper labelling include: */ /* "tuned STREAM benchmark results" */ /* "based on a variant of the STREAM benchmark code" */ /* Other comparable, clear, and reasonable labelling is */ /* acceptable. */ /* 3c. Submission of results to the STREAM benchmark web site */ /* is encouraged, but not required. */ /* 4. Use of this program or creation of derived works based on this */ /* program constitutes acceptance of these licensing restrictions. */ /* 5. Absolutely no warranty is expressed or implied. */ /*-----------------------------------------------------------------------*/ #include <stdio.h> #include <io.h> #include <math.h> #include <float.h> #include <limits.h> #include "time.h" /*----------------------------------------------------------------------- * INSTRUCTIONS: * * 1) STREAM requires different amounts of memory to run on different * systems, depending on both the system cache size(s) and the * granularity of the system timer. * You should adjust the value of 'STREAM_ARRAY_SIZE' (below) * to meet *both* of the following criteria: * (a) Each array must be at least 4 times the size of the * available cache memory. I don't worry about the difference * between 10^6 and 2^20, so in practice the minimum array size * is about 3.8 times the cache size. * Example 1: One Xeon E3 with 8 MB L3 cache * STREAM_ARRAY_SIZE should be >= 4 million, giving * an array size of 30.5 MB and a total memory requirement * of 91.5 MB. * Example 2: Two Xeon E5's with 20 MB L3 cache each (using OpenMP) * STREAM_ARRAY_SIZE should be >= 20 million, giving * an array size of 153 MB and a total memory requirement * of 458 MB. * (b) The size should be large enough so that the 'timing calibration' * output by the program is at least 20 clock-ticks. * Example: most versions of Windows have a 10 millisecond timer * granularity. 20 "ticks" at 10 ms/tic is 200 milliseconds. * If the chip is capable of 10 GB/s, it moves 2 GB in 200 msec. * This means the each array must be at least 1 GB, or 128M elements. * * Version 5.10 increases the default array size from 2 million * elements to 10 million elements in response to the increasing * size of L3 caches. The new default size is large enough for caches * up to 20 MB. * Version 5.10 changes the loop index variables from "register int" * to "ssize_t", which allows array indices >2^32 (4 billion) * on properly configured 64-bit systems. Additional compiler options * (such as "-mcmodel=medium") may be required for large memory runs. * * Array size can be set at compile time without modifying the source * code for the (many) compilers that support preprocessor definitions * on the compile line. E.g., * gcc -O -DSTREAM_ARRAY_SIZE=100000000 stream.c -o stream.100M * will override the default size of 10M with a new size of 100M elements * per array. */ #ifndef STREAM_ARRAY_SIZE # define STREAM_ARRAY_SIZE 1000000 #endif /* 2) STREAM runs each kernel "NTIMES" times and reports the *best* result * for any iteration after the first, therefore the minimum value * for NTIMES is 2. * There are no rules on maximum allowable values for NTIMES, but * values larger than the default are unlikely to noticeably * increase the reported performance. * NTIMES can also be set on the compile line without changing the source * code using, for example, "-DNTIMES=7". */ #ifdef NTIMES #if NTIMES<=1 # define NTIMES 10 #endif #endif #ifndef NTIMES # define NTIMES 10 #endif /* Users are allowed to modify the "OFFSET" variable, which *may* change the * relative alignment of the arrays (though compilers may change the * effective offset by making the arrays non-contiguous on some systems). * Use of non-zero values for OFFSET can be especially helpful if the * STREAM_ARRAY_SIZE is set to a value close to a large power of 2. * OFFSET can also be set on the compile line without changing the source * code using, for example, "-DOFFSET=56". */ #ifndef OFFSET # define OFFSET 0 #endif /* * 3) Compile the code with optimization. Many compilers generate * unreasonably bad code before the optimizer tightens things up. * If the results are unreasonably good, on the other hand, the * optimizer might be too smart for me! * * For a simple single-core version, try compiling with: * cc -O stream.c -o stream * This is known to work on many, many systems.... * * To use multiple cores, you need to tell the compiler to obey the OpenMP * directives in the code. This varies by compiler, but a common example is * gcc -O -fopenmp stream.c -o stream_omp * The environment variable OMP_NUM_THREADS allows runtime control of the * number of threads/cores used when the resulting "stream_omp" program * is executed. * * To run with single-precision variables and arithmetic, simply add * -DSTREAM_TYPE=float * to the compile line. * Note that this changes the minimum array sizes required --- see (1) above. * * The preprocessor directive "TUNED" does not do much -- it simply causes the * code to call separate functions to execute each kernel. Trivial versions * of these functions are provided, but they are *not* tuned -- they just * provide predefined interfaces to be replaced with tuned code. * * * 4) Optional: Mail the results to mccalpin@cs.virginia.edu * Be sure to include info that will help me understand: * a) the computer hardware configuration (e.g., processor model, memory type) * b) the compiler name/version and compilation flags * c) any run-time information (such as OMP_NUM_THREADS) * d) all of the output from the test case. * * Thanks! * *-----------------------------------------------------------------------*/ # define HLINE "-------------------------------------------------------------\n" # ifndef MIN # define MIN(x,y) ((x)<(y)?(x):(y)) # endif # ifndef MAX # define MAX(x,y) ((x)>(y)?(x):(y)) # endif #ifndef STREAM_TYPE #define STREAM_TYPE double #endif static STREAM_TYPE a[STREAM_ARRAY_SIZE + OFFSET], b[STREAM_ARRAY_SIZE + OFFSET], c[STREAM_ARRAY_SIZE + OFFSET]; static double avgtime[4] = { 0 }, maxtime[4] = { 0 }, mintime[4] = { FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX }; static char *label[4] = { "Copy: ", "Scale: ", "Add: ", "Triad: " }; static double bytes[4] = { 2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE, 3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE }; extern double mysecond(); extern void checkSTREAMresults(); #ifdef TUNED extern void tuned_STREAM_Copy(); extern void tuned_STREAM_Scale(STREAM_TYPE scalar); extern void tuned_STREAM_Add(); extern void tuned_STREAM_Triad(STREAM_TYPE scalar); #endif #ifdef _OPENMP extern int omp_get_num_threads(); #endif int main() { int quantum, checktick(); int BytesPerWord; int k; size_t j; STREAM_TYPE scalar; double t, times[4][NTIMES]; /* --- SETUP --- determine precision and check timing --- */ printf(HLINE); printf("STREAM version $Revision: 5.10 $\n"); printf(HLINE); BytesPerWord = sizeof(STREAM_TYPE); printf("This system uses %d bytes per array element.\n", BytesPerWord); printf(HLINE); #ifdef N printf("***** WARNING: ******\n"); printf(" It appears that you set the preprocessor variable N when compiling this code.\n"); printf(" This version of the code uses the preprocesor variable STREAM_ARRAY_SIZE to control the array size\n"); printf(" Reverting to default value of STREAM_ARRAY_SIZE=%llu\n", (unsigned long long) STREAM_ARRAY_SIZE); printf("***** WARNING: ******\n"); #endif printf("Array size = %llu (elements), Offset = %d (elements)\n", (unsigned long long) STREAM_ARRAY_SIZE, OFFSET); printf("Memory per array = %.1f MiB (= %.1f GiB).\n", BytesPerWord * ((double)STREAM_ARRAY_SIZE / 1024.0 / 1024.0), BytesPerWord * ((double)STREAM_ARRAY_SIZE / 1024.0 / 1024.0 / 1024.0)); printf("Total memory required = %.1f MiB (= %.1f GiB).\n", (3.0 * BytesPerWord) * ((double)STREAM_ARRAY_SIZE / 1024.0 / 1024.), (3.0 * BytesPerWord) * ((double)STREAM_ARRAY_SIZE / 1024.0 / 1024. / 1024.)); printf("Each kernel will be executed %d times.\n", NTIMES); printf(" The *best* time for each kernel (excluding the first iteration)\n"); printf(" will be used to compute the reported bandwidth.\n"); #ifdef _OPENMP printf(HLINE); #pragma omp parallel { #pragma omp master { k = omp_get_num_threads(); printf("Number of Threads requested = %i\n", k); } } #endif #ifdef _OPENMP k = 0; #pragma omp parallel #pragma omp atomic k++; printf("Number of Threads counted = %i\n", k); #endif /* Get initial value for system clock. */ #pragma omp parallel for for (j = 0; j<STREAM_ARRAY_SIZE; j++) { a[j] = 1.0; b[j] = 2.0; c[j] = 0.0; } printf(HLINE); if ((quantum = checktick()) >= 1) printf("Your clock granularity/precision appears to be " "%d microseconds.\n", quantum); else { printf("Your clock granularity appears to be " "less than one microsecond.\n"); quantum = 1; } t = mysecond(); #pragma omp parallel for for (j = 0; j < STREAM_ARRAY_SIZE; j++) a[j] = 2.0E0 * a[j]; t = 1.0E6 * (mysecond() - t); printf("Each test below will take on the order" " of %d microseconds.\n", (int)t); printf(" (= %d clock ticks)\n", (int)(t / quantum)); printf("Increase the size of the arrays if this shows that\n"); printf("you are not getting at least 20 clock ticks per test.\n"); printf(HLINE); printf("WARNING -- The above is only a rough guideline.\n"); printf("For best results, please be sure you know the\n"); printf("precision of your system timer.\n"); printf(HLINE); /* --- MAIN LOOP --- repeat test cases NTIMES times --- */ scalar = 3.0; for (k = 0; k<NTIMES; k++) { times[0][k] = mysecond(); #ifdef TUNED tuned_STREAM_Copy(); #else #pragma omp parallel for for (j = 0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]; #endif times[0][k] = mysecond() - times[0][k]; times[1][k] = mysecond(); #ifdef TUNED tuned_STREAM_Scale(scalar); #else #pragma omp parallel for for (j = 0; j<STREAM_ARRAY_SIZE; j++) b[j] = scalar * c[j]; #endif times[1][k] = mysecond() - times[1][k]; times[2][k] = mysecond(); #ifdef TUNED tuned_STREAM_Add(); #else #pragma omp parallel for for (j = 0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j] + b[j]; #endif times[2][k] = mysecond() - times[2][k]; times[3][k] = mysecond(); #ifdef TUNED tuned_STREAM_Triad(scalar); #else #pragma omp parallel for for (j = 0; j<STREAM_ARRAY_SIZE; j++) a[j] = b[j] + scalar * c[j]; #endif times[3][k] = mysecond() - times[3][k]; } /* --- SUMMARY --- */ for (k = 1; k<NTIMES; k++) /* note -- skip first iteration */ { for (j = 0; j<4; j++) { avgtime[j] = avgtime[j] + times[j][k]; mintime[j] = MIN(mintime[j], times[j][k]); maxtime[j] = MAX(maxtime[j], times[j][k]); } } printf("Function Best Rate MB/s Avg time Min time Max time\n"); for (j = 0; j<4; j++) { avgtime[j] = avgtime[j] / (double)(NTIMES - 1); printf("%s%12.1f %11.6f %11.6f %11.6f\n", label[j], 1.0E-06 * bytes[j] / mintime[j], avgtime[j], mintime[j], maxtime[j]); } printf(HLINE); /* --- Check Results --- */ checkSTREAMresults(); printf(HLINE); return 0; } # define M 20 int checktick() { int i, minDelta, Delta; double t1, t2, timesfound[M]; /* Collect a sequence of M unique time values from the system. */ for (i = 0; i < M; i++) { t1 = mysecond(); while (((t2 = mysecond()) - t1) < 1.0E-6) ; timesfound[i] = t1 = t2; } /* * Determine the minimum difference between these M values. * This result will be our estimate (in microseconds) for the * clock granularity. */ minDelta = 1000000; for (i = 1; i < M; i++) { Delta = (int)(1.0E6 * (timesfound[i] - timesfound[i - 1])); minDelta = MIN(minDelta, MAX(Delta, 0)); } return(minDelta); } /* A gettimeofday routine to give access to the wall clock timer on most UNIX-like systems. */ double mysecond() { struct timeval tp; int i; i = gettimeofday(&tp, NULL); return ((double)tp.tv_sec + (double)tp.tv_usec * 1.e-6); } #ifndef abs #define abs(a) ((a) >= 0 ? (a) : -(a)) #endif void checkSTREAMresults() { STREAM_TYPE aj, bj, cj, scalar; STREAM_TYPE aSumErr, bSumErr, cSumErr; STREAM_TYPE aAvgErr, bAvgErr, cAvgErr; double epsilon; size_t j; int k, ierr, err; /* reproduce initialization */ aj = 1.0; bj = 2.0; cj = 0.0; /* a[] is modified during timing check */ aj = 2.0E0 * aj; /* now execute timing loop */ scalar = 3.0; for (k = 0; k<NTIMES; k++) { cj = aj; bj = scalar * cj; cj = aj + bj; aj = bj + scalar * cj; } /* accumulate deltas between observed and expected results */ aSumErr = 0.0; bSumErr = 0.0; cSumErr = 0.0; for (j = 0; j<STREAM_ARRAY_SIZE; j++) { aSumErr += abs(a[j] - aj); bSumErr += abs(b[j] - bj); cSumErr += abs(c[j] - cj); // if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN } aAvgErr = aSumErr / (STREAM_TYPE)STREAM_ARRAY_SIZE; bAvgErr = bSumErr / (STREAM_TYPE)STREAM_ARRAY_SIZE; cAvgErr = cSumErr / (STREAM_TYPE)STREAM_ARRAY_SIZE; if (sizeof(STREAM_TYPE) == 4) { epsilon = 1.e-6; } else if (sizeof(STREAM_TYPE) == 8) { epsilon = 1.e-13; } else { printf("WEIRD: sizeof(STREAM_TYPE) = %lu\n", sizeof(STREAM_TYPE)); epsilon = 1.e-6; } err = 0; if (abs(aAvgErr / aj) > epsilon) { err++; printf("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n", epsilon); printf(" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n", aj, aAvgErr, abs(aAvgErr) / aj); ierr = 0; for (j = 0; j<STREAM_ARRAY_SIZE; j++) { if (abs(a[j] / aj - 1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n", j, aj, a[j], abs((aj - a[j]) / aAvgErr)); } #endif } } printf(" For array a[], %d errors were found.\n", ierr); } if (abs(bAvgErr / bj) > epsilon) { err++; printf("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n", epsilon); printf(" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n", bj, bAvgErr, abs(bAvgErr) / bj); printf(" AvgRelAbsErr > Epsilon (%e)\n", epsilon); ierr = 0; for (j = 0; j<STREAM_ARRAY_SIZE; j++) { if (abs(b[j] / bj - 1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n", j, bj, b[j], abs((bj - b[j]) / bAvgErr)); } #endif } } printf(" For array b[], %d errors were found.\n", ierr); } if (abs(cAvgErr / cj) > epsilon) { err++; printf("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n", epsilon); printf(" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n", cj, cAvgErr, abs(cAvgErr) / cj); printf(" AvgRelAbsErr > Epsilon (%e)\n", epsilon); ierr = 0; for (j = 0; j<STREAM_ARRAY_SIZE; j++) { if (abs(c[j] / cj - 1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n", j, cj, c[j], abs((cj - c[j]) / cAvgErr)); } #endif } } printf(" For array c[], %d errors were found.\n", ierr); } if (err == 0) { printf("Solution Validates: avg error less than %e on all three arrays\n", epsilon); } #ifdef VERBOSE printf("Results Validation Verbose Results: \n"); printf(" Expected a(1), b(1), c(1): %f %f %f \n", aj, bj, cj); printf(" Observed a(1), b(1), c(1): %f %f %f \n", a[1], b[1], c[1]); printf(" Rel Errors on a, b, c: %e %e %e \n", abs(aAvgErr / aj), abs(bAvgErr / bj), abs(cAvgErr / cj)); #endif } #ifdef TUNED /* stubs for "tuned" versions of the kernels */ void tuned_STREAM_Copy() { ssize_t j; #pragma omp parallel for for (j = 0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j]; } void tuned_STREAM_Scale(STREAM_TYPE scalar) { ssize_t j; #pragma omp parallel for for (j = 0; j<STREAM_ARRAY_SIZE; j++) b[j] = scalar * c[j]; } void tuned_STREAM_Add() { ssize_t j; #pragma omp parallel for for (j = 0; j<STREAM_ARRAY_SIZE; j++) c[j] = a[j] + b[j]; } void tuned_STREAM_Triad(STREAM_TYPE scalar) { ssize_t j; #pragma omp parallel for for (j = 0; j<STREAM_ARRAY_SIZE; j++) a[j] = b[j] + scalar * c[j]; } /* end of stubs for the "tuned" versions of the kernels */ #endif
signalMachine.c
#include <getopt.h> #include <string.h> #include "fasta_handler.h" #define ESTIMATE_PARAMS 1 #define ASSIGNMENT_THRESHOLD 0.1 typedef enum { full = 0, variantCaller = 1, assignments = 2, both = 3 } OutputFormat; void usage() { fprintf(stderr, "\n\tsignalMachine - Align ONT ionic current to a reference sequence\n\n"); fprintf(stderr, "--help: Display this super useful message and exit\n"); fprintf(stderr, "--sm3Hdp, -d: Flag, enable HMM-HDP model\n"); fprintf(stderr, "--twoD, -e: Flag, use 2D workflow (enables complement alignment)\n"); fprintf(stderr, "-s: Output format, 0=full, 1=variantCaller, 2=assignments\n"); fprintf(stderr, "-o: Degernate, 0=C/E, 1=C/E/O, 2=A/I, 3=A/C/G/T, 4=J/T, 5=A/F"); fprintf(stderr, "-T: Template HMM model\n"); fprintf(stderr, "-C: Complement HMM model\n"); fprintf(stderr, "-L: Read (output) label\n"); fprintf(stderr, "-q: NanoporeRead (in npRead format)\n"); fprintf(stderr, "-f: Forward reference to align to as a flat file\n"); fprintf(stderr, "-b: Backward reference to align to as a flat file\n"); fprintf(stderr, "-p: Guide alignment file, containing CIGARs in EXONERATE format\n"); fprintf(stderr, "-u: Posteriors (output) file path, place to put the output\n"); fprintf(stderr, "-v: TemplateHDP file\n"); fprintf(stderr, "-w: Complement HDP file\n"); fprintf(stderr, "-t: Template expectations (HMM transitions) output location\n"); fprintf(stderr, "-c: Complement expectations (HMM transitions) output location\n"); fprintf(stderr, "-x: Diagonal expansion, how much to expand the dynamic programming envelope\n"); fprintf(stderr, "-D: Posterior probability threshold, keep aligned pairs with posterior prob >= this\n"); fprintf(stderr, "-m: Constranint trim, how much to trim the guide alignment anchors by\n"); fprintf(stderr, "-g: traceBackDiagonals, how many backward diagonals to calculate during traceback\n"); fprintf(stderr, "-r: boolean option if read is RNA\n\n"); } void printPairwiseAlignmentSummary(struct PairwiseAlignment *pA) { st_uglyf("contig 1: %s\n", pA->contig1); st_uglyf("strand 1: %lld\n", pA->strand1); st_uglyf("start 1: %lld\n", pA->start1); st_uglyf("end 1: %lld\n", pA->end1); st_uglyf("contig 2: %s\n", pA->contig2); st_uglyf("strand 2: %lld\n", pA->strand2); st_uglyf("start 2: %lld\n", pA->start2); st_uglyf("end 2: %lld\n", pA->end2); } static inline int64_t adjustReferenceCoordinate(int64_t x_i, int64_t referenceSeqOffset, int64_t referenceLengthInKmers, int64_t referenceLength, Strand strand, bool forward) { if ((strand == template && forward) || (strand == complement && !forward)) { return x_i + referenceSeqOffset; } else { return referenceLengthInKmers - (x_i + (referenceLength - referenceSeqOffset)); } } static inline char *makeReferenceKmer(const char *k_i, Strand strand, bool forward) { if ((strand == template && forward) || (strand == complement && !forward)) { return stString_copy(k_i); } else { return stString_reverseComplementString(k_i); } } static inline char *kmerFromString(const char *string, int64_t start, int64_t kmerLength) { char *k_i = st_malloc((kmerLength + 1) * sizeof(char)); for (int64_t i = 0; i < kmerLength; i++) { k_i[i] = *(string + (start + i)); } k_i[kmerLength] = '\0'; return k_i; } static inline int64_t adjustQueryPosition(int64_t unadjustedQueryPosition, int64_t kmerLength, Strand strand, bool forward) { if ((strand == template && forward) || (strand == complement && !forward)) { return unadjustedQueryPosition; } else { return (kmerLength - 1) - unadjustedQueryPosition; } } void writePosteriorProbsFull(char *posteriorProbsFile, char *readLabel, StateMachine *sM, NanoporeReadAdjustmentParameters npp, double *events, char *target, bool forward, char *contig, int64_t eventSequenceOffset, int64_t referenceSequenceOffset, stList *alignedPairs, Strand strand, bool rna) { // label for tsv output char *strandLabel = strand == template ? "t" : "c"; // open the file for output FILE *fH = fopen(posteriorProbsFile, "a"); // get some lengths outside the loop int64_t refLength = (int64_t )strlen(target); int64_t refLengthInKmers = refLength - sM->kmerLength; // printf("%" PRIu64 "\n", stList_length(alignedPairs)); for(int64_t i = 0; i < stList_length(alignedPairs); i++) { // grab the aligned pair stIntTuple *aPair = stList_get(alignedPairs, i); if (stIntTuple_length(aPair) != 4) { st_errAbort("Aligned pair tuples should have length 4, this one has length %lld\n", stIntTuple_length(aPair)); } // nucleotide sequence coordinate int64_t x_i = stIntTuple_get(aPair, 1); // adjust back to reference coordinates int64_t x_adj = adjustReferenceCoordinate(x_i, referenceSequenceOffset, refLengthInKmers, refLength, strand, forward); // event index, adjust to to entire event sequence coordinates (event sequence is trimmed during alignment) int64_t y = stIntTuple_get(aPair, 2) + eventSequenceOffset; // posterior probability double p = ((double)stIntTuple_get(aPair, 0)) / PAIR_ALIGNMENT_PROB_1; // path (variant-called) kmer char *pathKmer = (char *)stIntTuple_get(aPair, 3); double eventMean = sequence_getEventMean(events, y); double eventNoise = sequence_getEventNoise(events, y); double eventDuration = sequence_getEventDuration(events, y); // make the kmer string at the target index, char *k_i = kmerFromString(target, x_i, sM->kmerLength); int64_t targetKmerIndex = kmer_id(pathKmer, sM->alphabet, sM->alphabetSize, sM->kmerLength); // get the expected event mean amplitude and noise double E_mean = sM->EMISSION_MATCH_MATRIX[(targetKmerIndex * MODEL_PARAMS)]; double E_noise = sM->EMISSION_MATCH_MATRIX[(targetKmerIndex * MODEL_PARAMS + 2)]; double scaled_Emean = E_mean * npp.scale + npp.shift; double scaled_Enoise = E_noise * npp.scale_sd; double descaledEventMean = emissions_signal_descaleEventMean_JordanStyle(eventMean, E_mean, npp.scale, npp.shift, npp.var); // make reference kmer char *refKmer = makeReferenceKmer(k_i, strand, forward); if (rna){ refKmer = stString_reverseComplementString(refKmer); } // write to file fprintf(fH, "%s\t%"PRId64"\t%s\t%s\t%s\t%"PRId64"\t%f\t%f\t%f\t%s\t%f\t%f\t%f\t%f\t%f\t%s\n", contig, x_adj, refKmer, readLabel, strandLabel, y, eventMean, eventNoise, eventDuration, k_i, scaled_Emean, scaled_Enoise, p, descaledEventMean, E_mean, pathKmer); // cleanup free(k_i); free(refKmer); } fclose(fH); } void writePosteriorProbsVC(char *posteriorProbsFile, char *readLabel, StateMachine *sM, char *target, bool forward, int64_t eventSequenceOffset, int64_t referenceSequenceOffset, stList *alignedPairs, Strand strand, double posteriorScore, bool rna, char *contig) { // label for tsv output char *strandLabel = strand == template ? "t" : "c"; if (rna || strand != template){ forward = !forward; } char *forwardLabel = forward ? "forward" : "backward"; if (rna || strand != template){ forward = !forward; } // open the file for output FILE *fH = fopen(posteriorProbsFile, "a"); // get some lengths outside the loop int64_t refLength = (int64_t )strlen(target); int64_t refLengthInKmers = refLength - sM->kmerLength; for(int64_t i = 0; i < stList_length(alignedPairs); i++) { // grab the aligned pair stIntTuple *aPair = stList_get(alignedPairs, i); if (stIntTuple_length(aPair) != 4) { st_errAbort("Aligned pair tuples should have length 4, this one has length %lld\n", stIntTuple_length(aPair)); } // trimmed nucleotide sequence coordinate int64_t x_i = stIntTuple_get(aPair, 1); // make the kmer string at the target index, char *k_i = kmerFromString(target, x_i, sM->kmerLength); char *refKmer = makeReferenceKmer(k_i, strand, forward); stList *queryPositions = path_findDegeneratePositions(refKmer, sM->kmerLength); // check if this aligned pair reports on a query position if (stList_length(queryPositions) == 0) { free(k_i); free(refKmer); stList_destruct(queryPositions); continue; } // adjust back to reference coordinates int64_t x_adj = adjustReferenceCoordinate(x_i, referenceSequenceOffset, refLengthInKmers, refLength, strand, forward); // event index, adjust to to entire event sequence coordinates (event sequence is trimmed during alignment) int64_t y = stIntTuple_get(aPair, 2) + eventSequenceOffset; // posterior probability double p = ((double)stIntTuple_get(aPair, 0)) / PAIR_ALIGNMENT_PROB_1; // path (variant-called) kmer char *pathKmer = (char *)stIntTuple_get(aPair, 3); // get the base that was called in this aligned pair int64_t nQueryPositions = stList_length(queryPositions); for (int64_t q = 0; q < nQueryPositions; q++) { // position in the reference kmer eg. AGXGG -> 2 int64_t unadjustedQueryPosition = *(int64_t *)stList_get(queryPositions, q); // position in the pathKmer int64_t queryPosition = adjustQueryPosition(unadjustedQueryPosition, sM->kmerLength, strand, forward); // called base char base = pathKmer[queryPosition]; // position in the reference we're reporting on int64_t reportPosition = x_adj + unadjustedQueryPosition; fprintf(fH, "%"PRId64"\t%"PRId64"\t%c\t%f\t%s\t%s\t%s\t%f\t%s\n", y, reportPosition, base, p, strandLabel, forwardLabel, readLabel, posteriorScore, contig); } free(k_i); free(refKmer); stList_destruct(queryPositions); } fclose(fH); } void writeAssignments(char *posteriorProbsFile, StateMachine *sM, double *events, int64_t eventSequenceOffset, NanoporeReadAdjustmentParameters npp, stList *alignedPairs, Strand strand) { // label for tsv output char *strandLabel = strand == template ? "t" : "c"; // open the file for output FILE *fH = fopen(posteriorProbsFile, "a"); for(int64_t i = 0; i < stList_length(alignedPairs); i++) { // grab the aligned pair stIntTuple *aPair = stList_get(alignedPairs, i); if (stIntTuple_length(aPair) != 4) { st_errAbort("Aligned pair tuples should have length 4, this one has length %lld\n", stIntTuple_length(aPair)); } // event index, adjust to to entire event sequence coordinates (event sequence is trimmed during alignment) int64_t y = stIntTuple_get(aPair, 2) + eventSequenceOffset; // posterior probability double p = ((double)stIntTuple_get(aPair, 0)) / PAIR_ALIGNMENT_PROB_1; // path (variant-called) kmer char *pathKmer = (char *)stIntTuple_get(aPair, 3); // get the observed event mean double eventMean = sequence_getEventMean(events, y); // get the kmer index int64_t targetKmerIndex = kmer_id(pathKmer, sM->alphabet, sM->alphabetSize, sM->kmerLength); // get the expected mean from the model double E_mean = sM->EMISSION_MATCH_MATRIX[(targetKmerIndex * MODEL_PARAMS)]; // descale the observed mean double descaledEventMean = emissions_signal_descaleEventMean_JordanStyle(eventMean, E_mean, npp.scale, npp.shift, npp.var); fprintf(fH, "%s\t%s\t%lf\t%lf\n", pathKmer, strandLabel, descaledEventMean, p); } fclose(fH); } void outputAlignment( OutputFormat fmt, char *posteriorProbsFile, char *readLabel, StateMachine *sM, NanoporeReadAdjustmentParameters npp, double *events, char *target, bool forward, char *contig, int64_t eventSequenceOffset, int64_t referenceSequenceOffset, stList *alignedPairs, double posteriorScore, Strand strand, bool rna, char *posteriorProbsFile2) { switch (fmt) { case full: writePosteriorProbsFull(posteriorProbsFile, readLabel, sM, npp, events, target, forward, contig, eventSequenceOffset, referenceSequenceOffset, alignedPairs, strand, rna); break; case variantCaller: writePosteriorProbsVC(posteriorProbsFile, readLabel, sM, target, forward, eventSequenceOffset, referenceSequenceOffset, alignedPairs, strand, posteriorScore, rna, contig); break; case assignments: writeAssignments(posteriorProbsFile, sM, events, eventSequenceOffset, npp, alignedPairs, strand); break; case both: writePosteriorProbsFull(posteriorProbsFile, readLabel, sM, npp, events, target, forward, contig, eventSequenceOffset, referenceSequenceOffset, alignedPairs, strand, rna); writePosteriorProbsVC(posteriorProbsFile2, readLabel, sM, target, forward, eventSequenceOffset, referenceSequenceOffset, alignedPairs, strand, posteriorScore, rna, contig); break; default: fprintf(stderr, "signalAlign - No valid output format provided\n"); return; } } StateMachine *buildStateMachine(const char *modelFile, NanoporeReadAdjustmentParameters npp, StateMachineType type, NanoporeHDP *nHdp) { if ((type != threeState) && (type != threeStateHdp)) { st_errAbort("signalAlign - incompatible stateMachine type request"); } if (!stFile_exists(modelFile)) { st_errAbort("signalAlign - ERROR: couldn't find model file here: %s\n", modelFile); } if (type == threeState) { StateMachine *sM = getStateMachine3_descaled(modelFile, npp, !ESTIMATE_PARAMS); return sM; } if (type == threeStateHdp) { StateMachine *sM = getHdpStateMachine(nHdp, modelFile, npp); return sM; } else { st_errAbort("signalAlign - ERROR: buildStateMachine, didn't get correct input\n"); } return 0; } StateMachine *buildStateMachine2(const char *modelFile, StateMachineType type, NanoporeHDP *nHdp) { if ((type != threeState) && (type != threeStateHdp)) { st_errAbort("signalAlign - incompatible stateMachine type request"); } if (!stFile_exists(modelFile)) { st_errAbort("signalAlign - ERROR: couldn't find model file here: %s\n", modelFile); } if (type == threeState) { StateMachine *sM = stateMachine3_loadFromFile(modelFile, threeState, emissions_kmer_getGapProb, emissions_signal_strawManGetKmerEventMatchProbWithDescaling_MeanOnly, stateMachine3_loadTransitionsFromFile, NULL); return sM; } if (type == threeStateHdp) { StateMachine *sM = stateMachine3_loadFromFile(modelFile, threeStateHdp, NULL, emissions_signal_getHdpKmerDensity, stateMachine3_loadTransitionsFromFile, nHdp); return sM; } else { st_errAbort("signalAlign - ERROR: buildStateMachine, didn't get correct input\n"); } return 0; } inline void loadHmmRoutine(const char *hmmFile, StateMachine *sM, StateMachineType type, Hmm *expectations) { if ((type != threeState) && (type != threeStateHdp)) { st_errAbort("LoadSignalHmm : unupported stateMachineType"); } hmmContinuous_loadSignalHmm(hmmFile, sM, type, expectations); } StateMachine *buildStateMachineAndLoadHmm(const char *modelFile, NanoporeReadAdjustmentParameters npp, StateMachineType type, NanoporeHDP *nHdp) { StateMachine *sM = buildStateMachine(modelFile, npp, type, nHdp); // commented out because now the model file has the transitions and the event model, so no longer need to // load the .hmm into the stateMachine //if (HmmFile != NULL) { // loadHmmRoutine(HmmFile, sM, sM->type, hmmExpectations); //} return sM; } void updateHdpFromAssignments(const char *nHdpFile, const char *expectationsFile, const char *nHdpOutFile) { NanoporeHDP *nHdp = deserialize_nhdp(nHdpFile); Hmm *hdpHmm = hdpHmm_loadFromFile(expectationsFile, threeStateHdp, nHdp); hmmContinuous_destruct(hdpHmm, hdpHmm->type); fprintf(stderr, "signalAlign - Running Gibbs on HDP\n"); execute_nhdp_gibbs_sampling(nHdp, 10000, 100000, 100, FALSE); finalize_nhdp_distributions(nHdp); fprintf(stderr, "signalAlign - Serializing HDP to %s\n", nHdpOutFile); serialize_nhdp(nHdp, nHdpOutFile); destroy_nanopore_hdp(nHdp); } static double totalScore(stList *alignedPairs) { double score = 0.0; for (int64_t i = 0; i < stList_length(alignedPairs); i++) { stIntTuple *aPair = stList_get(alignedPairs, i); score += stIntTuple_get(aPair, 0); } return score; } double scoreByPosteriorProbabilityIgnoringGaps(stList *alignedPairs) { /* * Gives the average posterior match probability per base of the two sequences, ignoring indels. */ return 100.0 * totalScore(alignedPairs) / ((double) stList_length(alignedPairs) * PAIR_ALIGNMENT_PROB_1); } stList *performSignalAlignment(StateMachine *sM, Sequence *eventSequence, int64_t *eventMap, int64_t mapOffset, char *target, PairwiseAlignmentParameters *p, stList *unmappedAnchors, char *ambig_path) { if ((sM->type != threeState) && (sM->type != threeStateHdp)) { st_errAbort("signalAlign - You're trying to do the wrong king of alignment"); } int64_t lX = sequence_correctSeqLength(strlen(target), kmer, sM->kmerLength); // remap anchor pairs stList *filteredRemappedAnchors = signalUtils_getRemappedAnchorPairs(unmappedAnchors, eventMap, mapOffset); // make sequences stHash* ambigBases = create_ambig_bases2(ambig_path); Sequence *sX = sequence_constructKmerSequence(lX, target, sequence_getKmer, sequence_sliceNucleotideSequence, kmer, ambigBases); // do alignment stList *alignedPairs = getAlignedPairsUsingAnchors(sM, sX, eventSequence, filteredRemappedAnchors, p, diagonalCalculationPosteriorMatchProbs, 1, 1); sequence_destruct(sX); return alignedPairs; } Sequence *makeEventSequenceFromPairwiseAlignment(double *events, int64_t queryStart, int64_t queryEnd, int64_t *eventMap) { // find the event mapped to the start and end of the 2D read alignment int64_t startIdx = eventMap[queryStart]; // We end up indexing past length of eventMap if we map to final base int64_t endIdx = eventMap[queryEnd-1]; // move the event pointer to the first event size_t elementSize = sizeof(double); void *elements = (char *)events + ((startIdx * NB_EVENT_PARAMS) * elementSize); // make the eventSequence Sequence *eventS = sequence_constructEventSequence(endIdx - startIdx, elements); return eventS; } void getSignalExpectations(StateMachine *sM, Hmm *hmmExpectations, Sequence *eventSequence, int64_t *eventMap, int64_t mapOffset, char *trainingTarget, PairwiseAlignmentParameters *p, stList *unmappedAnchors, char *ambig_path) { // correct sequence length int64_t lX = sequence_correctSeqLength(strlen(trainingTarget), event, sM->kmerLength); // remap the anchors stList *filteredRemappedAnchors = signalUtils_getRemappedAnchorPairs(unmappedAnchors, eventMap, mapOffset); stHash* ambigBases = create_ambig_bases2(ambig_path); Sequence *target = sequence_constructKmerSequence( lX, trainingTarget, sequence_getKmer, sequence_sliceNucleotideSequence, kmer, ambigBases); getExpectationsUsingAnchors(sM, hmmExpectations, target, eventSequence, filteredRemappedAnchors, p, diagonalCalculation_Expectations, 1, 1); } int main(int argc, char *argv[]) { StateMachineType sMtype = threeState; int64_t j = 0; int64_t diagExpansion = 50; double threshold = 0.01; int64_t constraintTrim = 14; int64_t traceBackDiagonals = 50; int64_t outFmt; bool twoD = FALSE; bool rna = FALSE; char *templateModelFile = NULL; char *complementModelFile = NULL; char *readLabel = NULL; char *npReadFile = NULL; char *exonerateCigarFile= NULL; char *posteriorProbsFile = NULL; char *templateExpectationsFile = NULL; char *complementExpectationsFile = NULL; char *templateHdp = NULL; char *complementHdp = NULL; char *forward_reference_path = NULL; char *backward_reference_path = NULL; char *posteriorProbsFile2 = NULL; const char *sequence_name = NULL; char *ambig_model = NULL; int key; while (1) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"sm3Hdp", no_argument, 0, 'd'}, {"sparse_output", no_argument, 0, 's'}, {"twoD", no_argument, 0, 'e'}, {"rna", no_argument, 0, 'r'}, {"templateModel", required_argument, 0, 'T'}, {"complementModel", required_argument, 0, 'C'}, {"readLabel", required_argument, 0, 'L'}, {"npRead", required_argument, 0, 'q'}, {"exonerate_cigar_file", required_argument, 0, 'p'}, {"posteriors", required_argument, 0, 'u'}, {"templateHdp", required_argument, 0, 'v'}, {"complementHdp", required_argument, 0, 'w'}, {"templateExpectations", required_argument, 0, 't'}, {"complementExpectations", required_argument, 0, 'c'}, {"diagonalExpansion", required_argument, 0, 'x'}, {"threshold", required_argument, 0, 'D'}, {"constraintTrim", required_argument, 0, 'm'}, {"forward_reference_path", required_argument, 0, 'f'}, {"backward_reference_path", optional_argument, 0, 'b'}, {"sequence_name", required_argument, 0, 'n'}, {"traceBackDiagonals", optional_argument, 0, 'g'}, {"posteriorProbsFile2", optional_argument, 0, 'i'}, {"ambig_model", optional_argument, 0, 'a'}, {0, 0, 0, 0} }; int option_index = 0; key = getopt_long(argc, argv, "h:d:e:s:r:o:a:T:C:a:L:q:f:b:g:i:p:u:v:w:t:c:x:D:m:n:", long_options, &option_index); if (key == -1) { //usage(); break; } switch (key) { case 'h': usage(); return 1; case 's': j = sscanf(optarg, "%" PRIi64 "", &outFmt); assert (j == 1); break; case 'e': twoD = TRUE; break; case 'a': ambig_model = stString_copy(optarg); break; case 'r': rna = TRUE; break; case 'd': sMtype = threeStateHdp; break; case 'T': templateModelFile = stString_copy(optarg); break; case 'C': complementModelFile = stString_copy(optarg); break; case 'L': readLabel = stString_copy(optarg); break; case 'q': npReadFile = stString_copy(optarg); break; case 'p': exonerateCigarFile = stString_copy(optarg); break; case 'u': posteriorProbsFile = stString_copy(optarg); break; case 't': templateExpectationsFile = stString_copy(optarg); break; case 'c': complementExpectationsFile = stString_copy(optarg); break; case 'v': templateHdp = stString_copy(optarg); break; case 'w': complementHdp = stString_copy(optarg); break; case 'x': j = sscanf(optarg, "%" PRIi64 "", &diagExpansion); assert (j == 1); assert (diagExpansion >= 0); diagExpansion = (int64_t)diagExpansion; break; case 'D': j = sscanf(optarg, "%lf", &threshold); assert (j == 1); assert (threshold >= 0); break; case 'm': j = sscanf(optarg, "%" PRIi64 "", &constraintTrim); assert (j == 1); assert (constraintTrim >= 0); constraintTrim = (int64_t)constraintTrim; break; case 'f': forward_reference_path = stString_copy(optarg); break; case 'b': backward_reference_path = stString_copy(optarg); break; case 'n': sequence_name = stString_copy(optarg); break; case 'g': j = sscanf(optarg, "%" PRIi64 "", &traceBackDiagonals); assert (j == 1); assert (traceBackDiagonals >= 0); traceBackDiagonals = (int64_t)traceBackDiagonals; break; case 'i': posteriorProbsFile2 = stString_copy(optarg); break; default: usage(); return 1; } } (void) j; // silence unused variable warning. // check for models if ((templateModelFile == NULL) || (complementModelFile == NULL && twoD)) { st_errAbort("Missing model files, exiting\n"); return 1; } if ((outFmt == 3) & (posteriorProbsFile2 == NULL)) { st_errAbort("Must pass in posteriorProbsFile2 if using 'both' outFmt\n"); return 1; } if (exonerateCigarFile == NULL) { st_errAbort("[signalMachine]ERROR: Need to provide input guide alignments, exiting\n"); return 1; } // Anchors // // get pairwise alignment from stdin, in exonerate CIGAR format //FILE *fileHandleIn = stdin; if (!stFile_exists(exonerateCigarFile)) { st_errAbort("[signalMachine]ERROR: Didn't find input alignment file, looked %s\n", exonerateCigarFile); } else { st_uglyf("[signalMachine]NOTICE: Using guide alignments from %s\n", exonerateCigarFile); } FILE *fileHandleIn = fopen(exonerateCigarFile, "r"); // parse input CIGAR to get anchors struct PairwiseAlignment *pA; pA = cigarRead(fileHandleIn); fclose(fileHandleIn); // Alignment Parameters // // make the pairwise alignment parameters PairwiseAlignmentParameters *p = pairwiseAlignmentBandingParameters_construct(); p->threshold = threshold; p->constraintDiagonalTrim = constraintTrim; p->diagonalExpansion = diagExpansion % 2 == 0 ? diagExpansion: diagExpansion+1; p->traceBackDiagonals = traceBackDiagonals; // HDP routines // // load HDPs NanoporeHDP *nHdpT, *nHdpC; // check if ((templateHdp != NULL) || (complementHdp != NULL)) { if ((templateHdp == NULL) || (complementHdp == NULL && twoD)) { st_errAbort("Need to have template and complement HDPs"); } if (sMtype != threeStateHdp) { sMtype = threeStateHdp; fprintf(stderr, "[signalAlign] - Using threeStateHdp stateMachine since you pass in an HDP file\n"); } else { fprintf(stderr, "[signalAlign] - using NanoporeHDPs\n"); } } #pragma omp parallel sections default(none) shared(nHdpT, nHdpC, templateHdp, complementHdp) { { nHdpT = (templateHdp == NULL) ? NULL : deserialize_nhdp(templateHdp); } #pragma omp section { nHdpC = (complementHdp == NULL) ? NULL : deserialize_nhdp(complementHdp); } } StateMachine *sMt = buildStateMachine2(templateModelFile, sMtype, nHdpT); StateMachine *sMc; if (twoD){ sMc = buildStateMachine2(complementModelFile, sMtype, nHdpC); } // Nanopore Read // // load nanopore read NanoporeRead *npRead = nanopore_loadNanoporeReadFromFile(npReadFile, sMt->alphabet, sMt->alphabetSize); if (rna){ int64_t tmp = pA->start2; pA->start2 = npRead->templateReadLength - pA->end2; pA->end2 = npRead->templateReadLength - tmp; } ReferenceSequence *R; R = fastaHandler_ReferenceSequenceConstructFull(forward_reference_path, backward_reference_path, pA, sequence_name, rna); // constrain the event sequence to the positions given by the guide alignment Sequence *tEventSequence = makeEventSequenceFromPairwiseAlignment(npRead->templateEvents, pA->start2, pA->end2, (twoD ? npRead->templateEventMap : npRead->templateStrandEventMap)); Sequence *cEventSequence; if (twoD) { cEventSequence = makeEventSequenceFromPairwiseAlignment(npRead->complementEvents, pA->start2, pA->end2, npRead->complementEventMap); } else { cEventSequence = NULL; } // the aligned pairs start at (0,0) so we need to correct them based on the guide alignment later. // record the pre-zeroed alignment start and end coordinates here // for the events: int64_t tCoordinateShift = twoD ? npRead->templateEventMap[pA->start2] : npRead->templateStrandEventMap[pA->start2]; int64_t cCoordinateShift = twoD ? npRead->complementEventMap[pA->start2] : 0; // and for the reference: int64_t rCoordinateShift_t = pA->start1; int64_t rCoordinateShift_c = twoD ? pA->end1 : 0; bool forward = pA->strand1; // keep track of whether this is a forward mapped read or not stList *anchorPairs = signalUtils_guideAlignmentToRebasedAnchorPairs(pA, p); // pA gets modified here, no turning back sMt->scale = npRead->templateParams.scale; sMt->shift = npRead->templateParams.shift; sMt->var = npRead->templateParams.var; if (!ESTIMATE_PARAMS && sMtype == threeState) { emissions_signal_scaleNoise(sMt, npRead->templateParams); } if (twoD) { sMc->scale = npRead->complementParams.scale; sMc->shift = npRead->complementParams.shift; sMc->var = npRead->complementParams.var; if (!ESTIMATE_PARAMS && sMtype == threeState) { emissions_signal_scaleNoise(sMc, npRead->complementParams); } } if ((templateExpectationsFile != NULL) || (complementExpectationsFile != NULL)) { st_uglyf("Starting expectations routine\n"); // Expectation Routine // // KMER_LENGTH = sMt->kmerLength; // NUM_OF_KMERS = pow(sMt->kmerLength, sMt->alphabetSize); // temporary way to 'turn off' estimates if I want to if (ESTIMATE_PARAMS) { //todo remove threshold, not used signalUtils_estimateNanoporeParams(sMt, npRead, &npRead->templateParams, ASSIGNMENT_THRESHOLD, signalUtils_templateOneDAssignmentsFromRead, nanopore_adjustTemplateEventsForDrift); } // make empty HMM to collect expectations Hmm *templateExpectations = hmmContinuous_getExpectationsHmm(sMt, p->threshold, 0.001, 0.001); // get expectations for template fprintf(stderr, "signalAlign - getting expectations for template\n"); getSignalExpectations(sMt, templateExpectations, tEventSequence, (twoD ? npRead->templateEventMap : npRead->templateStrandEventMap), pA->start2, R->getTemplateTargetSequence(R), p, anchorPairs, ambig_model); if (sMtype == threeStateHdp) { fprintf(stderr, "signalAlign - got %" PRId64 " template HDP assignments\n", hmmContinuous_howManyAssignments(templateExpectations)); } // write to file fprintf(stderr, "signalAlign - writing expectations to file: %s\n", templateExpectationsFile); hmmContinuous_writeToFile(templateExpectationsFile, templateExpectations, sMtype); // get expectations for the complement Hmm *complementExpectations = NULL; if (twoD) { fprintf(stderr, "signalAlign - getting expectations for complement\n"); if (ESTIMATE_PARAMS) { signalUtils_estimateNanoporeParams(sMc, npRead, &npRead->complementParams, ASSIGNMENT_THRESHOLD, signalUtils_complementOneDAssignmentsFromRead, nanopore_adjustComplementEventsForDrift); } complementExpectations = hmmContinuous_getExpectationsHmm(sMc, p->threshold, 0.001, 0.001); getSignalExpectations(sMc, complementExpectations, cEventSequence, npRead->complementEventMap, pA->start2, R->getComplementTargetSequence(R), p, anchorPairs, ambig_model); if (sMtype == threeStateHdp) { fprintf(stderr, "signalAlign - got %"PRId64"complement HDP assignments\n", hmmContinuous_howManyAssignments(complementExpectations)); } // write to file fprintf(stderr, "signalAlign - writing expectations to file: %s\n", complementExpectationsFile); hmmContinuous_writeToFile(complementExpectationsFile, complementExpectations, sMtype); } stateMachine_destruct(sMt); signalUtils_ReferenceSequenceDestruct(R); hmmContinuous_destruct(templateExpectations, sMtype); nanopore_nanoporeReadDestruct(npRead); sequence_destruct(tEventSequence); pairwiseAlignmentBandingParameters_destruct(p); destructPairwiseAlignment(pA); stList_destruct(anchorPairs); if (twoD) { stateMachine_destruct(sMc); sequence_destruct(cEventSequence); hmmContinuous_destruct(complementExpectations, sMtype); } fprintf(stderr, "signalAlign - SUCCESS: finished alignment of query %s, exiting\n", readLabel); return 0; } else { // Alignment Procedure // // Template alignment fprintf(stderr, "signalAlign - starting template alignment\n"); // re-estimate the nanoporeAdjustment parameters if (ESTIMATE_PARAMS) { signalUtils_estimateNanoporeParams(sMt, npRead, &npRead->templateParams, ASSIGNMENT_THRESHOLD, signalUtils_templateOneDAssignmentsFromRead, nanopore_adjustTemplateEventsForDrift); } if (sMtype == threeStateHdp) { stateMachine3_setModelToHdpExpectedValues(sMt, nHdpT); } stList *templateAlignedPairs = performSignalAlignment(sMt, tEventSequence, (twoD ? npRead->templateEventMap : npRead->templateStrandEventMap), pA->start2, R->getTemplateTargetSequence(R), p, anchorPairs, ambig_model); double templatePosteriorScore = scoreByPosteriorProbabilityIgnoringGaps(templateAlignedPairs); // sort stList_sort(templateAlignedPairs, sortByXPlusYCoordinate2); //Ensure the coordinates are increasing // write to file if (posteriorProbsFile != NULL) { outputAlignment(outFmt, posteriorProbsFile, readLabel, sMt, npRead->templateParams, npRead->templateEvents, R->getTemplateTargetSequence(R), forward, pA->contig1, tCoordinateShift, rCoordinateShift_t, templateAlignedPairs, templatePosteriorScore,template, rna, posteriorProbsFile2); } stList *complementAlignedPairs; double complementPosteriorScore = 0.0; if (twoD) { // Complement alignment fprintf(stderr, "signalAlign - starting complement alignment\n"); if (ESTIMATE_PARAMS) { signalUtils_estimateNanoporeParams(sMc, npRead, &npRead->complementParams, ASSIGNMENT_THRESHOLD, signalUtils_complementOneDAssignmentsFromRead, nanopore_adjustComplementEventsForDrift); } if (sMtype == threeStateHdp) { stateMachine3_setModelToHdpExpectedValues(sMc, nHdpC); } complementAlignedPairs = performSignalAlignment(sMc, cEventSequence, npRead->complementEventMap, pA->start2, R->getComplementTargetSequence(R), p, anchorPairs, ambig_model); complementPosteriorScore = scoreByPosteriorProbabilityIgnoringGaps(complementAlignedPairs); // sort stList_sort(complementAlignedPairs, sortByXPlusYCoordinate2); //Ensure the coordinates are increasing // write to file if (posteriorProbsFile != NULL) { outputAlignment(outFmt, posteriorProbsFile, readLabel, sMc, npRead->complementParams, npRead->complementEvents, R->getComplementTargetSequence(R), forward, pA->contig1, cCoordinateShift, rCoordinateShift_c, complementAlignedPairs, complementPosteriorScore, complement, rna, posteriorProbsFile2); } } fprintf(stdout, "%s %"PRId64"\t%"PRId64"(%f)\t", readLabel, stList_length(anchorPairs), stList_length(templateAlignedPairs), templatePosteriorScore); if (twoD) { fprintf(stdout, "%"PRId64"(%f)\n", stList_length(complementAlignedPairs), complementPosteriorScore); } else { fprintf(stdout, "\n"); } // final alignment clean up destructPairwiseAlignment(pA); nanopore_nanoporeReadDestruct(npRead); signalUtils_ReferenceSequenceDestruct(R); stateMachine_destruct(sMt); sequence_destruct(tEventSequence); stList_destruct(templateAlignedPairs); if (twoD) { stateMachine_destruct(sMc); sequence_destruct(cEventSequence); stList_destruct(complementAlignedPairs); } fprintf(stderr, "signalAlign - SUCCESS: finished alignment of query %s, exiting\n", readLabel); } return 0; }
simulate_blif.c
/* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "simulate_blif.h" #ifndef max #define max(a,b) (((a) > (b))? (a) : (b)) #define min(a,b) ((a) > (b)? (b) : (a)) #endif /* * Performs simulation. */ void simulate_netlist(netlist_t *netlist) { printf("Beginning simulation.\n"); fflush(stdout); // Create and verify the lines. lines_t *input_lines = create_lines(netlist, INPUT); if (!verify_lines(input_lines)) error_message(SIMULATION_ERROR, 0, -1, "Input lines could not be assigned."); lines_t *output_lines = create_lines(netlist, OUTPUT); if (!verify_lines(output_lines)) error_message(SIMULATION_ERROR, 0, -1, "Output lines could not be assigned."); // Open the output vector file. FILE *out = fopen(OUTPUT_VECTOR_FILE_NAME, "w"); if (!out) error_message(SIMULATION_ERROR, 0, -1, "Could not open output vector file."); // Open the input vector file. FILE *in_out = fopen( INPUT_VECTOR_FILE_NAME, "w"); if (!in_out) error_message(SIMULATION_ERROR, 0, -1, "Could not open input vector file."); // Open the modelsim vector file. FILE *modelsim_out = fopen("test.do", "w"); if (!modelsim_out) error_message(SIMULATION_ERROR, 0, -1, "Could not open modelsim output file."); FILE *in = NULL; int num_vectors; // Passed via the -t option. char *input_vector_file = global_args.sim_vector_input_file; // Input vectors can either come from a file or be randomly generated. if (input_vector_file) { in = fopen(input_vector_file, "r"); if (!in) error_message(SIMULATION_ERROR, 0, -1, "Could not open vector input file: %s", input_vector_file); num_vectors = count_test_vectors(in); // Read the vector headers and check to make sure they match the lines. if (!verify_test_vector_headers(in, input_lines)) error_message(SIMULATION_ERROR, 0, -1, "Invalid vector header format in %s.", input_vector_file); printf("Simulating %d existing vectors from \"%s\".\n", num_vectors, input_vector_file); fflush(stdout); } else { // Passed via the -g option. num_vectors = global_args.sim_num_test_vectors; printf("Simulating %d new vectors.\n", num_vectors); fflush(stdout); } // Determine which edge(s) we are outputting. int output_edge; if (global_args.sim_output_both_edges ) output_edge = -1; // Both edges else if (global_args.sim_output_rising_edge) output_edge = 1; // Rising edge only else output_edge = 0; // Falling edge only if (!num_vectors) { error_message(SIMULATION_ERROR, 0, -1, "No vectors to simulate."); } else { printf("\n"); int progress_bar_position = -1; const int progress_bar_length = 50; double total_time = 0; // Includes I/O double simulation_time = 0; // Does not include I/O stages *stages = 0; // Parse -L and -H options containing lists of pins to hold high or low during random vector generation. pin_names *hold_high = parse_pin_name_list(global_args.sim_hold_high); pin_names *hold_low = parse_pin_name_list(global_args.sim_hold_low); hashtable_t *hold_high_index = index_pin_name_list(hold_high); hashtable_t *hold_low_index = index_pin_name_list(hold_low); /* * Simulation is done in "waves" of SIM_WAVE_LENGTH cycles at a time. * Every second cycle gets a input new vector. */ int num_cycles = num_vectors * 2; int num_waves = ceil(num_cycles / (double)SIM_WAVE_LENGTH); int wave; test_vector *v = 0; for (wave = 0; wave < num_waves; wave++) { double wave_start_time = wall_time(); int cycle_offset = SIM_WAVE_LENGTH * wave; int wave_length = (wave < (num_waves-1))?SIM_WAVE_LENGTH:(num_cycles - cycle_offset); // Assign vectors to lines, either by reading or generating them. // Every second cycle gets a new vector. int cycle; for (cycle = cycle_offset; cycle < cycle_offset + wave_length; cycle++) { if (is_even_cycle(cycle)) { if (input_vector_file) { char buffer[BUFFER_MAX_SIZE]; if (!get_next_vector(in, buffer)) error_message(SIMULATION_ERROR, 0, -1, "Could not read next vector."); v = parse_test_vector(buffer); } else { v = generate_random_test_vector(input_lines, cycle, hold_high_index, hold_low_index); } } add_test_vector_to_lines(v, input_lines, cycle); if (!is_even_cycle(cycle)) free_test_vector(v); } // Record the input vectors we are using. write_wave_to_file(input_lines, in_out, cycle_offset, wave_length, 1); // Write ModelSim script. write_wave_to_modelsim_file(netlist, input_lines, modelsim_out, cycle_offset, wave_length); double simulation_start_time = wall_time(); // Perform simulation for (cycle = cycle_offset; cycle < cycle_offset + wave_length; cycle++) { //original_simulate_cycle(netlist, cycle); if (cycle) { simulate_cycle(cycle, stages); } else { // The first cycle produces the stages, and adds additional // lines as specified by the -p option. pin_names *p = parse_pin_name_list(global_args.sim_additional_pins); stages = simulate_first_cycle(netlist, cycle, p, output_lines); free_pin_name_list(p); // Make sure the output lines are still OK after adding custom lines. if (!verify_lines(output_lines)) error_message(SIMULATION_ERROR, 0, -1, "Problem detected with the output lines after the first cycle."); } } simulation_time += wall_time() - simulation_start_time; // Write the result of this wave to the output vector file. write_wave_to_file(output_lines, out, cycle_offset, wave_length, output_edge); total_time += wall_time() - wave_start_time; // Print netlist-specific statistics. if (!cycle_offset) print_netlist_stats(stages, num_vectors); // Delay drawing of the progress bar until the second wave to improve the accuracy of the ETA. if ((num_waves == 1) || cycle_offset) progress_bar_position = print_progress_bar( cycle/(double)num_cycles, progress_bar_position, progress_bar_length, total_time); } free_pin_name_list(hold_high); free_pin_name_list(hold_low); hold_high_index->destroy_free_items(hold_high_index); hold_low_index ->destroy_free_items(hold_low_index); fflush(out); fprintf(modelsim_out, "run %d\n", num_vectors*100); printf("\n"); // If a second output vector file was given via the -T option, verify that it matches. char *output_vector_file = global_args.sim_vector_output_file; if (output_vector_file) { if (verify_output_vectors(output_vector_file, num_vectors)) printf("Vector file \"%s\" matches output\n", output_vector_file); else error_message(SIMULATION_ERROR, 0, -1, "Vector files differ."); printf("\n"); } // Print statistics. print_simulation_stats(stages, num_vectors, total_time, simulation_time); free_stages(stages); } free_lines(output_lines); free_lines(input_lines); fclose(modelsim_out); fclose(in_out); if (input_vector_file) fclose(in); fclose(out); } /* * This simulates a single cycle using the stages generated * during the first cycle. Simulates in parallel if OpenMP is enabled. * * OpenMP simulation computes a small number of cycles sequentially and * a small number in parallel. The minimum parallel and sequential time is * taken for each stage, and that stage is computed in parallel for all subsequent * cycles if speedup is observed. */ void simulate_cycle(int cycle, stages *s) { #ifdef _OPENMP // -1 for cycle 0, -1 for the last cycle in the wave. const int test_cycles = SIM_WAVE_LENGTH - 2; const int st_length = test_cycles/2; const int st_start = 1; const int st_end = st_start + (st_length-1); const int pt_length = test_cycles - st_length; const int pt_start = st_end + 1; const int pt_end = pt_start + (pt_length-1); if (test_cycles < 2) error_message(SIMULATION_ERROR, -1, -1, "SIM_WAVE_LENGTH is too small."); // Range of cycles over which to test the sequential run times of each stage. char sequential_test = (cycle >= st_start && cycle <= st_end); // Range of cycles over which to test the parallel run times of each stage. char parallel_test = (cycle >= pt_start && cycle <= pt_end); #endif int i; for(i = 0; i < s->count; i++) { int j; #ifdef _OPENMP double time = 0.0; if (sequential_test || parallel_test) time = wall_time(); // Compute in parallel if we are profiling or if this stage is known to be faster in parallel. char compute_in_parallel = parallel_test || (!sequential_test && !parallel_test && s->sequential_times[i] > s->parallel_times[i]); if (compute_in_parallel) { // Compute the stage in parallel. #pragma omp parallel for schedule(static) for (j = 0; j < s->counts[i]; j++) compute_and_store_value(s->stages[i][j], cycle); } else { #endif // Compute the stage sequentially. for (j = 0; j < s->counts[i]; j++) compute_and_store_value(s->stages[i][j], cycle); #ifdef _OPENMP } if (sequential_test) { // Take the minimum sequential time. time = wall_time() - time; if (s->sequential_times[i] == 0 || time < s->sequential_times[i]) s->sequential_times[i] = time; } else if (parallel_test) { // Take the minimum parallel time. time = wall_time() - time; if (s->parallel_times[i] == 0 || time < s->parallel_times[i]) s->parallel_times[i] = time; } if (cycle == pt_end + 1) { //printf("%.10f\t %.10f\t %.10f\t %d\t %d\t %f\n", s->sequential_times[i], s->parallel_times[i], s->sequential_times[i]/s->parallel_times[i], s->counts[i], compute_in_parallel, s->num_children[i]/(double)s->counts[i]); //printf("%d %d %d %d %d %d\n", st_length, pt_length, st_start, st_end, pt_start, pt_end); // Record the number of nodes in parallelizable stages. if (compute_in_parallel) s->num_parallel_nodes += s->counts[i]; } #endif } } /* * Simulates the first cycle by traversing the netlist and returns * the nodes organised into parallelizable stages. Also adds lines to * custom pins and nodes as requested via the -p option. */ stages *simulate_first_cycle(netlist_t *netlist, int cycle, pin_names *p, lines_t *l) { queue_t *queue = create_queue(); // Enqueue top input nodes int i; for (i = 0; i < netlist->num_top_input_nodes; i++) enqueue_node_if_ready(queue,netlist->top_input_nodes[i],cycle); // Enqueue constant nodes. nnode_t *constant_nodes[] = {netlist->gnd_node, netlist->vcc_node, netlist->pad_node}; int num_constant_nodes = 3; for (i = 0; i < num_constant_nodes; i++) enqueue_node_if_ready(queue,constant_nodes[i],cycle); nnode_t **ordered_nodes = 0; int num_ordered_nodes = 0; nnode_t *node; while ((node = queue->remove(queue))) { compute_and_store_value(node, cycle); // Match node for items passed via -p and add to lines if there's a match. add_additional_items_to_lines(node, p, l); // Enqueue child nodes which are ready, not already queued, and not already complete. int num_children = 0; nnode_t **children = get_children_of(node, &num_children); for (i = 0; i < num_children; i++) { nnode_t* node = children[i]; if (!node->in_queue && is_node_ready(node, cycle) && !is_node_complete(node, cycle)) { node->in_queue = TRUE; queue->add(queue,node); } } free(children); node->in_queue = FALSE; // Add the node to the ordered nodes array. ordered_nodes = realloc(ordered_nodes, sizeof(nnode_t *) * (num_ordered_nodes + 1)); ordered_nodes[num_ordered_nodes++] = node; } queue->destroy(queue); // Reorganise the ordered nodes into stages for parallel computation. stages *s = stage_ordered_nodes(ordered_nodes, num_ordered_nodes); free(ordered_nodes); return s; } /* * Puts the ordered nodes in stages, each of which can be computed in parallel. */ stages *stage_ordered_nodes(nnode_t **ordered_nodes, int num_ordered_nodes) { stages *s = malloc(sizeof(stages)); s->stages = calloc(1,sizeof(nnode_t**)); s->counts = calloc(1,sizeof(int)); s->num_children = calloc(1,sizeof(int)); s->count = 1; s->num_connections = 0; s->num_nodes = num_ordered_nodes; s->num_parallel_nodes = 0; const int index_table_size = (num_ordered_nodes/100)+10; // Hash tables index the nodes in the current stage, as well as their children. hashtable_t *stage_children = create_hashtable(index_table_size); hashtable_t *stage_nodes = create_hashtable(index_table_size); int i; for (i = 0; i < num_ordered_nodes; i++) { nnode_t* node = ordered_nodes[i]; int stage = s->count-1; // Get the node's children for dependency checks. int num_children; nnode_t **children = get_children_of(node, &num_children); // Determine if the node is a child of any node in the current stage. int is_child_of_stage = stage_children->get(stage_children, node, sizeof(nnode_t*))?1:0; // Determine if any node in the current stage is a child of this node. int is_stage_child_of = FALSE; int j; if (!is_child_of_stage) for (j = 0; j < num_children; j++) if ((is_stage_child_of = stage_nodes->get(stage_nodes, children[j], sizeof(nnode_t*))?1:0)) break; // Start a new stage if this node is related to any node in the current stage. if (is_child_of_stage || is_stage_child_of) { s->stages = realloc(s->stages, sizeof(nnode_t**) * (s->count+1)); s->counts = realloc(s->counts, sizeof(int) * (s->count+1)); s->num_children = realloc(s->num_children, sizeof(int) * (s->count+1)); stage = s->count++; s->stages[stage] = 0; s->counts[stage] = 0; s->num_children[stage] = 0; stage_children->destroy(stage_children); stage_nodes ->destroy(stage_nodes); stage_children = create_hashtable(index_table_size); stage_nodes = create_hashtable(index_table_size); } // Add the node to the current stage. s->stages[stage] = realloc(s->stages[stage],sizeof(nnode_t*) * (s->counts[stage]+1)); s->stages[stage][s->counts[stage]++] = node; // Index the node. stage_nodes->add(stage_nodes, node, sizeof(nnode_t*), node); // Index its children. for (j = 0; j < num_children; j++) stage_children->add(stage_children, children[j], sizeof(nnode_t*), children[j]); // Record the number of children for computing the degree. s->num_connections += num_children; s->num_children[stage] += num_children; free(children); } stage_children->destroy(stage_children); stage_nodes ->destroy(stage_nodes); s->sequential_times = calloc(s->count, sizeof(double)); s->parallel_times = calloc(s->count, sizeof(double)); return s; } /* * Given a node, this function will simulate that node's new outputs, * and updates those pins. */ void compute_and_store_value(nnode_t *node, int cycle) { update_undriven_input_pins(node,cycle); operation_list type = is_clock_node(node)?CLOCK_NODE:node->type; switch(type) { case MUX_2: compute_mux_2_node(node, cycle); break; case FF_NODE: compute_flipflop_node(node, cycle); break; case MEMORY: compute_memory_node(node, cycle); break; case MULTIPLY: compute_multiply_node(node, cycle); break; case LOGICAL_AND: // && { oassert(node->num_output_pins == 1); char unknown = FALSE; char zero = FALSE; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; } else if (pin == 0) { zero = TRUE; break; } } if (zero) update_pin_value(node->output_pins[0], 0, cycle); else if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else update_pin_value(node->output_pins[0], 1, cycle); break; } case LOGICAL_OR: { // || oassert(node->num_output_pins == 1); char unknown = FALSE; char one = FALSE; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; } else if (pin == 1) { one = TRUE; break; } } if (one) update_pin_value(node->output_pins[0], 1, cycle); else if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case LOGICAL_NAND: { // !&& oassert(node->num_output_pins == 1); char unknown = FALSE; char one = FALSE; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; } else if (pin == 0) { one = TRUE; break; } } if (one) update_pin_value(node->output_pins[0], 1, cycle); else if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case LOGICAL_NOT: // ! case LOGICAL_NOR: // !| { oassert(node->num_output_pins == 1); char unknown = FALSE; char zero = FALSE; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; } else if (pin == 1) { zero = TRUE; break; } } if (zero) update_pin_value(node->output_pins[0], 0, cycle); else if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else update_pin_value(node->output_pins[0], 1, cycle); break; } case LT: // < 010 1 { oassert(node->num_input_port_sizes == 3); oassert(node->num_output_port_sizes == 1); signed char pin0 = get_pin_value(node->input_pins[0],cycle); signed char pin1 = get_pin_value(node->input_pins[1],cycle); signed char pin2 = get_pin_value(node->input_pins[2],cycle); if (pin0 < 0 || pin1 < 0 || pin2 < 0) update_pin_value(node->output_pins[0], -1, cycle); else if (pin0 == 0 && pin1 == 1 && pin2 == 0) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case GT: // > 100 1 { oassert(node->num_input_port_sizes == 3); oassert(node->num_output_port_sizes == 1); signed char pin0 = get_pin_value(node->input_pins[0],cycle); signed char pin1 = get_pin_value(node->input_pins[1],cycle); signed char pin2 = get_pin_value(node->input_pins[2],cycle); if (pin0 < 0 || pin1 < 0 || pin2 < 0) update_pin_value(node->output_pins[0], -1, cycle); else if (pin0 == 1 && pin1 == 0 && pin2 == 0) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case ADDER_FUNC: // 001 1\n010 1\n100 1\n111 1 { oassert(node->num_input_port_sizes == 3); oassert(node->num_output_port_sizes == 1); signed char pin0 = get_pin_value(node->input_pins[0],cycle); signed char pin1 = get_pin_value(node->input_pins[1],cycle); signed char pin2 = get_pin_value(node->input_pins[2],cycle); if (pin0 < 0 || pin1 < 0 || pin2 < 0) update_pin_value(node->output_pins[0], -1, cycle); else if ( (pin0 == 0 && pin1 == 0 && pin2 == 1) || (pin0 == 0 && pin1 == 1 && pin2 == 0) || (pin0 == 1 && pin1 == 0 && pin2 == 0) || (pin0 == 1 && pin1 == 1 && pin2 == 1) ) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case CARRY_FUNC: // 011 1\n100 1\n110 1\n111 1 { oassert(node->num_input_port_sizes == 3); oassert(node->num_output_port_sizes == 1); signed char pin0 = get_pin_value(node->input_pins[0],cycle); signed char pin1 = get_pin_value(node->input_pins[1],cycle); signed char pin2 = get_pin_value(node->input_pins[2],cycle); if (pin0 < 0 || pin1 < 0 || pin2 < 0) update_pin_value(node->output_pins[0], -1, cycle); else if ( (pin0 == 1 && (pin1 == 1 || pin2 == 1)) || (pin1 == 1 && pin2 == 1) ) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case NOT_EQUAL: // != case LOGICAL_XOR: // ^ { oassert(node->num_output_pins == 1); char unknown = FALSE; int ones = 0; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; break; } else if (pin == 1) { ones++; } } if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else if ((ones % 2) == 1) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); break; } case LOGICAL_EQUAL: // == case LOGICAL_XNOR: // !^ { oassert(node->num_output_pins == 1); char unknown = FALSE; int ones = 0; int i; for (i = 0; i < node->num_input_pins; i++) { signed char pin = get_pin_value(node->input_pins[i], cycle); if (pin < 0) { unknown = TRUE; break; } if (pin == 1) { ones++; } } if (unknown) update_pin_value(node->output_pins[0], -1, cycle); else if ((ones % 2) == 1) update_pin_value(node->output_pins[0], 0, cycle); else update_pin_value(node->output_pins[0], 1, cycle); break; } case BITWISE_NOT: { oassert(node->num_input_pins == 1); oassert(node->num_output_pins == 1); signed char pin = get_pin_value(node->input_pins[0], cycle); if (pin < 0) update_pin_value(node->output_pins[0], -1, cycle); else if (pin == 1) update_pin_value(node->output_pins[0], 0, cycle); else update_pin_value(node->output_pins[0], 1, cycle); break; } case CLOCK_NODE: { int i; for (i = 0; i < node->num_output_pins; i++) //toggle according to ratio update_pin_value(node->output_pins[i], is_even_cycle(cycle/node->ratio)?0:1, cycle); break; } case GND_NODE: oassert(node->num_output_pins == 1); update_pin_value(node->output_pins[0], 0, cycle); break; case VCC_NODE: oassert(node->num_output_pins == 1); update_pin_value(node->output_pins[0], 1, cycle); break; case PAD_NODE: oassert(node->num_output_pins == 1); update_pin_value(node->output_pins[0], 0, cycle); break; case INPUT_NODE: break; case OUTPUT_NODE: oassert(node->num_output_pins == 1); oassert(node->num_input_pins == 1); update_pin_value(node->output_pins[0], get_pin_value(node->input_pins[0],cycle), cycle); break; case HARD_IP: compute_hard_ip_node(node,cycle); break; case GENERIC : compute_generic_node(node,cycle); break; //case FULLADDER: case ADD: compute_add_node(node, cycle, 0); break; case MINUS: if(node->num_input_port_sizes == 3) compute_add_node(node, cycle, 1); else compute_unary_sub_node(node, cycle); break; /* These should have already been converted to softer versions. */ case BITWISE_AND: case BITWISE_NAND: case BITWISE_NOR: case BITWISE_XNOR: case BITWISE_XOR: case BITWISE_OR: case BUF_NODE: case MULTI_PORT_MUX: case SL: case SR: case CASE_EQUAL: case CASE_NOT_EQUAL: case DIVIDE: case MODULO: case GTE: case LTE: //case ADD: //case MINUS: default: error_message(SIMULATION_ERROR, 0, -1, "Node should have been converted to softer version: %s", node->name); break; } // Record coverage on any output pins that have changed. { int i; for (i = 0; i < node->num_output_pins; i++) if(get_pin_value(node->output_pins[i],cycle-1) != get_pin_value(node->output_pins[i],cycle)) node->output_pins[i]->coverage++; } } /* * Updates all pins which have been flagged as undriven * to -1 for the given cycle. * * Also checks that other pins have been updated * by cycle 3 and throws an error if they haven't been. * * This function is called when each node is updated as a * safeguard. */ void update_undriven_input_pins(nnode_t *node, int cycle) { int i; for (i = 0; i < node->num_undriven_pins; i++) { npin_t *pin = node->undriven_pins[i]; update_pin_value(pin, global_args.sim_initial_value, cycle); } // By the third cycle everything in the netlist should have been updated. if (cycle == 3) { for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; if (get_pin_cycle(pin) < cycle-1) #ifdef _OPENMP // Can't have multiple threads trying to error out at the same time. #pragma omp critical #endif { char *node_name = node->name; char *pin_name = pin->name; // Print the trace. nnode_t *root = print_update_trace(node, cycle); // Throw an error. error_message(SIMULATION_ERROR,0,-1,"Odin has detected that an input pin attached to %s isn't being updated.\n" "\tPin name: %s\n" "\tRoot node: %s\n" "\tSee the trace immediately above this message for details.\n", node_name, pin_name, root?root->name:"N/A" ); } } } } /* * Flags any inputs pins which are undriven and have * not already been flagged. */ void flag_undriven_input_pins(nnode_t *node) { int i; for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; if (!pin->net || !pin->net->driver_pin || !pin->net->driver_pin->node) { int already_flagged = FALSE; int j; for (j = 0; j < node->num_undriven_pins; j++) { if (node->undriven_pins[j] == pin) already_flagged = TRUE; } if (!already_flagged) { node->undriven_pins = realloc(node->undriven_pins, sizeof(npin_t *) * (node->num_undriven_pins + 1)); node->undriven_pins[node->num_undriven_pins++] = pin; warning_message(SIMULATION_ERROR,0,-1,"A node (%s) has an undriven input pin.", node->name); } } } } /* * Gets the number of nodes whose output pins have been sufficiently covered. */ int get_num_covered_nodes(stages *s) { int covered_nodes = 0; int i; for(i = 0; i < s->count; i++) { int j; for (j = 0; j < s->counts[i]; j++) { /* * To count as being covered, every pin should resolve, and * make at least one transition from one binary value to another * and back. (That's three transitions total.) */ nnode_t *node = s->stages[i][j]; int k; int covered = TRUE; for (k = 0; k < node->num_output_pins; k++) { if (node->output_pins[k]->coverage < 3) { covered = FALSE; break; } } if (covered) covered_nodes++; } } return covered_nodes; } /* * Enqueues the node in the given queue if is_node_ready returns TRUE. */ int enqueue_node_if_ready(queue_t* queue, nnode_t* node, int cycle) { if (is_node_ready(node, cycle)) { node->in_queue = TRUE; queue->add(queue, node); return TRUE; } else { return FALSE; } } /* * Determines if the given node has been simulated for the given cycle. */ int is_node_complete(nnode_t* node, int cycle) { int i; for (i = 0; i < node->num_output_pins; i++) if (node->output_pins[i] && (get_pin_cycle(node->output_pins[i]) < cycle)) return FALSE; return TRUE; } /* * Checks to see if the node is ready to be simulated for the given cycle. */ int is_node_ready(nnode_t* node, int cycle) { if (!cycle) { flag_undriven_input_pins(node); update_undriven_input_pins(node, cycle); } if (node->type == FF_NODE) { npin_t *D_pin = node->input_pins[0]; npin_t *clock_pin = node->input_pins[1]; // Flip-flops depend on the D input from the previous cycle and the clock from this cycle. if ( (get_pin_cycle(D_pin ) < cycle-1) || (get_pin_cycle(clock_pin) < cycle ) ) return FALSE; } else if (node->type == MEMORY) { int i; for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; // The data and write enable inputs rely on the values from the previous cycle. if ( !strcmp(pin->mapping, "data") || !strcmp(pin->mapping, "data1") || !strcmp(pin->mapping, "data2") || !strcmp(pin->mapping, "we") || !strcmp(pin->mapping, "we1") || !strcmp(pin->mapping, "we2") ) { if (get_pin_cycle(pin) < cycle-1) return FALSE; } else { if (get_pin_cycle(pin) < cycle) return FALSE; } } } else { int i; for (i = 0; i < node->num_input_pins; i++) if (get_pin_cycle(node->input_pins[i]) < cycle) return FALSE; } return TRUE; } /* * Returns the ration of a clock node. * */ int get_clock_ratio(nnode_t *node) { return node->ratio; } /* * Changes the ratio of a clock node */ void set_clock_ratio(int rat, nnode_t *node) { //change the value only for clocks if(node->type != CLOCK_NODE) return; node->ratio = rat; } /* * Gets the children of the given node. Returns the number of * children via the num_children parameter. Throws warnings * or errors if invalid connection patterns are detected. */ nnode_t **get_children_of(nnode_t *node, int *num_children) { nnode_t **children = 0; int count = 0; int i; for (i = 0; i < node->num_output_pins; i++) { npin_t *pin = node->output_pins[i]; nnet_t *net = pin->net; if (net) { /* * Detects a net that may be being driven by two * or more pins or has an incorrect driver pin assignment. */ if (net->driver_pin != pin && global_args.all_warnings) { char *pin_name = get_pin_name(pin->name); char *node_name = get_pin_name(node->name); char *net_name = get_pin_name(net->name); warning_message(SIMULATION_ERROR, -1, -1, "Found output pin \"%s\" (%ld) on node \"%s\" (%ld)\n" " which is mapped to a net \"%s\" (%ld) whose driver pin is \"%s\" (%ld) \n", pin_name, pin->unique_id, node_name, node->unique_id, net_name, net->unique_id, net->driver_pin->name, net->driver_pin->unique_id ); free(net_name); free(pin_name); free(node_name); } int j; for (j = 0; j < net->num_fanout_pins; j++) { npin_t *fanout_pin = net->fanout_pins[j]; if (fanout_pin && fanout_pin->type == INPUT && fanout_pin->node) { nnode_t *child_node = fanout_pin->node; // Check linkage for inconsistencies. if (fanout_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->node != node) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else { // Add child. children = realloc(children, sizeof(nnode_t*) * (count + 1)); children[count++] = child_node; } } } } } *num_children = count; return children; } /* * Gets the children of the given node. Returns the number of * children via the num_children parameter. Throws warnings * or errors if invalid connection patterns are detected. */ int *get_children_pinnumber_of(nnode_t *node, int *num_children) { int *pin_numbers = 0; int count = 0; int i; for (i = 0; i < node->num_output_pins; i++) { npin_t *pin = node->output_pins[i]; nnet_t *net = pin->net; if (net) { /* * Detects a net that may be being driven by two * or more pins or has an incorrect driver pin assignment. */ if (net->driver_pin != pin && global_args.all_warnings) { char *pin_name = get_pin_name(pin->name); char *node_name = get_pin_name(node->name); char *net_name = get_pin_name(net->name); warning_message(SIMULATION_ERROR, -1, -1, "Found output pin \"%s\" (%ld) on node \"%s\" (%ld)\n" " which is mapped to a net \"%s\" (%ld) whose driver pin is \"%s\" (%ld) \n", pin_name, pin->unique_id, node_name, node->unique_id, net_name, net->unique_id, net->driver_pin->name, net->driver_pin->unique_id ); free(net_name); free(pin_name); free(node_name); } int j; for (j = 0; j < net->num_fanout_pins; j++) { npin_t *fanout_pin = net->fanout_pins[j]; if (fanout_pin && fanout_pin->type == INPUT && fanout_pin->node) { nnode_t *child_node = fanout_pin->node; // Check linkage for inconsistencies. if (fanout_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->node != node) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else { // Add child. pin_numbers = realloc(pin_numbers, sizeof(int) * (count + 1)); pin_numbers[count++] = i; } } } } } *num_children = count; return pin_numbers; } /* * Gets the children of a specific output pin of the given node. Returns the number of * children via the num_children parameter. Throws warnings * or errors if invalid connection patterns are detected. */ nnode_t **get_children_of_nodepin(nnode_t *node, int *num_children, int output_pin) { nnode_t **children = 0; int count = 0; int output_pin_number = node->num_output_pins; if(output_pin < 0 || output_pin > output_pin_number) { error_message(SIMULATION_ERROR, -1, -1, "Requested pin not available"); return children; } npin_t *pin = node->output_pins[output_pin]; nnet_t *net = pin->net; if (net) { /* * Detects a net that may be being driven by two * or more pins or has an incorrect driver pin assignment. */ if (net->driver_pin != pin && global_args.all_warnings) { char *pin_name = get_pin_name(pin->name); char *node_name = get_pin_name(node->name); char *net_name = get_pin_name(net->name); warning_message(SIMULATION_ERROR, -1, -1, "Found output pin \"%s\" (%ld) on node \"%s\" (%ld)\n" " which is mapped to a net \"%s\" (%ld) whose driver pin is \"%s\" (%ld) \n", pin_name, pin->unique_id, node_name, node->unique_id, net_name, net->unique_id, net->driver_pin->name, net->driver_pin->unique_id ); free(net_name); free(pin_name); free(node_name); } int j; for (j = 0; j < net->num_fanout_pins; j++) { npin_t *fanout_pin = net->fanout_pins[j]; if (fanout_pin && fanout_pin->type == INPUT && fanout_pin->node) { nnode_t *child_node = fanout_pin->node; // Check linkage for inconsistencies. if (fanout_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->net != net) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else if (fanout_pin->net->driver_pin->node != node) { print_ancestry(child_node, 0); error_message(SIMULATION_ERROR, -1, -1, "Found mismapped node %s", node->name); } else { // Add child. children = realloc(children, sizeof(nnode_t*) * (count + 1)); children[count++] = child_node; } } } } *num_children = count; return children; } /* * Updates the value of a pin and its cycle. Pins should be updated using * only this function. * * Initializes the pin if need be. */ void update_pin_value(npin_t *pin, signed char value, int cycle) { if (!pin->values) initialize_pin(pin); pin->values[get_values_offset(cycle)] = value; set_pin_cycle(pin, cycle); } /* * Gets the value of a pin. Pins should be checked using this function only. */ signed char get_pin_value(npin_t *pin, int cycle) { if (!pin->values || cycle < 0){ /* If the pin's node has an initial value, then use it. Otherwise use the global initial value Need to make sure pin->node isn't NULL (e.g. for a dummy node) */ if(pin->node && pin->node->has_initial_value) { return pin->node->initial_value; } return global_args.sim_initial_value; } return pin->values[get_values_offset(cycle)]; } /* * Calculates the index in the values array for the given cycle. */ inline int get_values_offset(int cycle) { return (((cycle) + (SIM_WAVE_LENGTH)) % (SIM_WAVE_LENGTH)); } /* * Gets the cycle of the given pin */ inline int get_pin_cycle(npin_t *pin) { if (!pin->cycle) return -1; else return *(pin->cycle); } /* * Sets the cycle of the given pin. * * Only called from update_pin_value. */ inline void set_pin_cycle(npin_t *pin, int cycle) { *(pin->cycle) = cycle; } /* * Returns FALSE if the cycle is odd. */ int is_even_cycle(int cycle) { return !((cycle + 2) % 2); } /* * Allocates memory for the pin's value and cycle. * * Checks to see if this pin's net has a different driver, and * initialises that pin too. * * Fanout pins will share the same memory locations for cycle * and values so that the values don't have to be propagated * through the net. */ void initialize_pin(npin_t *pin) { // Initialise the driver pin if this pin is not the driver. if (pin->net && pin->net->driver_pin && pin->net->driver_pin != pin) initialize_pin(pin->net->driver_pin); // If initialising the driver initialised this pin, we're OK to return. if (pin->cycle || pin->values) return; if (pin->net) { pin->values = pin->net->values; pin->cycle = &(pin->net->cycle); int i; for (i = 0; i < pin->net->num_fanout_pins; i++) { npin_t *fanout_pin = pin->net->fanout_pins[i]; if (fanout_pin) { fanout_pin->values = pin->net->values; fanout_pin->cycle = &(pin->net->cycle); } } } else { pin->values = malloc(SIM_WAVE_LENGTH * sizeof(signed char)); pin->cycle = malloc(sizeof(int)); } int i; for (i = 0; i < SIM_WAVE_LENGTH; i++){ /* If the pin's node has an initial value, then use it. Otherwise use the global initial value Need to make sure pin->node isn't NULL (e.g. for a dummy node) */ if(pin->node && pin->node->has_initial_value) pin->values[i] = pin->node->initial_value; else pin->values[i] = global_args.sim_initial_value; } set_pin_cycle(pin, -1); } /* * Returns FALSE if the node is not a clock. */ inline int is_clock_node(nnode_t *node) { return ( (node->type == CLOCK_NODE) || !strcmp(node->name,"top^clk") // Strictly for memories. ); } /* * Returns TRUE if the pin's value for this * cycle is 1 and the value for the previous cycle * was not 1. Otherwise returns FALSE. */ int is_posedge(npin_t *pin, int cycle) { if (get_pin_value(pin,cycle) == 1 && get_pin_value(pin,cycle-1) != 1) return TRUE; else return FALSE; } /* * Computes a node of type FF_NODE for the given cycle. */ void compute_flipflop_node(nnode_t *node, int cycle) { oassert(node->num_output_pins == 1); oassert(node->num_input_pins == 2); npin_t *D_pin = node->input_pins[0]; npin_t *clock_pin = node->input_pins[1]; npin_t *output_pin = node->output_pins[0]; // Rising edge: update the flip-flop from the input value of the previous cycle. if (is_posedge(clock_pin, cycle)) update_pin_value(output_pin, get_pin_value(D_pin, cycle-1), cycle); // Falling edge: maintain the flip-flop value. else update_pin_value(output_pin, get_pin_value(output_pin,cycle-1), cycle); } /* * Computes a node of type MUX_2 for the given cycle. */ void compute_mux_2_node(nnode_t *node, int cycle) { oassert(node->num_output_pins == 1); oassert(node->num_input_port_sizes >= 2); oassert(node->input_port_sizes[0] == node->input_port_sizes[1]); ast_node_t *ast_node = node->related_ast_node; // Figure out which pin is being selected. char unknown = FALSE; int select = -1; int default_select = -1; int i; for (i = 0; i < node->input_port_sizes[0]; i++) { npin_t *pin = node->input_pins[i]; signed char value = get_pin_value(pin, cycle); if (value < 0) unknown = TRUE; else if (value == 1 && select == -1) // Take the first selection only. select = i; /* * If the pin comes from an "else" condition or a case "default" condition, * we favour it in the case where there are unknowns. */ if (ast_node && pin->is_default && (ast_node->type == IF || ast_node->type == CASE)) default_select = i; } // If there are unknowns and there is a default clause, select it. if (unknown && default_select >= 0) { unknown = FALSE; select = default_select; } npin_t *output_pin = node->output_pins[0]; // If any select pin is unknown (and we don't have a default), we take the value from the previous cycle. if (unknown) { /* * Conform to ModelSim's behaviour where in-line ifs are concerned. If the * condition is unknown, the inline if's output is unknown. */ if (ast_node && ast_node->type == IF_Q) update_pin_value(output_pin, -1, cycle); else update_pin_value(output_pin, get_pin_value(output_pin, cycle-1), cycle); } // If no selection is made (all 0) we output x. else if (select < 0) { update_pin_value(output_pin, -1, cycle); } else { npin_t *pin = node->input_pins[select + node->input_port_sizes[0]]; signed char value = get_pin_value(pin,cycle); // Drive implied drivers to unknown value. /*if (pin->is_implied && ast_node && (ast_node->type == CASE)) update_pin_value(output_pin, -1, cycle); else*/ update_pin_value(output_pin, value, cycle); } } // TODO: Needs to be verified. void compute_hard_ip_node(nnode_t *node, int cycle) { oassert(node->input_port_sizes[0] > 0); oassert(node->output_port_sizes[0] > 0); int *input_pins = malloc(sizeof(int)*node->num_input_pins); int *output_pins = malloc(sizeof(int)*node->num_output_pins); if (!node->simulate_block_cycle) { char *filename = malloc(sizeof(char)*strlen(node->name)); if (!index(node->name, '.')) error_message(SIMULATION_ERROR, 0, -1, "Couldn't extract the name of a shared library for hard-block simulation"); snprintf(filename, sizeof(char)*strlen(node->name), "%s.so", index(node->name, '.')+1); void *handle = dlopen(filename, RTLD_LAZY); if (!handle) error_message(SIMULATION_ERROR, 0, -1, "Couldn't open a shared library for hard-block simulation: %s", dlerror()); dlerror(); void (*func_pointer)(int, int, int*, int, int*) = (void(*)(int, int, int*, int, int*))dlsym(handle, "simulate_block_cycle"); char *error = dlerror(); if (error) error_message(SIMULATION_ERROR, 0, -1, "Couldn't load a shared library method for hard-block simulation: %s", error); node->simulate_block_cycle = func_pointer; free(filename); } int i; for (i = 0; i < node->num_input_pins; i++) input_pins[i] = get_pin_value(node->input_pins[i],cycle); (node->simulate_block_cycle) (cycle, node->num_input_pins, input_pins, node->num_output_pins, output_pins); for (i = 0; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], output_pins[i], cycle); free(input_pins); free(output_pins); } /* * Computes the given multiply node for the given cycle. */ void compute_multiply_node(nnode_t *node, int cycle) { oassert(node->num_input_port_sizes == 2); oassert(node->num_output_port_sizes == 1); int i; char unknown = FALSE; for (i = 0; i < node->input_port_sizes[0] + node->input_port_sizes[1]; i++) { signed char pin = get_pin_value(node->input_pins[i],cycle); if (pin < 0) { unknown = TRUE; break; } } if (unknown) { for (i = 0; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], -1, cycle); } else { int *a = malloc(sizeof(int)*node->input_port_sizes[0]); int *b = malloc(sizeof(int)*node->input_port_sizes[1]); for (i = 0; i < node->input_port_sizes[0]; i++) a[i] = get_pin_value(node->input_pins[i],cycle); for (i = 0; i < node->input_port_sizes[1]; i++) b[i] = get_pin_value(node->input_pins[node->input_port_sizes[0] + i],cycle); int *result = multiply_arrays(a, node->input_port_sizes[0], b, node->input_port_sizes[1]); for (i = 0; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], result[i], cycle); free(result); free(a); free(b); } } // TODO: Needs to be verified. void compute_generic_node(nnode_t *node, int cycle) { int line_count_bitmap = node->bit_map_line_count; char **bit_map = node->bit_map; int lut_size = 0; while (bit_map[0][lut_size] != 0) lut_size++; int found = 0; int i; for (i = 0; i < line_count_bitmap && (!found); i++) { int j; for (j = 0; j < lut_size; j++) { if (get_pin_value(node->input_pins[j],cycle) < 0) { update_pin_value(node->output_pins[0], -1, cycle); return; } if ((bit_map[i][j] != '-') && (bit_map[i][j]-'0' != get_pin_value(node->input_pins[j],cycle))) break; } if (j == lut_size) found = TRUE; } if (found) update_pin_value(node->output_pins[0], 1, cycle); else update_pin_value(node->output_pins[0], 0, cycle); } /* * Takes two arrays of integers (1's and 0's) and returns an array * of integers (1's and 0's) that represent their product. The * length of the returned array is twice that of the two parameters. * * This array will need to be freed later! */ int *multiply_arrays(int *a, int a_length, int *b, int b_length) { int result_size = a_length + b_length; int *result = calloc(sizeof(int), result_size); int i; for (i = 0; i < a_length; i++) { if (a[i] == 1) { int j; for (j = 0; j < b_length; j++) result[i+j] += b[j]; } } for (i = 0; i < result_size; i++) { while (result[i] > 1) { result[i] -= 2; result[i+1]++; } } return result; } /* * Computes the given add node for the given cycle. * add by Sen */ void compute_add_node(nnode_t *node, int cycle, int type) { oassert(node->num_input_port_sizes == 3); oassert(node->num_output_port_sizes == 2); int i, num; int flag = 0; int *a = malloc(sizeof(int)*node->input_port_sizes[0]); int *b = malloc(sizeof(int)*node->input_port_sizes[1]); int *c = malloc(sizeof(int)*node->input_port_sizes[2]); num = node->input_port_sizes[0]+ node->input_port_sizes[1]; //if cin connect to unconn(PAD_NODE), a[0] connect to ground(GND_NODE) and b[0] connect to ground, flag = 0 the initial adder for addition //if cin connect to unconn(PAD_NODE), a[0] connect to ground(GND_NODE) and b[0] connect to vcc, flag = 1 the initial adder for subtraction if(node->input_pins[num]->net->driver_pin->node->type == PAD_NODE) { if(node->input_pins[0]->net->driver_pin->node->type == GND_NODE && node->input_pins[node->input_port_sizes[0]]->net->driver_pin->node->type == GND_NODE) flag = 0; else if(node->input_pins[0]->net->driver_pin->node->type == GND_NODE && node->input_pins[node->input_port_sizes[0]]->net->driver_pin->node->type == VCC_NODE) flag = 1; } else flag = 2; for (i = 0; i < node->input_port_sizes[0]; i++) a[i] = get_pin_value(node->input_pins[i],cycle); for (i = 0; i < node->input_port_sizes[1]; i++) b[i] = get_pin_value(node->input_pins[node->input_port_sizes[0] + i],cycle); for (i = 0; i < node->input_port_sizes[2]; i++) //the initial cin of carry chain subtractor should be 1 if(flag == 1) c[i] = 1; //the initial cin of carry chain adder should be 0 else if(flag == 0) c[i] = 0; else c[i] = get_pin_value(node->input_pins[node->input_port_sizes[0]+ node->input_port_sizes[1] + i],cycle); int *result = add_arrays(a, node->input_port_sizes[0], b, node->input_port_sizes[1], c, node->input_port_sizes[2],type); //update the pin value of output for (i = 1; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], result[(i - 1)], cycle); update_pin_value(node->output_pins[0], result[(node->num_output_pins - 1)], cycle); free(result); free(a); free(b); free(c); } /* * Takes two arrays of integers (1's and 0's) and returns an array * of integers (1's and 0's) that represent their sum. The * length of the returned array is the maximum of the two parameters plus one. * add by Sen * This array will need to be freed later! */ int *add_arrays(int *a, int a_length, int *b, int b_length, int *c, int c_length, int flag) { int result_size = max(a_length , b_length) + 1; int *result = calloc(sizeof(int), result_size); int i; int temp_carry_in; //least significant bit would use the input carryIn, the other bits would use the compute value //if one of the number is unknown, then the answer should be unknown(same as ModelSim) if(a[0] == -1 || b[0] == -1 || c[0] == -1) { result[0] = -1; result[1] = -1; } else { result[0] = a[0] ^ b[0] ^ c[0]; result[1] = (a[0] & b[0]) | (c[0] & b[0]) | (a[0] & c[0]); } temp_carry_in = result[1]; if(result_size > 2){ for(i = 1; i < min(a_length,b_length); i++) { if(a[i] == -1 || b[i] == -1 || temp_carry_in == -1) { result[i] = -1; result[i+1] = -1; } else { result[i] = a[i] ^ b[i] ^ temp_carry_in; result[i+1] = (a[i] & b[i]) | (a[i] & temp_carry_in) | (temp_carry_in & b[i]); } temp_carry_in = result[i+1]; } if(a_length >= b_length) { for(i = b_length; i < a_length; i++) { if(a[i] == -1 || temp_carry_in == -1) { result[i] = -1; result[i+1] = -1; } else { result[i] = a[i] ^ temp_carry_in; result[i+1] = a[i] & temp_carry_in; } temp_carry_in = result[i+1]; } } else { for(i = a_length; i < b_length; i++) { if(b[i] == -1 || temp_carry_in == -1) { result[i] = -1; result[i+1] = -1; }else { result[i] = b[i] ^ temp_carry_in; result[i+1] = b[i] & temp_carry_in; } temp_carry_in = result[i+1]; } } } return result; } /* * Computes the given add node for the given cycle. * add by Sen */ void compute_unary_sub_node(nnode_t *node, int cycle) { oassert(node->num_input_port_sizes == 2); oassert(node->num_output_port_sizes == 2); int i; char unknown = FALSE; for (i = 0; i < (node->input_port_sizes[0] + node->input_port_sizes[1]); i++) { signed char pin = get_pin_value(node->input_pins[i],cycle); if (pin < 0) { unknown = TRUE; break; } } if (unknown) { for (i = 0; i < (node->output_port_sizes[0] + node->output_port_sizes[1]); i++) update_pin_value(node->output_pins[i], -1, cycle); } else { int *a = malloc(sizeof(int)*node->input_port_sizes[0]); int *c = malloc(sizeof(int)*node->input_port_sizes[1]); for (i = 0; i < node->input_port_sizes[0]; i++) a[i] = get_pin_value(node->input_pins[i],cycle); for (i = 0; i < node->input_port_sizes[1]; i++) if((node->input_pins[node->input_port_sizes[0]+ node->input_port_sizes[1] + i]->net->driver_pin->node->type == PAD_NODE)) c[i] = 1; else c[i] = get_pin_value(node->input_pins[node->input_port_sizes[0] + i],cycle); int *result = unary_sub_arrays(a, node->input_port_sizes[0], c, node->input_port_sizes[1]); for (i = 1; i < node->num_output_pins; i++) update_pin_value(node->output_pins[i], result[(i - 1)], cycle); update_pin_value(node->output_pins[0], result[(node->num_output_pins - 1)], cycle); free(result); free(a); free(c); } } /* * Takes two arrays of integers (1's and 0's) and returns an array * of integers (1's and 0's) that represent their sum. The * length of the returned array is the maximum of the two parameters plus one. * add by Sen * This array will need to be freed later! */ int *unary_sub_arrays(int *a, int a_length, int *c, int c_length) { int result_size = a_length + 1; int *result = calloc(sizeof(int), result_size); int i; int temp_carry_in; c[0] = 1; result[0] = (!a[0]) ^ c[0] ^ 0; result[1] = ((!a[0]) & 0) | (c[0] & 0) | ((!a[0]) & c[0]); temp_carry_in = result[1]; if(result_size > 2){ for(i = 1; i < a_length; i++) { result[i] = (!a[i]) ^ 0 ^ temp_carry_in; result[i+1] = ((!a[i]) & 0) | ((!a[i]) & temp_carry_in) | (temp_carry_in & 0); temp_carry_in = result[i+1]; } } return result; } /* * Computes the given memory node. */ void compute_memory_node(nnode_t *node, int cycle) { if (is_sp_ram(node)) compute_single_port_memory(node, cycle); else if (is_dp_ram(node)) compute_dual_port_memory(node, cycle); else error_message(SIMULATION_ERROR, 0, -1, "Could not resolve memory hard block %s to a valid type.", node->name); } /* * Computes single port memory. */ void compute_single_port_memory(nnode_t *node, int cycle) { sp_ram_signals *signals = get_sp_ram_signals(node); int posedge = is_posedge(signals->clk, cycle); if (!node->memory_data) instantiate_memory(node, signals->data->count, signals->addr->count); // On the rising edge, write the memory. if (posedge) { int we = get_pin_value(signals->we, cycle - 1); long address = compute_memory_address(signals->addr, cycle - 1); char address_ok = (address != -1)?1:0; int i; for (i = 0; i < signals->data->count; i++) { // Compute which bit we are addressing. long bit_address = address_ok?(i + (address * signals->data->count)):-1; // If write is enabled, copy the input to memory. if (address_ok && we) node->memory_data[bit_address] = get_pin_value(signals->data->pins[i],cycle-1); } } // Read data from the memory. { long address = compute_memory_address(signals->addr, cycle); char address_ok = (address != -1)?1:0; int i; for (i = 0; i < signals->data->count; i++) { // Compute which bit we are addressing. long bit_address = address_ok?(i + (address * signals->data->count)):-1; // Update the output. if (address_ok) update_pin_value(signals->out->pins[i], node->memory_data[bit_address], cycle); else update_pin_value(signals->out->pins[i], -1, cycle); } } free_sp_ram_signals(signals); } /* * Computes dual port memory. */ void compute_dual_port_memory(nnode_t *node, int cycle) { dp_ram_signals *signals = get_dp_ram_signals(node); int posedge = is_posedge(signals->clk, cycle); if (!node->memory_data) instantiate_memory(node, signals->data2->count, signals->addr2->count); // On the rising edge, we write the memory. if (posedge) { int we1 = get_pin_value(signals->we1, cycle - 1); int we2 = get_pin_value(signals->we2, cycle - 1); long address1 = compute_memory_address(signals->addr1, cycle - 1); long address2 = compute_memory_address(signals->addr2, cycle - 1); char address1_ok = (address1 != -1)?1:0; char address2_ok = (address2 != -1)?1:0; int i; for (i = 0; i < signals->data1->count; i++) { // Compute which bit we are addressing. long bit_address1 = address1_ok?(i + (address1 * signals->data1->count)):-1; long bit_address2 = address2_ok?(i + (address2 * signals->data2->count)):-1; // Write to the memory if (address1_ok && we1) node->memory_data[bit_address1] = get_pin_value(signals->data1->pins[i], cycle-1); if (address2_ok && we2) node->memory_data[bit_address2] = get_pin_value(signals->data2->pins[i], cycle-1); } } // Read data from memory. { long address1 = compute_memory_address(signals->addr1, cycle); long address2 = compute_memory_address(signals->addr2, cycle); char address1_ok = (address1 != -1)?1:0; char address2_ok = (address2 != -1)?1:0; int i; for (i = 0; i < signals->data1->count; i++) { // Compute which bit we are addressing. long bit_address1 = address1_ok?(i + (address1 * signals->data1->count)):-1; long bit_address2 = address2_ok?(i + (address2 * signals->data2->count)):-1; // Read the memory bit if (address1_ok) update_pin_value(signals->out1->pins[i], node->memory_data[bit_address1], cycle); else update_pin_value(signals->out1->pins[i], -1, cycle); if (address2_ok) update_pin_value(signals->out2->pins[i], node->memory_data[bit_address2], cycle); else update_pin_value(signals->out2->pins[i], -1, cycle); } } free_dp_ram_signals(signals); } /* * Calculates the memory address. Returns -1 if the address is unknown. */ long compute_memory_address(signal_list_t *addr, int cycle) { long address = 0; int i; for (i = 0; i < addr->count; i++) { // If any address pins are x's, write x's we return -1. if (get_pin_value(addr->pins[i],cycle) < 0) return -1; address += get_pin_value(addr->pins[i],cycle) << (i); } return address; } /* * Initialises memory using a memory information file (mif). If not * file is found, it is initialised to x's. */ void instantiate_memory(nnode_t *node, int data_width, int addr_width) { long max_address = 1 << addr_width; node->memory_data = malloc(sizeof(signed char) * max_address * data_width); // Initialise the memory to -1. int i; for (i = 0; i < max_address * data_width; i++) node->memory_data[i] = -1; char *filename = get_mif_filename(node); FILE *mif = fopen(filename, "r"); if (!mif) { printf("MIF %s (%dx%d) not found. \n", filename, data_width, addr_width); } else { assign_memory_from_mif_file(mif, filename, data_width, addr_width, node->memory_data); fclose(mif); } free(filename); } /* * Removes white space (except new lines) and comments from * the given mif file and returns the resulting temporary file. */ FILE *preprocess_mif_file(FILE *source) { FILE *destination = tmpfile(); destination = freopen(NULL, "r+", destination); rewind(source); char line[BUFFER_MAX_SIZE]; int in_multiline_comment = FALSE; while (fgets(line, BUFFER_MAX_SIZE, source)) { int i; for (i = 0; i < strlen(line); i++) { if (!in_multiline_comment) { // For a single line comment, skip the rest of the line. if (line[i] == '-' && line[i+1] == '-') break; // Start of a multiline comment else if (line[i] == '%') in_multiline_comment = TRUE; // Don't copy any white space over. else if (line[i] != '\n' && line[i] != ' ' && line[i] != '\r' && line[i] != '\t' ) fputc(line[i], destination); } else { // If we're in a multi-line comment, search for the % if (line[i] == '%') in_multiline_comment = FALSE; } } fputc('\n', destination); } rewind(destination); return destination; } int parse_mif_radix(char *radix) { if (radix) { if (!strcmp(radix, "HEX")) return 16; else if (!strcmp(radix, "DEC")) return 10; else if (!strcmp(radix, "OCT")) return 8; else if (!strcmp(radix, "BIN")) return 2; else return 0; } else { return 0; } } void assign_memory_from_mif_file(FILE *mif, char *filename, int width, long depth, signed char *memory) { FILE *file = preprocess_mif_file(mif); rewind(file); hashtable_t *symbols = create_hashtable(100000); char buffer[BUFFER_MAX_SIZE]; int in_content = FALSE; char *last_line = NULL; int line_number = 0; int addr_radix = 0; int data_radix = 0; while (fgets(buffer, BUFFER_MAX_SIZE, file)) { line_number++; // Remove the newline. trim_string(buffer, "\n"); // Only process lines which are not empty. if (strlen(buffer)) { char *line = strdup(buffer); // MIF files are case insensitive string_to_upper(line); // The content section of the file contains address:value; assignments. if (in_content) { // Parse at the : char *token = strtok(line, ":"); if (strlen(token)) { // END; signifies the end of the file. if(!strcmp(buffer, "END;")) break; // The part before the : is the address. char *address_string = token; token = strtok(NULL, ";"); // The reset (before the ;) is the data_value. char *data_string = token; if (token) { // Make sure the address and value are valid strings of the specified radix. if (!is_string_of_radix(address_string, addr_radix)) error_message(SIMULATION_ERROR, line_number, -1, "%s: address %s is not a base %d string.", filename, address_string, addr_radix); if (!is_string_of_radix(data_string, data_radix)) error_message(SIMULATION_ERROR, line_number, -1, "%s: data string %s is not a base %d string.", filename, data_string, data_radix); char *binary_data = convert_string_of_radix_to_bit_string(data_string, data_radix, width); long long address = convert_string_of_radix_to_long_long(address_string, addr_radix); if (address >= depth) error_message(SIMULATION_ERROR, line_number, -1, "%s: address %s is out of range.", filename, address_string); // Calculate the offset of this memory location in bits. long long offset = address * width; // Write the parsed value string to the memory location. long long i; for (i = offset; i < offset + width; i++) memory[i] = binary_data[i - offset] - '0'; } else { error_message(SIMULATION_ERROR, line_number, -1, "%s: MIF syntax error.", filename); } } } // The header section of the file contains parameters given as PARAMETER=value; else { // Grab the bit before the = sign. char *token = strtok(line, "="); if (strlen(token)) { char *symbol = token; token = strtok(NULL, ";"); // If is something after the equals sign and before the semicolon, add the symbol=value association to the symbol table. if (token) symbols->add(symbols, symbol, sizeof(char) * strlen(symbol), strdup(token)); else if(!strcmp(buffer, "CONTENT")) {} // We found "CONTENT" followed on the next line by "BEGIN". That means we're at the end of the parameters. else if(!strcmp(buffer, "BEGIN") && !strcmp(last_line, "CONTENT")) { // Sanity check parameters to make sure we have what we need. // Verify the width parameter. char *width_string = symbols->get(symbols, "WIDTH", sizeof(char) * 5); int mif_width = atoi(width_string); if (!width_string) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF WIDTH parameter unspecified.", filename); if (mif_width != width) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF width mismatch: must be %d but %d was given", filename, width, mif_width); // Verify the depth parameter. char *depth_string = symbols->get(symbols, "DEPTH", sizeof(char) * 5); int mif_depth = atoi(depth_string); if (!depth_string) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF DEPTH parameter unspecified.", filename); if (mif_depth != depth) error_message(SIMULATION_ERROR, -1, -1, "%s: MIF depth mismatch: must be %d but %d was given", filename, depth, mif_depth); // Parse the radix specifications and make sure they're OK. addr_radix = parse_mif_radix(symbols->get(symbols, "ADDRESS_RADIX", sizeof(char) * 13)); data_radix = parse_mif_radix(symbols->get(symbols, "DATA_RADIX", sizeof(char) * 10)); if (!addr_radix) error_message(SIMULATION_ERROR, -1, -1, "%s: invalid or missing ADDRESS_RADIX: must specify DEC, HEX, OCT, or BIN", filename); if (!data_radix) error_message(SIMULATION_ERROR, -1, -1, "%s: invalid or missing DATA_RADIX: must specify DEC, HEX, OCT, or BIN", filename); // If everything checks out, start reading the values. in_content = TRUE; } else { error_message(SIMULATION_ERROR, line_number, -1, "%s: MIF syntax error: %s", filename, line); } } else { error_message(SIMULATION_ERROR, line_number, -1, "%s: MIF syntax error: %s", filename, line); } free(line); } if (last_line) free(last_line); last_line = strdup(buffer); } } if (last_line) free(last_line); symbols->destroy_free_items(symbols); fclose(file); } /* * Assigns the given node to its corresponding line in the given array of line. * Assumes the line has already been created. */ void assign_node_to_line(nnode_t *node, lines_t *l, int type, int single_pin) { // Make sure the node has an output pin. if (!node->num_output_pins) { npin_t *pin = allocate_npin(); allocate_more_output_pins(node, 1); add_output_pin_to_node(node, pin, 0); } // Parse the node name into a pin number and a port name. int pin_number = get_pin_number(node->name); char *port_name; if (pin_number != -1 && !single_pin) { port_name = get_port_name(node->name); } else { port_name = get_pin_name(node->name); single_pin = TRUE; } // Search the lines for the port name. int j = find_portname_in_lines(port_name, l); free(port_name); if (single_pin) { if (j == -1) { warning_message(SIMULATION_ERROR, 0, -1, "Could not map single-bit node '%s' line", node->name); } else { pin_number = (pin_number == -1)?0:pin_number; int already_added = l->lines[j]->number_of_pins >= 1; if (!already_added) insert_pin_into_line(node->output_pins[0], pin_number, l->lines[j], type); } } else { if (j == -1) warning_message(SIMULATION_ERROR, 0, -1, "Could not map multi-bit node '%s' to line", node->name); else insert_pin_into_line(node->output_pins[0], pin_number, l->lines[j], type); } } /* * Inserts the given pin according to its pin number into the given line. */ void insert_pin_into_line(npin_t *pin, int pin_number, line_t *line, int type) { // Allocate memory for the new pin. line->pins = realloc(line->pins, sizeof(npin_t*) * (line->number_of_pins + 1)); line->pin_numbers = realloc(line->pin_numbers, sizeof(npin_t*) * (line->number_of_pins + 1)); // Find the proper place to insert this pin, and make room for it. int i; for (i = 0; i < line->number_of_pins; i++) { if (line->pin_numbers[i] > pin_number) { // Move other pins to the right to make room. int j; for (j = line->number_of_pins; j > i; j--) { line->pins[j] = line->pins[j-1]; line->pin_numbers[j] = line->pin_numbers[j-1]; } break; } } // Add the new pin. line->pins[i] = pin; line->pin_numbers[i] = pin_number; line->type = type; line->number_of_pins++; } /* * Given a netlist, this function maps the top_input_nodes * or top_output_nodes depending on the value of type * (INPUT or OUTPUT) to a line_t each. It stores them in a * lines_t struct and returns a pointer to it. */ lines_t *create_lines(netlist_t *netlist, int type) { lines_t *l = malloc(sizeof(lines_t)); l->lines = 0; l->count = 0; int num_nodes = (type == INPUT)?netlist->num_top_input_nodes:netlist->num_top_output_nodes; nnode_t **nodes = (type == INPUT)?netlist->top_input_nodes :netlist->top_output_nodes; int i; for (i = 0; i < num_nodes; i++) { nnode_t *node = nodes[i]; char *port_name = get_port_name(node->name); if (type == OUTPUT || !is_clock_node(node)) { if (find_portname_in_lines(port_name, l) == -1) { line_t *line = create_line(port_name); l->lines = realloc(l->lines, sizeof(line_t *)*(l->count + 1)); l->lines[l->count++] = line; } assign_node_to_line(node, l, type, 0); } free(port_name); } return l; } /* * Creates a vector file header from the given lines, * and writes it to the given file. */ void write_vector_headers(FILE *file, lines_t *l) { char* headers = generate_vector_header(l); fprintf(file, "%s", headers); free(headers); fflush(file); } /* * Parses the first line of the given file and compares it to the * given lines for identity. If there is any difference, a warning is printed, * and FALSE is returned. If there are no differences, the file pointer is left * at the start of the second line, and TRUE is returned. */ int verify_test_vector_headers(FILE *in, lines_t *l) { int current_line = 0; int buffer_length = 0; // Read the header from the vector file. char read_buffer [BUFFER_MAX_SIZE]; rewind(in); if (!get_next_vector(in, read_buffer)) error_message(SIMULATION_ERROR, 0, -1, "Failed to read vector headers."); // Parse the header, checking each entity against the corresponding line. char buffer [BUFFER_MAX_SIZE]; buffer[0] = '\0'; int i; for (i = 0; i < strlen(read_buffer) && i < BUFFER_MAX_SIZE; i++) { char next = read_buffer[i]; if (next == EOF) { warning_message(SIMULATION_ERROR, 0, -1, "Hit end of file."); return FALSE; } else if (next == ' ' || next == '\t' || next == '\n') { if (buffer_length) { if(strcmp(l->lines[current_line]->name,buffer)) { char *expected_header = generate_vector_header(l); warning_message(SIMULATION_ERROR, 0, -1, "Vector header mismatch: \n " " Found: %s " " Expected: %s", read_buffer, expected_header); free(expected_header); return FALSE; } else { buffer_length = 0; current_line++; } } if (next == '\n') break; } else { buffer[buffer_length++] = next; buffer[buffer_length] = '\0'; } } return TRUE; } /* * Verifies that no lines have null pins. */ int verify_lines (lines_t *l) { int i; for (i = 0; i < l->count; i++) { int j; for (j = 0; j < l->lines[i]->number_of_pins; j++) { if (!l->lines[i]->pins[j]) { warning_message(SIMULATION_ERROR, 0, -1, "A line %d:(%s) has a NULL pin. ", j, l->lines[i]->name); return FALSE; } } } return TRUE; } /* * Searches for a line with the given name in the lines. Returns the index * or -1 if no such line was found. */ int find_portname_in_lines(char* port_name, lines_t *l) { int j; for (j = 0; j < l->count; j++) if (!strcmp(l->lines[j]->name, port_name)) return j; return -1; } /* * allocates memory for and initialises a line_t struct */ line_t *create_line(char *name) { line_t *line = malloc(sizeof(line_t)); line->number_of_pins = 0; line->pins = 0; line->pin_numbers = 0; line->type = -1; line->name = malloc(sizeof(char)*(strlen(name)+1)); strcpy(line->name, name); return line; } /* * Generates the appropriate vector headers based on the given lines. */ char *generate_vector_header(lines_t *l) { char *header = calloc(BUFFER_MAX_SIZE, sizeof(char)); if (l->count) { int j; for (j = 0; j < l->count; j++) { // "+ 2" for null and newline/space. if ((strlen(header) + strlen(l->lines[j]->name) + 2) > BUFFER_MAX_SIZE) error_message(SIMULATION_ERROR, 0, -1, "Buffer overflow anticipated while generating vector header."); strcat(header,l->lines[j]->name); strcat(header," "); } header[strlen(header)-1] = '\n'; } else { header[0] = '\n'; } header = realloc(header, sizeof(char)*(strlen(header)+1)); return header; } /* * Stores the given test vector in the given lines, with some sanity checking to ensure that it * has a compatible geometry. */ void add_test_vector_to_lines(test_vector *v, lines_t *l, int cycle) { if (l->count < v->count) error_message(SIMULATION_ERROR, 0, -1, "Fewer lines (%d) than values (%d).", l->count, v->count); if (l->count > v->count) error_message(SIMULATION_ERROR, 0, -1, "More lines (%d) than values (%d).", l->count, v->count); int i; for (i = 0; i < v->count; i++) { line_t *line = l->lines[i]; if (line->number_of_pins < 1) error_message(SIMULATION_ERROR, 0, -1, "Found a line '%s' with no pins.", line->name); int j; for (j = 0; j < line->number_of_pins; j++) { if (j < v->counts[i]) update_pin_value(line->pins[j], v->values[i][j], cycle); else update_pin_value(line->pins[j], 0, cycle); } } } /* * Compares two test vectors for numerical and geometric identity. Returns FALSE if * they are found to be different, and TRUE otherwise. */ int compare_test_vectors(test_vector *v1, test_vector *v2) { if (v1->count != v2->count) { warning_message(SIMULATION_ERROR, 0, -1, "Vector lengths differ."); return FALSE; } int l; for (l = 0; l < v1->count; l++) { // Compare bit by bit. int i; for (i = 0; i < v1->counts[l] && i < v2->counts[l]; i++) if (v1->values[l][i] != v2->values[l][i]) return FALSE; /* * If one value has more bits than the other, they are still * equivalent as long as the higher order bits of the longer * one are zero. */ if (v1->counts[l] != v2->counts[l]) { test_vector *v = v1->counts[l] < v2->counts[l] ? v2 : v1; int j; for (j = i; j < v->counts[l]; j++) if (v->values[l][j] != 0) return FALSE; } } return TRUE; } /* * Parses the given line from a test vector file into a * test_vector data structure. */ test_vector *parse_test_vector(char *buffer) { buffer = strdup(buffer); test_vector *v = malloc(sizeof(test_vector)); v->values = 0; v->counts = 0; v->count = 0; trim_string(buffer,"\r\n"); const char *delim = " \t"; char *token = strtok(buffer, delim); while (token) { v->values = realloc(v->values, sizeof(signed char *) * (v->count + 1)); v->counts = realloc(v->counts, sizeof(int) * (v->count + 1)); v->values[v->count] = 0; v->counts[v->count] = 0; if (token[0] == '0' && (token[1] == 'x' || token[1] == 'X')) { // Value is hex. token += 2; int token_length = strlen(token); reverse_string(token, token_length); int i; for (i = 0; i < token_length; i++) { char temp[] = {token[i],'\0'}; int value = strtol(temp, NULL, 16); int k; for (k = 0; k < 4; k++) { signed char bit = 0; if (value > 0) { bit = value % 2; value /= 2; } v->values[v->count] = realloc(v->values[v->count], sizeof(signed char) * (v->counts[v->count] + 1)); v->values[v->count][v->counts[v->count]++] = bit; } } } else { // Value is binary. int i; for (i = strlen(token) - 1; i >= 0; i--) { signed char value = -1; if (token[i] == '0') value = 0; else if (token[i] == '1') value = 1; v->values[v->count] = realloc(v->values[v->count], sizeof(signed char) * (v->counts[v->count] + 1)); v->values[v->count][v->counts[v->count]++] = value; } } v->count++; token = strtok(NULL, delim); } free(buffer); return v; } /* * Generates a "random" test_vector structure based on the geometry of the given lines. * * If you want better randomness, call srand at some point. */ test_vector *generate_random_test_vector(lines_t *l, int cycle, hashtable_t *hold_high_index, hashtable_t *hold_low_index) { test_vector *v = malloc(sizeof(test_vector)); v->values = 0; v->counts = 0; v->count = 0; int i; for (i = 0; i < l->count; i++) { v->values = realloc(v->values, sizeof(signed char *) * (v->count + 1)); v->counts = realloc(v->counts, sizeof(int) * (v->count + 1)); v->values[v->count] = 0; v->counts[v->count] = 0; int j; for (j = 0; j < l->lines[i]->number_of_pins; j++) { char *name = l->lines[i]->name; signed char value; if (hold_high_index->count && hold_high_index->get(hold_high_index,name,sizeof(char)*strlen(name))) { if (!cycle) value = 0; else value = 1; } else if (hold_low_index->count && hold_low_index->get(hold_low_index,name,sizeof(char)*strlen(name))) { if (!cycle) value = 1; else value = 0; } else { // Passed via the -3 option. if (global_args.sim_generate_three_valued_logic) value = (rand() % 3) - 1; else value = (rand() % 2); } v->values[v->count] = realloc(v->values[v->count], sizeof(signed char) * (v->counts[v->count] + 1)); v->values[v->count][v->counts[v->count]++] = value; } v->count++; } return v; } /* * Writes a wave of vectors to the given file. Writes the headers * prior to cycle 0. * * When edge is -1, both edges of the clock are written. When edge is 0, * the falling edge is written. When edge is 1, the rising edge is written. */ void write_wave_to_file(lines_t *l, FILE* file, int cycle_offset, int wave_length, int edge) { if (!cycle_offset) write_vector_headers(file, l); int cycle; for (cycle = cycle_offset; cycle < (cycle_offset + wave_length); cycle++) { if (edge == -1 || (edge == 0 && is_even_cycle(cycle)) || (edge == 1 && !is_even_cycle(cycle))) write_vector_to_file(l, file, cycle); } } /* * Writes all values in the given lines to a line in the given file * for the given cycle. */ void write_vector_to_file(lines_t *l, FILE *file, int cycle) { char buffer[BUFFER_MAX_SIZE]; int i; for (i = 0; i < l->count; i++) { line_t *line = l->lines[i]; int num_pins = line->number_of_pins; if (line_has_unknown_pin(line, cycle) || num_pins == 1) { if ((num_pins + 1) > BUFFER_MAX_SIZE) error_message(SIMULATION_ERROR, 0, -1, "Buffer overflow anticipated while writing vector for line %s.", line->name); buffer[0] = 0; int j; int known_values = 0; for (j = num_pins - 1; j >= 0 ; j--) { signed char value = get_line_pin_value(line, j, cycle); if (value > 1){ error_message(SIMULATION_ERROR, 0, -1, "Invalid logic value of %d read from line %s.", value, line->name); } if (value < 0) { strcat(buffer, "x"); } else { known_values++; sprintf(buffer, "%s%d", buffer, value); } } // If there are no known values, print a single capital X. // (Only for testing. Breaks machine readability.) //if (!known_values && num_pins > 1) // sprintf(buffer, "X"); } else { // +1 for ceiling, +1 for null, +2 for "OX" if ((num_pins/4 + 1 + 1 + 2) > BUFFER_MAX_SIZE) error_message(SIMULATION_ERROR, 0, -1, "Buffer overflow anticipated while writing vector for line %s.", line->name); sprintf(buffer, "0X"); int hex_digit = 0; int j; for (j = num_pins - 1; j >= 0; j--) { signed char value = get_line_pin_value(line,j,cycle); if (value > 1) error_message(SIMULATION_ERROR, 0, -1, "Invalid logic value of %d read from line %s.", value, line->name); hex_digit += value << j % 4; if (!(j % 4)) { sprintf(buffer, "%s%X", buffer, hex_digit); hex_digit = 0; } } } // Expand the value to fill to space under the header. (Gets ugly sometimes.) //while (strlen(buffer) < strlen(l->lines[i]->name)) // strcat(buffer," "); fprintf(file,"%s ",buffer); } fprintf(file, "\n"); } /* * Writes a wave of vectors to the given modelsim out file. */ void write_wave_to_modelsim_file(netlist_t *netlist, lines_t *l, FILE* modelsim_out, int cycle_offset, int wave_length) { if (!cycle_offset) { fprintf(modelsim_out, "add wave *\n"); // Add clocks to the output file. int i; for (i = 0; i < netlist->num_top_input_nodes; i++) { nnode_t *node = netlist->top_input_nodes[i]; if (is_clock_node(node)) { char *port_name = get_port_name(node->name); fprintf(modelsim_out, "force %s 0 0, 1 50 -repeat 100\n", port_name); free(port_name); } } } int cycle; for (cycle = cycle_offset; cycle < (cycle_offset + wave_length); cycle ++) { if (!is_even_cycle(cycle)) write_vector_to_modelsim_file(l, modelsim_out, cycle); } } /* * Writes a vector to the given modelsim out file. */ void write_vector_to_modelsim_file(lines_t *l, FILE *modelsim_out, int cycle) { int i; for (i = 0; i < l->count; i++) { if (line_has_unknown_pin(l->lines[i], cycle) || l->lines[i]->number_of_pins == 1) { fprintf(modelsim_out, "force %s ",l->lines[i]->name); int j; for (j = l->lines[i]->number_of_pins - 1; j >= 0 ; j--) { int value = get_line_pin_value(l->lines[i],j,cycle); if (value < 0) fprintf(modelsim_out, "%s", "x"); else fprintf(modelsim_out, "%d", value); } fprintf(modelsim_out, " %d\n", cycle/2 * 100); } else { int value = 0; fprintf(modelsim_out, "force %s 16#", l->lines[i]->name); int j; for (j = l->lines[i]->number_of_pins - 1; j >= 0; j--) { if (get_line_pin_value(l->lines[i],j,cycle) > 0) value += my_power(2, j % 4); if (j % 4 == 0) { fprintf(modelsim_out, "%X", value); value = 0; } } fprintf(modelsim_out, " %d\n", cycle/2 * 100); } } } /* * Verify that the given output vector file is identical (numerically) * to the one written by the current simulation. This is done by parsing each * file vector by vector and comparing them. Also verifies that the headers are identical. * * Prints appropriate warning messages when differences are found. * * Returns false if the files differ and true if they are identical, with the exception of * number format. */ int verify_output_vectors(char* output_vector_file, int num_vectors) { if (global_args.sim_output_both_edges) num_vectors *= 2; int error = FALSE; // The filename cannot be the same as our default output file. if (!strcmp(output_vector_file,OUTPUT_VECTOR_FILE_NAME)) { error = TRUE; warning_message(SIMULATION_ERROR,0,-1, "Vector file \"%s\" given for verification " "is the same as the default output file \"%s\". " "Ignoring.", output_vector_file, OUTPUT_VECTOR_FILE_NAME); } else { // The file being verified against. FILE *existing_out = fopen(output_vector_file, "r"); if (!existing_out) error_message(SIMULATION_ERROR, 0, -1, "Could not open vector output file: %s", output_vector_file); // Our current output vectors. (Just produced.) FILE *current_out = fopen(OUTPUT_VECTOR_FILE_NAME, "r"); if (!current_out) error_message(SIMULATION_ERROR, 0, -1, "Could not open output vector file."); int cycle; char buffer1[BUFFER_MAX_SIZE]; char buffer2[BUFFER_MAX_SIZE]; // Start at cycle -1 to check the headers. for (cycle = -1; cycle < num_vectors; cycle++) { if (!get_next_vector(existing_out, buffer1)) { error = TRUE; warning_message(SIMULATION_ERROR, 0, -1,"Too few vectors in %s \n", output_vector_file); break; } else if (!get_next_vector(current_out, buffer2)) { error = TRUE; warning_message(SIMULATION_ERROR, 0, -1,"Simulation produced fewer than %d vectors. \n", num_vectors); break; } // The headers differ. else if ((cycle == -1) && strcmp(buffer1,buffer2)) { error = TRUE; warning_message(SIMULATION_ERROR, 0, -1, "Vector headers do not match: \n" "\t%s" "in %s does not match\n" "\t%s" "in %s.\n\n", buffer2, OUTPUT_VECTOR_FILE_NAME, buffer1, output_vector_file ); break; } else { // Parse both vectors. test_vector *v1 = parse_test_vector(buffer1); test_vector *v2 = parse_test_vector(buffer2); // Compare them and print an appropriate message if they differ. if (!compare_test_vectors(v1,v2)) { trim_string(buffer1, "\n\t"); trim_string(buffer2, "\n\t"); error = TRUE; warning_message(SIMULATION_ERROR, 0, -1, "Vector %d mismatch:\n" "\t%s in %s\n" "\t%s in %s\n", cycle, buffer2, OUTPUT_VECTOR_FILE_NAME, buffer1, output_vector_file ); } free_test_vector(v1); free_test_vector(v2); } } // If the file we're checking against is longer than the current output, print an appropriate warning. if (!error && get_next_vector(existing_out, buffer1)) { error = TRUE; warning_message(SIMULATION_ERROR, 0, -1,"%s contains more than %d vectors.\n", output_vector_file, num_vectors); } fclose(existing_out); fclose(current_out); } return !error; } /* * Creates a hastable_t index of the given pin names list * of the form pin name hashes to pin name array index. */ hashtable_t *index_pin_name_list(pin_names *list) { hashtable_t *index = create_hashtable(list->count * 2+1); int i; for (i = 0; i < list->count; i++) { int *id = malloc(sizeof(int)); *id = i; index->add(index, list->pins[i], sizeof(char)*strlen(list->pins[i]), id); } return index; } /* * Parses the given comma separated list into a * pin_names struct. If the list is empty or null * an empty struct is returned. */ pin_names *parse_pin_name_list(char *list) { pin_names *p = malloc(sizeof(pin_names)); p->pins = 0; p->count = 0; // Parse the list of additional pins passed via the -p option. if (list) { char *pin_list = strdup(list); char *token = strtok(pin_list, ","); while (token) { p->pins = realloc(p->pins, sizeof(char *) * (p->count + 1)); p->pins[p->count++] = strdup(token); token = strtok(NULL, ","); } free(pin_list); } return p; } /* * If the given node matches one of the additional names (passed via -p), * it's added to the lines. (Matches on output pin names, net names, and node names). */ void add_additional_items_to_lines(nnode_t *node, pin_names *p, lines_t *l) { if (p->count) { int add = FALSE; int j, k = 0; // Search the output pin names for each user-defined item. for (j = 0; j < node->num_output_pins; j++) { npin_t *pin = node->output_pins[j]; if (pin->name) { for (k = 0; k < p->count; k++) { if (strstr(pin->name, p->pins[k])) { add = TRUE; break; } } if (add) break; } if (pin->net && pin->net->name) { for (k = 0; k < p->count; k++) { if (strstr(pin->net->name, p->pins[k])) { add = TRUE; break; } } if (add) break; } } // Search the node name for each user defined item. if (!add && node->name && strlen(node->name) && strchr(node->name, '^')) { for (k = 0; k < p->count; k++) { if (strstr(node->name, p->pins[k])) { add = TRUE; break; } } } if (add) { int single_pin = strchr(p->pins[k], '~')?1:0; if (strchr(node->name, '^')) { char *port_name; if (single_pin) port_name = get_pin_name(node->name); else port_name = get_port_name(node->name); if (find_portname_in_lines(port_name, l) == -1) { line_t *line = create_line(port_name); l->lines = realloc(l->lines, sizeof(line_t *)*((l->count)+1)); l->lines[l->count++] = line; } assign_node_to_line(node, l, OUTPUT, single_pin); free(port_name); } } } } /* * Parses the given (memory) node name into a corresponding * mif file name. */ char *get_mif_filename(nnode_t *node) { char buffer[BUFFER_MAX_SIZE]; buffer[0] = 0; strcat(buffer, node->name); char *filename = strrchr(buffer, '+'); if (filename) filename += 1; else filename = buffer; strcat(filename, ".mif"); filename = strdup(filename); return filename; } /* * Trims characters in the given "chars" string * from the end of the given string. */ void trim_string(char* string, char *chars) { if (string) { int length; while((length = strlen(string))) { int trimmed = FALSE; int i; for (i = 0; i < strlen(chars); i++) { if (string[length-1] == chars[i]) { trimmed = TRUE; string[length-1] = '\0'; break; } } if (!trimmed) break; } } } /* * Returns TRUE if the given line has a pin for * the given cycle whose value is -1. */ int line_has_unknown_pin(line_t *line, int cycle) { int unknown = FALSE; int j; for (j = line->number_of_pins - 1; j >= 0; j--) { if (get_line_pin_value(line, j, cycle) < 0) { unknown = TRUE; break; } } return unknown; } /* * Gets the value of the pin given pin within the given line * for the given cycle. */ signed char get_line_pin_value(line_t *line, int pin_num, int cycle) { return get_pin_value(line->pins[pin_num],cycle); } /* * Returns a value from a test_vectors struct in hex. Works * for the values arrays in pins as well. */ char *vector_value_to_hex(signed char *value, int length) { char *tmp; char *string = calloc((length + 1),sizeof(char)); int j; for (j = 0; j < length; j++) string[j] = value[j] + '0'; reverse_string(string,strlen(string)); char *hex_string = malloc(sizeof(char) * ((length/4 + 1) + 1)); sprintf(hex_string, "%X ", (unsigned int)strtol(string, &tmp, 2)); free(string); return hex_string; } /* * Counts the number of vectors in the given file. */ int count_test_vectors(FILE *in) { rewind(in); int count = 0; char buffer[BUFFER_MAX_SIZE]; while (get_next_vector(in, buffer)) count++; if (count) // Don't count the headers. count--; rewind(in); return count; } /* * A given line is a vector if it contains one or more * non-whitespace characters and does not being with a #. */ int is_vector(char *buffer) { char *line = strdup(buffer); trim_string(line," \t\r\n"); if (line[0] != '#' && strlen(line)) { free(line); return TRUE; } else { free(line); return FALSE; } } /* * Gets the next line from the given file that * passes the is_vector() test and places it in * the buffer. Returns TRUE if a vector was found, * and FALSE if no vector was found. */ int get_next_vector(FILE *file, char *buffer) { while (fgets(buffer, BUFFER_MAX_SIZE, file)) if (is_vector(buffer)) return TRUE; return FALSE; } /* * Free each element in lines[] and the array itself */ void free_lines(lines_t *l) { int i; for (i = 0; i < l->count; i++) { free(l->lines[i]->name); free(l->lines[i]->pins); free(l->lines[i]); } free(l->lines); free(l); } /* * Free stages. */ void free_stages(stages *s) { while (s->count--) free(s->stages[s->count]); free(s->stages); free(s->counts); free(s); } /* * Free the given test_vector. */ void free_test_vector(test_vector* v) { while (v->count--) free(v->values[v->count]); free(v->values); free(v->counts); free(v); } /* * Frees pin_names struct. */ void free_pin_name_list(pin_names *p) { while (p->count--) free(p->pins[p->count]); free(p->pins); free(p); } /* * Prints/updates an ASCII progress bar of length "length" to position length * completion * from previous position "position". Updates ETA based on the elapsed time "time". * Returns the new position. If the position is unchanged the bar is not redrawn. * * Call with position = -1 to draw for the first time. Returns the new * position, calculated based on completion. */ int print_progress_bar(double completion, int position, int length, double time) { if (position == -1 || ((int)(completion * length)) > position) { printf("%3.0f%%|", completion * (double)100); position = completion * length; int i; for (i = 0; i < position; i++) printf("="); printf(">"); for (; i < length; i++) printf("-"); if (completion < 1.0) { printf("| Remaining: "); double remaining_time = time/(double)completion - time; print_time(remaining_time); } else { printf("| Total time: "); print_time(time); } printf(" \r"); if (position == length) printf("\n"); fflush(stdout); } return position; } /* * Prints information about the netlist we are simulating. */ void print_netlist_stats(stages *stages, int num_vectors) { printf("%s:\n", get_circuit_filename()); printf(" Nodes: %d\n", stages->num_nodes); printf(" Connections: %d\n", stages->num_connections); printf(" Degree: %3.2f\n", stages->num_connections/(float)stages->num_nodes); printf(" Stages: %d\n", stages->count); #ifdef _OPENMP printf(" Parallel nodes: %d (%4.1f%%)\n", stages->num_parallel_nodes, (stages->num_parallel_nodes/(double)stages->num_nodes) * 100); #endif printf("\n"); } /* * Prints statistics. (Coverage and times.) */ void print_simulation_stats(stages *stages, int num_vectors, double total_time, double simulation_time) { int covered_nodes = get_num_covered_nodes(stages); printf("Simulation time: "); print_time(simulation_time); printf("\n"); printf("Elapsed time: "); print_time(total_time); printf("\n"); printf("Coverage: " "%d (%4.1f%%)\n", covered_nodes, (covered_nodes/(double)stages->num_nodes) * 100); } /* * Prints the time in appropriate units. */ void print_time(double time) { if (time > 24*3600) printf("%.1fd", time/(24*3600.0)); else if (time > 3600) printf("%.1fh", time/3600.0); else if (time > 60) printf("%.1fm", time/60.0); else if (time > 1) printf("%.1fs", time); else printf("%.1fms", time*1000); } /* * Prints n ancestors of the given node, complete * with their parents, ids, etc. */ void print_ancestry(nnode_t *bottom_node, int n) { if (!n) n = 10; queue_t *queue = create_queue(); queue->add(queue, bottom_node); nnode_t *node; printf( " ------------\n"); printf( " BACKTRACE\n"); printf( " ------------\n"); while (n-- && (node = queue->remove(queue))) { char *name = get_pin_name(node->name); printf(" %s (%ld):\n", name, node->unique_id); free(name); int i; for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; nnet_t *net = pin->net; nnode_t *node = net->driver_pin->node; queue->add(queue, node); char *name = get_pin_name(node->name); printf("\t%s %s (%ld)\n", pin->mapping, name, node->unique_id);fflush(stdout); free(name); } /*int count = 0; { printf( " ------------\n"); printf( " CHILDREN \n"); printf( " ------------\n"); printf( " O: %d\n", node->num_output_pins);fflush(stdout); for (i = 0; i < node->num_output_pins; i++) { npin_t *pin = node->output_pins[i]; if (pin) { nnet_t *net = pin->net; if (net) { int j; for (j = 0; j < net->num_fanout_pins; j++) { npin_t *pin = net->fanout_pins[j]; if (pin) { nnode_t *node = pin->node; if (node) { char *name = get_pin_name(node->name); printf("\t%s %s (%ld)\n", pin->mapping, name, node->unique_id);fflush(stdout); free(name); } else { printf(" Null node %d\n", ++count);fflush(stdout); } } else { printf(" Null fanout pin\n");fflush(stdout); } } } else { printf(" Null net\n");fflush(stdout); } } } }*/ printf( " ------------\n"); } queue->destroy(queue); printf( " END OF TRACE\n"); printf( " ------------\n"); } /* * Traces an node which is failing to update back to parent of * the earliest node in the net list with an unupdated pin. * (Pin whose cycle is less than cycle-1). Prints all nodes * traversed during the trace with the original node printed * first, and the root of the issue printed last. * * Returns the root node for inspection. */ nnode_t *print_update_trace(nnode_t *bottom_node, int cycle) { // Limit the length of the trace. 0 for unlimited. const int max_depth = 0; printf( " --------------------------------------------------------------------------\n" " --------------------------------------------------------------------------\n" " BACKTRACE:\n" "\tFormat: Each node is listed followed by its parents. The parent \n" "\twhich is not updating is indicated with an astrisk. (*)\n" "\tEach node is listed in the form:\n" "\t\t(<mapping>) <Name> (<Unique ID>) <# of Parents> <# of Children> \n" " --------------------------------------------------------------------------\n" ); nnode_t *root_node = NULL; // Used to detect cycles. Based table size of max depth. If unlimited, set to something big. hashtable_t *index = create_hashtable(max_depth?(max_depth * 2):100000); queue_t *queue = create_queue(); queue->add(queue, bottom_node); nnode_t *node; int depth = 0; // Traverse the netlist in reverse, starting with our current location. while ((node = queue->remove(queue))) { int found_undriven_pin = FALSE; int is_duplicate = index->get(index, &node->unique_id, sizeof(long))?1:0; if (!is_duplicate) { depth++; index->add(index, &node->unique_id, sizeof(long), (void *)1); char *name = get_pin_name(node->name); printf(" %s (%ld) %d %d\n", name, node->unique_id, node->num_input_pins, node->num_output_pins); free(name); int i; for (i = 0; i < node->num_input_pins; i++) { npin_t *pin = node->input_pins[i]; nnet_t *net = pin->net; nnode_t *node = net->driver_pin->node; // If an input is found which hasn't been updated since before cycle-1, traverse it. int is_undriven = FALSE; if (get_pin_cycle(pin) < cycle-1) { // Only add each node for traversal once. if (!found_undriven_pin) { found_undriven_pin = TRUE; queue->add(queue, node); } is_undriven = TRUE; } char *name = get_pin_name(node->name); printf("\t(%s) %s (%ld) %d %d %s \n", pin->mapping, name, node->unique_id, node->num_input_pins, node->num_output_pins, is_undriven?"*":""); free(name); } printf(" ------------\n"); } else { printf(" CYCLE DETECTED AFTER %d NODES.\n", depth); printf(" ------------\n"); break; } if (!found_undriven_pin) { printf(" TOP OF TRACE\n"); printf(" ------------\n"); root_node = node; break; } else if (max_depth && depth >=max_depth) { printf(" TRACE TRUNCATED AT %d NODES.\n", max_depth); printf(" ------------\n"); break; } } index->destroy(index); queue->destroy(queue); return root_node; } /* * Gets the current time in seconds. */ inline double wall_time() { struct timeval tv; gettimeofday(&tv, 0); return (1000000*tv.tv_sec+tv.tv_usec)/1.0e6; } /* * Gets the name of the file we are simulating as passed by the -b or -V option. */ char *get_circuit_filename() { return global_args.verilog_file?global_args.verilog_file:global_args.blif_file; }
deconv_dw_kernel_arm.c
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the License); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright (c) 2021, OPEN AI LAB Author: haoluo@openailab.com */ #include "deconv_dw_kernel_arm.h" #include <stdint.h> #include <stdlib.h> #include <math.h> #include <arm_neon.h> #define DECONV_DW_MAX(a, b) ((a) > (b) ? (a) : (b)) #define DECONV_DW_MIN(a, b) ((a) < (b) ? (a) : (b)) #ifdef __aarch64__ #else #endif inline static float do_activation(float input, int activation) { if (activation == 0) { input = DECONV_DW_MAX(input, 0); if (activation == 6) input = DECONV_DW_MIN(input, 6); } return input; } inline static void initial_output(float* output, float* bias, int output_ch, int output_wh) { int i, j; // no bias if (bias == NULL) { memset(output, 0.f, output_ch * output_wh * sizeof(float)); } else { float* out_ptr = output; for (i = 0; i < output_ch; i++) for (j = 0; j < output_wh; j++) *out_ptr++ = bias[i]; } } inline static void deconv_dw_genreal_3x3s1(const float* input, const float* kernel, float* output, int group, int input_h, int input_w, int output_h, int output_w, int num_thread) { #pragma omp parallel for num_threads(num_thread) for (int c = 0; c < group; c++) { const float* cur_input = input + c * input_h * input_w; const float* cur_kernel = kernel + c * 9; float32x4_t _k0 = vld1q_f32(cur_kernel); float32x4_t _k1 = vld1q_f32(cur_kernel + 3); float32x4_t _k2 = vld1q_f32(cur_kernel + 6); for (int i = 0; i < input_h; i++) { float* cur_out0 = output + c * output_h * output_w + output_w * i; float* cur_out1 = output + c * output_h * output_w + output_w * (i + 1); float* cur_out2 = output + c * output_h * output_w + output_w * (i + 2); int j = 0; for (; j + 3 < input_w; j += 4) { float32x4_t input_4 = vld1q_f32(cur_input); float32x4_t out_00 = vld1q_f32(cur_out0 + 0); out_00 = vmlaq_lane_f32(out_00, input_4, vget_low_f32(_k0), 0); vst1q_f32(cur_out0 + 0, out_00); float32x4_t out_01 = vld1q_f32(cur_out0 + 1); out_01 = vmlaq_lane_f32(out_01, input_4, vget_low_f32(_k0), 1); vst1q_f32(cur_out0 + 1, out_01); float32x4_t out_02 = vld1q_f32(cur_out0 + 2); out_02 = vmlaq_lane_f32(out_02, input_4, vget_high_f32(_k0), 0); vst1q_f32(cur_out0 + 2, out_02); float32x4_t out_10 = vld1q_f32(cur_out1 + 0); out_10 = vmlaq_lane_f32(out_10, input_4, vget_low_f32(_k1), 0); vst1q_f32(cur_out1 + 0, out_10); float32x4_t out_11 = vld1q_f32(cur_out1 + 1); out_11 = vmlaq_lane_f32(out_11, input_4, vget_low_f32(_k1), 1); vst1q_f32(cur_out1 + 1, out_11); float32x4_t out_12 = vld1q_f32(cur_out1 + 2); out_12 = vmlaq_lane_f32(out_12, input_4, vget_high_f32(_k1), 0); vst1q_f32(cur_out1 + 2, out_12); float32x4_t out_20 = vld1q_f32(cur_out2 + 0); out_20 = vmlaq_lane_f32(out_20, input_4, vget_low_f32(_k2), 0); vst1q_f32(cur_out2 + 0, out_20); float32x4_t out_21 = vld1q_f32(cur_out2 + 1); out_21 = vmlaq_lane_f32(out_21, input_4, vget_low_f32(_k2), 1); vst1q_f32(cur_out2 + 1, out_21); float32x4_t out_22 = vld1q_f32(cur_out2 + 2); out_22 = vmlaq_lane_f32(out_22, input_4, vget_high_f32(_k2), 0); vst1q_f32(cur_out2 + 2, out_22); cur_input += 4; cur_out0 += 4; cur_out1 += 4; cur_out2 += 4; } for (; j < input_w; j++) { float val = cur_input[0]; cur_out0[0] += val * cur_kernel[0]; cur_out0[1] += val * cur_kernel[1]; cur_out0[2] += val * cur_kernel[2]; cur_out1[0] += val * cur_kernel[3]; cur_out1[1] += val * cur_kernel[4]; cur_out1[2] += val * cur_kernel[5]; cur_out2[0] += val * cur_kernel[6]; cur_out2[1] += val * cur_kernel[7]; cur_out2[2] += val * cur_kernel[8]; cur_input++; cur_out0++; cur_out1++; cur_out2++; } } } } inline static void deconv_dw_genreal_3x3s2(const float* input, const float* kernel, float* output, int group, int input_h, int input_w, int output_h, int output_w, int num_thread) { #pragma omp parallel for num_threads(num_thread) for (int c = 0; c < group; c++) { const float* cur_input = input + c * input_h * input_w; const float* cur_kernel = kernel + c * 9; float32x4_t _k0 = vld1q_f32(cur_kernel); float32x4_t _k1 = vld1q_f32(cur_kernel + 3); float32x4_t _k2 = vld1q_f32(cur_kernel + 6); for (int i = 0; i < input_h; i++) { float* cur_out0 = output + c * output_h * output_w + output_w * i * 2; float* cur_out1 = output + c * output_h * output_w + output_w * (i * 2 + 1); float* cur_out2 = output + c * output_h * output_w + output_w * (i * 2 + 2); int j = 0; for (; j + 3 < input_w; j += 4) { float32x4_t input_4 = vld1q_f32(cur_input); // out row 0 float32x4_t out_00 = vmulq_lane_f32(input_4, vget_low_f32(_k0), 0); // 0,2,4,6 float32x4_t out_01 = vmulq_lane_f32(input_4, vget_low_f32(_k0), 1); // 1,3,5,7 float32x4_t out_02 = vmulq_lane_f32(input_4, vget_high_f32(_k0), 0); // 2,4,6,8 float32x4x2_t out_0 = vld2q_f32(cur_out0); out_0.val[0] = vaddq_f32(out_0.val[0], out_00); // 0,2,4,6 out_0.val[1] = vaddq_f32(out_0.val[1], out_01); // 1,3,5,7 vst2q_f32(cur_out0, out_0); out_0 = vld2q_f32(cur_out0 + 2); out_0.val[0] = vaddq_f32(out_0.val[0], out_02); // 2,4,6,8 vst2q_f32(cur_out0 + 2, out_0); // out row 1 float32x4_t out_10 = vmulq_lane_f32(input_4, vget_low_f32(_k1), 0); // 0,2,4,6 float32x4_t out_11 = vmulq_lane_f32(input_4, vget_low_f32(_k1), 1); // 1,3,5,7 float32x4_t out_12 = vmulq_lane_f32(input_4, vget_high_f32(_k1), 0); // 2,4,6,8 float32x4x2_t out_1 = vld2q_f32(cur_out1); out_1.val[0] = vaddq_f32(out_1.val[0], out_10); // 0,2,4,6 out_1.val[1] = vaddq_f32(out_1.val[1], out_11); // 1,3,5,7 vst2q_f32(cur_out1, out_1); out_1 = vld2q_f32(cur_out1 + 2); out_1.val[0] = vaddq_f32(out_1.val[0], out_12); // 2,4,6,8 vst2q_f32(cur_out1 + 2, out_1); // out row 2 float32x4_t out_20 = vmulq_lane_f32(input_4, vget_low_f32(_k2), 0); // 0,2,4,6 float32x4_t out_21 = vmulq_lane_f32(input_4, vget_low_f32(_k2), 1); // 1,3,5,7 float32x4_t out_22 = vmulq_lane_f32(input_4, vget_high_f32(_k2), 0); // 2,4,6,8 float32x4x2_t out_2 = vld2q_f32(cur_out2); out_2.val[0] = vaddq_f32(out_2.val[0], out_20); // 0,2,4,6 out_2.val[1] = vaddq_f32(out_2.val[1], out_21); // 1,3,5,7 vst2q_f32(cur_out2, out_2); out_2 = vld2q_f32(cur_out2 + 2); out_2.val[0] = vaddq_f32(out_2.val[0], out_22); // 2,4,6,8 vst2q_f32(cur_out2 + 2, out_2); cur_input += 4; cur_out0 += 8; cur_out1 += 8; cur_out2 += 8; } for (; j < input_w; j++) { float val = cur_input[0]; cur_out0[0] += val * cur_kernel[0]; cur_out0[1] += val * cur_kernel[1]; cur_out0[2] += val * cur_kernel[2]; cur_out1[0] += val * cur_kernel[4]; cur_out1[1] += val * cur_kernel[5]; cur_out1[2] += val * cur_kernel[6]; cur_out2[0] += val * cur_kernel[8]; cur_out2[1] += val * cur_kernel[9]; cur_out2[2] += val * cur_kernel[10]; cur_input++; cur_out0 += 2; cur_out1 += 2; cur_out2 += 2; } } } } inline static void deconv_dw_genreal_4x4s1(const float* input, const float* kernel, float* output, int group, int input_h, int input_w, int output_h, int output_w, int num_thread) { #pragma omp parallel for num_threads(num_thread) for (int c = 0; c < group; c++) { const float* cur_input = input + c * input_h * input_w; const float* cur_kernel = kernel + c * 16; float32x4_t _k0 = vld1q_f32(cur_kernel); float32x4_t _k1 = vld1q_f32(cur_kernel + 4); float32x4_t _k2 = vld1q_f32(cur_kernel + 8); float32x4_t _k3 = vld1q_f32(cur_kernel + 12); for (int i = 0; i < input_h; i++) { float* cur_out0 = output + c * output_h * output_w + output_w * i; float* cur_out1 = output + c * output_h * output_w + output_w * (i + 1); float* cur_out2 = output + c * output_h * output_w + output_w * (i + 2); float* cur_out3 = output + c * output_h * output_w + output_w * (i + 3); int j = 0; for (; j + 3 < input_w; j += 4) { float32x4_t input_4 = vld1q_f32(cur_input); float32x4_t out_00 = vld1q_f32(cur_out0 + 0); out_00 = vmlaq_lane_f32(out_00, input_4, vget_low_f32(_k0), 0); vst1q_f32(cur_out0 + 0, out_00); float32x4_t out_01 = vld1q_f32(cur_out0 + 1); out_01 = vmlaq_lane_f32(out_01, input_4, vget_low_f32(_k0), 1); vst1q_f32(cur_out0 + 1, out_01); float32x4_t out_02 = vld1q_f32(cur_out0 + 2); out_02 = vmlaq_lane_f32(out_02, input_4, vget_high_f32(_k0), 0); vst1q_f32(cur_out0 + 2, out_02); float32x4_t out_03 = vld1q_f32(cur_out0 + 3); out_03 = vmlaq_lane_f32(out_03, input_4, vget_high_f32(_k0), 1); vst1q_f32(cur_out0 + 3, out_03); float32x4_t out_10 = vld1q_f32(cur_out1 + 0); out_10 = vmlaq_lane_f32(out_10, input_4, vget_low_f32(_k1), 0); vst1q_f32(cur_out1 + 0, out_10); float32x4_t out_11 = vld1q_f32(cur_out1 + 1); out_11 = vmlaq_lane_f32(out_11, input_4, vget_low_f32(_k1), 1); vst1q_f32(cur_out1 + 1, out_11); float32x4_t out_12 = vld1q_f32(cur_out1 + 2); out_12 = vmlaq_lane_f32(out_12, input_4, vget_high_f32(_k1), 0); vst1q_f32(cur_out1 + 2, out_12); float32x4_t out_13 = vld1q_f32(cur_out1 + 3); out_13 = vmlaq_lane_f32(out_13, input_4, vget_high_f32(_k1), 1); vst1q_f32(cur_out1 + 3, out_13); float32x4_t out_20 = vld1q_f32(cur_out2 + 0); out_20 = vmlaq_lane_f32(out_20, input_4, vget_low_f32(_k2), 0); vst1q_f32(cur_out2 + 0, out_20); float32x4_t out_21 = vld1q_f32(cur_out2 + 1); out_21 = vmlaq_lane_f32(out_21, input_4, vget_low_f32(_k2), 1); vst1q_f32(cur_out2 + 1, out_21); float32x4_t out_22 = vld1q_f32(cur_out2 + 2); out_22 = vmlaq_lane_f32(out_22, input_4, vget_high_f32(_k2), 0); vst1q_f32(cur_out2 + 2, out_22); float32x4_t out_23 = vld1q_f32(cur_out2 + 3); out_23 = vmlaq_lane_f32(out_23, input_4, vget_high_f32(_k2), 1); vst1q_f32(cur_out2 + 3, out_23); float32x4_t out_30 = vld1q_f32(cur_out3 + 0); out_30 = vmlaq_lane_f32(out_30, input_4, vget_low_f32(_k3), 0); vst1q_f32(cur_out3 + 0, out_30); float32x4_t out_31 = vld1q_f32(cur_out3 + 1); out_31 = vmlaq_lane_f32(out_31, input_4, vget_low_f32(_k3), 1); vst1q_f32(cur_out3 + 1, out_31); float32x4_t out_32 = vld1q_f32(cur_out3 + 2); out_32 = vmlaq_lane_f32(out_32, input_4, vget_high_f32(_k3), 0); vst1q_f32(cur_out3 + 2, out_32); float32x4_t out_33 = vld1q_f32(cur_out3 + 3); out_33 = vmlaq_lane_f32(out_33, input_4, vget_high_f32(_k3), 1); vst1q_f32(cur_out3 + 3, out_33); cur_input += 4; cur_out0 += 4; cur_out1 += 4; cur_out2 += 4; cur_out3 += 4; } for (; j < input_w; j++) { float val = cur_input[0]; cur_out0[0] += val * cur_kernel[0]; cur_out0[1] += val * cur_kernel[1]; cur_out0[2] += val * cur_kernel[2]; cur_out0[3] += val * cur_kernel[3]; cur_out1[0] += val * cur_kernel[4]; cur_out1[1] += val * cur_kernel[5]; cur_out1[2] += val * cur_kernel[6]; cur_out1[3] += val * cur_kernel[7]; cur_out2[0] += val * cur_kernel[8]; cur_out2[1] += val * cur_kernel[9]; cur_out2[2] += val * cur_kernel[10]; cur_out2[3] += val * cur_kernel[11]; cur_out3[0] += val * cur_kernel[12]; cur_out3[1] += val * cur_kernel[13]; cur_out3[2] += val * cur_kernel[14]; cur_out3[3] += val * cur_kernel[15]; cur_input++; cur_out0++; cur_out1++; cur_out2++; cur_out3++; } } } } void deconv_dw_genreal(float* input, float* output, float* kernel, int input_h, int input_w, int output_h, int output_w, int group, int kernel_h, int kernel_w, int stride_h, int stride_w, int dilation_h, int dilation_w, int pad_h, int pad_w, int activation, int num_thread) { int h, w, k_h, k_w; #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < group; g++) { for (h = 0; h < input_h; h++) { for (w = 0; w < input_w; w++) { int org_out_x = w * stride_w - pad_w; int org_out_y = h * stride_h - pad_h; int input_offset = g * input_h * input_w + h * input_w + w; for (k_h = 0; k_h < kernel_h; k_h++) { for (k_w = 0; k_w < kernel_w; k_w++) { int cur_out_x = org_out_x + k_w * dilation_w; int cur_out_y = org_out_y + k_h * dilation_h; if (cur_out_x >= 0 && cur_out_x < output_w && cur_out_y >= 0 && cur_out_y < output_h) { int kernel_offset = g * kernel_h * kernel_w + k_h * kernel_w + k_w; int output_offset = g * output_w * output_h + cur_out_y * output_w + cur_out_x; output[output_offset] += kernel[kernel_offset] * input[input_offset]; } } } } } } if (activation == 0 || activation == 6) { int size = group * output_h * output_w; for (int i = 0; i < size; i++) { output[i] = do_activation(output[i], activation); } } } int deconv_dw_run(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct deconv_param* param, int num_thread, int cpu_affinity) { /* param */ int pads[4]; int group = param->group; int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int stride_h = param->stride_h; int stride_w = param->stride_w; int dilation_h = param->dilation_h; int dilation_w = param->dilation_w; pads[0] = param->pad_h0; pads[1] = param->pad_w0; pads[2] = param->pad_h1; pads[3] = param->pad_w1; if (stride_h != stride_w) return -1; int act_type = param->activation; int batch = input_tensor->dims[0]; int in_c = input_tensor->dims[1] / group; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; int input_size = in_c * in_h * in_w; int kernel_size = in_c * kernel_h * kernel_w; int out_c = output_tensor->dims[1] / group; int out_h = output_tensor->dims[2]; int out_w = output_tensor->dims[3]; int out_hw = out_h * out_w; int output_size = out_c * out_h * out_w; int out_c_align = ((out_c + 3) & -4); /* buffer addr */ float* input_buf = (float*)input_tensor->data; float* kernel_buf = (float*)filter_tensor->data; float* output_buf = (float*)output_tensor->data; float* biases_buf = (float*)bias_tensor->data; for (int n = 0; n < batch; n++) // batch size { float* cur_input = input_buf + n * input_size * group; float* cur_output = output_buf + n * output_size * group; initial_output(cur_output, biases_buf, group, out_hw); if (pads[0] == 0) { if (stride_h == 1 && kernel_h == 4) { deconv_dw_genreal_4x4s1(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w, num_thread); } else if (kernel_h == 3) { if (stride_h == 1) deconv_dw_genreal_3x3s1(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w, num_thread); else deconv_dw_genreal_3x3s2(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w, num_thread); } else { deconv_dw_genreal(cur_input, cur_output, kernel_buf, in_h, in_w, out_h, out_w, group, kernel_h, kernel_w, stride_h, stride_w, dilation_h, dilation_w, pads[0], pads[1], act_type, num_thread); } } else { int out_h_pad = out_h + pads[0] * 2; int out_w_pad = out_w + pads[1] * 2; float* output_buf = (float*)malloc(sizeof(float) * group * out_h_pad * out_w_pad + 128); if (stride_h == 1 && kernel_h == 4) { deconv_dw_genreal_4x4s1(cur_input, kernel_buf, output_buf, group, in_h, in_w, out_h, out_w, num_thread); for (int g = 0; g < group; g++) { for (int i = 0; i < out_h; i++) { float* cur_src = output_buf + g * out_h_pad * out_w_pad + (pads[0] + i) * out_w_pad + pads[1]; float* cur_dst = cur_output + g * out_hw + i * out_w; for (int j = 0; j < out_w; j++) cur_dst[j] += cur_src[j]; } } } else if (kernel_h == 3) { if (stride_h == 1) deconv_dw_genreal_3x3s1(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w, num_thread); else deconv_dw_genreal_3x3s2(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w, num_thread); for (int g = 0; g < group; g++) { for (int i = 0; i < out_h; i++) { float* cur_src = output_buf + g * out_h_pad * out_w_pad + (pads[0] + i) * out_w_pad + pads[1]; float* cur_dst = cur_output + g * out_hw + i * out_w; for (int j = 0; j < out_w; j++) cur_dst[j] += cur_src[j]; } } } else { deconv_dw_genreal(cur_input, cur_output, kernel_buf, in_h, in_w, out_h, out_w, group, kernel_h, kernel_w, stride_h, stride_w, dilation_h, dilation_w, pads[0], pads[1], act_type, num_thread); } free(output_buf); } } return 0; }
threshold.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/property.h" #include "magick/blob.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/configure.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/effect.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/montage.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/shear.h" #include "magick/signature-private.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/xml-tree.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* Static declarations. */ static const char *MinimalThresholdMap = "<?xml version=\"1.0\"?>" "<thresholds>" " <threshold map=\"threshold\" alias=\"1x1\">" " <description>Threshold 1x1 (non-dither)</description>" " <levels width=\"1\" height=\"1\" divisor=\"2\">" " 1" " </levels>" " </threshold>" " <threshold map=\"checks\" alias=\"2x1\">" " <description>Checkerboard 2x1 (dither)</description>" " <levels width=\"2\" height=\"2\" divisor=\"3\">" " 1 2" " 2 1" " </levels>" " </threshold>" "</thresholds>"; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image, % const size_t width,const size_t height, % const ssize_t offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o offset: the mean offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if ((width == 0) || (height == 0)) return(threshold_image); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) (width*height); image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket channel_bias, channel_sum; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict threshold_indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); channel_bias=zero; channel_sum=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) { channel_bias.red+=r[u].red; channel_bias.green+=r[u].green; channel_bias.blue+=r[u].blue; channel_bias.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } channel_sum.red+=r[u].red; channel_sum.green+=r[u].green; channel_sum.blue+=r[u].blue; channel_sum.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } r+=image->columns+width; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean; mean=zero; r=p; channel_sum.red-=channel_bias.red; channel_sum.green-=channel_bias.green; channel_sum.blue-=channel_bias.blue; channel_sum.opacity-=channel_bias.opacity; channel_sum.index-=channel_bias.index; channel_bias=zero; for (v=0; v < (ssize_t) height; v++) { channel_bias.red+=r[0].red; channel_bias.green+=r[0].green; channel_bias.blue+=r[0].blue; channel_bias.opacity+=r[0].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0); channel_sum.red+=r[width-1].red; channel_sum.green+=r[width-1].green; channel_sum.blue+=r[width-1].blue; channel_sum.opacity+=r[width-1].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+ width-1); r+=image->columns+width; } mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset); mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset); mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset); mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex( threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoThresholdImage() automatically performs image thresholding % dependent on which method you specify. % % The format of the AutoThresholdImage method is: % % MagickBooleanType AutoThresholdImage(Image *image, % const AutoThresholdMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-threshold. % % o method: choose from Kapur, OTSU, or Triangle. % % o exception: return any errors or warnings in this structure. % */ static double KapurThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { #define MaxIntensity 255 double *black_entropy, *cumulative_histogram, entropy, epsilon, maximum_entropy, *white_entropy; register ssize_t i, j; size_t threshold; /* Compute optimal threshold from the entopy of the histogram. */ cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*cumulative_histogram)); black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*black_entropy)); white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*white_entropy)); if ((cumulative_histogram == (double *) NULL) || (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL)) { if (white_entropy != (double *) NULL) white_entropy=(double *) RelinquishMagickMemory(white_entropy); if (black_entropy != (double *) NULL) black_entropy=(double *) RelinquishMagickMemory(black_entropy); if (cumulative_histogram != (double *) NULL) cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Entropy for black and white parts of the histogram. */ cumulative_histogram[0]=histogram[0]; for (i=1; i <= MaxIntensity; i++) cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i]; epsilon=MagickMinimumValue; for (j=0; j <= MaxIntensity; j++) { /* Black entropy. */ black_entropy[j]=0.0; if (cumulative_histogram[j] > epsilon) { entropy=0.0; for (i=0; i <= j; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/cumulative_histogram[j]* log(histogram[i]/cumulative_histogram[j]); black_entropy[j]=entropy; } /* White entropy. */ white_entropy[j]=0.0; if ((1.0-cumulative_histogram[j]) > epsilon) { entropy=0.0; for (i=j+1; i <= MaxIntensity; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/(1.0-cumulative_histogram[j])* log(histogram[i]/(1.0-cumulative_histogram[j])); white_entropy[j]=entropy; } } /* Find histogram bin with maximum entropy. */ maximum_entropy=black_entropy[0]+white_entropy[0]; threshold=0; for (j=1; j <= MaxIntensity; j++) if ((black_entropy[j]+white_entropy[j]) > maximum_entropy) { maximum_entropy=black_entropy[j]+white_entropy[j]; threshold=(size_t) j; } /* Free resources. */ white_entropy=(double *) RelinquishMagickMemory(white_entropy); black_entropy=(double *) RelinquishMagickMemory(black_entropy); cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); return(100.0*threshold/MaxIntensity); } static double OTSUThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { double max_sigma, *myu, *omega, *probability, *sigma, threshold; register ssize_t i; /* Compute optimal threshold from maximization of inter-class variance. */ myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu)); omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega)); probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*probability)); sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma)); if ((myu == (double *) NULL) || (omega == (double *) NULL) || (probability == (double *) NULL) || (sigma == (double *) NULL)) { if (sigma != (double *) NULL) sigma=(double *) RelinquishMagickMemory(sigma); if (probability != (double *) NULL) probability=(double *) RelinquishMagickMemory(probability); if (omega != (double *) NULL) omega=(double *) RelinquishMagickMemory(omega); if (myu != (double *) NULL) myu=(double *) RelinquishMagickMemory(myu); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Calculate probability density. */ for (i=0; i <= (ssize_t) MaxIntensity; i++) probability[i]=histogram[i]; /* Generate probability of graylevels and mean value for separation. */ omega[0]=probability[0]; myu[0]=0.0; for (i=1; i <= (ssize_t) MaxIntensity; i++) { omega[i]=omega[i-1]+probability[i]; myu[i]=myu[i-1]+i*probability[i]; } /* Sigma maximization: inter-class variance and compute optimal threshold. */ threshold=0; max_sigma=0.0; for (i=0; i < (ssize_t) MaxIntensity; i++) { sigma[i]=0.0; if ((omega[i] != 0.0) && (omega[i] != 1.0)) sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0- omega[i])); if (sigma[i] > max_sigma) { max_sigma=sigma[i]; threshold=(double) i; } } /* Free resources. */ myu=(double *) RelinquishMagickMemory(myu); omega=(double *) RelinquishMagickMemory(omega); probability=(double *) RelinquishMagickMemory(probability); sigma=(double *) RelinquishMagickMemory(sigma); return(100.0*threshold/MaxIntensity); } static double TriangleThreshold(const Image *image,const double *histogram) { double a, b, c, count, distance, inverse_ratio, max_distance, segment, x1, x2, y1, y2; register ssize_t i; ssize_t end, max, start, threshold; /* Compute optimal threshold with triangle algorithm. */ magick_unreferenced(image); start=0; /* find start bin, first bin not zero count */ for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > 0.0) { start=i; break; } end=0; /* find end bin, last bin not zero count */ for (i=(ssize_t) MaxIntensity; i >= 0; i--) if (histogram[i] > 0.0) { end=i; break; } max=0; /* find max bin, bin with largest count */ count=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) if (histogram[i] > count) { max=i; count=histogram[i]; } /* Compute threshold at split point. */ x1=(double) max; y1=histogram[max]; x2=(double) end; if ((max-start) >= (end-max)) x2=(double) start; y2=0.0; a=y1-y2; b=x2-x1; c=(-1.0)*(a*x1+b*y1); inverse_ratio=1.0/sqrt(a*a+b*b+c*c); threshold=0; max_distance=0.0; if (x2 == (double) start) for (i=start; i < max; i++) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment > 0.0)) { threshold=i; max_distance=distance; } } else for (i=end; i > max; i--) { segment=inverse_ratio*(a*i+b*histogram[i]+c); distance=sqrt(segment*segment); if ((distance > max_distance) && (segment < 0.0)) { threshold=i; max_distance=distance; } } return(100.0*threshold/MaxIntensity); } MagickExport MagickBooleanType AutoThresholdImage(Image *image, const AutoThresholdMethod method,ExceptionInfo *exception) { CacheView *image_view; char property[MagickPathExtent]; double gamma, *histogram, sum, threshold; MagickBooleanType status; register ssize_t i; ssize_t y; /* Form histogram. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; (void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { double intensity = GetPixelIntensity(image,p); histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++; p++; } } image_view=DestroyCacheView(image_view); /* Normalize histogram. */ sum=0.0; for (i=0; i <= (ssize_t) MaxIntensity; i++) sum+=histogram[i]; gamma=PerceptibleReciprocal(sum); for (i=0; i <= (ssize_t) MaxIntensity; i++) histogram[i]=gamma*histogram[i]; /* Discover threshold from histogram. */ switch (method) { case KapurThresholdMethod: { threshold=KapurThreshold(image,histogram,exception); break; } case OTSUThresholdMethod: default: { threshold=OTSUThreshold(image,histogram,exception); break; } case TriangleThresholdMethod: { threshold=TriangleThreshold(image,histogram); break; } } histogram=(double *) RelinquishMagickMemory(histogram); if (threshold < 0.0) status=MagickFalse; if (status == MagickFalse) return(MagickFalse); /* Threshold image. */ (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold); (void) SetImageProperty(image,"auto-threshold:threshold",property); return(BilevelImage(image,QuantumRange*threshold/100.0)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImageChannel method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold) % MagickBooleanType BilevelImageChannel(Image *image, % const ChannelType channel,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o threshold: define the threshold values. % % Aside: You can get the same results as operator using LevelImageChannels() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold) { MagickBooleanType status; status=BilevelImageChannel(image,DefaultChannels,threshold); return(status); } MagickExport MagickBooleanType BilevelImageChannel(Image *image, const ChannelType channel,const double threshold) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); /* Bilevel threshold image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); if ((channel & SyncChannels) != 0) { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelIntensity(image,q) <= threshold ? 0 : QuantumRange); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold ? 0 : QuantumRange); else SetPixelAlpha(q,(MagickRealType) GetPixelAlpha(q) <= threshold ? OpaqueOpacity : TransparentOpacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image,const char *threshold) % MagickBooleanType BlackThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=BlackThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); GetMagickPixelPacket(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* Black threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) < threshold.red)) SetPixelRed(q,0); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) < threshold.green)) SetPixelGreen(q,0); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) < threshold.blue)) SetPixelBlue(q,0); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) < threshold.opacity)) SetPixelOpacity(q,0); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x) < threshold.index)) SetPixelIndex(indexes+x,0); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() set each pixel whose value is below zero to zero and any the % pixel whose value is above the quantum range to the quantum range (e.g. % 65535) otherwise the pixel value remains unchanged. % % The format of the ClampImageChannel method is: % % MagickBooleanType ClampImage(Image *image) % MagickBooleanType ClampImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % */ MagickExport MagickBooleanType ClampImage(Image *image) { MagickBooleanType status; status=ClampImageChannel(image,DefaultChannels); return(status); } MagickExport MagickBooleanType ClampImageChannel(Image *image, const ChannelType channel) { #define ClampImageTag "Clamp/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q))); SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q))); SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q))); SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q))); q++; } return(SyncImage(image)); } /* Clamp image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q))); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,ClampPixel((MagickRealType) GetPixelIndex( indexes+x))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ClampImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMapFile(const char *xml, const char *filename,const char *map_id,ExceptionInfo *exception) { const char *attribute, *content; double value; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; map = (ThresholdMap *) NULL; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(map); for (threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { attribute=GetXMLTreeAttribute(threshold, "map"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; attribute=GetXMLTreeAttribute(threshold, "alias"); if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0)) break; } if (threshold == (XMLTreeInfo *) NULL) { thresholds=DestroyXMLTree(thresholds); return(map); } description=GetXMLTreeChild(threshold,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } levels=GetXMLTreeChild(threshold,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); return(map); } /* The map has been found -- allocate a Threshold Map to return */ map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap)); if (map == (ThresholdMap *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); map->map_id=(char *) NULL; map->description=(char *) NULL; map->levels=(ssize_t *) NULL; /* Assign basic attributeibutes. */ attribute=GetXMLTreeAttribute(threshold,"map"); if (attribute != (char *) NULL) map->map_id=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) map->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->width=StringToUnsignedLong(attribute); if (map->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->height=StringToUnsignedLong(attribute); if (map->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } attribute=GetXMLTreeAttribute(levels, "divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->divisor=(ssize_t) StringToLong(attribute); if (map->divisor < 2) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } /* Allocate theshold levels array. */ content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if (map->levels == (ssize_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); { char *p; register ssize_t i; /* Parse levels into integer array. */ for (i=0; i< (ssize_t) (map->width*map->height); i++) { map->levels[i]=(ssize_t) strtol(content,&p,10); if (p == content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } if ((map->levels[i] < 0) || (map->levels[i] > map->divisor)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } content=p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } } thresholds=DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() load and search one or more threshold map files for the % a map matching the given name or aliase. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; ThresholdMap *map; map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception); if (map != (ThresholdMap *) NULL) return(map); options=GetConfigureOptions(ThresholdsFilename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); if (map != (ThresholdMap *) NULL) break; option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { XMLTreeInfo *thresholds,*threshold,*description; const char *map,*alias,*content; assert( xml != (char *) NULL ); assert( file != (FILE *) NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *) NULL ) return(MagickFalse); (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description"); (void) FormatLocaleFile(file, "----------------------------------------------------\n"); for( threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *) NULL; threshold = GetNextXMLTreeTag(threshold) ) { map = GetXMLTreeAttribute(threshold, "map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias = GetXMLTreeAttribute(threshold, "alias"); /* alias is optional, no if test needed */ description=GetXMLTreeChild(threshold,"description"); if ( description == (XMLTreeInfo *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if ( content == (char *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickTrue; if (file == (FILE *) NULL) file=stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) FormatLocaleFile(file, "\n Threshold Maps for Ordered Dither Operations\n"); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option)); status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() uses the ordered dithering technique of reducing color % images to monochrome using positional information to retain as much % information as possible. % % WARNING: This function is deprecated, and is now just a call to % the more more powerful OrderedPosterizeImage(); function. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image) % MagickBooleanType OrderedDitherImageChannel(Image *image, % const ChannelType channel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image) { MagickBooleanType status; status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception); return(status); } MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image, const ChannelType channel,ExceptionInfo *exception) { MagickBooleanType status; /* Call the augumented function OrderedPosterizeImage() */ status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedPosterizeImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedPosterizeImage method is: % % MagickBooleanType OrderedPosterizeImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % MagickBooleanType OrderedPosterizeImageChannel(Image *image, % const ChannelType channel,const char *threshold_map, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivalent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { MagickBooleanType status; status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map, exception); return(status); } MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image, const ChannelType channel,const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; LongPixelPacket levels; MagickBooleanType status; MagickOffsetType progress; ssize_t y; ThresholdMap *map; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (threshold_map == (const char *) NULL) return(MagickTrue); { char token[MaxTextExtent]; register const char *p; p=(char *)threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= (MaxTextExtent-1)) break; token[p-threshold_map] = *p; p++; } token[p-threshold_map] = '\0'; map = GetThresholdMap(token, exception); if ( map == (ThresholdMap *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } } /* Set channel levels from extra comma separated arguments Default to 2, the single value given, or individual channel values */ #if 1 { /* parse directly as a comma separated list of integers */ char *p; p = strchr((char *) threshold_map,','); if ( p != (char *) NULL && isdigit((int) ((unsigned char) *(++p))) ) levels.index = (unsigned int) strtoul(p, &p, 10); else levels.index = 2; levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0; levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0; levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0; levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0; levels.index = ((channel & IndexChannel) != 0 && (image->colorspace == CMYKColorspace)) ? levels.index : 0; /* if more than a single number, each channel has a separate value */ if ( p != (char *) NULL && *p == ',' ) { p=strchr((char *) threshold_map,','); p++; if ((channel & RedChannel) != 0) levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & GreenChannel) != 0) levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & BlueChannel) != 0) levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & OpacityChannel) != 0) levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); } } #else /* Parse level values as a geometry */ /* This difficult! * How to map GeometryInfo structure elements into * LongPixelPacket structure elements, but according to channel? * Note the channels list may skip elements!!!! * EG -channel BA -ordered-dither map,2,3 * will need to map g.rho -> l.blue, and g.sigma -> l.opacity * A simpler way is needed, probably converting geometry to a temporary * array, then using channel to advance the index into ssize_t pixel packet. */ #endif #if 0 printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n", levels.red, levels.green, levels.blue, levels.opacity, levels.index); #endif { /* Do the posterized ordered dithering of the image */ ssize_t d; /* d = number of psuedo-level divisions added between color levels */ d = map->divisor-1; /* reduce levels to levels - 1 */ levels.red = levels.red ? levels.red-1 : 0; levels.green = levels.green ? levels.green-1 : 0; levels.blue = levels.blue ? levels.blue-1 : 0; levels.opacity = levels.opacity ? levels.opacity-1 : 0; levels.index = levels.index ? levels.index-1 : 0; if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t threshold, t, l; /* Figure out the dither threshold for this pixel This must be a integer from 1 to map->divisor-1 */ threshold = map->levels[(x%map->width) +map->width*(y%map->height)]; /* Dither each channel in the image as appropriate Notes on the integer Math... total number of divisions = (levels-1)*(divisor-1)+1) t1 = this colors psuedo_level = q->red * total_divisions / (QuantumRange+1) l = posterization level 0..levels t = dither threshold level 0..divisor-1 NB: 0 only on last Each color_level is of size QuantumRange / (levels-1) NB: All input levels and divisor are already had 1 subtracted Opacity is inverted so 'off' represents transparent. */ if (levels.red) { t = (ssize_t) (QuantumScale*GetPixelRed(q)*(levels.red*d+1)); l = t/d; t = t-l*d; SetPixelRed(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red))); } if (levels.green) { t = (ssize_t) (QuantumScale*GetPixelGreen(q)* (levels.green*d+1)); l = t/d; t = t-l*d; SetPixelGreen(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green))); } if (levels.blue) { t = (ssize_t) (QuantumScale*GetPixelBlue(q)* (levels.blue*d+1)); l = t/d; t = t-l*d; SetPixelBlue(q,ClampToQuantum((MagickRealType) ((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue))); } if (levels.opacity) { t = (ssize_t) ((1.0-QuantumScale*GetPixelOpacity(q))* (levels.opacity*d+1)); l = t/d; t = t-l*d; SetPixelOpacity(q,ClampToQuantum((MagickRealType) ((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/ levels.opacity))); } if (levels.index) { t = (ssize_t) (QuantumScale*GetPixelIndex(indexes+x)* (levels.index*d+1)); l = t/d; t = t-l*d; SetPixelIndex(indexes+x,ClampToQuantum((MagickRealType) ((l+ (t>=threshold))*(MagickRealType) QuantumRange/levels.index))); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,DitherImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P e r c e p t i b l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PerceptibleImage() set each pixel whose value is less than |epsilon| to % epsilon or -epsilon (whichever is closer) otherwise the pixel value remains % unchanged. % % The format of the PerceptibleImageChannel method is: % % MagickBooleanType PerceptibleImage(Image *image,const double epsilon) % MagickBooleanType PerceptibleImageChannel(Image *image, % const ChannelType channel,const double epsilon) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o epsilon: the epsilon threshold (e.g. 1.0e-9). % */ static inline Quantum PerceptibleThreshold(const Quantum quantum, const double epsilon) { double sign; sign=(double) quantum < 0.0 ? -1.0 : 1.0; if ((sign*quantum) >= epsilon) return(quantum); return((Quantum) (sign*epsilon)); } MagickExport MagickBooleanType PerceptibleImage(Image *image, const double epsilon) { MagickBooleanType status; status=PerceptibleImageChannel(image,DefaultChannels,epsilon); return(status); } MagickExport MagickBooleanType PerceptibleImageChannel(Image *image, const ChannelType channel,const double epsilon) { #define PerceptibleImageTag "Perceptible/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *magick_restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon)); SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); q++; } return(SyncImage(image)); } /* Perceptible image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,PerceptibleThreshold(GetPixelIndex(indexes+x), epsilon)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,PerceptibleImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImageChannel(Image *image, % const char *thresholds,ExceptionInfo *exception) % MagickBooleanType RandomThresholdImageChannel(Image *image, % const ChannelType channel,const char *thresholds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o thresholds: a geometry string containing low,high thresholds. If the % string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4 % is performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { MagickBooleanType status; status=RandomThresholdImageChannel(image,DefaultChannels,thresholds, exception); return(status); } MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickStatusType flags; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickRealType min_threshold, max_threshold; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (thresholds == (const char *) NULL) return(MagickTrue); GetMagickPixelPacket(image,&threshold); min_threshold=0.0; max_threshold=(MagickRealType) QuantumRange; flags=ParseGeometry(thresholds,&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(thresholds,'%') != (char *) NULL) { max_threshold*=(MagickRealType) (0.01*QuantumRange); min_threshold*=(MagickRealType) (0.01*QuantumRange); } else if (((max_threshold == min_threshold) || (max_threshold == 1)) && (min_threshold <= 8)) { /* Backward Compatibility -- ordered-dither -- IM v 6.2.9-6. */ status=OrderedPosterizeImageChannel(image,channel,thresholds,exception); return(status); } /* Random threshold image. */ status=MagickTrue; progress=0; if (channel == CompositeChannels) { if (AcquireImageColormap(image,2) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { IndexPacket index; MagickRealType intensity; intensity=GetPixelIntensity(image,q); if (intensity < min_threshold) threshold.index=min_threshold; else if (intensity > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType)(QuantumRange* GetPseudoRandomValue(random_info[id])); index=(IndexPacket) (intensity <= threshold.index ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { if ((MagickRealType) GetPixelRed(q) < min_threshold) threshold.red=min_threshold; else if ((MagickRealType) GetPixelRed(q) > max_threshold) threshold.red=max_threshold; else threshold.red=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & GreenChannel) != 0) { if ((MagickRealType) GetPixelGreen(q) < min_threshold) threshold.green=min_threshold; else if ((MagickRealType) GetPixelGreen(q) > max_threshold) threshold.green=max_threshold; else threshold.green=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & BlueChannel) != 0) { if ((MagickRealType) GetPixelBlue(q) < min_threshold) threshold.blue=min_threshold; else if ((MagickRealType) GetPixelBlue(q) > max_threshold) threshold.blue=max_threshold; else threshold.blue=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & OpacityChannel) != 0) { if ((MagickRealType) GetPixelOpacity(q) < min_threshold) threshold.opacity=min_threshold; else if ((MagickRealType) GetPixelOpacity(q) > max_threshold) threshold.opacity=max_threshold; else threshold.opacity=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((MagickRealType) GetPixelIndex(indexes+x) < min_threshold) threshold.index=min_threshold; else if ((MagickRealType) GetPixelIndex(indexes+x) > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & RedChannel) != 0) SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold.red ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold.green ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold.blue ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <= threshold.opacity ? 0 : QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <= threshold.index ? 0 : QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold) % MagickBooleanType WhiteThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=WhiteThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); flags=ParseGeometry(thresholds,&geometry_info); GetMagickPixelPacket(image,&threshold); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(MagickRealType) (QuantumRange/100.0); threshold.green*=(MagickRealType) (QuantumRange/100.0); threshold.blue*=(MagickRealType) (QuantumRange/100.0); threshold.opacity*=(MagickRealType) (QuantumRange/100.0); threshold.index*=(MagickRealType) (QuantumRange/100.0); } if ((IsMagickGray(&threshold) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace); /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if (((channel & RedChannel) != 0) && ((MagickRealType) GetPixelRed(q) > threshold.red)) SetPixelRed(q,QuantumRange); if (((channel & GreenChannel) != 0) && ((MagickRealType) GetPixelGreen(q) > threshold.green)) SetPixelGreen(q,QuantumRange); if (((channel & BlueChannel) != 0) && ((MagickRealType) GetPixelBlue(q) > threshold.blue)) SetPixelBlue(q,QuantumRange); if (((channel & OpacityChannel) != 0) && ((MagickRealType) GetPixelOpacity(q) > threshold.opacity)) SetPixelOpacity(q,QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) GetPixelIndex(indexes+x)) > threshold.index) SetPixelIndex(indexes+x,QuantumRange); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
2d.np.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <omp.h> #define ceild(n,d) (((n)-1)/(d) + 1)// ceil(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) #define myabs(x,y) (((x) > (y))? ((x)-(y)) : ((y)-(x))) #if !defined(point) #define point 5 #endif #if point == 5 #define kernel(A) A[(t+1)%2][x][y] = 0.125 * (A[t%2][x+1][y] - 2.0 * A[t%2][x][y] + A[t%2][x-1][y]) + \ 0.125 * (A[t%2][x][y+1] - 2.0 * A[t%2][x][y] + A[t%2][x][y-1]) + \ A[t%2][x][y]; #define XSLOPE 1 #define YSLOPE 1 #define DATA_TYPE double #elif point == 9 #define kernel(A) A[(t+1)%2][x][y] = 0.96 * A[t%2][x][y] + \ 0.0051 * (A[t%2][x+1][y] + A[t%2][x-1][y] + A[t%2][x][y+1]+A[t%2][x][y-1]) + \ 0.0049 * (A[t%2][x+1][y-1] + A[t%2][x-1][y+1] + A[t%2][x-1][y-1] + A[t%2][x+1][y+1]); #define XSLOPE 1 #define YSLOPE 1 #define DATA_TYPE double #elif point == 0 #define kernel(A) A[(t+1)%2][x][y] = b2s23(A[t%2][x][y], A[t%2][x-1][y+1] + A[t%2][x-1][y] + \ A[t%2][x-1][y-1] + A[t%2][x][y+1] + \ A[t%2][x][y-1] + A[t%2][x+1][y+1] + \ A[t%2][x+1][y] + A[t%2][x+1][y-1]); #define XSLOPE 1 #define YSLOPE 1 #define DATA_TYPE int int b2s23(int cell, int neighbors) { if((cell == 1 && ((neighbors < 2) || (neighbors > 3)))) { return 0; } if((cell == 1 && (neighbors == 2 || neighbors == 3))) { return 1; } if((cell == 0 && neighbors == 3)) { return 1; } return cell; } #endif #ifdef CHECK #define TOLERANCE 0 #endif int main(int argc, char * argv[]) { struct timeval start, end; long int t, i, j; int NX = atoi(argv[1]); int NY = atoi(argv[2]); int T = atoi(argv[3]); int Bx = atoi(argv[4]); int By = atoi(argv[5]); int tb = atoi(argv[6]); if(Bx<(2*XSLOPE+1) || By<(2*YSLOPE+1) || Bx>NX || By>NY || tb>min(((Bx-1)/2)/XSLOPE,((By-1)/2)/YSLOPE)){ return 0; } DATA_TYPE (*A)[NX+2*XSLOPE][NY+2*YSLOPE] = (DATA_TYPE (*)[NX+2*XSLOPE][NY+2*YSLOPE])malloc(sizeof(DATA_TYPE)*(NX+2*XSLOPE)*(NY+2*YSLOPE)*2); if(NULL == A) return 0; #ifdef CHECK DATA_TYPE (*B)[NX+2*XSLOPE][NY+2*YSLOPE] = (DATA_TYPE (*)[NX+2*XSLOPE][NY+2*YSLOPE])malloc(sizeof(DATA_TYPE)*(NX+2*XSLOPE)*(NY+2*YSLOPE)*2); if(NULL == B) return 0; #endif srand(100); for (i = 0; i < NX+2*XSLOPE; i++) { for (j = 0; j < NY+2*YSLOPE; j++) { A[0][i][j] = (DATA_TYPE) (1.0 * (rand() % 1024)); #if point == 0 A[0][i][j] = ((int)A[0][i][j])%2; #endif A[1][i][j] = 0; #ifdef CHECK B[0][i][j] = A[0][i][j]; B[1][i][j] = 0; #endif } } int bx = Bx-2*(tb*XSLOPE); int by = By-2*(tb*YSLOPE); int ix = Bx+bx; int iy = By+by; // ix and iy are even. int xnb0 = ceild(NX-bx,ix); int ynb0 = ceild(NY-by,iy); int xnb11 = ceild(NX+(Bx-bx)/2,ix); int ynb12 = ceild(NY+(By-by)/2,iy); int ynb11 = ynb0; int xnb12 = xnb0; int xnb2 = xnb11; int ynb2 = ynb12; int nb1[2] = {xnb11 * ynb11, xnb12 * ynb12}; int nb02[2] = {xnb0 * ynb0, xnb2 * ynb2}; int xnb1[2] = {xnb11, xnb12}; int xnb02[2] = {xnb0, xnb2}; int xleft02[2] = {XSLOPE + bx, XSLOPE - (Bx-bx)/2}; // the start x dimension of the first B11 block is bx int ybottom02[2] = {YSLOPE + by, YSLOPE - (By-by)/2}; // the start y dimension of the first B11 block is by int xleft11[2] = {XSLOPE, XSLOPE + ix/2}; int ybottom11[2] = {YSLOPE + by, YSLOPE - (By-by)/2}; int xleft12[2] = {XSLOPE + bx, XSLOPE - (Bx-bx)/2}; int ybottom12[2] = {YSLOPE, YSLOPE + iy/2}; printf("%d\t%d\n", NX - xnb0 * ix, NY - ynb0 * iy); int level = 0; int tt,n; int x, y; register int ymin, ymax; int xmin,xmax; gettimeofday(&start,0); for(tt = -tb; tt < T; tt += tb){ #pragma omp parallel for schedule(dynamic) private(xmin,xmax,ymin,ymax,t,x,y) for(n = 0; n < nb02[level]; n++){ for(t = max(tt,0); t < min(tt + 2*tb, T); t++) { xmin = max( XSLOPE, xleft02[level] + (n%xnb02[level]) * ix + myabs(t+1,tt+tb) * XSLOPE); xmax = min(NX+XSLOPE, xleft02[level] + (n%xnb02[level]) * ix + Bx - myabs(t+1,tt+tb) * XSLOPE); ymin = max( YSLOPE, ybottom02[level] + (n/xnb02[level]) * iy + myabs(t+1,tt+tb) * YSLOPE); ymax = min(NY+YSLOPE, ybottom02[level] + (n/xnb02[level]) * iy + By - myabs(t+1,tt+tb) * YSLOPE); for(x = xmin; x < xmax; x++) { #pragma ivdep #pragma vector always for(y = ymin; y < ymax; y++) { kernel(A); } } } } #pragma omp parallel for schedule(dynamic) private(xmin,xmax,ymin,ymax,t,x,y) for(n = 0; n < nb1[0] + nb1[1]; n++) { for(t = tt + tb; t < min(tt + 2*tb, T); t++) { if(n < nb1[level]) { xmin = max( XSLOPE, xleft11[level] + (n%xnb1[level]) * ix - (t+1-tt-tb) * XSLOPE); xmax = min(NX + XSLOPE, xleft11[level] + (n%xnb1[level]) * ix + bx + (t+1-tt-tb) * XSLOPE); ymin = max( YSLOPE, ybottom11[level] + (n/xnb1[level]) * iy + (t+1-tt-tb) * YSLOPE); ymax = min(NY + YSLOPE, ybottom11[level] + (n/xnb1[level]) * iy + By - (t+1-tt-tb) * YSLOPE); } else { xmin = max( XSLOPE, xleft12[level] + ((n-nb1[level])%xnb1[1-level]) * ix + (t+1-tt-tb) * XSLOPE); xmax = min(NX + XSLOPE, xleft12[level] + ((n-nb1[level])%xnb1[1-level]) * ix + Bx - (t+1-tt-tb) * XSLOPE); ymin = max( YSLOPE, ybottom12[level] + ((n-nb1[level])/xnb1[1-level]) * iy - (t+1-tt-tb) * YSLOPE); ymax = min(NY + YSLOPE, ybottom12[level] + ((n-nb1[level])/xnb1[1-level]) * iy + by + (t+1-tt-tb) * YSLOPE); } for(x = xmin; x < xmax; x++) { #pragma ivdep #pragma vector always for(y = ymin; y < ymax; y++) { kernel(A); } } } } level = 1 - level; } gettimeofday(&end,0); printf("GStencil/s = %f\n", ((double)NX * NY * T) / (double)(end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec) * 1.0e-6) / 1000000000L); #ifdef CHECK for (t = 0; t < T; t++) { for (x = XSLOPE; x < NX + XSLOPE; x++) { for (y = YSLOPE; y < NY + YSLOPE; y++) { kernel(B); } } } for (i = XSLOPE; i < NX+XSLOPE; i++) { for (j = YSLOPE; j < NY+YSLOPE; j++) { if(myabs(A[T%2][i][j],B[T%2][i][j]) > TOLERANCE) printf("Naive[%d][%d] = %f, Check = %f: FAILED!\n", i, j, B[T%2][i][j], A[T%2][i][j]); } } #endif }
par_rap.c
/****************************************************************************** * Copyright (c) 1998 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "_hypre_parcsr_ls.h" #include "_hypre_utilities.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGBuildCoarseOperator *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildCoarseOperator( hypre_ParCSRMatrix *RT, hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *P, hypre_ParCSRMatrix **RAP_ptr ) { hypre_BoomerAMGBuildCoarseOperatorKT( RT, A, P, 0, RAP_ptr); return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGBuildCoarseOperatorKT( hypre_ParCSRMatrix *RT, hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *P, HYPRE_Int keepTranspose, hypre_ParCSRMatrix **RAP_ptr ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RAP] -= hypre_MPI_Wtime(); #endif MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *RT_diag = hypre_ParCSRMatrixDiag(RT); hypre_CSRMatrix *RT_offd = hypre_ParCSRMatrixOffd(RT); HYPRE_Int num_cols_diag_RT = hypre_CSRMatrixNumCols(RT_diag); HYPRE_Int num_cols_offd_RT = hypre_CSRMatrixNumCols(RT_offd); HYPRE_Int num_rows_offd_RT = hypre_CSRMatrixNumRows(RT_offd); hypre_ParCSRCommPkg *comm_pkg_RT = hypre_ParCSRMatrixCommPkg(RT); HYPRE_Int num_recvs_RT = 0; HYPRE_Int num_sends_RT = 0; HYPRE_Int *send_map_starts_RT; HYPRE_Int *send_map_elmts_RT; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); hypre_CSRMatrix *P_diag = hypre_ParCSRMatrixDiag(P); HYPRE_Real *P_diag_data = hypre_CSRMatrixData(P_diag); HYPRE_Int *P_diag_i = hypre_CSRMatrixI(P_diag); HYPRE_Int *P_diag_j = hypre_CSRMatrixJ(P_diag); hypre_CSRMatrix *P_offd = hypre_ParCSRMatrixOffd(P); HYPRE_BigInt *col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P); HYPRE_Real *P_offd_data = hypre_CSRMatrixData(P_offd); HYPRE_Int *P_offd_i = hypre_CSRMatrixI(P_offd); HYPRE_Int *P_offd_j = hypre_CSRMatrixJ(P_offd); HYPRE_BigInt first_col_diag_P = hypre_ParCSRMatrixFirstColDiag(P); HYPRE_BigInt last_col_diag_P; HYPRE_Int num_cols_diag_P = hypre_CSRMatrixNumCols(P_diag); HYPRE_Int num_cols_offd_P = hypre_CSRMatrixNumCols(P_offd); HYPRE_BigInt *coarse_partitioning = hypre_ParCSRMatrixColStarts(P); HYPRE_BigInt *RT_partitioning = hypre_ParCSRMatrixColStarts(RT); hypre_ParCSRMatrix *RAP; HYPRE_BigInt *col_map_offd_RAP = NULL; HYPRE_BigInt *new_col_map_offd_RAP = NULL; hypre_CSRMatrix *RAP_int = NULL; HYPRE_Real *RAP_int_data; HYPRE_Int *RAP_int_i; HYPRE_BigInt *RAP_int_j; hypre_CSRMatrix *RAP_ext; HYPRE_Real *RAP_ext_data = NULL; HYPRE_Int *RAP_ext_i = NULL; HYPRE_BigInt *RAP_ext_j = NULL; hypre_CSRMatrix *RAP_diag; HYPRE_Real *RAP_diag_data; HYPRE_Int *RAP_diag_i; HYPRE_Int *RAP_diag_j; hypre_CSRMatrix *RAP_offd; HYPRE_Real *RAP_offd_data = NULL; HYPRE_Int *RAP_offd_i = NULL; HYPRE_Int *RAP_offd_j = NULL; HYPRE_Int RAP_size; HYPRE_Int RAP_ext_size; HYPRE_Int RAP_diag_size; HYPRE_Int RAP_offd_size; HYPRE_Int P_ext_diag_size; HYPRE_Int P_ext_offd_size; HYPRE_BigInt first_col_diag_RAP; HYPRE_BigInt last_col_diag_RAP; HYPRE_Int num_cols_offd_RAP = 0; hypre_CSRMatrix *R_diag; HYPRE_Real *R_diag_data; HYPRE_Int *R_diag_i; HYPRE_Int *R_diag_j; hypre_CSRMatrix *R_offd; HYPRE_Real *R_offd_data; HYPRE_Int *R_offd_i; HYPRE_Int *R_offd_j; HYPRE_Real *RA_diag_data_array = NULL; HYPRE_Int *RA_diag_j_array = NULL; HYPRE_Real *RA_offd_data_array = NULL; HYPRE_Int *RA_offd_j_array = NULL; hypre_CSRMatrix *Ps_ext; HYPRE_Real *Ps_ext_data; HYPRE_Int *Ps_ext_i; HYPRE_BigInt *Ps_ext_j; HYPRE_Real *P_ext_diag_data = NULL; HYPRE_Int *P_ext_diag_i = NULL; HYPRE_Int *P_ext_diag_j = NULL; HYPRE_Real *P_ext_offd_data = NULL; HYPRE_Int *P_ext_offd_i = NULL; HYPRE_Int *P_ext_offd_j = NULL; HYPRE_BigInt *P_big_offd_j = NULL; HYPRE_BigInt *col_map_offd_Pext; HYPRE_Int *map_P_to_Pext = NULL; HYPRE_Int *map_P_to_RAP = NULL; HYPRE_Int *map_Pext_to_RAP = NULL; HYPRE_Int *P_marker; HYPRE_Int **P_mark_array; HYPRE_Int **A_mark_array; HYPRE_Int *A_marker; HYPRE_BigInt *temp; HYPRE_BigInt n_coarse, n_coarse_RT; HYPRE_Int square = 1; HYPRE_Int num_cols_offd_Pext = 0; HYPRE_Int ic, i, j, k; HYPRE_Int i1, i2, i3, ii, ns, ne, size, rest; HYPRE_Int cnt = 0; /*value; */ HYPRE_Int jj1, jj2, jj3, jcol; HYPRE_Int *jj_count, *jj_cnt_diag, *jj_cnt_offd; HYPRE_Int jj_counter, jj_count_diag, jj_count_offd; HYPRE_Int jj_row_begining, jj_row_begin_diag, jj_row_begin_offd; HYPRE_Int start_indexing = 0; /* start indexing for RAP_data at 0 */ HYPRE_Int num_nz_cols_A; HYPRE_Int num_procs; HYPRE_Int num_threads; HYPRE_Real r_entry; HYPRE_Real r_a_product; HYPRE_Real r_a_p_product; HYPRE_Real zero = 0.0; HYPRE_Int *prefix_sum_workspace; /*----------------------------------------------------------------------- * Copy ParCSRMatrix RT into CSRMatrix R so that we have row-wise access * to restriction . *-----------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs); num_threads = hypre_NumThreads(); if (comm_pkg_RT) { num_recvs_RT = hypre_ParCSRCommPkgNumRecvs(comm_pkg_RT); num_sends_RT = hypre_ParCSRCommPkgNumSends(comm_pkg_RT); send_map_starts_RT = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_RT); send_map_elmts_RT = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_RT); } else if (num_procs > 1) { hypre_MatvecCommPkgCreate(RT); comm_pkg_RT = hypre_ParCSRMatrixCommPkg(RT); num_recvs_RT = hypre_ParCSRCommPkgNumRecvs(comm_pkg_RT); num_sends_RT = hypre_ParCSRCommPkgNumSends(comm_pkg_RT); send_map_starts_RT = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_RT); send_map_elmts_RT = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_RT); } hypre_CSRMatrixTranspose(RT_diag, &R_diag, 1); if (num_cols_offd_RT) { hypre_CSRMatrixTranspose(RT_offd, &R_offd, 1); R_offd_data = hypre_CSRMatrixData(R_offd); R_offd_i = hypre_CSRMatrixI(R_offd); R_offd_j = hypre_CSRMatrixJ(R_offd); } /*----------------------------------------------------------------------- * Access the CSR vectors for R. Also get sizes of fine and * coarse grids. *-----------------------------------------------------------------------*/ R_diag_data = hypre_CSRMatrixData(R_diag); R_diag_i = hypre_CSRMatrixI(R_diag); R_diag_j = hypre_CSRMatrixJ(R_diag); n_coarse = hypre_ParCSRMatrixGlobalNumCols(P); num_nz_cols_A = num_cols_diag_A + num_cols_offd_A; n_coarse_RT = hypre_ParCSRMatrixGlobalNumCols(RT); if (n_coarse != n_coarse_RT || num_cols_diag_RT != num_cols_diag_P) { square = 0; } /*----------------------------------------------------------------------- * Generate Ps_ext, i.e. portion of P that is stored on neighbor procs * and needed locally for triple matrix product *-----------------------------------------------------------------------*/ #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_UnorderedIntMap send_map_elmts_RT_inverse_map; HYPRE_Int *send_map_elmts_starts_RT_aggregated = NULL; HYPRE_Int *send_map_elmts_RT_aggregated = NULL; HYPRE_Int send_map_elmts_RT_inverse_map_initialized = num_sends_RT > 0 && send_map_starts_RT[num_sends_RT] - send_map_starts_RT[0] > 0; if (send_map_elmts_RT_inverse_map_initialized) { hypre_UnorderedIntSet send_map_elmts_set; hypre_UnorderedIntSetCreate(&send_map_elmts_set, 2 * (send_map_starts_RT[num_sends_RT] - send_map_starts_RT[0]), 16 * hypre_NumThreads()); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = send_map_starts_RT[0]; i < send_map_starts_RT[num_sends_RT]; i++) { HYPRE_Int key = send_map_elmts_RT[i]; hypre_UnorderedIntSetPut(&send_map_elmts_set, key); } HYPRE_Int send_map_elmts_unique_size; HYPRE_Int *send_map_elmts_unique = hypre_UnorderedIntSetCopyToArray(&send_map_elmts_set, &send_map_elmts_unique_size); hypre_UnorderedIntSetDestroy(&send_map_elmts_set); hypre_UnorderedIntMapCreate(&send_map_elmts_RT_inverse_map, 2 * send_map_elmts_unique_size, 16 * hypre_NumThreads()); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = 0; i < send_map_elmts_unique_size; i++) { hypre_UnorderedIntMapPutIfAbsent(&send_map_elmts_RT_inverse_map, send_map_elmts_unique[i], i); } hypre_TFree(send_map_elmts_unique, HYPRE_MEMORY_HOST); send_map_elmts_starts_RT_aggregated = hypre_TAlloc(HYPRE_Int, send_map_elmts_unique_size + 1, HYPRE_MEMORY_HOST); send_map_elmts_RT_aggregated = hypre_TAlloc(HYPRE_Int, send_map_starts_RT[num_sends_RT], HYPRE_MEMORY_HOST); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = 0; i < send_map_elmts_unique_size; i++) { send_map_elmts_starts_RT_aggregated[i] = 0; } #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = send_map_starts_RT[0]; i < send_map_starts_RT[num_sends_RT]; i++) { HYPRE_Int idx = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, send_map_elmts_RT[i]); #pragma omp atomic send_map_elmts_starts_RT_aggregated[idx]++; } for (i = 0; i < send_map_elmts_unique_size - 1; i++) { send_map_elmts_starts_RT_aggregated[i + 1] += send_map_elmts_starts_RT_aggregated[i]; } send_map_elmts_starts_RT_aggregated[send_map_elmts_unique_size] = send_map_starts_RT[num_sends_RT]; #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = send_map_starts_RT[num_sends_RT] - 1; i >= send_map_starts_RT[0]; i--) { HYPRE_Int idx = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, send_map_elmts_RT[i]); HYPRE_Int offset = hypre_fetch_and_add(send_map_elmts_starts_RT_aggregated + idx, -1) - 1; send_map_elmts_RT_aggregated[offset] = i; } } #endif /* HYPRE_CONCURRENT_HOPSCOTCH */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] -= hypre_MPI_Wtime(); #endif if (num_procs > 1) { Ps_ext = hypre_ParCSRMatrixExtractBExt(P, A, 1); Ps_ext_data = hypre_CSRMatrixData(Ps_ext); Ps_ext_i = hypre_CSRMatrixI(Ps_ext); Ps_ext_j = hypre_CSRMatrixBigJ(Ps_ext); } P_ext_diag_i = hypre_TAlloc(HYPRE_Int, num_cols_offd_A + 1, HYPRE_MEMORY_HOST); P_ext_offd_i = hypre_TAlloc(HYPRE_Int, num_cols_offd_A + 1, HYPRE_MEMORY_HOST); P_ext_diag_i[0] = 0; P_ext_offd_i[0] = 0; P_ext_diag_size = 0; P_ext_offd_size = 0; last_col_diag_P = first_col_diag_P + (HYPRE_BigInt) num_cols_diag_P - 1; /*HYPRE_Int prefix_sum_workspace[2*(num_threads + 1)];*/ prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, 2 * (num_threads + 1), HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j) #endif /* This threading causes problem, maybe the prefix_sum in combination with BigInt? */ { HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_A); HYPRE_Int P_ext_diag_size_private = 0; HYPRE_Int P_ext_offd_size_private = 0; for (i = i_begin; i < i_end; i++) { for (j = Ps_ext_i[i]; j < Ps_ext_i[i + 1]; j++) if (Ps_ext_j[j] < first_col_diag_P || Ps_ext_j[j] > last_col_diag_P) { P_ext_offd_size_private++; } else { P_ext_diag_size_private++; } } hypre_prefix_sum_pair(&P_ext_diag_size_private, &P_ext_diag_size, &P_ext_offd_size_private, &P_ext_offd_size, prefix_sum_workspace); #ifdef HYPRE_USING_OPENMP #pragma omp master #endif { if (P_ext_diag_size) { P_ext_diag_j = hypre_CTAlloc(HYPRE_Int, P_ext_diag_size, HYPRE_MEMORY_HOST); P_ext_diag_data = hypre_CTAlloc(HYPRE_Real, P_ext_diag_size, HYPRE_MEMORY_HOST); } if (P_ext_offd_size) { P_ext_offd_j = hypre_CTAlloc(HYPRE_Int, P_ext_offd_size, HYPRE_MEMORY_HOST); P_big_offd_j = hypre_CTAlloc(HYPRE_BigInt, P_ext_offd_size, HYPRE_MEMORY_HOST); P_ext_offd_data = hypre_CTAlloc(HYPRE_Real, P_ext_offd_size, HYPRE_MEMORY_HOST); //temp = hypre_CTAlloc(HYPRE_BigInt, P_ext_offd_size+num_cols_offd_P, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = i_begin; i < i_end; i++) { for (j = Ps_ext_i[i]; j < Ps_ext_i[i + 1]; j++) { HYPRE_BigInt value = Ps_ext_j[j]; if (value < first_col_diag_P || value > last_col_diag_P) { //Ps_ext_j[P_ext_offd_size_private] = value; //temp[P_ext_offd_size_private] = value; P_big_offd_j[P_ext_offd_size_private] = value; P_ext_offd_data[P_ext_offd_size_private++] = Ps_ext_data[j]; } else { P_ext_diag_j[P_ext_diag_size_private] = (HYPRE_Int)(Ps_ext_j[j] - first_col_diag_P); P_ext_diag_data[P_ext_diag_size_private++] = Ps_ext_data[j]; } } P_ext_diag_i[i + 1] = P_ext_diag_size_private; P_ext_offd_i[i + 1] = P_ext_offd_size_private; } } /* omp parallel */ hypre_TFree(prefix_sum_workspace, HYPRE_MEMORY_HOST); if (num_procs > 1) { hypre_CSRMatrixDestroy(Ps_ext); Ps_ext = NULL; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (P_ext_offd_size || num_cols_offd_P) { hypre_UnorderedBigIntSet found_set; hypre_UnorderedBigIntSetCreate(&found_set, P_ext_offd_size + num_cols_offd_P, 16 * hypre_NumThreads()); #pragma omp parallel private(i) { #pragma omp for HYPRE_SMP_SCHEDULE for (i = 0; i < P_ext_offd_size; i++) { //hypre_UnorderedBigIntSetPut(&found_set, Ps_ext_j[i]); hypre_UnorderedBigIntSetPut(&found_set, P_big_offd_j[i]); } #pragma omp for HYPRE_SMP_SCHEDULE for (i = 0; i < num_cols_offd_P; i++) { hypre_UnorderedBigIntSetPut(&found_set, col_map_offd_P[i]); } } /* omp parallel */ /* Warning on getting temp right !!!!! */ temp = hypre_UnorderedBigIntSetCopyToArray(&found_set, &num_cols_offd_Pext); hypre_UnorderedBigIntSetDestroy(&found_set); hypre_UnorderedBigIntMap col_map_offd_Pext_inverse; hypre_big_sort_and_create_inverse_map(temp, num_cols_offd_Pext, &col_map_offd_Pext, &col_map_offd_Pext_inverse); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = 0 ; i < P_ext_offd_size; i++) //Ps_ext_j[i] = hypre_UnorderedBigIntMapGet(&col_map_offd_Pext_inverse, Ps_ext_j[i]); { P_ext_offd_j[i] = hypre_UnorderedBigIntMapGet(&col_map_offd_Pext_inverse, P_big_offd_j[i]); } if (num_cols_offd_Pext) { hypre_UnorderedBigIntMapDestroy(&col_map_offd_Pext_inverse); } } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (P_ext_offd_size || num_cols_offd_P) { temp = hypre_CTAlloc(HYPRE_BigInt, P_ext_offd_size + num_cols_offd_P, HYPRE_MEMORY_HOST); for (i = 0; i < P_ext_offd_size; i++) //Ps_ext_j[i] = temp[i]; //temp[i] = Ps_ext_j[i]; { temp[i] = P_big_offd_j[i]; } cnt = P_ext_offd_size; for (i = 0; i < num_cols_offd_P; i++) { temp[cnt++] = col_map_offd_P[i]; } } if (cnt) { hypre_BigQsort0(temp, 0, cnt - 1); num_cols_offd_Pext = 1; HYPRE_BigInt value = temp[0]; for (i = 1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_Pext++] = value; } } } if (num_cols_offd_Pext) { col_map_offd_Pext = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_Pext, HYPRE_MEMORY_HOST); } for (i = 0; i < num_cols_offd_Pext; i++) { col_map_offd_Pext[i] = temp[i]; } if (P_ext_offd_size || num_cols_offd_P) { hypre_TFree(temp, HYPRE_MEMORY_HOST); } /*if (P_ext_offd_size) P_ext_offd_j = hypre_CTAlloc(HYPRE_Int, P_ext_offd_size, HYPRE_MEMORY_HOST);*/ for (i = 0 ; i < P_ext_offd_size; i++) P_ext_offd_j[i] = hypre_BigBinarySearch(col_map_offd_Pext, //Ps_ext_j[i], P_big_offd_j[i], num_cols_offd_Pext); #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (P_ext_offd_size) { hypre_TFree(P_big_offd_j, HYPRE_MEMORY_HOST); } /*if (num_procs > 1) { hypre_CSRMatrixDestroy(Ps_ext); Ps_ext = NULL; }*/ if (num_cols_offd_P) { map_P_to_Pext = hypre_CTAlloc(HYPRE_Int, num_cols_offd_P, HYPRE_MEMORY_HOST); cnt = 0; for (i = 0; i < num_cols_offd_Pext; i++) if (col_map_offd_Pext[i] == col_map_offd_P[cnt]) { map_P_to_Pext[cnt++] = i; if (cnt == num_cols_offd_P) { break; } } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] += hypre_MPI_Wtime(); #endif /*----------------------------------------------------------------------- * First Pass: Determine size of RAP_int and set up RAP_int_i if there * are more than one processor and nonzero elements in R_offd *-----------------------------------------------------------------------*/ P_mark_array = hypre_CTAlloc(HYPRE_Int *, num_threads, HYPRE_MEMORY_HOST); A_mark_array = hypre_CTAlloc(HYPRE_Int *, num_threads, HYPRE_MEMORY_HOST); if (num_cols_offd_RT) { jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_counter,jj_row_begining,A_marker,P_marker) HYPRE_SMP_SCHEDULE #endif for (ii = 0; ii < num_threads; ii++) { size = num_cols_offd_RT / num_threads; rest = num_cols_offd_RT - size * num_threads; if (ii < rest) { ns = ii * size + ii; ne = (ii + 1) * size + ii + 1; } else { ns = ii * size + rest; ne = (ii + 1) * size + rest; } /*----------------------------------------------------------------------- * Allocate marker arrays. *-----------------------------------------------------------------------*/ if (num_cols_offd_Pext || num_cols_diag_P) { P_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_cols_diag_P + num_cols_offd_Pext, HYPRE_MEMORY_HOST); P_marker = P_mark_array[ii]; } A_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_nz_cols_A, HYPRE_MEMORY_HOST); A_marker = A_mark_array[ii]; /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ jj_counter = start_indexing; for (ic = 0; ic < num_cols_diag_P + num_cols_offd_Pext; ic++) { P_marker[ic] = -1; } for (i = 0; i < num_nz_cols_A; i++) { A_marker[i] = -1; } /*----------------------------------------------------------------------- * Loop over exterior c-points *-----------------------------------------------------------------------*/ for (ic = ns; ic < ne; ic++) { jj_row_begining = jj_counter; /*-------------------------------------------------------------------- * Loop over entries in row ic of R_offd. *--------------------------------------------------------------------*/ for (jj1 = R_offd_i[ic]; jj1 < R_offd_i[ic + 1]; jj1++) { i1 = R_offd_j[jj1]; /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1 + 1]; jj2++) { i2 = A_offd_j[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_ext. *-----------------------------------------------------------*/ for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2 + 1]; jj3++) { i3 = P_ext_diag_j[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; jj_counter++; } } for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2 + 1]; jj3++) { i3 = P_ext_offd_j[jj3] + num_cols_diag_P; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; jj_counter++; } } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1 + 1]; jj2++) { i2 = A_diag_j[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2 + num_cols_offd_A] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2 + num_cols_offd_A] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_diag. *-----------------------------------------------------------*/ for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2 + 1]; jj3++) { i3 = P_diag_j[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; jj_counter++; } } /*----------------------------------------------------------- * Loop over entries in row i2 of P_offd. *-----------------------------------------------------------*/ for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2 + 1]; jj3++) { i3 = map_P_to_Pext[P_offd_j[jj3]] + num_cols_diag_P; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; jj_counter++; } } } } } } jj_count[ii] = jj_counter; } /*----------------------------------------------------------------------- * Allocate RAP_int_data and RAP_int_j arrays. *-----------------------------------------------------------------------*/ for (i = 0; i < num_threads - 1; i++) { jj_count[i + 1] += jj_count[i]; } RAP_size = jj_count[num_threads - 1]; RAP_int_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_RT + 1, HYPRE_MEMORY_HOST); RAP_int_data = hypre_CTAlloc(HYPRE_Real, RAP_size, HYPRE_MEMORY_HOST); RAP_int_j = hypre_CTAlloc(HYPRE_BigInt, RAP_size, HYPRE_MEMORY_HOST); RAP_int_i[num_cols_offd_RT] = RAP_size; /*----------------------------------------------------------------------- * Second Pass: Fill in RAP_int_data and RAP_int_j. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_counter,jj_row_begining,A_marker,P_marker,r_entry,r_a_product,r_a_p_product) HYPRE_SMP_SCHEDULE #endif for (ii = 0; ii < num_threads; ii++) { size = num_cols_offd_RT / num_threads; rest = num_cols_offd_RT - size * num_threads; if (ii < rest) { ns = ii * size + ii; ne = (ii + 1) * size + ii + 1; } else { ns = ii * size + rest; ne = (ii + 1) * size + rest; } /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ if (num_cols_offd_Pext || num_cols_diag_P) { P_marker = P_mark_array[ii]; } A_marker = A_mark_array[ii]; jj_counter = start_indexing; if (ii > 0) { jj_counter = jj_count[ii - 1]; } for (ic = 0; ic < num_cols_diag_P + num_cols_offd_Pext; ic++) { P_marker[ic] = -1; } for (i = 0; i < num_nz_cols_A; i++) { A_marker[i] = -1; } /*----------------------------------------------------------------------- * Loop over exterior c-points. *-----------------------------------------------------------------------*/ for (ic = ns; ic < ne; ic++) { jj_row_begining = jj_counter; RAP_int_i[ic] = jj_counter; /*-------------------------------------------------------------------- * Loop over entries in row ic of R_offd. *--------------------------------------------------------------------*/ for (jj1 = R_offd_i[ic]; jj1 < R_offd_i[ic + 1]; jj1++) { i1 = R_offd_j[jj1]; r_entry = R_offd_data[jj1]; /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1 + 1]; jj2++) { i2 = A_offd_j[jj2]; r_a_product = r_entry * A_offd_data[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_ext. *-----------------------------------------------------------*/ for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2 + 1]; jj3++) { i3 = P_ext_diag_j[jj3]; r_a_p_product = r_a_product * P_ext_diag_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; RAP_int_data[jj_counter] = r_a_p_product; RAP_int_j[jj_counter] = (HYPRE_BigInt)i3 + first_col_diag_P; jj_counter++; } else { RAP_int_data[P_marker[i3]] += r_a_p_product; } } for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2 + 1]; jj3++) { i3 = P_ext_offd_j[jj3] + num_cols_diag_P; r_a_p_product = r_a_product * P_ext_offd_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; RAP_int_data[jj_counter] = r_a_p_product; RAP_int_j[jj_counter] = col_map_offd_Pext[i3 - num_cols_diag_P]; jj_counter++; } else { RAP_int_data[P_marker[i3]] += r_a_p_product; } } } /*-------------------------------------------------------------- * If i2 is previously visited ( A_marker[12]=ic ) it yields * no new entries in RAP and can just add new contributions. *--------------------------------------------------------------*/ else { for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2 + 1]; jj3++) { i3 = P_ext_diag_j[jj3]; r_a_p_product = r_a_product * P_ext_diag_data[jj3]; RAP_int_data[P_marker[i3]] += r_a_p_product; } for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2 + 1]; jj3++) { i3 = P_ext_offd_j[jj3] + num_cols_diag_P; r_a_p_product = r_a_product * P_ext_offd_data[jj3]; RAP_int_data[P_marker[i3]] += r_a_p_product; } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1 + 1]; jj2++) { i2 = A_diag_j[jj2]; r_a_product = r_entry * A_diag_data[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2 + num_cols_offd_A] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2 + num_cols_offd_A] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_diag. *-----------------------------------------------------------*/ for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2 + 1]; jj3++) { i3 = P_diag_j[jj3]; r_a_p_product = r_a_product * P_diag_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; RAP_int_data[jj_counter] = r_a_p_product; RAP_int_j[jj_counter] = (HYPRE_BigInt)i3 + first_col_diag_P; jj_counter++; } else { RAP_int_data[P_marker[i3]] += r_a_p_product; } } for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2 + 1]; jj3++) { i3 = map_P_to_Pext[P_offd_j[jj3]] + num_cols_diag_P; r_a_p_product = r_a_product * P_offd_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; RAP_int_data[jj_counter] = r_a_p_product; RAP_int_j[jj_counter] = col_map_offd_Pext[i3 - num_cols_diag_P]; jj_counter++; } else { RAP_int_data[P_marker[i3]] += r_a_p_product; } } } /*-------------------------------------------------------------- * If i2 is previously visited ( A_marker[12]=ic ) it yields * no new entries in RAP and can just add new contributions. *--------------------------------------------------------------*/ else { for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2 + 1]; jj3++) { i3 = P_diag_j[jj3]; r_a_p_product = r_a_product * P_diag_data[jj3]; RAP_int_data[P_marker[i3]] += r_a_p_product; } for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2 + 1]; jj3++) { i3 = map_P_to_Pext[P_offd_j[jj3]] + num_cols_diag_P; r_a_p_product = r_a_product * P_offd_data[jj3]; RAP_int_data[P_marker[i3]] += r_a_p_product; } } } } } if (num_cols_offd_Pext || num_cols_diag_P) { hypre_TFree(P_mark_array[ii], HYPRE_MEMORY_HOST); } hypre_TFree(A_mark_array[ii], HYPRE_MEMORY_HOST); } RAP_int = hypre_CSRMatrixCreate(num_cols_offd_RT, num_rows_offd_RT, RAP_size); hypre_CSRMatrixMemoryLocation(RAP_int) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI(RAP_int) = RAP_int_i; hypre_CSRMatrixBigJ(RAP_int) = RAP_int_j; hypre_CSRMatrixData(RAP_int) = RAP_int_data; hypre_TFree(jj_count, HYPRE_MEMORY_HOST); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] -= hypre_MPI_Wtime(); #endif RAP_ext_size = 0; if (num_sends_RT || num_recvs_RT) { void *request; hypre_ExchangeExternalRowsInit(RAP_int, comm_pkg_RT, &request); RAP_ext = hypre_ExchangeExternalRowsWait(request); RAP_ext_i = hypre_CSRMatrixI(RAP_ext); RAP_ext_j = hypre_CSRMatrixBigJ(RAP_ext); RAP_ext_data = hypre_CSRMatrixData(RAP_ext); RAP_ext_size = RAP_ext_i[hypre_CSRMatrixNumRows(RAP_ext)]; } if (num_cols_offd_RT) { hypre_CSRMatrixDestroy(RAP_int); RAP_int = NULL; } RAP_diag_i = hypre_TAlloc(HYPRE_Int, num_cols_diag_RT + 1, HYPRE_MEMORY_DEVICE); RAP_offd_i = hypre_TAlloc(HYPRE_Int, num_cols_diag_RT + 1, HYPRE_MEMORY_DEVICE); first_col_diag_RAP = first_col_diag_P; last_col_diag_RAP = first_col_diag_P + num_cols_diag_P - 1; /*----------------------------------------------------------------------- * check for new nonzero columns in RAP_offd generated through RAP_ext *-----------------------------------------------------------------------*/ #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_UnorderedBigIntMap col_map_offd_RAP_inverse; if (RAP_ext_size || num_cols_offd_Pext) { hypre_UnorderedBigIntSet found_set; hypre_UnorderedBigIntSetCreate(&found_set, 2 * (RAP_ext_size + num_cols_offd_Pext), 16 * hypre_NumThreads()); cnt = 0; #pragma omp parallel private(i) { #pragma omp for HYPRE_SMP_SCHEDULE for (i = 0; i < RAP_ext_size; i++) { if (RAP_ext_j[i] < first_col_diag_RAP || RAP_ext_j[i] > last_col_diag_RAP) { hypre_UnorderedBigIntSetPut(&found_set, RAP_ext_j[i]); } } #pragma omp for HYPRE_SMP_SCHEDULE for (i = 0; i < num_cols_offd_Pext; i++) { hypre_UnorderedBigIntSetPut(&found_set, col_map_offd_Pext[i]); } } /* omp parallel */ temp = hypre_UnorderedBigIntSetCopyToArray(&found_set, &num_cols_offd_RAP); hypre_UnorderedBigIntSetDestroy(&found_set); hypre_big_sort_and_create_inverse_map(temp, num_cols_offd_RAP, &col_map_offd_RAP, &col_map_offd_RAP_inverse); } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (RAP_ext_size || num_cols_offd_Pext) { temp = hypre_CTAlloc(HYPRE_BigInt, RAP_ext_size + num_cols_offd_Pext, HYPRE_MEMORY_HOST); cnt = 0; for (i = 0; i < RAP_ext_size; i++) if (RAP_ext_j[i] < first_col_diag_RAP || RAP_ext_j[i] > last_col_diag_RAP) { temp[cnt++] = RAP_ext_j[i]; } for (i = 0; i < num_cols_offd_Pext; i++) { temp[cnt++] = col_map_offd_Pext[i]; } if (cnt) { hypre_BigQsort0(temp, 0, cnt - 1); HYPRE_BigInt value = temp[0]; num_cols_offd_RAP = 1; for (i = 1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_RAP++] = value; } } } /* now evaluate col_map_offd_RAP */ if (num_cols_offd_RAP) { col_map_offd_RAP = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_RAP, HYPRE_MEMORY_HOST); } for (i = 0 ; i < num_cols_offd_RAP; i++) { col_map_offd_RAP[i] = temp[i]; } hypre_TFree(temp, HYPRE_MEMORY_HOST); } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (num_cols_offd_P) { map_P_to_RAP = hypre_TAlloc(HYPRE_Int, num_cols_offd_P, HYPRE_MEMORY_HOST); cnt = 0; for (i = 0; i < num_cols_offd_RAP; i++) if (col_map_offd_RAP[i] == col_map_offd_P[cnt]) { map_P_to_RAP[cnt++] = i; if (cnt == num_cols_offd_P) { break; } } } if (num_cols_offd_Pext) { map_Pext_to_RAP = hypre_TAlloc(HYPRE_Int, num_cols_offd_Pext, HYPRE_MEMORY_HOST); cnt = 0; for (i = 0; i < num_cols_offd_RAP; i++) if (col_map_offd_RAP[i] == col_map_offd_Pext[cnt]) { map_Pext_to_RAP[cnt++] = i; if (cnt == num_cols_offd_Pext) { break; } } } /*----------------------------------------------------------------------- * Convert RAP_ext column indices *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = 0; i < RAP_ext_size; i++) if (RAP_ext_j[i] < first_col_diag_RAP || RAP_ext_j[i] > last_col_diag_RAP) RAP_ext_j[i] = (HYPRE_BigInt)num_cols_diag_P #ifdef HYPRE_CONCURRENT_HOPSCOTCH + (HYPRE_BigInt)hypre_UnorderedBigIntMapGet(&col_map_offd_RAP_inverse, RAP_ext_j[i]); #else +(HYPRE_BigInt)hypre_BigBinarySearch(col_map_offd_RAP, RAP_ext_j[i], num_cols_offd_RAP); #endif else { RAP_ext_j[i] -= first_col_diag_RAP; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (num_cols_offd_RAP) { hypre_UnorderedBigIntMapDestroy(&col_map_offd_RAP_inverse); } #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] += hypre_MPI_Wtime(); #endif /* need to allocate new P_marker etc. and make further changes */ /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ jj_cnt_diag = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); jj_cnt_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,k,jcol,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_count_diag,jj_count_offd,jj_row_begin_diag,jj_row_begin_offd,A_marker,P_marker) HYPRE_SMP_SCHEDULE #endif for (ii = 0; ii < num_threads; ii++) { size = num_cols_diag_RT / num_threads; rest = num_cols_diag_RT - size * num_threads; if (ii < rest) { ns = ii * size + ii; ne = (ii + 1) * size + ii + 1; } else { ns = ii * size + rest; ne = (ii + 1) * size + rest; } P_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_cols_diag_P + num_cols_offd_RAP, HYPRE_MEMORY_HOST); A_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_nz_cols_A, HYPRE_MEMORY_HOST); P_marker = P_mark_array[ii]; A_marker = A_mark_array[ii]; jj_count_diag = start_indexing; jj_count_offd = start_indexing; for (ic = 0; ic < num_cols_diag_P + num_cols_offd_RAP; ic++) { P_marker[ic] = -1; } for (i = 0; i < num_nz_cols_A; i++) { A_marker[i] = -1; } /*----------------------------------------------------------------------- * Loop over interior c-points. *-----------------------------------------------------------------------*/ for (ic = ns; ic < ne; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, RAP_{ic,ic}. and for all points * being added to row ic of RAP_diag and RAP_offd through RAP_ext *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if (square) { P_marker[ic] = jj_count_diag++; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (send_map_elmts_RT_inverse_map_initialized) { HYPRE_Int i = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, ic); if (i != -1) { for (j = send_map_elmts_starts_RT_aggregated[i]; j < send_map_elmts_starts_RT_aggregated[i + 1]; j++) { HYPRE_Int jj = send_map_elmts_RT_aggregated[j]; for (k = RAP_ext_i[jj]; k < RAP_ext_i[jj + 1]; k++) { jcol = (HYPRE_Int)RAP_ext_j[k]; if (jcol < num_cols_diag_P) { if (P_marker[jcol] < jj_row_begin_diag) { P_marker[jcol] = jj_count_diag; jj_count_diag++; } } else { if (P_marker[jcol] < jj_row_begin_offd) { P_marker[jcol] = jj_count_offd; jj_count_offd++; } } } } } // if (set) } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ for (i = 0; i < num_sends_RT; i++) for (j = send_map_starts_RT[i]; j < send_map_starts_RT[i + 1]; j++) if (send_map_elmts_RT[j] == ic) { for (k = RAP_ext_i[j]; k < RAP_ext_i[j + 1]; k++) { jcol = (HYPRE_Int) RAP_ext_j[k]; if (jcol < num_cols_diag_P) { if (P_marker[jcol] < jj_row_begin_diag) { P_marker[jcol] = jj_count_diag; jj_count_diag++; } } else { if (P_marker[jcol] < jj_row_begin_offd) { P_marker[jcol] = jj_count_offd; jj_count_offd++; } } } break; } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ /*-------------------------------------------------------------------- * Loop over entries in row ic of R_diag. *--------------------------------------------------------------------*/ for (jj1 = R_diag_i[ic]; jj1 < R_diag_i[ic + 1]; jj1++) { i1 = R_diag_j[jj1]; /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1 + 1]; jj2++) { i2 = A_offd_j[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_ext. *-----------------------------------------------------------*/ for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2 + 1]; jj3++) { i3 = P_ext_diag_j[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_diag) { P_marker[i3] = jj_count_diag; jj_count_diag++; } } for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2 + 1]; jj3++) { i3 = map_Pext_to_RAP[P_ext_offd_j[jj3]] + num_cols_diag_P; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_offd) { P_marker[i3] = jj_count_offd; jj_count_offd++; } } } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1 + 1]; jj2++) { i2 = A_diag_j[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2 + num_cols_offd_A] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2 + num_cols_offd_A] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_diag. *-----------------------------------------------------------*/ for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2 + 1]; jj3++) { i3 = P_diag_j[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_diag) { P_marker[i3] = jj_count_diag; jj_count_diag++; } } /*----------------------------------------------------------- * Loop over entries in row i2 of P_offd. *-----------------------------------------------------------*/ if (num_cols_offd_P) { for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2 + 1]; jj3++) { i3 = map_P_to_RAP[P_offd_j[jj3]] + num_cols_diag_P; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_offd) { P_marker[i3] = jj_count_offd; jj_count_offd++; } } } } } } /*-------------------------------------------------------------------- * Set RAP_diag_i and RAP_offd_i for this row. *--------------------------------------------------------------------*/ /* RAP_diag_i[ic] = jj_row_begin_diag; RAP_offd_i[ic] = jj_row_begin_offd; */ } jj_cnt_diag[ii] = jj_count_diag; jj_cnt_offd[ii] = jj_count_offd; } for (i = 0; i < num_threads - 1; i++) { jj_cnt_diag[i + 1] += jj_cnt_diag[i]; jj_cnt_offd[i + 1] += jj_cnt_offd[i]; } jj_count_diag = jj_cnt_diag[num_threads - 1]; jj_count_offd = jj_cnt_offd[num_threads - 1]; RAP_diag_i[num_cols_diag_RT] = jj_count_diag; RAP_offd_i[num_cols_diag_RT] = jj_count_offd; /*----------------------------------------------------------------------- * Allocate RAP_diag_data and RAP_diag_j arrays. * Allocate RAP_offd_data and RAP_offd_j arrays. *-----------------------------------------------------------------------*/ RAP_diag_size = jj_count_diag; if (RAP_diag_size) { RAP_diag_data = hypre_CTAlloc(HYPRE_Real, RAP_diag_size, HYPRE_MEMORY_DEVICE); RAP_diag_j = hypre_CTAlloc(HYPRE_Int, RAP_diag_size, HYPRE_MEMORY_DEVICE); } RAP_offd_size = jj_count_offd; if (RAP_offd_size) { RAP_offd_data = hypre_CTAlloc(HYPRE_Real, RAP_offd_size, HYPRE_MEMORY_DEVICE); RAP_offd_j = hypre_CTAlloc(HYPRE_Int, RAP_offd_size, HYPRE_MEMORY_DEVICE); } if (RAP_offd_size == 0 && num_cols_offd_RAP != 0) { num_cols_offd_RAP = 0; hypre_TFree(col_map_offd_RAP, HYPRE_MEMORY_HOST); } RA_diag_data_array = hypre_TAlloc(HYPRE_Real, num_cols_diag_A * num_threads, HYPRE_MEMORY_HOST); RA_diag_j_array = hypre_TAlloc(HYPRE_Int, num_cols_diag_A * num_threads, HYPRE_MEMORY_HOST); if (num_cols_offd_A) { RA_offd_data_array = hypre_TAlloc(HYPRE_Real, num_cols_offd_A * num_threads, HYPRE_MEMORY_HOST); RA_offd_j_array = hypre_TAlloc(HYPRE_Int, num_cols_offd_A * num_threads, HYPRE_MEMORY_HOST); } /*----------------------------------------------------------------------- * Second Pass: Fill in RAP_diag_data and RAP_diag_j. * Second Pass: Fill in RAP_offd_data and RAP_offd_j. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,k,jcol,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_count_diag,jj_count_offd,jj_row_begin_diag,jj_row_begin_offd,A_marker,P_marker,r_entry,r_a_product,r_a_p_product) HYPRE_SMP_SCHEDULE #endif for (ii = 0; ii < num_threads; ii++) { size = num_cols_diag_RT / num_threads; rest = num_cols_diag_RT - size * num_threads; if (ii < rest) { ns = ii * size + ii; ne = (ii + 1) * size + ii + 1; } else { ns = ii * size + rest; ne = (ii + 1) * size + rest; } /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ P_marker = P_mark_array[ii]; A_marker = A_mark_array[ii]; for (ic = 0; ic < num_cols_diag_P + num_cols_offd_RAP; ic++) { P_marker[ic] = -1; } for (i = 0; i < num_nz_cols_A ; i++) { A_marker[i] = -1; } jj_count_diag = start_indexing; jj_count_offd = start_indexing; if (ii > 0) { jj_count_diag = jj_cnt_diag[ii - 1]; jj_count_offd = jj_cnt_offd[ii - 1]; } // temporal matrix RA = R*A // only need to store one row per thread because R*A and (R*A)*P are fused // into one loop. hypre_CSRMatrix RA_diag, RA_offd; RA_diag.data = RA_diag_data_array + num_cols_diag_A * ii; RA_diag.j = RA_diag_j_array + num_cols_diag_A * ii; RA_diag.num_nonzeros = 0; RA_offd.num_nonzeros = 0; if (num_cols_offd_A) { RA_offd.data = RA_offd_data_array + num_cols_offd_A * ii; RA_offd.j = RA_offd_j_array + num_cols_offd_A * ii; } /*----------------------------------------------------------------------- * Loop over interior c-points. *-----------------------------------------------------------------------*/ for (ic = ns; ic < ne; ic++) { /*-------------------------------------------------------------------- * Create diagonal entry, RAP_{ic,ic} and add entries of RAP_ext *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; RAP_diag_i[ic] = jj_row_begin_diag; RAP_offd_i[ic] = jj_row_begin_offd; HYPRE_Int ra_row_begin_diag = RA_diag.num_nonzeros; HYPRE_Int ra_row_begin_offd = RA_offd.num_nonzeros; if (square) { P_marker[ic] = jj_count_diag; RAP_diag_data[jj_count_diag] = zero; RAP_diag_j[jj_count_diag] = ic; jj_count_diag++; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (send_map_elmts_RT_inverse_map_initialized) { HYPRE_Int i = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, ic); if (i != -1) { for (j = send_map_elmts_starts_RT_aggregated[i]; j < send_map_elmts_starts_RT_aggregated[i + 1]; j++) { HYPRE_Int jj = send_map_elmts_RT_aggregated[j]; for (k = RAP_ext_i[jj]; k < RAP_ext_i[jj + 1]; k++) { jcol = (HYPRE_Int)RAP_ext_j[k]; if (jcol < num_cols_diag_P) { if (P_marker[jcol] < jj_row_begin_diag) { P_marker[jcol] = jj_count_diag; RAP_diag_data[jj_count_diag] = RAP_ext_data[k]; RAP_diag_j[jj_count_diag] = jcol; jj_count_diag++; } else RAP_diag_data[P_marker[jcol]] += RAP_ext_data[k]; } else { if (P_marker[jcol] < jj_row_begin_offd) { P_marker[jcol] = jj_count_offd; RAP_offd_data[jj_count_offd] = RAP_ext_data[k]; RAP_offd_j[jj_count_offd] = jcol - num_cols_diag_P; jj_count_offd++; } else RAP_offd_data[P_marker[jcol]] += RAP_ext_data[k]; } } } } // if (set) } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ for (i = 0; i < num_sends_RT; i++) for (j = send_map_starts_RT[i]; j < send_map_starts_RT[i + 1]; j++) if (send_map_elmts_RT[j] == ic) { for (k = RAP_ext_i[j]; k < RAP_ext_i[j + 1]; k++) { jcol = (HYPRE_Int)RAP_ext_j[k]; if (jcol < num_cols_diag_P) { if (P_marker[jcol] < jj_row_begin_diag) { P_marker[jcol] = jj_count_diag; RAP_diag_data[jj_count_diag] = RAP_ext_data[k]; RAP_diag_j[jj_count_diag] = jcol; jj_count_diag++; } else RAP_diag_data[P_marker[jcol]] += RAP_ext_data[k]; } else { if (P_marker[jcol] < jj_row_begin_offd) { P_marker[jcol] = jj_count_offd; RAP_offd_data[jj_count_offd] = RAP_ext_data[k]; RAP_offd_j[jj_count_offd] = jcol - num_cols_diag_P; jj_count_offd++; } else RAP_offd_data[P_marker[jcol]] += RAP_ext_data[k]; } } break; } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ /*-------------------------------------------------------------------- * Loop over entries in row ic of R_diag and compute row ic of RA. *--------------------------------------------------------------------*/ for (jj1 = R_diag_i[ic]; jj1 < R_diag_i[ic + 1]; jj1++) { i1 = R_diag_j[jj1]; r_entry = R_diag_data[jj1]; /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1 + 1]; jj2++) { i2 = A_offd_j[jj2]; HYPRE_Real a_entry = A_offd_data[jj2]; HYPRE_Int marker = A_marker[i2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (marker < ra_row_begin_offd) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2] = RA_offd.num_nonzeros; RA_offd.data[RA_offd.num_nonzeros - ra_row_begin_offd] = r_entry * a_entry; RA_offd.j[RA_offd.num_nonzeros - ra_row_begin_offd] = i2; RA_offd.num_nonzeros++; } /*-------------------------------------------------------------- * If i2 is previously visited ( A_marker[12]=ic ) it yields * no new entries in RA and can just add new contributions. *--------------------------------------------------------------*/ else { RA_offd.data[marker - ra_row_begin_offd] += r_entry * a_entry; // JSP: compiler will more likely to generate FMA instructions // when we don't eliminate common subexpressions of // r_entry * A_offd_data[jj2] manually. } } // loop over entries in row i1 of A_offd } // num_cols_offd_A /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1 + 1]; jj2++) { i2 = A_diag_j[jj2]; HYPRE_Real a_entry = A_diag_data[jj2]; HYPRE_Int marker = A_marker[i2 + num_cols_offd_A]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (marker < ra_row_begin_diag) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2 + num_cols_offd_A] = RA_diag.num_nonzeros; RA_diag.data[RA_diag.num_nonzeros - ra_row_begin_diag] = r_entry * a_entry; RA_diag.j[RA_diag.num_nonzeros - ra_row_begin_diag] = i2; RA_diag.num_nonzeros++; } /*-------------------------------------------------------------- * If i2 is previously visited ( A_marker[12]=ic ) it yields * no new entries in RA and can just add new contributions. *--------------------------------------------------------------*/ else { RA_diag.data[marker - ra_row_begin_diag] += r_entry * a_entry; } } // loop over entries in row i1 of A_diag } // loop over entries in row ic of R_diag /*-------------------------------------------------------------------- * Loop over entries in row ic of RA_offd. *--------------------------------------------------------------------*/ for (jj1 = ra_row_begin_offd; jj1 < RA_offd.num_nonzeros; jj1++) { i1 = RA_offd.j[jj1 - ra_row_begin_offd]; r_a_product = RA_offd.data[jj1 - ra_row_begin_offd]; /*----------------------------------------------------------- * Loop over entries in row i1 of P_ext. *-----------------------------------------------------------*/ for (jj2 = P_ext_diag_i[i1]; jj2 < P_ext_diag_i[i1 + 1]; jj2++) { i2 = P_ext_diag_j[jj2]; HYPRE_Real p_entry = P_ext_diag_data[jj2]; HYPRE_Int marker = P_marker[i2]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i2} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (marker < jj_row_begin_diag) { P_marker[i2] = jj_count_diag; RAP_diag_data[jj_count_diag] = r_a_product * p_entry; RAP_diag_j[jj_count_diag] = i2; jj_count_diag++; } else { RAP_diag_data[marker] += r_a_product * p_entry; } } for (jj2 = P_ext_offd_i[i1]; jj2 < P_ext_offd_i[i1 + 1]; jj2++) { i2 = map_Pext_to_RAP[P_ext_offd_j[jj2]] + num_cols_diag_P; HYPRE_Real p_entry = P_ext_offd_data[jj2]; HYPRE_Int marker = P_marker[i2]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i2} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (marker < jj_row_begin_offd) { P_marker[i2] = jj_count_offd; RAP_offd_data[jj_count_offd] = r_a_product * p_entry; RAP_offd_j[jj_count_offd] = i2 - num_cols_diag_P; jj_count_offd++; } else { RAP_offd_data[marker] += r_a_product * p_entry; } } } // loop over entries in row ic of RA_offd /*-------------------------------------------------------------------- * Loop over entries in row ic of RA_diag. *--------------------------------------------------------------------*/ for (jj1 = ra_row_begin_diag; jj1 < RA_diag.num_nonzeros; jj1++) { HYPRE_Int i1 = RA_diag.j[jj1 - ra_row_begin_diag]; HYPRE_Real r_a_product = RA_diag.data[jj1 - ra_row_begin_diag]; /*----------------------------------------------------------------- * Loop over entries in row i1 of P_diag. *-----------------------------------------------------------------*/ for (jj2 = P_diag_i[i1]; jj2 < P_diag_i[i1 + 1]; jj2++) { i2 = P_diag_j[jj2]; HYPRE_Real p_entry = P_diag_data[jj2]; HYPRE_Int marker = P_marker[i2]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i2} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (marker < jj_row_begin_diag) { P_marker[i2] = jj_count_diag; RAP_diag_data[jj_count_diag] = r_a_product * p_entry; RAP_diag_j[jj_count_diag] = i2; jj_count_diag++; } else { RAP_diag_data[marker] += r_a_product * p_entry; } } if (num_cols_offd_P) { for (jj2 = P_offd_i[i1]; jj2 < P_offd_i[i1 + 1]; jj2++) { i2 = map_P_to_RAP[P_offd_j[jj2]] + num_cols_diag_P; HYPRE_Real p_entry = P_offd_data[jj2]; HYPRE_Int marker = P_marker[i2]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i2} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (marker < jj_row_begin_offd) { P_marker[i2] = jj_count_offd; RAP_offd_data[jj_count_offd] = r_a_product * p_entry; RAP_offd_j[jj_count_offd] = i2 - num_cols_diag_P; jj_count_offd++; } else { RAP_offd_data[marker] += r_a_product * p_entry; } } } // num_cols_offd_P } // loop over entries in row ic of RA_diag. } // Loop over interior c-points. hypre_TFree(P_mark_array[ii], HYPRE_MEMORY_HOST); hypre_TFree(A_mark_array[ii], HYPRE_MEMORY_HOST); } // omp parallel for /* check if really all off-diagonal entries occurring in col_map_offd_RAP are represented and eliminate if necessary */ P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_offd_RAP, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols_offd_RAP; i++) { P_marker[i] = -1; } jj_count_offd = 0; #ifdef HYPRE_USING_ATOMIC #pragma omp parallel for private(i3) reduction(+:jj_count_offd) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < RAP_offd_size; i++) { i3 = RAP_offd_j[i]; #ifdef HYPRE_USING_ATOMIC if (hypre_compare_and_swap(P_marker + i3, -1, 0) == -1) { jj_count_offd++; } #else if (P_marker[i3]) { P_marker[i3] = 0; jj_count_offd++; } #endif } if (jj_count_offd < num_cols_offd_RAP) { new_col_map_offd_RAP = hypre_CTAlloc(HYPRE_BigInt, jj_count_offd, HYPRE_MEMORY_HOST); jj_counter = 0; for (i = 0; i < num_cols_offd_RAP; i++) if (!P_marker[i]) { P_marker[i] = jj_counter; new_col_map_offd_RAP[jj_counter++] = col_map_offd_RAP[i]; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i3) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < RAP_offd_size; i++) { i3 = RAP_offd_j[i]; RAP_offd_j[i] = P_marker[i3]; } num_cols_offd_RAP = jj_count_offd; hypre_TFree(col_map_offd_RAP, HYPRE_MEMORY_HOST); col_map_offd_RAP = new_col_map_offd_RAP; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); RAP = hypre_ParCSRMatrixCreate(comm, n_coarse_RT, n_coarse, RT_partitioning, coarse_partitioning, num_cols_offd_RAP, RAP_diag_size, RAP_offd_size); RAP_diag = hypre_ParCSRMatrixDiag(RAP); hypre_CSRMatrixI(RAP_diag) = RAP_diag_i; if (RAP_diag_size) { hypre_CSRMatrixData(RAP_diag) = RAP_diag_data; hypre_CSRMatrixJ(RAP_diag) = RAP_diag_j; } RAP_offd = hypre_ParCSRMatrixOffd(RAP); hypre_CSRMatrixI(RAP_offd) = RAP_offd_i; if (num_cols_offd_RAP) { hypre_CSRMatrixData(RAP_offd) = RAP_offd_data; hypre_CSRMatrixJ(RAP_offd) = RAP_offd_j; hypre_ParCSRMatrixColMapOffd(RAP) = col_map_offd_RAP; } if (num_procs > 1) { /* hypre_GenerateRAPCommPkg(RAP, A); */ hypre_MatvecCommPkgCreate(RAP); } *RAP_ptr = RAP; /*----------------------------------------------------------------------- * Free R, P_ext and marker arrays. *-----------------------------------------------------------------------*/ if (keepTranspose) { hypre_ParCSRMatrixDiagT(RT) = R_diag; } else { hypre_CSRMatrixDestroy(R_diag); } R_diag = NULL; if (num_cols_offd_RT) { if (keepTranspose) { hypre_ParCSRMatrixOffdT(RT) = R_offd; } else { hypre_CSRMatrixDestroy(R_offd); } R_offd = NULL; } if (num_sends_RT || num_recvs_RT) { hypre_CSRMatrixDestroy(RAP_ext); RAP_ext = NULL; } hypre_TFree(P_mark_array, HYPRE_MEMORY_HOST); hypre_TFree(A_mark_array, HYPRE_MEMORY_HOST); hypre_TFree(P_ext_diag_i, HYPRE_MEMORY_HOST); hypre_TFree(P_ext_offd_i, HYPRE_MEMORY_HOST); hypre_TFree(jj_cnt_diag, HYPRE_MEMORY_HOST); hypre_TFree(jj_cnt_offd, HYPRE_MEMORY_HOST); if (num_cols_offd_P) { hypre_TFree(map_P_to_Pext, HYPRE_MEMORY_HOST); hypre_TFree(map_P_to_RAP, HYPRE_MEMORY_HOST); } if (num_cols_offd_Pext) { hypre_TFree(col_map_offd_Pext, HYPRE_MEMORY_HOST); hypre_TFree(map_Pext_to_RAP, HYPRE_MEMORY_HOST); } if (P_ext_diag_size) { hypre_TFree(P_ext_diag_data, HYPRE_MEMORY_HOST); hypre_TFree(P_ext_diag_j, HYPRE_MEMORY_HOST); } if (P_ext_offd_size) { hypre_TFree(P_ext_offd_data, HYPRE_MEMORY_HOST); hypre_TFree(P_ext_offd_j, HYPRE_MEMORY_HOST); } hypre_TFree(RA_diag_data_array, HYPRE_MEMORY_HOST); hypre_TFree(RA_diag_j_array, HYPRE_MEMORY_HOST); if (num_cols_offd_A) { hypre_TFree(RA_offd_data_array, HYPRE_MEMORY_HOST); hypre_TFree(RA_offd_j_array, HYPRE_MEMORY_HOST); } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (send_map_elmts_RT_inverse_map_initialized) { hypre_UnorderedIntMapDestroy(&send_map_elmts_RT_inverse_map); } hypre_TFree(send_map_elmts_starts_RT_aggregated, HYPRE_MEMORY_HOST); hypre_TFree(send_map_elmts_RT_aggregated, HYPRE_MEMORY_HOST); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RAP] += hypre_MPI_Wtime(); #endif return (0); }
builder.h
// Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef BUILDER_H_ #define BUILDER_H_ #include <algorithm> #include <parallel/algorithm> #include <cinttypes> #include <fstream> #include <functional> #include <type_traits> #include <utility> #include <omp.h> #include <cassert> #include <vector> #include "command_line.h" #include "generator.h" #include "graph.h" #include "platform_atomics.h" #include "pvector.h" #include "reader.h" #include "timer.h" #include "util.h" #include "sliding_queue.h" /* GAP Benchmark Suite Class: BuilderBase Author: Scott Beamer Given arguements from the command line (cli), returns a built graph - MakeGraph() will parse cli and obtain edgelist and call MakeGraphFromEL(edgelist) to perform actual graph construction - edgelist can be from file (reader) or synthetically generated (generator) - Common case: BuilderBase typedef'd (w/ params) to be Builder (benchmark.h) */ template <typename NodeID_, typename DestID_ = NodeID_, typename WeightT_ = NodeID_, bool invert = true> class BuilderBase { typedef EdgePair<NodeID_, DestID_> Edge; typedef pvector<Edge> EdgeList; const CLBase &cli_; bool symmetrize_; bool needs_weights_; int64_t num_nodes_ = -1; public: explicit BuilderBase(const CLBase &cli) : cli_(cli) { symmetrize_ = cli_.symmetrize(); needs_weights_ = !std::is_same<NodeID_, DestID_>::value; } DestID_ GetSource(EdgePair<NodeID_, NodeID_> e) { return e.u; } DestID_ GetSource(EdgePair<NodeID_, NodeWeight<NodeID_, WeightT_>> e) { return NodeWeight<NodeID_, WeightT_>(e.u, e.v.w); } NodeID_ FindMaxNodeID(const EdgeList &el) { NodeID_ max_seen = 0; #pragma omp parallel for reduction(max : max_seen) for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; max_seen = std::max(max_seen, e.u); max_seen = std::max(max_seen, (NodeID_) e.v); } return max_seen; } pvector<NodeID_> CountDegrees(const EdgeList &el, bool transpose) { pvector<NodeID_> degrees(num_nodes_, 0); #pragma omp parallel for for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; if (symmetrize_ || (!symmetrize_ && !transpose)) fetch_and_add(degrees[e.u], 1); if (symmetrize_ || (!symmetrize_ && transpose)) fetch_and_add(degrees[(NodeID_) e.v], 1); } return degrees; } static pvector<SGOffset> PrefixSum(const pvector<NodeID_> &degrees) { pvector<SGOffset> sums(degrees.size() + 1); SGOffset total = 0; for (size_t n=0; n < degrees.size(); n++) { sums[n] = total; total += degrees[n]; } sums[degrees.size()] = total; return sums; } static pvector<SGOffset> ParallelPrefixSum(const pvector<NodeID_> &degrees) { const size_t block_size = 1<<20; const size_t num_blocks = (degrees.size() + block_size - 1) / block_size; pvector<SGOffset> local_sums(num_blocks); #pragma omp parallel for for (size_t block=0; block < num_blocks; block++) { SGOffset lsum = 0; size_t block_end = std::min((block + 1) * block_size, degrees.size()); for (size_t i=block * block_size; i < block_end; i++) lsum += degrees[i]; local_sums[block] = lsum; } pvector<SGOffset> bulk_prefix(num_blocks+1); SGOffset total = 0; for (size_t block=0; block < num_blocks; block++) { bulk_prefix[block] = total; total += local_sums[block]; } bulk_prefix[num_blocks] = total; pvector<SGOffset> prefix(degrees.size() + 1); #pragma omp parallel for for (size_t block=0; block < num_blocks; block++) { SGOffset local_total = bulk_prefix[block]; size_t block_end = std::min((block + 1) * block_size, degrees.size()); for (size_t i=block * block_size; i < block_end; i++) { prefix[i] = local_total; local_total += degrees[i]; } } prefix[degrees.size()] = bulk_prefix[num_blocks]; return prefix; } // Removes self-loops and redundant edges // Side effect: neighbor IDs will be sorted void SquishCSR(const CSRGraph<NodeID_, DestID_, invert> &g, bool transpose, DestID_*** sq_index, DestID_** sq_neighs) { pvector<NodeID_> diffs(g.num_nodes()); DestID_ *n_start, *n_end; #pragma omp parallel for private(n_start, n_end) for (NodeID_ n=0; n < g.num_nodes(); n++) { if (transpose) { n_start = g.in_neigh(n).begin(); n_end = g.in_neigh(n).end(); } else { n_start = g.out_neigh(n).begin(); n_end = g.out_neigh(n).end(); } std::sort(n_start, n_end); DestID_ *new_end = std::unique(n_start, n_end); new_end = std::remove(n_start, new_end, n); diffs[n] = new_end - n_start; } pvector<SGOffset> sq_offsets = ParallelPrefixSum(diffs); *sq_neighs = new DestID_[sq_offsets[g.num_nodes()]]; *sq_index = CSRGraph<NodeID_, DestID_>::GenIndex(sq_offsets, *sq_neighs); #pragma omp parallel for private(n_start) for (NodeID_ n=0; n < g.num_nodes(); n++) { if (transpose) n_start = g.in_neigh(n).begin(); else n_start = g.out_neigh(n).begin(); std::copy(n_start, n_start+diffs[n], (*sq_index)[n]); } } CSRGraph<NodeID_, DestID_, invert> SquishGraph( const CSRGraph<NodeID_, DestID_, invert> &g) { DestID_ **out_index, *out_neighs, **in_index, *in_neighs; SquishCSR(g, false, &out_index, &out_neighs); if (g.directed()) { if (invert) SquishCSR(g, true, &in_index, &in_neighs); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), out_index, out_neighs, in_index, in_neighs); } else { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), out_index, out_neighs); } } /* Graph Bulding Steps (for CSR): - Read edgelist once to determine vertex degrees (CountDegrees) - Determine vertex offsets by a prefix sum (ParallelPrefixSum) - Allocate storage and set points according to offsets (GenIndex) - Copy edges into storage */ void MakeCSR(const EdgeList &el, bool transpose, DestID_*** index, DestID_** neighs) { pvector<NodeID_> degrees = CountDegrees(el, transpose); pvector<SGOffset> offsets = ParallelPrefixSum(degrees); *neighs = new DestID_[offsets[num_nodes_]]; *index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, *neighs); #pragma omp parallel for for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; if (symmetrize_ || (!symmetrize_ && !transpose)) (*neighs)[fetch_and_add(offsets[e.u], 1)] = e.v; if (symmetrize_ || (!symmetrize_ && transpose)) (*neighs)[fetch_and_add(offsets[static_cast<NodeID_>(e.v)], 1)] = GetSource(e); } } CSRGraph<NodeID_, DestID_, invert> MakeGraphFromEL(EdgeList &el) { DestID_ **index = nullptr, **inv_index = nullptr; DestID_ *neighs = nullptr, *inv_neighs = nullptr; Timer t; t.Start(); if (num_nodes_ == -1) num_nodes_ = FindMaxNodeID(el)+1; //#if 0 //TEMP if (needs_weights_) Generator<NodeID_, DestID_, WeightT_>::InsertWeights(el); //#endif MakeCSR(el, false, &index, &neighs); if (!symmetrize_ && invert) MakeCSR(el, true, &inv_index, &inv_neighs); t.Stop(); PrintTime("Build Time", t.Seconds()); if (symmetrize_) return CSRGraph<NodeID_, DestID_, invert>(num_nodes_, index, neighs); else return CSRGraph<NodeID_, DestID_, invert>(num_nodes_, index, neighs, inv_index, inv_neighs); } #if 0 //will complete the code later CSRGraph<NodeID_, DestID_, invert> relabelForSpatialLocality( const CSRGraph<NodeID_, DestID_, invert> &g) { if (g.directed()) { // Will add support soon } else { Timer t; t.start(); /* STEP I: make a map between new and old vertex labels */ long long counter = 0; //keep track of local counts std::map<NodeID_, int64_t> reMap[128]; //Conservatively assuming we will never use more than 128 threads /* relabel vertices in parallel (using local counter) */ #pragma omp parallel for firstprivate(count) for (NodeID_ v = 0; v < g.num_nodes(); v++) { if (reMap[omp_get_thread_num()].find(v) == reMap.end()) { // vertex hasn't been labelled reMap.insert(std::pair<NodeID_, int64_t>(v, counter)); counter++; } for (NodeID_ u : g.in_neigh(v)) { if (reMap[omp_get_thread_num()].find(u) == reMap.end()) { // vertex hasn't been labelled reMap.insert(std::pair<NodeID_, int64_t>(u, counter)); counter++; } } } /* Update counts based on maximum count for each thread */ int64_t offset = 0; for (int i = 0; i < 128; i++) { if (reMap[i].size() != 0) { // adding offset to all counts of current map std::map<NodeID_, int64_t>::iterator it, it_end; #pragma omp parallel for for (it = reMap[i].begin(), it_end = reMap[i].end(); it != it_end; it++) { it->second += offset; } // finding maximum value of current set int64_t maxVal = 0; #pragma omp parallel for reduction(max: maxVal) for (it = reMap[i].begin(), it_end = reMap[i].end(); it != it_end; it++) { if (it->second > maxVal) { maxVal = it->second; } } offset = maxVal; } } /* Merge local containers */ std::map <NodeID_, int64_t> merged_reMap; for (int i = 0; i < 128; i++) { if (reMap[i].size() != 0) { merged_reMap.insert(reMap[i].begin(), reMap[i].end()); } } /* STEP II: rewrite CSR based on this reMap */ DestID_* neighs = new DestID_[2 * g.num_edges()]; DestID_** index = CSRGraph<NodeID_, DestID_>::relabelIndex(offsets, neighs, reMap); } } #endif CSRGraph<NodeID_, DestID_, invert> MakeGraph() { CSRGraph<NodeID_, DestID_, invert> g; { // extra scope to trigger earlier deletion of el (save memory) EdgeList el; if (cli_.filename() != "") { Reader<NodeID_, DestID_, WeightT_, invert> r(cli_.filename()); if ((r.GetSuffix() == ".sg") || (r.GetSuffix() == ".wsg")) { return r.ReadSerializedGraph(); } else { el = r.ReadFile(needs_weights_); } } else if (cli_.scale() != -1) { Generator<NodeID_, DestID_> gen(cli_.scale(), cli_.degree()); el = gen.GenerateEL(cli_.uniform()); } g = MakeGraphFromEL(el); } #if 0 if (cli_.relabel() == 1) { g_new = relabelForSpatialLocality(g); } #endif return SquishGraph(g); } // Relabels (and rebuilds) graph by order of decreasing degree static CSRGraph<NodeID_, DestID_, invert> RelabelByDegree( const CSRGraph<NodeID_, DestID_, invert> &g) { if (g.directed()) { std::cout << "Cannot relabel directed graph" << std::endl; std::exit(-11); } Timer t; t.Start(); typedef std::pair<int64_t, NodeID_> degree_node_p; pvector<degree_node_p> degree_id_pairs(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); std::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); pvector<NodeID_> degrees(g.num_nodes()); pvector<NodeID_> new_ids(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[n] = degree_id_pairs[n].first; new_ids[degree_id_pairs[n].second] = n; } pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; std::sort(index[new_ids[u]], index[new_ids[u]+1]); } t.Stop(); PrintTime("Relabel", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } // Frequency-based Clustering as described in the CAGRA paper [BigData 17] static CSRGraph<NodeID_, DestID_, invert> degreeCluster( const CSRGraph<NodeID_, DestID_, invert> &g, bool outDegree, pvector<NodeID_> &new_ids, bool createOnlyDegList, bool createBothCSRs, int cutoffFactor) { Timer t; t.Start(); typedef std::pair<int64_t, NodeID_> degree_node_p; pvector<degree_node_p> degree_id_pairs(g.num_nodes()); NodeID_ avgDegree = g.num_edges_directed() / g.num_nodes(); NodeID_ degreeCutoff = avgDegree * cutoffFactor; NodeID_ hubCount(0); if (g.directed() == true) { /* Step I: Create a list of degrees */ #pragma omp parallel for reduction(+ : hubCount) for (NodeID_ n=0; n < g.num_nodes(); n++) { degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); if (outDegree == true) { if (g.out_degree(n) > degreeCutoff) { ++hubCount; } } else { if (g.in_degree(n) > degreeCutoff) { ++hubCount; } } } /* Step II: Sort based on degree order */ __gnu_parallel::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); //TODO:Use parallel sort /* Step III: assigned remap for the hub vertices */ #pragma omp parallel for for (NodeID_ n=0; n < hubCount; n++) { new_ids[degree_id_pairs[n].second] = n; } /* Step IV: assigning remap for (easy) non hub vertices */ NodeID_ numHubs = hubCount; SlidingQueue<NodeID_> queue(numHubs); int numThreads = omp_get_max_threads(); #pragma omp parallel { QueueBuffer<NodeID_> lqueue(queue, numHubs / numThreads); #pragma omp for for (NodeID_ n = numHubs; n < g.num_nodes(); ++n) { if (new_ids[n] == -1) { new_ids[n] = n; } else { NodeID_ remappedTo = new_ids[n]; if (new_ids[remappedTo] == -1) { new_ids[remappedTo] = n; //Swap ids } else { lqueue.push_back(n); } } } lqueue.flush(); } queue.slide_window(); /* Step V: assigning remaps for remaining non hubs */ NodeID_ unassignedCtr = 0; auto q_iter = queue.begin(); #pragma omp parallel for for (NodeID_ n = 0; n < numHubs; ++n) { if (new_ids[n] == -1) { NodeID_ u = *(q_iter + __sync_fetch_and_add(&unassignedCtr, 1)); new_ids[n] = u; } } /* Step VI: generate degree to build a new graph */ pvector<NodeID_> degrees(g.num_nodes()); pvector<NodeID_> inv_degrees(g.num_nodes()); if (outDegree == true) { #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.out_degree(n); inv_degrees[new_ids[n]] = g.in_degree(n); } } else { #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.in_degree(n); inv_degrees[new_ids[n]] = g.out_degree(n); } } /* Graph building phase */ pvector<SGOffset> offsets = ParallelPrefixSum(inv_degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { if (outDegree == true) { for (NodeID_ v : g.in_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; } else { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; } } DestID_* inv_neighs(nullptr); DestID_** inv_index(nullptr); if (createOnlyDegList == true || createBothCSRs == true) { // making the inverse list (in-degrees in this case) pvector<SGOffset> inv_offsets = ParallelPrefixSum(degrees); inv_neighs = new DestID_[inv_offsets[g.num_nodes()]]; inv_index = CSRGraph<NodeID_, DestID_>::GenIndex(inv_offsets, inv_neighs); if (createBothCSRs == true) { #pragma omp parallel for schedule(dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { if (outDegree == true) { for (NodeID_ v : g.out_neigh(u)) inv_neighs[inv_offsets[new_ids[u]]++] = new_ids[v]; } else { for (NodeID_ v : g.in_neigh(u)) inv_neighs[inv_offsets[new_ids[u]]++] = new_ids[v]; } } } } t.Stop(); PrintTime("HubSort time", t.Seconds()); if (outDegree == true) { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), inv_index, inv_neighs, index, neighs); } else { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs, inv_index, inv_neighs); } } else { /* Undirected graphs - no need to make separate lists for in and out degree */ /* Step I: Create a list of degrees */ #pragma omp parallel for reduction(+ : hubCount) for (NodeID_ n=0; n < g.num_nodes(); n++) { degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); if (g.out_degree(n) > degreeCutoff) { ++hubCount; } } /* Step II: Sort based on degree order */ __gnu_parallel::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); //TODO:Use parallel sort /* Step III: assigned remap for the hub vertices */ #pragma omp parallel for for (NodeID_ n=0; n < hubCount; n++) { new_ids[degree_id_pairs[n].second] = n; } /* Step IV: assigning remap for (easy) non hub vertices */ NodeID_ numHubs = hubCount; SlidingQueue<NodeID_> queue(numHubs); int numThreads = omp_get_max_threads(); #pragma omp parallel { QueueBuffer<NodeID_> lqueue(queue, numHubs / numThreads); #pragma omp for for (NodeID_ n = numHubs; n < g.num_nodes(); ++n) { if (new_ids[n] == -1) { new_ids[n] = n; } else { NodeID_ remappedTo = new_ids[n]; if (new_ids[remappedTo] == -1) { new_ids[remappedTo] = n; //Swap ids } else { lqueue.push_back(n); } } } lqueue.flush(); } queue.slide_window(); /* Step V: assigning remaps for remaining non hubs */ NodeID_ unassignedCtr = 0; auto q_iter = queue.begin(); #pragma omp parallel for for (NodeID_ n = 0; n < numHubs; ++n) { if (new_ids[n] == -1) { NodeID_ u = *(q_iter + __sync_fetch_and_add(&unassignedCtr, 1)); new_ids[n] = u; } } /* Step VI: generate degree to build a new graph */ pvector<NodeID_> degrees(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.out_degree(n); } /* Graph building phase */ pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; } t.Stop(); PrintTime("HubSort time", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } } // Similar to the previous function but handles directed graphs, // weighted graphs, and also does relabeling by user specified method static CSRGraph<NodeID_, DestID_, invert> degreeCluster_weighted( const CSRGraph<NodeID_, DestID_, invert> &g, bool outDegree, pvector<NodeID_> &new_ids, bool createOnlyDegList, bool createBothCSRs, int cutoffFactor) { Timer t; t.Start(); typedef std::pair<int64_t, NodeID_> degree_node_p; pvector<degree_node_p> degree_id_pairs(g.num_nodes()); NodeID_ avgDegree = g.num_edges_directed() / g.num_nodes(); NodeID_ degreeCutoff = avgDegree * cutoffFactor; NodeID_ hubCount(0); if (g.directed() == true) { /* Step I: Create a list of degrees */ #pragma omp parallel for reduction(+ : hubCount) for (NodeID_ n=0; n < g.num_nodes(); n++) { degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); if (outDegree == true) { if (g.out_degree(n) > degreeCutoff) { ++hubCount; } } else { if (g.in_degree(n) > degreeCutoff) { ++hubCount; } } } /* Step II: Sort based on degree order */ __gnu_parallel::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); //TODO:Use parallel sort /* Step III: assigned remap for the hub vertices */ #pragma omp parallel for for (NodeID_ n=0; n < hubCount; n++) { new_ids[degree_id_pairs[n].second] = n; } /* Step IV: assigning remap for (easy) non hub vertices */ NodeID_ numHubs = hubCount; SlidingQueue<NodeID_> queue(numHubs); int numThreads = omp_get_max_threads(); #pragma omp parallel { QueueBuffer<NodeID_> lqueue(queue, numHubs / numThreads); #pragma omp for for (NodeID_ n = numHubs; n < g.num_nodes(); ++n) { if (new_ids[n] == -1) { new_ids[n] = n; } else { NodeID_ remappedTo = new_ids[n]; if (new_ids[remappedTo] == -1) { new_ids[remappedTo] = n; //Swap ids } else { lqueue.push_back(n); } } } lqueue.flush(); } queue.slide_window(); /* Step V: assigning remaps for remaining non hubs */ NodeID_ unassignedCtr = 0; auto q_iter = queue.begin(); #pragma omp parallel for for (NodeID_ n = 0; n < numHubs; ++n) { if (new_ids[n] == -1) { NodeID_ u = *(q_iter + __sync_fetch_and_add(&unassignedCtr, 1)); new_ids[n] = u; } } /* Step VI: generate degree to build a new graph */ pvector<NodeID_> degrees(g.num_nodes()); pvector<NodeID_> inv_degrees(g.num_nodes()); if (outDegree == true) { #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.out_degree(n); inv_degrees[new_ids[n]] = g.in_degree(n); } } else { #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.in_degree(n); inv_degrees[new_ids[n]] = g.out_degree(n); } } /* Graph building phase */ pvector<SGOffset> offsets = ParallelPrefixSum(inv_degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule(dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { if (outDegree) { for (auto v : g.in_neigh(u)) { auto oldWeight = v.w; auto newID = new_ids[(NodeID_) v.v]; DestID_ newV (newID, oldWeight); neighs[offsets[new_ids[u]]++] = newV; } } else { for (auto v : g.out_neigh(u)) { auto oldWeight = v.w; auto newID = new_ids[(NodeID_) v.v]; DestID_ newV (newID, oldWeight); neighs[offsets[new_ids[u]]++] = newV; } } } DestID_* inv_neighs(nullptr); DestID_** inv_index(nullptr); if (createBothCSRs == true || createOnlyDegList == true) { // making the inverse list (in-degrees in this case) pvector<SGOffset> inv_offsets = ParallelPrefixSum(degrees); inv_neighs = new DestID_[inv_offsets[g.num_nodes()]]; inv_index = CSRGraph<NodeID_, DestID_>::GenIndex(inv_offsets, inv_neighs); if (createBothCSRs == true) { #pragma omp parallel for schedule(dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { if (outDegree == true) { for (auto v : g.out_neigh(u)) { auto oldWeight = v.w; auto newID = new_ids[(NodeID_) v.v]; DestID_ newV (newID, oldWeight); inv_neighs[inv_offsets[new_ids[u]]++] = newV; } } else { for (auto v : g.in_neigh(u)) { auto oldWeight = v.w; auto newID = new_ids[(NodeID_) v.v]; DestID_ newV (newID, oldWeight); inv_neighs[inv_offsets[new_ids[u]]++] = newV; } } } } } t.Stop(); PrintTime("HubSort time", t.Seconds()); if (outDegree == true) { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), inv_index, inv_neighs, index, neighs); } else { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs, inv_index, inv_neighs); } } else { /* Undirected graphs - no need to make separate lists for in and out degree */ /* Step I: Create a list of degrees */ #pragma omp parallel for reduction(+ : hubCount) for (NodeID_ n=0; n < g.num_nodes(); n++) { degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); if (g.out_degree(n) > degreeCutoff) { ++hubCount; } } /* Step II: Sort based on degree order */ __gnu_parallel::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); //TODO:Use parallel sort /* Step III: assigned remap for the hub vertices */ #pragma omp parallel for for (NodeID_ n=0; n < hubCount; n++) { new_ids[degree_id_pairs[n].second] = n; } /* Step IV: assigning remap for (easy) non hub vertices */ NodeID_ numHubs = hubCount; SlidingQueue<NodeID_> queue(numHubs); int numThreads = omp_get_max_threads(); #pragma omp parallel { QueueBuffer<NodeID_> lqueue(queue, numHubs / numThreads); #pragma omp for for (NodeID_ n = numHubs; n < g.num_nodes(); ++n) { if (new_ids[n] == -1) { new_ids[n] = n; } else { NodeID_ remappedTo = new_ids[n]; if (new_ids[remappedTo] == -1) { new_ids[remappedTo] = n; //Swap ids } else { lqueue.push_back(n); } } } lqueue.flush(); } queue.slide_window(); /* Step V: assigning remaps for remaining non hubs */ NodeID_ unassignedCtr = 0; auto q_iter = queue.begin(); #pragma omp parallel for for (NodeID_ n = 0; n < numHubs; ++n) { if (new_ids[n] == -1) { NodeID_ u = *(q_iter + __sync_fetch_and_add(&unassignedCtr, 1)); new_ids[n] = u; } } /* Step VI: generate degree to build a new graph */ pvector<NodeID_> degrees(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[new_ids[n]] = g.out_degree(n); } /* Graph building phase */ pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for schedule (dynamic, 1024) for (NodeID_ u=0; u < g.num_nodes(); u++) { for (auto v : g.out_neigh(u)) { auto oldWeight = v.w; auto newID = new_ids[(NodeID_) v.v]; DestID_ newV (newID, oldWeight); neighs[offsets[new_ids[u]]++] = newV; } } t.Stop(); PrintTime("HubSort time", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } } }; #endif // BUILDER_H_
ROF_TV_core.c
/* * This work is part of the Core Imaging Library developed by * Visual Analytics and Imaging System Group of the Science Technology * Facilities Council, STFC * * Copyright 2017 Daniil Kazantsev * Copyright 2017 Srikanth Nagella, Edoardo Pasca * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ROF_TV_core.h" #define EPS 1.0e-8 #define MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) /*sign function*/ int sign(float x) { return (x > 0) - (x < 0); } /* C-OMP implementation of ROF-TV denoising/regularization model [1] (2D/3D case) * * * Input Parameters: * 1. Noisy image/volume [REQUIRED] * 2. lambda - regularization parameter [REQUIRED] * 3. tau - marching step for explicit scheme, ~1 is recommended [REQUIRED] * 4. Number of iterations, for explicit scheme >= 150 is recommended [REQUIRED] * 5. eplsilon: tolerance constant * * Output: * [1] Regularized image/volume * [2] Information vector which contains [iteration no., reached tolerance] * * This function is based on the paper by * [1] Rudin, Osher, Fatemi, "Nonlinear Total Variation based noise removal algorithms" */ /* Running iterations of TV-ROF function */ float TV_ROF_CPU_main(float *Input, float *Output, float *infovector, float lambdaPar, int iterationsNumb, float tau, float epsil, int dimX, int dimY, int dimZ) { float *D1=NULL, *D2=NULL, *D3=NULL, *Output_prev=NULL; float re, re1; re = 0.0f; re1 = 0.0f; int count = 0; int i; long DimTotal,j; DimTotal = (long)(dimX*dimY*dimZ); D1 = calloc(DimTotal, sizeof(float)); D2 = calloc(DimTotal, sizeof(float)); D3 = calloc(DimTotal, sizeof(float)); /* copy into output */ copyIm(Input, Output, (long)(dimX), (long)(dimY), (long)(dimZ)); if (epsil != 0.0f) Output_prev = calloc(DimTotal, sizeof(float)); /* start TV iterations */ for(i=0; i < iterationsNumb; i++) { if ((epsil != 0.0f) && (i % 5 == 0)) copyIm(Output, Output_prev, (long)(dimX), (long)(dimY), (long)(dimZ)); /* calculate differences */ D1_func(Output, D1, (long)(dimX), (long)(dimY), (long)(dimZ)); D2_func(Output, D2, (long)(dimX), (long)(dimY), (long)(dimZ)); if (dimZ > 1) D3_func(Output, D3, (long)(dimX), (long)(dimY), (long)(dimZ)); TV_kernel(D1, D2, D3, Output, Input, lambdaPar, tau, (long)(dimX), (long)(dimY), (long)(dimZ)); /* check early stopping criteria */ if ((epsil != 0.0f) && (i % 5 == 0)) { re = 0.0f; re1 = 0.0f; for(j=0; j<DimTotal; j++) { re += powf(Output[j] - Output_prev[j],2); re1 += powf(Output[j],2); } re = sqrtf(re)/sqrtf(re1); if (re < epsil) count++; if (count > 3) break; } } free(D1);free(D2); free(D3); if (epsil != 0.0f) free(Output_prev); /*adding info into info_vector */ infovector[0] = (float)(i); /*iterations number (if stopped earlier based on tolerance)*/ infovector[1] = re; /* reached tolerance */ return 0; } /* calculate differences 1 */ float D1_func(float *A, float *D1, long dimX, long dimY, long dimZ) { float NOMx_1, NOMy_1, NOMy_0, NOMz_1, NOMz_0, denom1, denom2,denom3, T1; long i,j,k,i1,i2,k1,j1,j2,k2,index; if (dimZ > 1) { #pragma omp parallel for shared (A, D1, dimX, dimY, dimZ) private(index, i, j, k, i1, j1, k1, i2, j2, k2, NOMx_1,NOMy_1,NOMy_0,NOMz_1,NOMz_0,denom1,denom2,denom3,T1) for(j=0; j<dimY; j++) { for(i=0; i<dimX; i++) { for(k=0; k<dimZ; k++) { index = (dimX*dimY)*k + j*dimX+i; /* symmetric boundary conditions (Neuman) */ i1 = i + 1; if (i1 >= dimX) i1 = i-1; i2 = i - 1; if (i2 < 0) i2 = i+1; j1 = j + 1; if (j1 >= dimY) j1 = j-1; j2 = j - 1; if (j2 < 0) j2 = j+1; k1 = k + 1; if (k1 >= dimZ) k1 = k-1; k2 = k - 1; if (k2 < 0) k2 = k+1; /* Forward-backward differences */ NOMx_1 = A[(dimX*dimY)*k + j1*dimX + i] - A[index]; /* x+ */ NOMy_1 = A[(dimX*dimY)*k + j*dimX + i1] - A[index]; /* y+ */ /*NOMx_0 = (A[(i)*dimY + j] - A[(i2)*dimY + j]); */ /* x- */ NOMy_0 = A[index] - A[(dimX*dimY)*k + j*dimX + i2]; /* y- */ NOMz_1 = A[(dimX*dimY)*k1 + j*dimX + i] - A[index]; /* z+ */ NOMz_0 = A[index] - A[(dimX*dimY)*k2 + j*dimX + i]; /* z- */ denom1 = NOMx_1*NOMx_1; denom2 = 0.5f*(sign(NOMy_1) + sign(NOMy_0))*(MIN(fabs(NOMy_1),fabs(NOMy_0))); denom2 = denom2*denom2; denom3 = 0.5f*(sign(NOMz_1) + sign(NOMz_0))*(MIN(fabs(NOMz_1),fabs(NOMz_0))); denom3 = denom3*denom3; T1 = sqrt(denom1 + denom2 + denom3 + EPS); D1[index] = NOMx_1/T1; }}} } else { #pragma omp parallel for shared (A, D1, dimX, dimY) private(i, j, i1, j1, i2, j2,NOMx_1,NOMy_1,NOMy_0,denom1,denom2,T1,index) for(j=0; j<dimY; j++) { for(i=0; i<dimX; i++) { index = j*dimX+i; /* symmetric boundary conditions (Neuman) */ i1 = i + 1; if (i1 >= dimX) i1 = i-1; i2 = i - 1; if (i2 < 0) i2 = i+1; j1 = j + 1; if (j1 >= dimY) j1 = j-1; j2 = j - 1; if (j2 < 0) j2 = j+1; /* Forward-backward differences */ NOMx_1 = A[j1*dimX + i] - A[index]; /* x+ */ NOMy_1 = A[j*dimX + i1] - A[index]; /* y+ */ /*NOMx_0 = (A[(i)*dimY + j] - A[(i2)*dimY + j]); */ /* x- */ NOMy_0 = A[index] - A[(j)*dimX + i2]; /* y- */ denom1 = NOMx_1*NOMx_1; denom2 = 0.5f*(sign(NOMy_1) + sign(NOMy_0))*(MIN(fabs(NOMy_1),fabs(NOMy_0))); denom2 = denom2*denom2; T1 = sqrtf(denom1 + denom2 + EPS); D1[index] = NOMx_1/T1; }} } return *D1; } /* calculate differences 2 */ float D2_func(float *A, float *D2, long dimX, long dimY, long dimZ) { float NOMx_1, NOMy_1, NOMx_0, NOMz_1, NOMz_0, denom1, denom2, denom3, T2; long i,j,k,i1,i2,k1,j1,j2,k2,index; if (dimZ > 1) { #pragma omp parallel for shared (A, D2, dimX, dimY, dimZ) private(index, i, j, k, i1, j1, k1, i2, j2, k2, NOMx_1, NOMy_1, NOMx_0, NOMz_1, NOMz_0, denom1, denom2, denom3, T2) for(j=0; j<dimY; j++) { for(i=0; i<dimX; i++) { for(k=0; k<dimZ; k++) { index = (dimX*dimY)*k + j*dimX+i; /* symmetric boundary conditions (Neuman) */ i1 = i + 1; if (i1 >= dimX) i1 = i-1; i2 = i - 1; if (i2 < 0) i2 = i+1; j1 = j + 1; if (j1 >= dimY) j1 = j-1; j2 = j - 1; if (j2 < 0) j2 = j+1; k1 = k + 1; if (k1 >= dimZ) k1 = k-1; k2 = k - 1; if (k2 < 0) k2 = k+1; /* Forward-backward differences */ NOMx_1 = A[(dimX*dimY)*k + (j1)*dimX + i] - A[index]; /* x+ */ NOMy_1 = A[(dimX*dimY)*k + (j)*dimX + i1] - A[index]; /* y+ */ NOMx_0 = A[index] - A[(dimX*dimY)*k + (j2)*dimX + i]; /* x- */ NOMz_1 = A[(dimX*dimY)*k1 + j*dimX + i] - A[index]; /* z+ */ NOMz_0 = A[index] - A[(dimX*dimY)*k2 + (j)*dimX + i]; /* z- */ denom1 = NOMy_1*NOMy_1; denom2 = 0.5f*(sign(NOMx_1) + sign(NOMx_0))*(MIN(fabs(NOMx_1),fabs(NOMx_0))); denom2 = denom2*denom2; denom3 = 0.5f*(sign(NOMz_1) + sign(NOMz_0))*(MIN(fabs(NOMz_1),fabs(NOMz_0))); denom3 = denom3*denom3; T2 = sqrtf(denom1 + denom2 + denom3 + EPS); D2[index] = NOMy_1/T2; }}} } else { #pragma omp parallel for shared (A, D2, dimX, dimY) private(i, j, i1, j1, i2, j2, NOMx_1,NOMy_1,NOMx_0,denom1,denom2,T2,index) for(j=0; j<dimY; j++) { for(i=0; i<dimX; i++) { index = j*dimX+i; /* symmetric boundary conditions (Neuman) */ i1 = i + 1; if (i1 >= dimX) i1 = i-1; i2 = i - 1; if (i2 < 0) i2 = i+1; j1 = j + 1; if (j1 >= dimY) j1 = j-1; j2 = j - 1; if (j2 < 0) j2 = j+1; /* Forward-backward differences */ NOMx_1 = A[j1*dimX + i] - A[index]; /* x+ */ NOMy_1 = A[j*dimX + i1] - A[index]; /* y+ */ NOMx_0 = A[index] - A[j2*dimX + i]; /* x- */ /*NOMy_0 = A[(i)*dimY + j] - A[(i)*dimY + j2]; */ /* y- */ denom1 = NOMy_1*NOMy_1; denom2 = 0.5f*(sign(NOMx_1) + sign(NOMx_0))*(MIN(fabs(NOMx_1),fabs(NOMx_0))); denom2 = denom2*denom2; T2 = sqrtf(denom1 + denom2 + EPS); D2[index] = NOMy_1/T2; }} } return *D2; } /* calculate differences 3 */ float D3_func(float *A, float *D3, long dimX, long dimY, long dimZ) { float NOMx_1, NOMy_1, NOMx_0, NOMy_0, NOMz_1, denom1, denom2, denom3, T3; long index,i,j,k,i1,i2,k1,j1,j2,k2; #pragma omp parallel for shared (A, D3, dimX, dimY, dimZ) private(index, i, j, k, i1, j1, k1, i2, j2, k2, NOMx_1, NOMy_1, NOMy_0, NOMx_0, NOMz_1, denom1, denom2, denom3, T3) for(j=0; j<dimY; j++) { for(i=0; i<dimX; i++) { for(k=0; k<dimZ; k++) { index = (dimX*dimY)*k + j*dimX+i; /* symmetric boundary conditions (Neuman) */ i1 = i + 1; if (i1 >= dimX) i1 = i-1; i2 = i - 1; if (i2 < 0) i2 = i+1; j1 = j + 1; if (j1 >= dimY) j1 = j-1; j2 = j - 1; if (j2 < 0) j2 = j+1; k1 = k + 1; if (k1 >= dimZ) k1 = k-1; k2 = k - 1; if (k2 < 0) k2 = k+1; /* Forward-backward differences */ NOMx_1 = A[(dimX*dimY)*k + (j1)*dimX + i] - A[index]; /* x+ */ NOMy_1 = A[(dimX*dimY)*k + (j)*dimX + i1] - A[index]; /* y+ */ NOMy_0 = A[index] - A[(dimX*dimY)*k + (j)*dimX + i2]; /* y- */ NOMx_0 = A[index] - A[(dimX*dimY)*k + (j2)*dimX + i]; /* x- */ NOMz_1 = A[(dimX*dimY)*k1 + j*dimX + i] - A[index]; /* z+ */ /*NOMz_0 = A[(dimX*dimY)*k + (i)*dimY + j] - A[(dimX*dimY)*k2 + (i)*dimY + j]; */ /* z- */ denom1 = NOMz_1*NOMz_1; denom2 = 0.5f*(sign(NOMx_1) + sign(NOMx_0))*(MIN(fabs(NOMx_1),fabs(NOMx_0))); denom2 = denom2*denom2; denom3 = 0.5f*(sign(NOMy_1) + sign(NOMy_0))*(MIN(fabs(NOMy_1),fabs(NOMy_0))); denom3 = denom3*denom3; T3 = sqrtf(denom1 + denom2 + denom3 + EPS); D3[index] = NOMz_1/T3; }}} return *D3; } /* calculate divergence */ float TV_kernel(float *D1, float *D2, float *D3, float *B, float *A, float lambda, float tau, long dimX, long dimY, long dimZ) { float dv1, dv2, dv3; long index,i,j,k,i1,i2,k1,j1,j2,k2; if (dimZ > 1) { #pragma omp parallel for shared (D1, D2, D3, B, dimX, dimY, dimZ) private(index, i, j, k, i1, j1, k1, i2, j2, k2, dv1,dv2,dv3) for(j=0; j<dimY; j++) { for(i=0; i<dimX; i++) { for(k=0; k<dimZ; k++) { index = (dimX*dimY)*k + j*dimX+i; /* symmetric boundary conditions (Neuman) */ i1 = i + 1; if (i1 >= dimX) i1 = i-1; i2 = i - 1; if (i2 < 0) i2 = i+1; j1 = j + 1; if (j1 >= dimY) j1 = j-1; j2 = j - 1; if (j2 < 0) j2 = j+1; k1 = k + 1; if (k1 >= dimZ) k1 = k-1; k2 = k - 1; if (k2 < 0) k2 = k+1; /*divergence components */ dv1 = D1[index] - D1[(dimX*dimY)*k + j2*dimX+i]; dv2 = D2[index] - D2[(dimX*dimY)*k + j*dimX+i2]; dv3 = D3[index] - D3[(dimX*dimY)*k2 + j*dimX+i]; B[index] += tau*(lambda*(dv1 + dv2 + dv3) - (B[index] - A[index])); }}} } else { #pragma omp parallel for shared (D1, D2, B, dimX, dimY) private(index, i, j, i1, j1, i2, j2,dv1,dv2) for(j=0; j<dimY; j++) { for(i=0; i<dimX; i++) { index = j*dimX+i; /* symmetric boundary conditions (Neuman) */ i1 = i + 1; if (i1 >= dimX) i1 = i-1; i2 = i - 1; if (i2 < 0) i2 = i+1; j1 = j + 1; if (j1 >= dimY) j1 = j-1; j2 = j - 1; if (j2 < 0) j2 = j+1; /* divergence components */ dv1 = D1[index] - D1[j2*dimX + i]; dv2 = D2[index] - D2[j*dimX + i2]; B[index] += tau*(lambda*(dv1 + dv2) - (B[index] - A[index])); }} } return *B; }
utils.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015 by Contributors * \file utils.h * \brief Basic utilility functions. */ #ifndef MXNET_COMMON_UTILS_H_ #define MXNET_COMMON_UTILS_H_ #include <dmlc/logging.h> #include <dmlc/omp.h> #include <nnvm/graph.h> #include <nnvm/node.h> #include <mxnet/engine.h> #include <mxnet/ndarray.h> #include <mxnet/op_attr_types.h> #include <mxnet/graph_attr_types.h> #include <nnvm/graph_attr_types.h> #include <memory> #include <vector> #include <type_traits> #include <utility> #include <random> #include <string> #include <thread> #include <algorithm> #include <functional> #include <limits> #include "../operator/mxnet_op.h" #if MXNET_USE_MKLDNN == 1 #include "../operator/nn/mkldnn/mkldnn_base-inl.h" #endif #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) #include <windows.h> #else #include <unistd.h> #endif namespace mxnet { namespace common { #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) inline size_t current_process_id() { return ::GetCurrentProcessId(); } #else inline size_t current_process_id() { return getpid(); } #endif /*! * \brief IndPtr should be non-negative, in non-decreasing order, start with 0 * and end with value equal with size of indices. */ struct csr_indptr_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* indptr, const nnvm::dim_t end, const nnvm::dim_t idx_size) { if (indptr[i+1] < 0 || indptr[i+1] < indptr[i] || (i == 0 && indptr[i] != 0) || (i == end - 1 && indptr[end] != idx_size)) *out = kCSRIndPtrErr; } }; /*! * \brief Indices should be non-negative, less than the number of columns * and in ascending order per row. */ struct csr_idx_check { template<typename DType, typename IType, typename RType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const RType* indptr, const nnvm::dim_t ncols) { for (RType j = indptr[i]; j < indptr[i+1]; j++) { if (idx[j] >= ncols || idx[j] < 0 || (j < indptr[i+1] - 1 && idx[j] >= idx[j+1])) { *out = kCSRIdxErr; break; } } } }; /*! * \brief Indices of RSPNDArray should be non-negative, * less than the size of first dimension and in ascending order */ struct rsp_idx_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const nnvm::dim_t end, const nnvm::dim_t nrows) { if ((i < end && idx[i+1] <= idx[i]) || idx[i] < 0 || idx[i] >= nrows) *out = kRSPIdxErr; } }; template<typename xpu> void CheckFormatWrapper(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check); /*! * \brief Check the validity of CSRNDArray. * \param rctx Execution context. * \param input Input NDArray of CSRStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatCSRImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kCSRStorage) << "CheckFormatCSRImpl is for CSRNDArray"; const mxnet::TShape shape = input.shape(); const mxnet::TShape idx_shape = input.aux_shape(csr::kIdx); const mxnet::TShape indptr_shape = input.aux_shape(csr::kIndPtr); const mxnet::TShape storage_shape = input.storage_shape(); if ((shape.ndim() != 2) || (idx_shape.ndim() != 1 || indptr_shape.ndim() != 1 || storage_shape.ndim() != 1) || (indptr_shape[0] != shape[0] + 1) || (idx_shape[0] != storage_shape[0])) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kCSRShapeErr; }); return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<csr_indptr_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), indptr_shape[0] - 1, idx_shape[0]); // no need to check indices if indices are empty if (idx_shape[0] != 0) { Kernel<csr_idx_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIdx).dptr<IType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), shape[1]); } mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); }); } } /*! * \brief Check the validity of RowSparseNDArray. * \param rctx Execution context. * \param input Input NDArray of RowSparseStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatRSPImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kRowSparseStorage) << "CheckFormatRSPImpl is for RSPNDArray"; const mxnet::TShape idx_shape = input.aux_shape(rowsparse::kIdx); if (idx_shape[0] != input.storage_shape()[0]) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kRSPShapeErr; }); return; } if (idx_shape[0] == 0) { return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<rsp_idx_check, xpu>::Launch(s, idx_shape[0], val_xpu.dptr<DType>(), input.aux_data(rowsparse::kIdx).dptr<IType>(), idx_shape[0] - 1, input.shape()[0]); mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); } } template<typename xpu> void CheckFormatImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { int stype = input.storage_type(); if (stype == kCSRStorage) { CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kRowSparseStorage) { CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kDefaultStorage) { // no-op for default storage } else { LOG(FATAL) << "Unknown storage type " << stype; } } /*! \brief Pick rows specified by user input index array from a row sparse ndarray * and save them in the output sparse ndarray. */ template<typename xpu> void SparseRetainOpForwardRspWrapper(mshadow::Stream<xpu> *s, const NDArray& input_nd, const TBlob& idx_data, const OpReqType req, NDArray* output_nd); /* \brief Casts tensor storage type to the new type. */ template<typename xpu> void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output); /*! \brief returns true if all storage types in `vstorage` are the same as target `stype`. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype) { if (!vstorage.empty()) { for (const auto& i : vstorage) { if (i != stype) return false; } return true; } return false; } /*! \brief returns true if all storage types in `vstorage` are the same as target `stype1` * or `stype2'. Sets boolean if both found. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!vstorage.empty()) { uint8_t has = 0; for (const auto i : vstorage) { if (i == stype1) { has |= 1; } else if (i == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as target `stype`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() != stype) { return false; } } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as targets `stype1` or `stype2`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!ndarrays.empty()) { uint8_t has = 0; for (const auto& nd : ndarrays) { const NDArrayStorageType stype = nd.storage_type(); if (stype == stype1) { has |= 1; } else if (stype == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if storage type of any array in `ndarrays` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() == stype) { return true; } } } return false; } /*! \brief returns true if any storage type `ndstype` in `ndstypes` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<int>& ndstypes, const NDArrayStorageType stype) { if (!ndstypes.empty()) { for (const auto& ndstype : ndstypes) { if (ndstype == stype) { return true; } } } return false; } /*! \brief get string representation of dispatch_mode */ inline std::string dispatch_mode_string(const DispatchMode x) { switch (x) { case DispatchMode::kFCompute: return "fcompute"; case DispatchMode::kFComputeEx: return "fcompute_ex"; case DispatchMode::kFComputeFallback: return "fcompute_fallback"; case DispatchMode::kVariable: return "variable"; case DispatchMode::kUndefined: return "undefined"; } return "unknown"; } /*! \brief get string representation of storage_type */ inline std::string stype_string(const int x) { switch (x) { case kDefaultStorage: return "default"; case kCSRStorage: return "csr"; case kRowSparseStorage: return "row_sparse"; } return "unknown"; } /*! \brief get string representation of device type */ inline std::string dev_type_string(const int dev_type) { switch (dev_type) { case Context::kCPU: return "cpu"; case Context::kGPU: return "gpu"; case Context::kCPUPinned: return "cpu_pinned"; case Context::kCPUShared: return "cpu_shared"; } return "unknown"; } /*! \brief get string representation of the operator stypes */ inline std::string operator_stype_string(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>& in_attrs, const std::vector<int>& out_attrs) { std::ostringstream os; os << "operator = " << attrs.op->name << "\ninput storage types = ["; for (const int attr : in_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "output storage types = ["; for (const int attr : out_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "params = {"; for (auto kv : attrs.dict) { os << "\"" << kv.first << "\" : " << kv.second << ", "; } os << "}\n" << "context.dev_mask = " << dev_type_string(dev_mask); return os.str(); } /*! \brief get string representation of the operator */ inline std::string operator_string(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<NDArray>& inputs, const std::vector<OpReqType>& req, const std::vector<NDArray>& outputs) { std::string result = ""; std::vector<int> in_stypes; std::vector<int> out_stypes; in_stypes.reserve(inputs.size()); out_stypes.reserve(outputs.size()); auto xform = [](const NDArray arr) -> int { return arr.storage_type(); }; std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform); std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform); result += operator_stype_string(attrs, ctx.run_ctx.ctx.dev_mask(), in_stypes, out_stypes); return result; } /*! \brief log message once. Intended for storage fallback warning messages. */ inline void LogOnce(const std::string& message) { typedef dmlc::ThreadLocalStore<std::unordered_set<std::string>> LogStore; auto log_store = LogStore::Get(); if (log_store->find(message) == log_store->end()) { LOG(INFO) << message; log_store->insert(message); } } /*! \brief log storage fallback event */ inline void LogStorageFallback(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>* in_attrs, const std::vector<int>* out_attrs) { static bool log = dmlc::GetEnv("MXNET_STORAGE_FALLBACK_LOG_VERBOSE", true); if (!log) return; const std::string op_str = operator_stype_string(attrs, dev_mask, *in_attrs, *out_attrs); std::ostringstream os; const char* warning = "\nThe operator with default storage type will be dispatched " "for execution. You're seeing this warning message because the operator above is unable " "to process the given ndarrays with specified storage types, context and parameter. " "Temporary dense ndarrays are generated in order to execute the operator. " "This does not affect the correctness of the programme. " "You can set environment variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to " "0 to suppress this warning."; os << "\nStorage type fallback detected:\n" << op_str << warning; LogOnce(os.str()); #if MXNET_USE_MKLDNN == 1 if (!MKLDNNEnvSet()) common::LogOnce("MXNET_MKLDNN_ENABLED flag is off. " "You can re-enable by setting MXNET_MKLDNN_ENABLED=1"); if (GetMKLDNNCacheSize() != -1) common::LogOnce("MXNET_MKLDNN_CACHE_NUM is set." "Should only be set if " "your model has variable input shapes, " "as cache size may grow unbounded"); #endif } // heuristic to dermine number of threads per GPU inline int GetNumThreadsPerGPU() { // This is resource efficient option. return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2); } // heuristic to get number of matching colors. // this decides how much parallelism we can get in each GPU. inline int GetExecNumMatchColor() { // This is resource efficient option. int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1); return std::min(num_match_color, GetNumThreadsPerGPU()); } template<typename T, typename V> V ParallelAccumulate(const T* a, const int n, V start) { V sum = start; #pragma omp parallel for reduction(+:sum) for (int i = 0; i < n; ++i) { sum += a[i]; } return sum; } /*! * \brief * Helper function for ParallelSort. * DO NOT call this function directly. * Use the interface ParallelSort instead. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare& comp) { if (len < grainsize) { std::sort(first, first+len, comp); } else { std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len/2, grainsize, comp); ParallelSortHelper(first+len/2, len - len/2, grainsize, comp); thr.join(); std::inplace_merge(first, first+len/2, first+len, comp); } } /*! * \brief * Sort the elements in the range [first, last) into the ascending order defined by * the comparator comp. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) { const auto num = std::distance(first, last); size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024*16)); ParallelSortHelper(first, num, grainsize, comp); } /*! * \brief * Sort the elements in the range [first, last) into ascending order. * The elements are compared using the default < operator. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) { ParallelSort(first, last, num_threads, std::less<typename std::iterator_traits<RandomIt>::value_type>()); } /*! * \brief Random Engine */ typedef std::mt19937 RANDOM_ENGINE; /*! * \brief Helper functions. */ namespace helper { /*! * \brief Helper for non-array type `T`. */ template <class T> struct UniqueIf { /*! * \brief Type of `T`. */ using SingleObject = std::unique_ptr<T>; }; /*! * \brief Helper for an array of unknown bound `T`. */ template <class T> struct UniqueIf<T[]> { /*! * \brief Type of `T`. */ using UnknownBound = std::unique_ptr<T[]>; }; /*! * \brief Helper for an array of known bound `T`. */ template <class T, size_t kSize> struct UniqueIf<T[kSize]> { /*! * \brief Type of `T`. */ using KnownBound = void; }; } // namespace helper /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs a non-array type `T`. The arguments `args` are passed to the * constructor of `T`. The function does not participate in the overload * resolution if `T` is an array type. */ template <class T, class... Args> typename helper::UniqueIf<T>::SingleObject MakeUnique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param n The size of the array to construct. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs an array of unknown bound `T`. The function does not participate * in the overload resolution unless `T` is an array of unknown bound. */ template <class T> typename helper::UniqueIf<T>::UnknownBound MakeUnique(size_t n) { using U = typename std::remove_extent<T>::type; return std::unique_ptr<T>(new U[n]{}); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * * Constructs an arrays of known bound is disallowed. */ template <class T, class... Args> typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete; template<typename FCompType> FCompType GetFCompute(const nnvm::Op* op, const std::string& name, const Context& ctx) { static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>"); static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>"); if (ctx.dev_mask() == cpu::kDevMask) { return fcompute_cpu.get(op, nullptr); } else if (ctx.dev_mask() == gpu::kDevMask) { return fcompute_gpu.get(op, nullptr); } else { LOG(FATAL) << "Unknown device mask " << ctx.dev_mask(); return nullptr; } } /*! * \brief Return the max integer value representable in the type `T` without loss of precision. */ template <typename T> constexpr size_t MaxIntegerValue() { return std::is_integral<T>::value ? std::numeric_limits<T>::max(): size_t(2) << (std::numeric_limits<T>::digits - 1); } template <> constexpr size_t MaxIntegerValue<mshadow::half::half_t>() { return size_t(2) << 10; } MSHADOW_XINLINE int ilog2ul(size_t a) { int k = 1; while (a >>= 1) ++k; return k; } MSHADOW_XINLINE int ilog2ui(unsigned int a) { int k = 1; while (a >>= 1) ++k; return k; } /*! * \brief Return an NDArray of all zeros. */ inline NDArray InitZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype) { // NDArray with default storage if (stype == kDefaultStorage) { NDArray ret(shape, ctx, false, dtype); ret = 0; return ret; } // NDArray with non-default storage. Storage allocation is always delayed. return NDArray(stype, shape, ctx, true, dtype); } /*! * \brief Helper to add a NDArray of zeros to a std::vector. */ inline void EmplaceBackZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype, std::vector<NDArray> *vec) { // NDArray with default storage if (stype == kDefaultStorage) { vec->emplace_back(shape, ctx, false, dtype); vec->back() = 0; } else { // NDArray with non-default storage. Storage allocation is always delayed. vec->emplace_back(stype, shape, ctx, true, dtype); } } /*! * \brief parallelize copy by OpenMP. */ template<typename DType> inline void ParallelCopy(DType* dst, const DType* src, index_t size) { static index_t copy_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_COPY_SIZE", 200000); if (size >= copy_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] = src[i]; } } else { std::memcpy(dst, src, sizeof(DType) * size); } } /*! * \brief If numpy compatibility is turned off (default), the shapes passed in * by users follow the legacy shape definition: * 1. 0 ndim means the shape is completely unknown. * 2. 0 dim size means the dim size is unknown. * We need to convert those shapes to use the numpy shape definition: * 1. 0 ndim means it's a scalar tensor. * 2. -1 ndim means the shape is unknown. * 3. 0 dim size means no elements in that dimension. * 4. -1 dim size means the dimension's size is unknown. * so that operator's infer shape function can work in backend. * \param shape to be converted. * Note: It is possible that the shape to be converted is already * numpy compatible. For example, when a subgraph operator's infer * shape function is called from the infer shape pass of the whole * graph, its input/output shapes have been converted to numpy * compatible shapes. */ inline void ConvertToNumpyShape(mxnet::TShape* shape) { if (shape->ndim() == 0) { // legacy shape ndim = 0 means unknown *shape = mxnet::TShape(); // unknown shape ndim = -1 } else { for (int j = 0; j < shape->ndim(); ++j) { if ((*shape)[j] == 0) { // legacy shape dim_size = 0 means unknown (*shape)[j] = -1; // unknown dim size = -1 } } } } inline void ConvertToNumpyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToNumpyShape(&(shapes->at(i))); } } /*! * \brief This is function is used to convert shapes returned by * the infer shape functions/pass to the legacy shape definition. */ inline void ConvertToLegacyShape(mxnet::TShape* shape) { if (!mxnet::ndim_is_known(*shape)) { *shape = mxnet::TShape(0, -1); } else { for (int j = 0; j < shape->ndim(); ++j) { if (!mxnet::dim_size_is_known(*shape, j)) { (*shape)[j] = 0; } } } } inline void ConvertToLegacyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToLegacyShape(&(shapes->at(i))); } } void ExecuteMonInputCallback( const nnvm::IndexedGraph &idx, const std::vector<NDArray *> &state_arrays, size_t nid, const std::function<void(const char *, const char *, void *)> &monitor_callback); void ExecuteMonOutputCallback( const nnvm::IndexedGraph &idx, const std::vector<NDArray *> &state_arrays, size_t nid, const std::function<void(const char *, const char *, void *)> &monitor_callback); /*! * \brief This is function can return the output names of a NodeEntry. */ static inline std::string GetOutputName(const nnvm::NodeEntry& e) { nnvm::Symbol sym; sym.outputs.push_back(e); return sym.ListOutputNames()[0]; } inline mxnet::TShape CanonicalizeAxes(const mxnet::TShape& src) { // convert negative axes to positive values const int ndim = src.ndim(); mxnet::TShape axes = src; for (int i = 0; i < ndim; ++i) { if (axes[i] < 0) { axes[i] += ndim; } CHECK(axes[i] >= 0 && axes[i] < ndim) << "axes[" << i << "]=" << axes[i] << " exceeds the range [" << 0 << ", " << ndim << ")"; } return axes; } } // namespace common } // namespace mxnet #endif // MXNET_COMMON_UTILS_H_
GB_binop__rdiv_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__rdiv_uint32) // A.*B function (eWiseMult): GB (_AemultB_01__rdiv_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__rdiv_uint32) // A.*B function (eWiseMult): GB (_AemultB_03__rdiv_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_uint32) // A*D function (colscale): GB (_AxD__rdiv_uint32) // D*A function (rowscale): GB (_DxB__rdiv_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__rdiv_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__rdiv_uint32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_uint32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_uint32) // C=scalar+B GB (_bind1st__rdiv_uint32) // C=scalar+B' GB (_bind1st_tran__rdiv_uint32) // C=A+scalar GB (_bind2nd__rdiv_uint32) // C=A'+scalar GB (_bind2nd_tran__rdiv_uint32) // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = GB_IDIV_UNSIGNED (bij, aij, 32) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IDIV_UNSIGNED (y, x, 32) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_RDIV || GxB_NO_UINT32 || GxB_NO_RDIV_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__rdiv_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__rdiv_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__rdiv_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__rdiv_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__rdiv_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IDIV_UNSIGNED (bij, x, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rdiv_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IDIV_UNSIGNED (y, aij, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_UNSIGNED (aij, x, 32) ; \ } GrB_Info GB (_bind1st_tran__rdiv_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_UNSIGNED (y, aij, 32) ; \ } GrB_Info GB (_bind2nd_tran__rdiv_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
seq_multivector.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Member functions for hypre_Vector class. * *****************************************************************************/ #include "seq_multivector.h" #include "_hypre_utilities.h" #include <stdlib.h> #include <string.h> /*-------------------------------------------------------------------------- * hypre_SeqMultivectorCreate *--------------------------------------------------------------------------*/ hypre_Multivector * hypre_SeqMultivectorCreate( HYPRE_Int size, HYPRE_Int num_vectors ) { hypre_Multivector *mvector; mvector = (hypre_Multivector *) hypre_MAlloc(sizeof(hypre_Multivector), HYPRE_MEMORY_HOST); hypre_MultivectorNumVectors(mvector) = num_vectors; hypre_MultivectorSize(mvector) = size; hypre_MultivectorOwnsData(mvector) = 1; hypre_MultivectorData(mvector) = NULL; mvector->num_active_vectors=0; mvector->active_indices=NULL; return mvector; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorInitialize( hypre_Multivector *mvector ) { HYPRE_Int ierr = 0, i, size, num_vectors; size = hypre_MultivectorSize(mvector); num_vectors = hypre_MultivectorNumVectors(mvector); if (NULL==hypre_MultivectorData(mvector)) hypre_MultivectorData(mvector) = (HYPRE_Complex *) hypre_MAlloc(sizeof(HYPRE_Complex)*size*num_vectors, HYPRE_MEMORY_HOST); /* now we create a "mask" of "active" vectors; initially all active */ if (NULL==mvector->active_indices) { mvector->active_indices hypre_CTAlloc(HYPRE_Int, num_vectors, HYPRE_MEMORY_HOST); for (i=0; i<num_vectors; i++) mvector->active_indices[i] = i; mvector->num_active_vectors=num_vectors; } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetDataOwner(hypre_Multivector *mvector, HYPRE_Int owns_data) { HYPRE_Int ierr=0; hypre_MultivectorOwnsData(mvector) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorDestroy(hypre_Multivector *mvector) { HYPRE_Int ierr=0; if (NULL!=mvector) { if (hypre_MultivectorOwnsData(mvector) && NULL!=hypre_MultivectorData(mvector)) hypre_TFree( hypre_MultivectorData(mvector) , HYPRE_MEMORY_HOST); if (NULL!=mvector->active_indices) hypre_TFree(mvector->active_indices, HYPRE_MEMORY_HOST); hypre_TFree(mvector, HYPRE_MEMORY_HOST); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetMask * (this routine accepts mask in "zeros and ones format, and converts it to the one used in the structure "hypre_Multivector") *-------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetMask(hypre_Multivector *mvector, HYPRE_Int * mask) { HYPRE_Int i, num_vectors = mvector->num_vectors; if (mvector->active_indices != NULL) hypre_TFree(mvector->active_indices, HYPRE_MEMORY_HOST); mvector->active_indices hypre_CTAlloc(HYPRE_Int, num_vectors, HYPRE_MEMORY_HOST); mvector->num_active_vectors=0; if (mask!=NULL) for (i=0; i<num_vectors; i++) { if ( mask[i] ) mvector->active_indices[mvector->num_active_vectors++]=i; } else for (i=0; i<num_vectors; i++) mvector->active_indices[mvector->num_active_vectors++]=i; return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetConstantValues *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetConstantValues(hypre_Multivector *v, HYPRE_Complex value) { HYPRE_Int i, j, start_offset, end_offset; HYPRE_Int size = hypre_MultivectorSize(v); HYPRE_Complex *vector_data = hypre_MultivectorData(v); if (v->num_active_vectors == v->num_vectors) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < v->num_vectors*size; j++) vector_data[j] = value; } else { for (i = 0; i < v->num_active_vectors; i++) { start_offset = v->active_indices[i]*size; end_offset = start_offset+size; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = start_offset; j < end_offset; j++) vector_data[j]= value; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetRandomValues * * returns vector of values randomly distributed between -1.0 and +1.0 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetRandomValues(hypre_Multivector *v, HYPRE_Int seed) { HYPRE_Int i, j, start_offset, end_offset; HYPRE_Int size = hypre_MultivectorSize(v); HYPRE_Complex *vector_data = hypre_MultivectorData(v); hypre_SeedRand(seed); /* comment from vector.c: RDF: threading this loop may cause problems because of hypre_Rand() */ if (v->num_active_vectors == v->num_vectors) { for (j = 0; j < v->num_vectors*size; j++) vector_data[j] = 2.0 * hypre_Rand() - 1.0; } else { for (i = 0; i < v->num_active_vectors; i++) { start_offset = v->active_indices[i]*size; end_offset = start_offset+size; for (j = start_offset; j < end_offset; j++) vector_data[j]= 2.0 * hypre_Rand() - 1.0; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorCopy * copies data from x to y * y should have already been initialized at the same size as x *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorCopy(hypre_Multivector *x, hypre_Multivector *y) { HYPRE_Int i, size, num_bytes, num_active_vectors, *x_active_ind, * y_active_ind; HYPRE_Complex *x_data, *y_data, *dest, * src; hypre_assert (x->size == y->size && x->num_active_vectors == y->num_active_vectors); num_active_vectors = x->num_active_vectors; size = x->size; x_data = x->data; y_data = y->data; x_active_ind=x->active_indices; y_active_ind=y->active_indices; if (x->num_active_vectors == x->num_vectors && y->num_active_vectors == y->num_vectors) { num_bytes = x->num_vectors * size; hypre_TMemcpy(y_data, x_data, HYPRE_Complex, num_bytes, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); } else { num_bytes = size; for (i=0; i < num_active_vectors; i++) { src=x_data + size * x_active_ind[i]; dest = y_data + size * y_active_ind[i]; hypre_Memcpy(dest, src, HYPRE_Complex, num_bytes, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); } } return 0; } HYPRE_Int hypre_SeqMultivectorCopyWithoutMask(hypre_Multivector *x , hypre_Multivector *y) { HYPRE_Int byte_count; hypre_assert (x->size == y->size && x->num_vectors == y->num_vectors); byte_count = x->size * x->num_vectors; hypre_Memcpy(y->data, x->data, HYPRE_Complex, byte_count, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorAxpy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorAxpy(HYPRE_Complex alpha, hypre_Multivector *x, hypre_Multivector *y) { HYPRE_Int i, j, size, num_active_vectors, *x_active_ind, *y_active_ind; HYPRE_Complex *x_data, *y_data, *src, *dest; hypre_assert (x->size == y->size && x->num_active_vectors == y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; num_active_vectors = x->num_active_vectors; x_active_ind = x->active_indices; y_active_ind = y->active_indices; if (x->num_active_vectors == x->num_vectors && y->num_active_vectors == y->num_vectors) { for(i = 0; i < x->num_vectors*size; i++) dest[i] += alpha * src[i]; } else { for(i = 0; i < num_active_vectors; i++) { src = x_data + x_active_ind[i]*size; dest = y_data + y_active_ind[i]*size; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < size; j++) dest[j] += alpha * src[j]; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorByDiag: " y(<y_mask>) = alpha(<mask>) .* x(<x_mask>) " *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorByDiag(hypre_Multivector *x, HYPRE_Int *mask, HYPRE_Int n, HYPRE_Complex *alpha, hypre_Multivector *y) { HYPRE_Int i, j, size, num_active_vectors, *x_active_ind, *y_active_ind; HYPRE_Int *al_active_ind, num_active_als; HYPRE_Complex *x_data, *y_data, *dest, *src, current_alpha; hypre_assert (x->size == y->size && x->num_active_vectors == y->num_active_vectors); /* build list of active indices in alpha */ al_active_ind = hypre_TAlloc(HYPRE_Int, n, HYPRE_MEMORY_HOST); num_active_als = 0; if (mask!=NULL) for (i=0; i<n; i++) { if (mask[i]) al_active_ind[num_active_als++]=i; } else for (i=0; i<n; i++) al_active_ind[num_active_als++]=i; hypre_assert (num_active_als==x->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; num_active_vectors = x->num_active_vectors; x_active_ind = x->active_indices; y_active_ind = y->active_indices; for(i = 0; i < num_active_vectors; i++) { src = x_data + x_active_ind[i]*size; dest = y_data + y_active_ind[i]*size; current_alpha=alpha[ al_active_ind[i] ]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < size; j++) dest[j] = current_alpha*src[j]; } hypre_TFree(al_active_ind, HYPRE_MEMORY_HOST); return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorInnerProd *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorInnerProd(hypre_Multivector *x, hypre_Multivector *y, HYPRE_Real *results ) { HYPRE_Int i, j, k, size, *x_active_ind, *y_active_ind; HYPRE_Int x_num_active_vectors, y_num_active_vectors; HYPRE_Complex *x_data, *y_data, *y_ptr, *x_ptr; HYPRE_Real current_product; hypre_assert (x->size==y->size); x_data = x->data; y_data = y->data; size = x->size; x_num_active_vectors = x->num_active_vectors; y_num_active_vectors = y->num_active_vectors; /* we assume that "results" points to contiguous array of (x_num_active_vectors X y_num_active_vectors) doubles */ x_active_ind = x->active_indices; y_active_ind = y->active_indices; for(j = 0; j < y_num_active_vectors; j++) { y_ptr = y_data + y_active_ind[j]*size; for (i = 0; i < x_num_active_vectors; i++) { x_ptr = x_data + x_active_ind[i]*size; current_product = 0.0; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) reduction(+:current_product) HYPRE_SMP_SCHEDULE #endif for(k = 0; k < size; k++) current_product += x_ptr[k] * hypre_conj(y_ptr[k]); /* column-wise storage for results */ *results++ = current_product; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorInnerProdDiag *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorInnerProdDiag(hypre_Multivector *x, hypre_Multivector *y, HYPRE_Real *diagResults) { HYPRE_Complex *x_data, *y_data, *y_ptr, *x_ptr; HYPRE_Real current_product; HYPRE_Int i, k, size, num_active_vectors, *x_active_ind, *y_active_ind; hypre_assert(x->size==y->size && x->num_active_vectors == y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; num_active_vectors = x->num_active_vectors; x_active_ind = x->active_indices; y_active_ind = y->active_indices; for (i=0; i<num_active_vectors; i++) { x_ptr = x_data + x_active_ind[i]*size; y_ptr = y_data + y_active_ind[i]*size; current_product = 0.0; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) reduction(+:current_product) HYPRE_SMP_SCHEDULE #endif for(k=0; k<size; k++) current_product += x_ptr[k] * hypre_conj(y_ptr[k]); *diagResults++ = current_product; } return 0; } HYPRE_Int hypre_SeqMultivectorByMatrix(hypre_Multivector *x, HYPRE_Int rGHeight, HYPRE_Int rHeight, HYPRE_Int rWidth, HYPRE_Complex* rVal, hypre_Multivector *y) { HYPRE_Int i, j, k, size, gap, *x_active_ind, *y_active_ind; HYPRE_Complex *x_data, *y_data, *x_ptr, *y_ptr, current_coef; hypre_assert(rHeight>0); hypre_assert (rHeight==x->num_active_vectors && rWidth==y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; x_active_ind = x->active_indices; y_active_ind = y->active_indices; gap = rGHeight - rHeight; for (j=0; j<rWidth; j++) { y_ptr = y_data + y_active_ind[j]*size; /* ------ set current "y" to first member in a sum ------ */ x_ptr = x_data + x_active_ind[0]*size; current_coef = *rVal++; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) HYPRE_SMP_SCHEDULE #endif for (k=0; k<size; k++) y_ptr[k] = current_coef * x_ptr[k]; /* ------ now add all other members of a sum to "y" ----- */ for (i=1; i<rHeight; i++) { x_ptr = x_data + x_active_ind[i]*size; current_coef = *rVal++; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) HYPRE_SMP_SCHEDULE #endif for (k=0; k<size; k++) y_ptr[k] += current_coef * x_ptr[k]; } rVal += gap; } return 0; } HYPRE_Int hypre_SeqMultivectorXapy (hypre_Multivector *x, HYPRE_Int rGHeight, HYPRE_Int rHeight, HYPRE_Int rWidth, HYPRE_Complex* rVal, hypre_Multivector *y) { HYPRE_Complex *x_data, *y_data, *x_ptr, *y_ptr, current_coef; HYPRE_Int i, j, k, size, gap, *x_active_ind, *y_active_ind; hypre_assert (rHeight==x->num_active_vectors && rWidth==y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; x_active_ind = x->active_indices; y_active_ind = y->active_indices; gap = rGHeight - rHeight; for (j=0; j<rWidth; j++) { y_ptr = y_data + y_active_ind[j]*size; for (i=0; i<rHeight; i++) { x_ptr = x_data + x_active_ind[i]*size; current_coef = *rVal++; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) HYPRE_SMP_SCHEDULE #endif for (k=0; k<size; k++) y_ptr[k] += current_coef * x_ptr[k]; } rVal += gap; } return 0; }
graphCSR.c
// ----------------------------------------------------------------------------- // // "00_AccelGraph" // // ----------------------------------------------------------------------------- // Copyright (c) 2014-2019 All rights reserved // ----------------------------------------------------------------------------- // Author : Abdullah Mughrabi // Email : atmughra@ncsu.edu||atmughrabi@gmail.com // File : graphCSR.c // Create : 2019-06-29 12:31:24 // Revise : 2019-09-28 15:36:13 // Editor : Abdullah Mughrabi // ----------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <err.h> #include <string.h> #include "myMalloc.h" #include "timer.h" #include "graphConfig.h" #include "edgeList.h" #include "sortRun.h" #include "vertex.h" #include "graphCSR.h" #include "reorder.h" //edgelist prerpcessing // #include "countsort.h" // #include "radixsort.h" void graphCSRFree (struct GraphCSR *graphCSR) { if(graphCSR) { if(graphCSR->vertices) freeVertexArray(graphCSR->vertices); if(graphCSR->sorted_edges_array) freeEdgeList(graphCSR->sorted_edges_array); #if DIRECTED if(graphCSR->inverse_vertices) freeVertexArray(graphCSR->inverse_vertices); if(graphCSR->inverse_sorted_edges_array) freeEdgeList(graphCSR->inverse_sorted_edges_array); #endif free(graphCSR); } } void graphCSRPrint(struct GraphCSR *graphCSR) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "GraphCSR Properties"); printf(" -----------------------------------------------------\n"); #if WEIGHTED printf("| %-51s | \n", "WEIGHTED"); printf("| %-51s | \n", "MAX WEIGHT"); printf("| %-51f | \n", graphCSR->max_weight); #else printf("| %-51s | \n", "UN-WEIGHTED"); #endif #if DIRECTED printf("| %-51s | \n", "DIRECTED"); #else printf("| %-51s | \n", "UN-DIRECTED"); #endif printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Average Degree (D)"); printf("| %-51u | \n", graphCSR->avg_degree); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Number of Vertices (V)"); printf("| %-51u | \n", graphCSR->num_vertices); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Number of Edges (E)"); printf("| %-51u | \n", graphCSR->num_edges); printf(" -----------------------------------------------------\n"); vertexArrayMaxOutdegree(graphCSR->vertices, graphCSR->num_vertices); #if DIRECTED vertexArrayMaxInDegree(graphCSR->inverse_vertices, graphCSR->num_vertices); #endif } struct GraphCSR *graphCSRNew(uint32_t V, uint32_t E, uint8_t inverse) { struct GraphCSR *graphCSR = (struct GraphCSR *) my_malloc( sizeof(struct GraphCSR)); graphCSR->num_vertices = V; graphCSR->num_edges = E; graphCSR->avg_degree = E / V; graphCSR->sorted_edges_array = NULL; // sorted edge array #if DIRECTED graphCSR->inverse_sorted_edges_array = NULL; // sorted edge array #endif #if WEIGHTED graphCSR->max_weight = 0; #endif graphCSR->vertices = newVertexArray(V); #if DIRECTED if (inverse) { graphCSR->inverse_vertices = newVertexArray(V); } #endif return graphCSR; } struct GraphCSR *graphCSRAssignEdgeList (struct GraphCSR *graphCSR, struct EdgeList *edgeList, uint8_t inverse) { #if DIRECTED if(inverse) graphCSR->inverse_sorted_edges_array = edgeList; else graphCSR->sorted_edges_array = edgeList; #else graphCSR->sorted_edges_array = edgeList; #endif #if WEIGHTED graphCSR->max_weight = edgeList->max_weight; #endif return mapVerticesWithInOutDegree (graphCSR, inverse); } struct GraphCSR *graphCSRPreProcessingStep (struct Arguments *arguments) { struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); Start(timer); struct EdgeList *edgeList = readEdgeListsbin(arguments->fnameb, 0, arguments->symmetric, arguments->weighted); // read edglist from binary file Stop(timer); // edgeListPrint(edgeList); graphCSRPrintMessageWithtime("Read Edge List From File (Seconds)", Seconds(timer)); edgeList = sortRunAlgorithms(edgeList, arguments->sort); if(arguments->dflag) { Start(timer); edgeList = removeDulpicatesSelfLoopEdges(edgeList); Stop(timer); graphCSRPrintMessageWithtime("Removing duplicate edges (Seconds)", Seconds(timer)); } if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } // add another layer 2 of reordering to test how DBG affect Gorder, or Gorder affect Rabbit order ...etc arguments->lmode = arguments->lmode_l2; if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } arguments->lmode = arguments->lmode_l3; if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } if(arguments->mmode) edgeList = maskGraphProcess(edgeList, arguments); #if DIRECTED struct GraphCSR *graphCSR = graphCSRNew(edgeList->num_vertices, edgeList->num_edges, 1); #else struct GraphCSR *graphCSR = graphCSRNew(edgeList->num_vertices, edgeList->num_edges, 0); #endif // edgeListPrint(edgeList); Start(timer); graphCSR = graphCSRAssignEdgeList (graphCSR, edgeList, 0); Stop(timer); graphCSRPrintMessageWithtime("Mappign Vertices to CSR (Seconds)", Seconds(timer)); #if DIRECTED Start(timer); struct EdgeList *inverse_edgeList = readEdgeListsMem(edgeList, 1, 0, 0); // read edglist from memory since we pre loaded it Stop(timer); graphCSRPrintMessageWithtime("Read Inverse Edge List From Memory (Seconds)", Seconds(timer)); inverse_edgeList = sortRunAlgorithms(inverse_edgeList, arguments->sort); Start(timer); graphCSR = graphCSRAssignEdgeList (graphCSR, inverse_edgeList, 1); Stop(timer); graphCSRPrintMessageWithtime("Process In/Out degrees of Inverse Nodes (Seconds)", Seconds(timer)); #endif graphCSRPrint(graphCSR); free(timer); return graphCSR; } struct GraphCSR *graphCSRPreProcessingStepDualOrder (struct Arguments *arguments) { struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); Start(timer); struct EdgeList *edgeList = readEdgeListsbin(arguments->fnameb, 0, arguments->symmetric, arguments->weighted); // read edglist from binary file Stop(timer); // edgeListPrint(edgeList); graphCSRPrintMessageWithtime("Read Edge List From File (Seconds)", Seconds(timer)); edgeList = sortRunAlgorithms(edgeList, arguments->sort); if(arguments->dflag) { Start(timer); edgeList = removeDulpicatesSelfLoopEdges(edgeList); Stop(timer); graphCSRPrintMessageWithtime("Removing duplicate edges (Seconds)", Seconds(timer)); } if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } #if DIRECTED struct GraphCSR *graphCSR = graphCSRNew(edgeList->num_vertices, edgeList->num_edges, 1); #else struct GraphCSR *graphCSR = graphCSRNew(edgeList->num_vertices, edgeList->num_edges, 0); #endif #if DIRECTED Start(timer); struct EdgeList *inverse_edgeList = readEdgeListsMem(edgeList, 1, 0, 0); // read edglist from memory since we pre loaded it Stop(timer); graphCSRPrintMessageWithtime("Read Inverse Edge List From Memory (Seconds)", Seconds(timer)); inverse_edgeList = sortRunAlgorithms(inverse_edgeList, arguments->sort); // add another layer 2 of reordering to test how DBG affect Gorder, or Gorder affect Rabbit order ...etc arguments->lmode = arguments->lmode_l2; if(arguments->lmode) { inverse_edgeList = reorderGraphProcess(inverse_edgeList, arguments); inverse_edgeList = sortRunAlgorithms(inverse_edgeList, arguments->sort); } // edgeListPrint(inverse_edgeList); Start(timer); graphCSR = graphCSRAssignEdgeList (graphCSR, inverse_edgeList, 1); Stop(timer); graphCSRPrintMessageWithtime("Process In/Out degrees of Inverse Nodes (Seconds)", Seconds(timer)); #endif // add another layer 2 of reordering to test how DBG affect Gorder, or Gorder affect Rabbit order ...etc arguments->lmode = arguments->lmode_l2; if(arguments->lmode) { edgeList = reorderGraphProcess(edgeList, arguments); edgeList = sortRunAlgorithms(edgeList, arguments->sort); } // edgeListPrint(edgeList); Start(timer); graphCSR = graphCSRAssignEdgeList (graphCSR, edgeList, 0); graphCSRVertexLabelRemappingDualOrder (graphCSR); Stop(timer); graphCSRPrintMessageWithtime("Mappign Vertices to CSR (Seconds)", Seconds(timer)); // edgeListPrint(edgeList); graphCSRPrint(graphCSR); free(timer); return graphCSR; } void graphCSRVertexLabelRemappingDualOrder (struct GraphCSR *graphCSR) { uint32_t *label_array_el = NULL; uint32_t *label_array_iel = NULL; uint32_t *inverse_label_array_el = NULL; uint32_t *inverse_label_array_iel = NULL; uint32_t num_vertices = graphCSR->num_vertices; uint32_t v; #if DIRECTED inverse_label_array_iel = graphCSR->inverse_sorted_edges_array->inverse_label_array; label_array_iel = graphCSR->inverse_sorted_edges_array->label_array; #else inverse_label_array_iel = graphCSR->sorted_edges_array->inverse_label_array; label_array_iel = graphCSR->sorted_edges_array->label_array; #endif inverse_label_array_el = graphCSR->sorted_edges_array->inverse_label_array; label_array_el = graphCSR->sorted_edges_array->label_array; #pragma omp parallel for for (v = 0; v < num_vertices; ++v) { uint32_t u = label_array_el[v]; uint32_t t = label_array_iel[v]; inverse_label_array_el[u] = t; } #if DIRECTED #pragma omp parallel for for (v = 0; v < num_vertices; ++v) { uint32_t u = label_array_el[v]; uint32_t t = label_array_iel[v]; inverse_label_array_iel[t] = u; } #endif } void writeToBinFileGraphCSR (const char *fname, struct GraphCSR *graphCSR) { FILE *pBinary; uint32_t vertex_id; char *fname_txt = (char *) malloc((strlen(fname) + 10) * sizeof(char)); char *fname_bin = (char *) malloc((strlen(fname) + 10) * sizeof(char)); fname_txt = strcpy (fname_txt, fname); fname_bin = strcat (fname_txt, ".csr"); pBinary = fopen(fname_bin, "wb"); if (pBinary == NULL) { err(1, "open: %s", fname_bin); return ; } fwrite(&(graphCSR->num_edges), sizeof (graphCSR->num_edges), 1, pBinary); fwrite(&(graphCSR->num_vertices), sizeof (graphCSR->num_vertices), 1, pBinary); #if WEIGHTED fwrite(&(graphCSR->max_weight), sizeof (graphCSR->max_weight), 1, pBinary); #endif for(vertex_id = 0; vertex_id < graphCSR->num_vertices ; vertex_id++) { fwrite(&(graphCSR->vertices->out_degree[vertex_id]), sizeof (graphCSR->vertices->out_degree[vertex_id]), 1, pBinary); fwrite(&(graphCSR->vertices->in_degree[vertex_id]), sizeof (graphCSR->vertices->in_degree[vertex_id]), 1, pBinary); fwrite(&(graphCSR->vertices->edges_idx[vertex_id]), sizeof (graphCSR->vertices->edges_idx[vertex_id]), 1, pBinary); #if DIRECTED if(graphCSR->inverse_vertices) { fwrite(&(graphCSR->inverse_vertices->out_degree[vertex_id]), sizeof (graphCSR->inverse_vertices->out_degree[vertex_id]), 1, pBinary); fwrite(&(graphCSR->inverse_vertices->in_degree[vertex_id]), sizeof (graphCSR->inverse_vertices->in_degree[vertex_id]), 1, pBinary); fwrite(&(graphCSR->inverse_vertices->edges_idx[vertex_id]), sizeof (graphCSR->inverse_vertices->edges_idx[vertex_id]), 1, pBinary); } #endif } for(vertex_id = 0; vertex_id < graphCSR->num_edges ; vertex_id++) { fwrite(&(graphCSR->sorted_edges_array->edges_array_src[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_src[vertex_id]), 1, pBinary); fwrite(&(graphCSR->sorted_edges_array->edges_array_dest[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_dest[vertex_id]), 1, pBinary); #if WEIGHTED fwrite(&(graphCSR->sorted_edges_array->edges_array_weight[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_weight[vertex_id]), 1, pBinary); #endif #if DIRECTED if(graphCSR->inverse_vertices) { fwrite(&(graphCSR->inverse_sorted_edges_array->edges_array_src[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_src[vertex_id]), 1, pBinary); fwrite(&(graphCSR->inverse_sorted_edges_array->edges_array_dest[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_dest[vertex_id]), 1, pBinary); #if WEIGHTED fwrite(&(graphCSR->inverse_sorted_edges_array->edges_array_weight[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_weight[vertex_id]), 1, pBinary); #endif } #endif } fclose(pBinary); } struct GraphCSR *readFromBinFileGraphCSR (const char *fname) { FILE *pBinary; uint32_t vertex_id; uint32_t num_vertices; uint32_t num_edges; #if WEIGHTED float max_weight; #endif size_t ret; pBinary = fopen(fname, "rb"); if (pBinary == NULL) { err(1, "open: %s", fname); return NULL; } ret = fread(&num_edges, sizeof(num_edges), 1, pBinary); ret = fread(&num_vertices, sizeof(num_vertices), 1, pBinary); #if WEIGHTED ret = fread(&max_weight, sizeof(max_weight), 1, pBinary); #endif #if DIRECTED struct GraphCSR *graphCSR = graphCSRNew(num_vertices, num_edges, 1); #else struct GraphCSR *graphCSR = graphCSRNew(num_vertices, num_edges, 0); #endif #if WEIGHTED graphCSR->max_weight = max_weight; #endif struct EdgeList *sorted_edges_array = newEdgeList(num_edges); sorted_edges_array->num_vertices = num_vertices; #if WEIGHTED sorted_edges_array->max_weight = max_weight; #endif graphCSR->sorted_edges_array = sorted_edges_array; #if DIRECTED struct EdgeList *inverse_sorted_edges_array = newEdgeList(num_edges); inverse_sorted_edges_array->num_vertices = num_vertices; #if WEIGHTED inverse_sorted_edges_array->max_weight = max_weight; #endif graphCSR->inverse_sorted_edges_array = inverse_sorted_edges_array; #endif for(vertex_id = 0; vertex_id < graphCSR->num_vertices ; vertex_id++) { ret = fread(&(graphCSR->vertices->out_degree[vertex_id]), sizeof (graphCSR->vertices->out_degree[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->vertices->in_degree[vertex_id]), sizeof (graphCSR->vertices->in_degree[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->vertices->edges_idx[vertex_id]), sizeof (graphCSR->vertices->edges_idx[vertex_id]), 1, pBinary); #if DIRECTED if(graphCSR->inverse_vertices) { ret = fread(&(graphCSR->inverse_vertices->out_degree[vertex_id]), sizeof (graphCSR->inverse_vertices->out_degree[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->inverse_vertices->in_degree[vertex_id]), sizeof (graphCSR->inverse_vertices->in_degree[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->inverse_vertices->edges_idx[vertex_id]), sizeof (graphCSR->inverse_vertices->edges_idx[vertex_id]), 1, pBinary); } #endif } for(vertex_id = 0; vertex_id < graphCSR->num_edges ; vertex_id++) { ret = fread(&(graphCSR->sorted_edges_array->edges_array_src[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_src[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->sorted_edges_array->edges_array_dest[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_dest[vertex_id]), 1, pBinary); #if WEIGHTED ret = fread(&(graphCSR->sorted_edges_array->edges_array_weight[vertex_id]), sizeof (graphCSR->sorted_edges_array->edges_array_weight[vertex_id]), 1, pBinary); #endif #if DIRECTED if(graphCSR->inverse_vertices) { ret = fread(&(graphCSR->inverse_sorted_edges_array->edges_array_src[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_src[vertex_id]), 1, pBinary); ret = fread(&(graphCSR->inverse_sorted_edges_array->edges_array_dest[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_dest[vertex_id]), 1, pBinary); #if WEIGHTED ret = fread(&(graphCSR->inverse_sorted_edges_array->edges_array_weight[vertex_id]), sizeof (graphCSR->inverse_sorted_edges_array->edges_array_weight[vertex_id]), 1, pBinary); #endif } #endif } if(ret) { graphCSRPrint(graphCSR); } fclose(pBinary); return graphCSR; } void graphCSRPrintMessageWithtime(const char *msg, double time) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", msg); printf(" -----------------------------------------------------\n"); printf("| %-51f | \n", time); printf(" -----------------------------------------------------\n"); }
modernFft.h
/** * @cond ___LICENSE___ * * Copyright (c) 2016-2018 Zefiros Software. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @endcond */ #include "bspedupack.h" #include <complex> /****************** Sequential functions ********************************/ void UFft( double *x, uint32_t n, int sign, std::vector<double> &w ) { /* This sequential function computes the unordered discrete Fourier transform of a complex vector x of length n, stored in a real array of length 2n as pairs (Re x[j], Im x[j]), 0 <= j < n. n=2^m, m >= 0. If sign = 1, then the forward unordered dft FRx is computed; if sign =-1, the backward unordered dft conjg(F)Rx is computed, where F is the n by n Fourier matrix and R the n by n bit-reversal matrix. The output overwrites x. w is a table of n/2 complex weights, stored as pairs of reals, exp(-2*pi*i*j/n), 0 <= j < n/2, which must have been initialized before calling this function. */ #ifdef _MSC_VER unsigned long end; _BitScanReverse( &end, n | 1 ); const uint32_t mEnd = static_cast< uint32_t >( end ); #else const uint32_t mEnd = 31 - __builtin_clz( n ); #endif for ( uint32_t m = 1; m <= mEnd; ++m ) { // const uint32_t k = 1 << m; const uint32_t nk = n >> m; const uint32_t jEnd = 1 << ( m - 1 ); for ( uint32_t r = 0; r < nk; ++r ) { const uint32_t rk = r << ( m + 1 ); #pragma omp simd for ( uint32_t j = 0; j < jEnd; ++j ) { const uint32_t jprime = j << 1; const uint32_t jnk = jprime * nk; const double wr = w[jnk]; const double wi = sign * w[ jnk + 1 ]; const uint32_t j0 = rk + jprime; const uint32_t j1 = j0 + 1; const uint32_t j2 = j0 + ( 1 << m ); const uint32_t j3 = j2 + 1; const double taur = wr * x[j2] - wi * x[j3]; const double taui = wi * x[j2] + wr * x[j3]; x[j2] = x[j0] - taur; x[j3] = x[j1] - taui; x[j0] += taur; x[j1] += taui; } } } } /* end ufft */ void UFftInit( uint32_t n, std::vector<double> &w ) { /* This function initializes the n/2 weights to be used in a sequential radix-2 FFT of length n. n=2^m, m >= 0. w is a table of n/2 complex weights, stored as pairs of reals, exp(-2*pi*i*j/n), 0 <= j < n/2. */ if ( n == 1 ) { return; } const double theta = ( -2.0 * M_PI ) / n; w[0] = 1.0; w[1] = 0.0; if ( n == 4 ) { w[2] = 0.0; w[3] = -1.0; } else if ( n >= 8 ) { /* weights 1 .. n/8 */ for ( uint32_t j = 1, jEnd = n >> 3; j <= jEnd; ++j ) { const uint32_t j2 = j << 1; // std::complex<double> wComplex( 0, j * theta ); // wComplex = std::exp( wComplex ); // //w[j2] = cos( j * theta ); // w[j2] = wComplex.real(); // //w[j2 + 1] = sin( j * theta ); // w[j2 + 1] = wComplex.imag(); #ifdef _MSC_VER w[j2] = std::cos( j * theta ); w[j2 + 1] = std::sin( j * theta ); #else __builtin_sincos( j * theta, &w[j2 + 1], &w[j2] ); #endif // _MSC_VER } /* weights n/8+1 .. n/4 */ for ( uint32_t j = 0, jEnd = n >> 3, n4 = n >> 2; j < jEnd; ++j ) { const uint32_t n4j2 = ( n4 - j ) << 1; const uint32_t j2 = j << 1; w[n4j2] = -w[j2 + 1]; w[n4j2 + 1] = -w[j2]; } /* weights n/4+1 .. n/2-1 */ for ( uint32_t j = 1, jEnd = n >> 2, n2 = n >> 1; j < jEnd; ++j ) { const uint32_t n2j2 = ( n2 - j ) << 1; const uint32_t j2 = j << 1; w[n2j2] = -w[j2]; w[n2j2 + 1] = w[j2 + 1]; } } } /* end UFftInit */ void Twiddle( std::vector<double> &x, uint32_t n, int sign, double *w ) { /* This sequential function multiplies a complex vector x of length n, stored as pairs of reals, componentwise by a complex vector w of length n, if sign=1, and by conjg(w), if sign=-1. The result overwrites x. */ for ( uint32_t j = 0, jEnd = 2 * n; j < jEnd; j += 2 ) { const uint32_t j1 = j + 1; const double wr = w[j]; const double wi = sign * w[j1]; const double xr = x[j]; const double xi = x[j1]; x[j] = wr * xr - wi * xi; x[j1] = wi * xr + wr * xi; } } /* end Twiddle */ void TwiddleInit( uint32_t n, double alpha, std::vector<uint32_t> &rho, double *w ) { /* This sequential function initializes the weight table w to be used in twiddling with a complex vector of length n, stored as pairs of reals. n=2^m, m >= 0. alpha is a real shift parameter. rho is the bit-reversal permutation of length n, which must have been initialized before calling this function. The output w is a table of n complex values, stored as pairs of reals, exp(-2*pi*i*rho(j)*alpha/n), 0 <= j < n. */ const double theta = ( -2.0 * M_PI * alpha ) / n; for ( uint32_t j = 0; j < n; ++j ) { const uint32_t j2 = j << 1; const double rhoTheta = rho[j] * theta; w[j2] = cos( rhoTheta ); w[j2 + 1] = sin( rhoTheta ); } } /* end TwiddleInit */ void Permute( std::vector<double> &x, uint32_t n, std::vector<uint32_t> &sigma ) { /* This in-place sequential function permutes a complex vector x of length n >= 1, stored as pairs of reals, by the permutation sigma, y[j] = x[sigma[j]], 0 <= j < n. The output overwrites the vector x. sigma is a permutation of length n that must be decomposable into disjoint swaps. */ for ( uint32_t j = 0; j < n; j++ ) { if ( j < sigma[j] ) { /* swap components j and sigma[j] */ const uint32_t j0 = j << 1; const uint32_t j1 = j0 + 1; const uint32_t j2 = sigma[j] << 1; const uint32_t j3 = j2 + 1; const double tmpr = x[j0]; const double tmpi = x[j1]; x[j0] = x[j2]; x[j1] = x[j3]; x[j2] = tmpr; x[j3] = tmpi; } } } /* end Permute */ void BitRevInit( uint32_t n, std::vector<uint32_t> &rho ) { /* This function initializes the bit-reversal permutation rho of length n, with n=2^m, m >= 0. */ if ( n == 1 ) { rho[0] = 0; return; } #ifdef _MSC_VER unsigned long end; _BitScanReverse( &end, n | 1 ); const uint32_t kEnd = static_cast<uint32_t>( end ); #else const uint32_t kEnd = 31 - __builtin_clz( n ); #endif for ( uint32_t j = 0; j < n; ++j ) { uint32_t val = 0; for ( uint32_t k = 0; k < kEnd; ++k ) { const uint32_t lastbit = ( j >> k ) & 0x1; val = ( val << 1 ) | lastbit; } rho[j] = val; } } /* end BitRevInit */ /****************** Parallel functions ********************************/ int K1Init( uint32_t n, uint32_t p ) { /* This function computes the largest butterfly size k1 of the first superstep in a parallel FFT of length n on p processors with p < n. */ uint32_t np = n / p; uint32_t c; for ( c = 1; c < p; c *= np ); return n / c; } /* end K1Init */ void BSPRedistr( std::vector<double> &x, uint32_t n, uint32_t p, uint32_t s, uint32_t c0, uint32_t c1, bool rev, std::vector<uint32_t> &rho_p ) { /* This function redistributes the complex vector x of length n, stored as pairs of reals, from group-cyclic distribution over p processors with cycle c0 to cycle c1, where c0, c1, p, n are powers of two with 1 <= c0 <= c1 <= p <= n. s is the processor number, 0 <= s < p. If rev=true, the function assumes the processor numbering is bit reversed on input. rho_p is the bit-reversal permutation of length p. */ const uint32_t np = n / p; const uint32_t ratio = c1 / c0; const uint32_t size = std::max( np / ratio, 1u ); const uint32_t npackets = np / size; std::vector<double> tmp( 2 * size ); uint32_t j0, j2; if ( rev ) { j2 = rho_p[s] / c0; j0 = rho_p[s] - c0 * j2; } else { j2 = s / c0; j0 = s - c0 * j2; } const uint32_t jglobInit = j2 * c0 * np + j0; const uint32_t c1np = c1 * np; BSPProf::InitCommunication(); for ( uint32_t j = 0; j < npackets; ++j ) { //jglob = j2 * c0 * np + j * c0 + j0; const uint32_t jglob = jglobInit + j * c0; const uint32_t jglobDiv = jglob / c1np; //destproc = ( jglob / ( c1 * np ) ) * c1 + jglob % c1; const uint32_t destproc = jglobDiv * c1 + jglob % c1; //destindex = ( jglob % ( c1 * np ) ) / c1; const uint32_t destindex = ( jglob - jglobDiv * c1np ) / c1; for ( uint32_t r = 0; r < size; ++r ) { const uint32_t r2 = r << 1; const uint32_t jRRatio = ( j + r * ratio ) << 1; tmp[r2] = x[jRRatio]; tmp[r2 + 1] = x[jRRatio + 1]; } BSPLib::PutIterator( destproc, tmp.begin(), size * 2, x.begin(), destindex * 2 ); } BSPProf::FinishCommunication(); BSPLib::SyncPutRequests(); } /* end BSPRedistr */ void bspfft( std::vector<double> &x, uint32_t n, uint32_t p, uint32_t s, int sign, std::vector<double> &w0, std::vector<double> &w, std::vector<double> &tw, std::vector<uint32_t> &rho_np, std::vector<uint32_t> &rho_p ) { /* This parallel function computes the discrete Fourier transform of a complex array x of length n=2^m, m >= 1, stored in a real array of length 2n as pairs (Re x[j], Im x[j]), 0 <= j < n. x must have been registered before calling this function. p is the number of processors, p=2^q, 0 <= q < m. s is the processor number, 0 <= s < p. The function uses three weight tables: w0 for the unordered fft of length k1, w for the unordered fft of length n/p, tw for a number of Twiddles, each of length n/p. The function uses two bit-reversal permutations: rho_np of length n/p, rho_p of length p. The weight tables and bit-reversal permutations must have been initialized before calling this function. If sign = 1, then the dft is computed, y[k] = sum j=0 to n-1 exp(-2*pi*i*k*j/n)*x[j], for 0 <= k < n. If sign =-1, then the inverse dft is computed, y[k] = (1/n) sum j=0 to n-1 exp(+2*pi*i*k*j/n)*x[j], for 0 <= k < n. Here, i=sqrt(-1). The output vector y overwrites x. */ const uint32_t np = n / p; const uint32_t k1 = K1Init( n, p ); Permute( x, np, rho_np ); bool rev = true; for ( uint32_t r = 0, rEnd = np / k1; r < rEnd; ++r ) { UFft( &x[2 * r * k1], k1, sign, w0 ); } for ( uint32_t c = k1, c0 = 1, ntw = 0; c <= p; c *= np, ++ntw ) { BSPRedistr( x, n, p, s, c0, c, rev, rho_p ); rev = false; Twiddle( x, np, sign, &tw[2 * ntw * np] ); UFft( x.data(), np, sign, w ); c0 = c; } if ( sign == -1 ) { const double ninv = 1 / ( double )n; for ( uint32_t j = 0; j < 2 * np; j++ ) { x[j] *= ninv; } } } /* end bspfft */ void BSPFftInit( uint32_t n, uint32_t p, uint32_t s, std::vector<double> &w0, std::vector<double> &w, std::vector<double> &tw, std::vector<uint32_t> &rho_np, std::vector<uint32_t> &rho_p ) { /* This parallel function initializes all the tables used in the FFT. */ const uint32_t np = n / p; BitRevInit( np, rho_np ); BitRevInit( p, rho_p ); const uint32_t k1 = K1Init( n, p ); UFftInit( k1, w0 ); UFftInit( np, w ); for ( uint32_t c = k1, ntw = 0; c <= p; c *= np, ++ntw ) { const double alpha = ( s % c ) / ( double )( c ); TwiddleInit( np, alpha, rho_np, &tw[2 * ntw * np] ); } } /* end BSPFftInit */
lastprivate-conditional-2.c
void foo (int *p) { int a = -1, b = -1, c = -1, d = -1, e = -1, f = -1, g = -1, h = -1; int i; #pragma omp parallel #pragma omp for lastprivate (conditional: a) for (i = 0; i < 32; i++) if (p[i]) a = i; #pragma omp simd lastprivate (conditional: b) for (i = 0; i < 32; i++) if (p[i]) b = i; #pragma omp parallel #pragma omp for simd lastprivate (conditional: c) for (i = 0; i < 32; i++) if (p[i]) c = i; #pragma omp parallel for lastprivate (conditional: d) for (i = 0; i < 32; i++) if (p[i]) d = i; #pragma omp parallel for simd lastprivate (conditional: e) for (i = 0; i < 32; i++) if (p[i]) e = i; }
factorize_gmp_2step.c
/***************************************************************************************************************** * Compiling: mpicc fattor.c -lgmp -fopenmp -o fattor * Running: mpirun -n PROCNUM --bind-to none fattor NUMBER * Note: PROCNUM is the number of processes that will be ran, and it must be >=2, NUMBER is the number to factorize *****************************************************************************************************************/ #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #include <gmp.h> struct elem { // Very basic and non-reusable stack mpz_t val; struct elem* next; }; void add(struct elem** head, mpz_t val) { struct elem* app = malloc(sizeof(struct elem)); mpz_init(app->val); mpz_set(app->val, val); // app->val = val; app->next = *head; *head = app; } void pick(struct elem** head, mpz_t toret) { mpz_init(toret); struct elem* app; if(*head == NULL) mpz_set_ui(toret, 0); // toret = 0; else { mpz_set(toret, (*head)->val); // toret = (*head)->val; app = *head; *head = (*head)->next; // mpz_finalize(app->val); free(app); } } void master_procedure(int comm_size) { int i = 1; long long rec; int shit_happened; unsigned char buffer[50]; MPI_Status stat; int count; mpz_t received_number; mpz_init(received_number); char stringa[200]; while(i < comm_size) { shit_happened = MPI_Recv(buffer, 50, MPI_UNSIGNED_CHAR, i, MPI_ANY_TAG, MPI_COMM_WORLD, &stat); MPI_Get_count(&stat, MPI_UNSIGNED_CHAR, &count); mpz_import(received_number, count, 1, 1, 1, 0, buffer); if(shit_happened) { fprintf(stderr, "Recv failed"); MPI_Abort(MPI_COMM_WORLD, 1); } if(mpz_cmp_ui(received_number, 0) == 0) // if(received_number == 0) ++i; else { mpz_get_str(stringa, 10, received_number); printf("Factor: %s\n", stringa); } } } void slave_procedure(int my_rank, int comm_size, mpz_t the_number) { int shit_happened; struct elem* head = NULL; unsigned char* buffer; mpz_t temp; mpz_t from; mpz_t to; mpz_t to_send; mpz_t div2; mpz_t number2; mpz_init(temp); mpz_init(from); mpz_init(to); mpz_init(to_send); mpz_init(div2); mpz_init(number2); mpz_set_ui(number2, 2); mpz_root(temp, the_number, 2); // temp = sqrt(the_number); mpz_div_ui(temp, temp, comm_size - 1); // temp = temp / (comm_size - 1); mpz_mul_ui(from, temp, my_rank - 1); // from = temp * (my_rank - 1); mpz_mul_ui(to, temp, my_rank); // to = temp * my_rank; if(mpz_cmp_ui(from, 0) == 0) { // if(from == 0) if(mpz_divisible_ui_p(the_number, 2)) { mpz_divexact_ui(div2, the_number, 2); // divided = the_number / from_thread; // Only works if the_number % from_thread == 0; add(&head, number2); add(&head, div2); } mpz_set_ui(from, 1); // from = 1; } if(mpz_divisible_ui_p(from, 2)) // if(from % 2 == 0) mpz_add_ui(from, from, 1); // ++from; #pragma omp parallel shared(from, to) { int my_thread = omp_get_thread_num(); int threads = omp_get_num_threads(); mpz_t from_thread; mpz_t to_thread; mpz_t divided; mpz_init(from_thread); mpz_init(to_thread); mpz_init(divided); mpz_sub(to_thread, to, from); // to_thread = to - from; mpz_set(from_thread, to_thread); // from_thread = to_thread; mpz_div_ui(to_thread, to_thread, threads); // to_thread = to_thread / threads; mpz_mul_ui(to_thread, to_thread, my_thread + 1); // to_thread = to_thread * (my_thread + 1); mpz_div_ui(from_thread, from_thread, threads); // from_thread = from_thread / threads; mpz_mul_ui(from_thread, from_thread, my_thread); // from_thread = from_thread * my_thread; mpz_add(from_thread, from_thread, from); // from_thread = from_thread + from; mpz_add(to_thread, to_thread, from); // to_thread = to_thread + from; if(mpz_divisible_ui_p(from_thread, 2)) // if(from_thread % 2 == 0) mpz_add_ui(from_thread, from_thread, 1); // from_thread = from_thread + 1; while(mpz_cmp(from_thread, to_thread) <= 0) { if(mpz_divisible_p(the_number, from_thread)) { mpz_divexact(divided, the_number, from_thread); // divided = the_number / from_thread; // Only works if the_number % from_thread == 0; #pragma omp critical { add(&head, from_thread); add(&head, divided); } } mpz_add_ui(from_thread, from_thread, 2); // from_thread += 2; } } do { pick(&head, to_send); int how_many_bytes = (mpz_sizeinbase(to_send, 2) + 7) / 8; // How many bytes is to_send buffer = malloc(how_many_bytes); *buffer = 0; mpz_export(buffer, NULL, 1, 1, 1, 0, to_send); // Export the number to buffer shit_happened = MPI_Send(buffer, how_many_bytes, MPI_UNSIGNED_CHAR, 0, 0, MPI_COMM_WORLD); if(shit_happened) { fprintf(stderr, "Send failed"); MPI_Abort(MPI_COMM_WORLD, 1); } free(buffer); }while(mpz_cmp_ui(to_send, 0)); } int main(int argc, char** argv) { int my_rank, comm_size; mpz_t the_number; mpz_init(the_number); MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &comm_size); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); if(argc <= 1) { fprintf(stderr, "Missing number as argument"); MPI_Abort(MPI_COMM_WORLD, 1); } else mpz_set_str(the_number, argv[1], 10); // 10 is the base if(my_rank == 0) master_procedure(comm_size); else slave_procedure(my_rank, comm_size, the_number); MPI_Finalize(); return 0; }
fabio_c.c
/* Contains the IO routines for fabio module */ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <float.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #if !defined(WIN32) #include <unistd.h> #else #include <io.h> typedef int mode_t; #endif #ifndef WIN32 #define FILE_MODE ( S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) #define DIR_MODE (FILE_MODE | S_IXUSR | S_IXGRP | S_IXOTH) #define O_BINARY 0 #else #define FILE_MODE (-1) #define DIR_MODE (-1) #endif #if defined(BL_FORT_USE_UNDERSCORE) #define FABIO_UNLINK_IF_EMPTY_STR fabio_unlink_if_empty_str_ #define FABIO_OPEN_STR fabio_open_str_ #define FABIO_MKDIR_STR fabio_mkdir_str_ #define FABIO_CLOSE fabio_close_ #define FAB_CONTAINS_NAN fab_contains_nan_ #define FAB_CONTAINS_INF fab_contains_inf_ #define VAL_IS_INF val_is_inf_ #define VAL_IS_NAN val_is_nan_ #elif defined(BL_FORT_USE_DBL_UNDERSCORE) #define FABIO_UNLINK_IF_EMPTY_STR fabio_unlink_if_empty_str__ #define FABIO_OPEN_STR fabio_open_str__ #define FABIO_MKDIR_STR fabio_mkdir_str__ #define FABIO_CLOSE fabio_close__ #define FAB_CONTAINS_NAN fab_contains_nan__ #define FAB_CONTAINS_INF fab_contains_inf__ #define VAL_IS_INF val_is_inf__ #define VAL_IS_NAN val_is_nan__ #elif defined(BL_FORT_USE_LOWERCASE) #define FABIO_UNLINK_IF_EMPTY_STR fabio_unlink_if_empty_str #define FABIO_OPEN_STR fabio_open_str #define FABIO_MKDIR_STR fabio_mkdir_str #define FABIO_CLOSE fabio_close #define FAB_CONTAINS_NAN fab_contains_nan #define FAB_CONTAINS_INF fab_contains_inf #define VAL_IS_INF val_is_inf #define VAL_IS_NAN val_is_nan #endif static const int BUFFER_SIZE = 512; static const int FABIO_MAX_PATH_NAME = 512; static void int_2_str(char f[], int n, const int* fi) { int i; for ( i = 0; i < n; ++i ) { if ( fi[i] < 0 ) { f[i] = 0; break; } f[i] = (char)fi[i]; } if ( i == n ) { fprintf(stderr, "name to long, probably not terminated ifilename\n"); exit(1); } } void FABIO_OPEN_STR(int* fdp, const int* ifilename, const int* flagp) { int lflag; int lmode; char filename[FABIO_MAX_PATH_NAME]; int_2_str(filename, sizeof(filename), ifilename); switch ( *flagp ) { case 0: lflag = O_RDONLY; break; case 1: lflag = O_WRONLY | O_CREAT | O_TRUNC | O_BINARY; lmode = FILE_MODE; break; case 2: lflag = O_RDWR; break; case 3: lflag = O_RDWR | O_APPEND; break; default: fprintf(stderr, "FABIO_OPEN_STR: invalid flag, %d, must be <=0<=2", *flagp); exit(1); } *fdp = open(filename, lflag, lmode); if ( *fdp == -1 ) { fprintf(stderr, "FABIO_OPEN_STR: failed to open \"%s\": %s\n", filename, strerror(errno)); exit(1); } } /* * DOUBLE data * FAB ((8, (64 11 52 0 1 12 0 1023)),(8, (1 2 3 4 5 6 7 8)))((0,0) (63,63) (0,0)) 27 * FLOAT data * FAB ((8, (32 8 23 0 1 9 0 127)),(4, (1 2 3 4) ))((0,0) (63,63) (0,0)) 27 */ /* * NORDER_? : normal byte order floats(f), doubles(d) on this architecture */ static const char* str_ieee_d = "64 11 52 0 1 12 0 1023"; static const char* str_ieee_f = "32 8 23 0 1 9 0 127"; #if defined(BL_AIX) || defined(BL_Darwin) static const int norder_d[8] = { 1, 2, 3, 4, 5, 6, 7, 8}; static const char* str_norder_d = "1 2 3 4 5 6 7 8"; static const int norder_f[4] = { 1, 2, 3, 4}; static const char* str_norder_f = "1 2 3 4"; #else static const int norder_d[8] = { 8, 7, 6, 5, 4, 3, 2, 1}; static const char* str_norder_d = "8 7 6 5 4 3 2 1"; static const int norder_f[4] = { 4, 3, 2, 1 }; static const char* str_norder_f = "4 3 2 1"; #endif enum { FABIO_ERR = 0, /* cf. fabio.f90 */ FABIO_SINGLE = 2, FABIO_DOUBLE = 1 }; static int scan_buffer(const char* buffer, int border[]) { int i; int bcount; char bstr[1024]; /* first try for double data */ i = sscanf(buffer, "FAB ((8, (64 11 52 0 1 12 0 1023)),(%d, (%[^)])))", &bcount, bstr); if ( i == 2 ) { i = sscanf(bstr, "%d %d %d %d %d %d %d %d", border + 0, border + 1, border + 2, border + 3, border + 4, border + 5, border + 6, border + 7 ); if ( i != 8 ) { fprintf(stderr, "FABIO: scan_buffer failed to parse FAB border\n" "Not double precision data\n"); exit(1); } return FABIO_DOUBLE; } /* second, try for float data */ i = sscanf(buffer, "FAB ((8, (32 8 23 0 1 9 0 127)),(%d, (%[^)])))", &bcount, bstr); if ( i == 2 ) { i = sscanf(bstr, "%d %d %d %d", border + 0, border + 1, border + 2, border + 3 ); if ( i != 4) { fprintf(stderr, "FABIO: scan_buffer failed to parse FAB border\n" "Not double precision data\n"); exit(1); } return FABIO_SINGLE; } fprintf(stderr, "FABIO: scan_buffer failed to parse FAB header\n" "Architecture difference for floating point format\n"); exit(1); return FABIO_ERR; } void FABIO_READ_SKIP_D(const int* fdp, const long* offsetp, const long* skipp, double dp[], const long* countp) { int fd = *fdp; char c; size_t count = *countp; off_t offset = *offsetp; off_t skip = *skipp; int i,j; char buffer[1024]; int border[8]; int swap_bytes = 0; if ( lseek(fd, offset, SEEK_SET) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to seek to %ld: %s\n", offset, strerror(errno)); exit(1); } for (i=0;;i++) { if ( read(fd, &c, 1) != 1 ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to read a char: %s\n", strerror(errno)); exit(1); } if ( c == '\n' ) break; if ( i == sizeof(buffer) ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed FAB header\n"); exit(1); } buffer[i] = c; } buffer[i] = 0; i = scan_buffer(buffer, border); if ( i == FABIO_DOUBLE ) { /* should be positioned to read the doubles */ if ( skip && lseek(fd, skip*sizeof(double), SEEK_CUR) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to seek to comp %ld: %s\n", offset, strerror(errno)); exit(1); } if ( count*sizeof(double) != read(fd, dp, count*sizeof(double)) ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to read %ld doubles: %s\n", (long)count, strerror(errno)); exit(1); } for ( j = 0; j < 8; ++j ) { if (border[j] != norder_d[j] ) { swap_bytes = 1; break; } } if ( swap_bytes ) { unsigned char* cdp = (unsigned char*)dp; for ( i = 0; i < count; i++ ) { unsigned char t[8]; for ( j = 0; j < 8; j++ ) { t[j] = cdp[border[j]-1]; } for ( j = 0; j < 8; j++ ) { cdp[j] = t[norder_d[j]-1]; } cdp += 8; } } } else if ( i == FABIO_SINGLE ) { float* fp; if ( (fp = (float *) malloc(count*sizeof(float))) == NULL) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to allocate fp\n"); exit(1); } /* should be positioned to read the doubles */ if ( skip && lseek(fd, skip*sizeof(float), SEEK_CUR) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to seek to comp %ld: %s\n", offset, strerror(errno)); exit(1); } if ( count*sizeof(float) != read(fd, fp, count*sizeof(float)) ) { fprintf(stderr, "FABIO_READ_SKIP_D: failed to read %ld doubles: %s\n", (long)count, strerror(errno)); exit(1); } for ( j = 0; j < 4; ++j ) { if (border[j] != norder_f[j] ) { swap_bytes = 1; break; } } if ( swap_bytes ) { unsigned char* csp = (unsigned char*)fp; for ( i = 0; i < count; i++ ) { unsigned char t[4]; for ( j = 0; j < 4; j++ ) { t[j] = csp[border[j]-1]; } for ( j = 0; j < 4; j++ ) { csp[j] = t[norder_f[j]-1]; } csp += 4; } } for ( i = 0; i < count; i++) { dp[i] = (double)fp[i]; } free(fp); } } void FABIO_READ_SKIP_S(const int* fdp, const long* offsetp, const long* skipp, float sp[], const long* countp) { int fd = *fdp; char c; size_t count = *countp; off_t offset = *offsetp; off_t skip = *skipp; int i,j; char buffer[1024]; int border[8]; int swap_bytes = 0; if ( lseek(fd, offset, SEEK_SET) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to seek to %ld: %s\n", offset, strerror(errno)); exit(1); } for (i=0;;i++) { if ( read(fd, &c, 1) != 1 ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to read a char: %s\n", strerror(errno)); exit(1); } if ( c == '\n' ) break; if ( i == sizeof(buffer) ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed FAB header\n"); exit(1); } buffer[i] = c; } buffer[i] = 0; i = scan_buffer(buffer, border); if ( i == FABIO_DOUBLE ) { double* dp; if ( (dp = (double *) malloc(count*sizeof(double))) == NULL) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to allocate sp\n"); exit(1); } /* should be positioned to read the doubles */ if ( skip && lseek(fd, skip*sizeof(double), SEEK_CUR) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to seek to comp %ld: %s\n", offset, strerror(errno)); exit(1); } if ( count*sizeof(double) != read(fd, dp, count*sizeof(double)) ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to read %ld doubles: %s\n", (long)count, strerror(errno)); exit(1); } for ( j = 0; j < 8; ++j ) { if (border[j] != norder_d[j] ) { swap_bytes = 1; break; } } if ( swap_bytes ) { unsigned char* cdp = (unsigned char*)dp; for ( i = 0; i < count; i++ ) { unsigned char t[8]; for ( j = 0; j < 8; j++ ) { t[j] = cdp[border[j]-1]; } for ( j = 0; j < 8; j++ ) { cdp[j] = t[norder_d[j]-1]; } cdp += 8; } } free(dp); for ( i = 0; i < count; i++ ) { if ( dp[i] > FLT_MAX ) sp[i] = FLT_MAX; else if ( dp[i] < -FLT_MAX ) sp[i] = -FLT_MAX; else sp[i] = (float)dp[i]; } } else if ( i == FABIO_SINGLE ) { /* should be positioned to read the doubles */ if ( skip && lseek(fd, skip*sizeof(float), SEEK_CUR) < 0 ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to seek to comp %ld: %s\n", offset, strerror(errno)); exit(1); } if ( count*sizeof(float) != read(fd, sp, count*sizeof(float)) ) { fprintf(stderr, "FABIO_READ_SKIP_S: failed to read %ld doubles: %s\n", (long)count, strerror(errno)); exit(1); } for ( j = 0; j < 4; ++j ) { if (border[j] != norder_f[j] ) { swap_bytes = 1; break; } } if ( swap_bytes ) { unsigned char* csp = (unsigned char*)sp; for ( i = 0; i < count; i++ ) { unsigned char t[4]; for ( j = 0; j < 4; j++ ) { t[j] = csp[border[j]-1]; } for ( j = 0; j < 4; j++ ) { csp[j] = t[norder_f[j]-1]; } csp += 4; } } } } /* ** These four guys are used by the particle code. */ void FABIO_WRITE_RAW_ARRAY_D(const int* fdp, const double* vp, const int* countp) { int fd = *fdp; size_t count = *countp; int ilen = sizeof(double) * count; lseek(fd, 0, SEEK_END); if ( ilen != write(fd, vp, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_ARRAY_D: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } } void FABIO_WRITE_RAW_ARRAY_I(const int* fdp, const int* vp, const int* countp) { int fd = *fdp; size_t count = *countp; int ilen = sizeof(int) * count; lseek(fd, 0, SEEK_END); if ( ilen != write(fd, vp, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_ARRAY_I: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } } void FABIO_READ_RAW_ARRAY_D(const int* fdp, double* vp, const int* countp) { int fd = *fdp; size_t count = *countp; int ilen = sizeof(double) * count; if ( ilen != read(fd, vp, ilen) ) { fprintf(stderr, "FABIO_READ_RAW_ARRAY_D: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } } void FABIO_READ_RAW_ARRAY_I(const int* fdp, int* vp, const int* countp) { int fd = *fdp; size_t count = *countp; int ilen = sizeof(int) * count; if ( ilen != read(fd, vp, ilen) ) { fprintf(stderr, "FABIO_READ_RAW_ARRAY_I: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } } void FABIO_WRITE_RAW_D(const int* fdp, long* offsetp, const double* vp, const long* countp, const int* dmp, const int lo[], const int hi[], const int nd[], const int* ncp) { int fd = *fdp; int dm = *dmp; int nc = *ncp; size_t count = *countp; off_t offset; char buffer[BUFFER_SIZE]; int ilen; double* dp = (double*)vp; offset = lseek(fd, 0, SEEK_END); if ( snprintf(buffer, BUFFER_SIZE, "FAB ((8, (%s)),(8, (%s)))", str_ieee_d, str_norder_d) >= BUFFER_SIZE ) { fprintf(stderr, "FABIO_WRITE_RAW_D: buffer too small"); exit(1); } ilen = strlen(buffer); if ( ilen != write(fd, buffer, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_D: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } switch ( dm ) { case 1: ilen = snprintf(buffer, BUFFER_SIZE, "((%d) (%d) (%d)) %d\n", lo[0], hi[0], nd[0], nc); break; case 2: ilen = snprintf(buffer, BUFFER_SIZE, "((%d,%d) (%d,%d) (%d,%d)) %d\n", lo[0], lo[1], hi[0], hi[1], nd[0], nd[1], nc); break; case 3: ilen = snprintf(buffer, BUFFER_SIZE, "((%d,%d,%d) (%d,%d,%d) (%d,%d,%d)) %d\n", lo[0], lo[1], lo[2], hi[0], hi[1], hi[2], nd[0], nd[1], nd[2], nc); break; default: fprintf(stderr, "FABIO_WRITE_RAW_D: strange dimension = %d\n", dm); exit(1); } if ( ilen >= BUFFER_SIZE ) { fprintf(stderr, "FABIO_WRITE_RAW_D: buffer too small"); exit(1); } ilen = write(fd, buffer, strlen(buffer)); if ( ilen != strlen(buffer) ) { fprintf(stderr, "FABIO_WRITE_RAW_D: write of buffer failed\n"); exit(1); } ilen = nc*count*sizeof(double); if ( ilen != write(fd, dp, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_D: failed to write %ld doubles: %s\n", (long)nc*count, strerror(errno)); exit(1); } if ( offset > LONG_MAX ) { fprintf(stderr, "FABIO_WRITE_RAW_D: offset will overflow offsetp"); exit(1); } *offsetp = offset; } void FABIO_WRITE_RAW_S(const int* fdp, long* offsetp, const float* vp, const long* countp, const int* dmp, const int lo[], const int hi[], const int nd[], const int* ncp) { int fd = *fdp; int dm = *dmp; int nc = *ncp; size_t count = *countp; off_t offset; char buffer[BUFFER_SIZE]; int ilen; float* sp = (float*)vp; offset = lseek(fd, 0, SEEK_END); if ( snprintf(buffer, BUFFER_SIZE, "FAB ((8, (%s)),(4, (%s)))", str_ieee_f, str_norder_f) >= BUFFER_SIZE ) { fprintf(stderr, "FABIO_WRITE_RAW_S: buffer too small"); exit(1); } ilen = strlen(buffer); if ( ilen != write(fd, buffer, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_S: failed to write %d bytes: %s\n", ilen, strerror(errno)); exit(1); } switch ( dm ) { case 1: ilen = snprintf(buffer, BUFFER_SIZE, "((%d) (%d) (%d)) %d\n", lo[0], hi[0], nd[0], nc); break; case 2: ilen = snprintf(buffer, BUFFER_SIZE, "((%d,%d) (%d,%d) (%d,%d)) %d\n", lo[0], lo[1], hi[0], hi[1], nd[0], nd[1], nc); break; case 3: ilen = snprintf(buffer, BUFFER_SIZE, "((%d,%d,%d) (%d,%d,%d) (%d,%d,%d)) %d\n", lo[0], lo[1], lo[2], hi[0], hi[1], hi[2], nd[0], nd[1], nd[2], nc); break; default: fprintf(stderr, "FABIO_WRITE_RAW_S: strange dimension = %d\n", dm); exit(1); } if ( ilen >= BUFFER_SIZE ) { fprintf(stderr, "FABIO_WRITE_RAW_S: buffer too small"); exit(1); } ilen = write(fd, buffer, strlen(buffer)); if ( ilen != strlen(buffer) ) { fprintf(stderr, "FABIO_WRITE_RAW_S: write of buffer failed\n"); exit(1); } ilen = nc*count*sizeof(float); if ( ilen != write(fd, sp, ilen) ) { fprintf(stderr, "FABIO_WRITE_RAW_S: failed to write %ld floats: %s\n", (long)nc*count, strerror(errno)); exit(1); } if ( offset > LONG_MAX ) { fprintf(stderr, "FABIO_WRITE_RAW_S: offset will overflow offsetp"); exit(1); } *offsetp = offset; } void FABIO_READ_D(const int* fdp, const long* offsetp, double dp[], const long* countp) { long skip = 0; FABIO_READ_SKIP_D(fdp, offsetp, &skip, dp, countp); } void FABIO_READ_S(const int* fdp, const long* offsetp, float sp[], const long* countp) { long skip = 0; FABIO_READ_SKIP_S(fdp, offsetp, &skip, sp, countp); } void FABIO_CLOSE(const int* fdp) { int fd = *fdp; if ( close(fd) < 0 ) { fprintf(stderr, "FABIO_CLOSE: failed to close %d: %s\n", fd, strerror(errno)); exit(1); } } #if defined(WIN32) #include <direct.h> #define mkdir(a,b) _mkdir((a)) /* static const char* path_sep_str = "\\"; */ #else /* static const char* path_sep_str = "/"; */ #endif void FABIO_MKDIR_STR(const int* idirname, int* statp) { mode_t mode = DIR_MODE; int st = *statp; char dirname[FABIO_MAX_PATH_NAME]; int_2_str(dirname, sizeof(dirname), idirname); *statp = 0; /* we allow the mkdir on an existing directory */ if ( mkdir(dirname, mode) <0 && errno != EEXIST ) { if ( st ) { *statp = 1; return; } else { fprintf(stderr, "FABIO_MKDIR_STR: mkdir(%s,%d): %s\n", dirname, mode, strerror(errno)); exit(1); } } } void FABIO_UNLINK_IF_EMPTY_STR(const int* ifilename) { int fd; char filename[FABIO_MAX_PATH_NAME]; int lmode = FILE_MODE; int pos; int_2_str(filename, sizeof(filename), ifilename); if ((fd = open(filename, O_RDONLY, lmode)) < 0) { fprintf(stderr, "FABIO_UNLINK_IF_EMPTY: open() failed: \"%s\": %s\n", filename, strerror(errno)); exit(1); } if ((pos = lseek(fd, 0, SEEK_END)) < 0) { fprintf(stderr, "FABIO_UNLINK_IF_EMPTY: lseek() failed: \"%s\": %s\n", filename, strerror(errno)); exit(1); } close(fd); if (pos == 0) { if (unlink(filename) < 0) { fprintf(stderr, "FABIO_UNLINK_IF_EMPTY: unlink() failed: \"%s\": %s\n", filename, strerror(errno)); exit(1); } } } void FAB_CONTAINS_NAN (double dptr[], const int* countp, int* result) { int i; int rr=0; #ifdef _OPENMP #pragma omp parallel reduction(+:rr) #endif { #ifdef _OPENMP #pragma omp for private(i) #endif for (i = 0; i < *countp; i++) { if (isnan(dptr[i])) { rr++; } } } *result = (rr>0) ? 1 : 0; } void FAB_CONTAINS_INF (double dptr[], const int* countp, int* result) { int i; int rr=0; #ifdef _OPENMP #pragma omp parallel reduction(+:rr) #endif { #ifdef _OPENMP #pragma omp for private(i) #endif for (i = 0; i < *countp; i++) { if (isinf(dptr[i])) { rr++; } } } *result = (rr>0) ? 1 : 0; } void VAL_IS_INF (double* val, int* result) { *result = (isinf(*val) ? 1 : 0); } void VAL_IS_NAN (double* val, int* result) { *result = (isnan(*val) ? 1 : 0); }
GB_extractTuples.c
//------------------------------------------------------------------------------ // GB_extractTuples: extract all the tuples from a matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Extracts all tuples from a matrix, like [I,J,X] = find (A). If any // parameter I, J and/or X is NULL, then that component is not extracted. The // size of the I, J, and X arrays (those that are not NULL) is given by nvals, // which must be at least as large as GrB_nvals (&nvals, A). The values in the // matrix are typecasted to the type of X, as needed. // This function does the work for the user-callable GrB_*_extractTuples // functions, and helps build the tuples for GB_concat_hyper. // Tf A is iso and X is not NULL, the iso scalar Ax [0] is expanded into X. #include "GB.h" #define GB_FREE_ALL \ { \ GB_FREE_WORK (&Ap, Ap_size) ; \ GB_FREE_WORK (&X_bitmap, X_bitmap_size) ; \ } GrB_Info GB_extractTuples // extract all tuples from a matrix ( GrB_Index *I_out, // array for returning row indices of tuples GrB_Index *J_out, // array for returning col indices of tuples void *X, // array for returning values of tuples GrB_Index *p_nvals, // I,J,X size on input; # tuples on output const GB_Type_code xcode, // type of array X const GrB_Matrix A, // matrix to extract tuples from GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; GB_void *restrict X_bitmap = NULL ; size_t X_bitmap_size = 0 ; int64_t *restrict Ap = NULL ; size_t Ap_size = 0 ; ASSERT_MATRIX_OK (A, "A to extract", GB0) ; ASSERT (p_nvals != NULL) ; // delete any lingering zombies and assemble any pending tuples; // allow A to remain jumbled GB_MATRIX_WAIT_IF_PENDING_OR_ZOMBIES (A) ; GB_BURBLE_DENSE (A, "(A %s) ") ; ASSERT (xcode <= GB_UDT_code) ; const GB_Type_code acode = A->type->code ; const size_t asize = A->type->size ; // xcode and A must be compatible if (!GB_code_compatible (xcode, acode)) { return (GrB_DOMAIN_MISMATCH) ; } const int64_t anz = GB_nnz (A) ; if (anz == 0) { // no work to do (*p_nvals) = 0 ; return (GrB_SUCCESS) ; } int64_t nvals = *p_nvals ; // size of I,J,X on input if (nvals < anz && (I_out != NULL || J_out != NULL || X != NULL)) { // output arrays are not big enough return (GrB_INSUFFICIENT_SPACE) ; } //------------------------------------------------------------------------- // determine the number of threads to use //------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (anz + A->nvec, chunk, nthreads_max) ; //------------------------------------------------------------------------- // handle the CSR/CSC format //-------------------------------------------------------------------------- GrB_Index *I, *J ; if (A->is_csc) { I = I_out ; J = J_out ; } else { I = J_out ; J = I_out ; } //-------------------------------------------------------------------------- // bitmap case //-------------------------------------------------------------------------- if (GB_IS_BITMAP (A)) { //---------------------------------------------------------------------- // allocate workspace //---------------------------------------------------------------------- bool need_typecast = (X != NULL) && (xcode != acode) ; if (need_typecast) { // X must be typecasted int64_t anzmax = GB_IMAX (anz, 1) ; X_bitmap = GB_MALLOC_WORK (anzmax*asize, GB_void, &X_bitmap_size) ; } Ap = GB_MALLOC_WORK (A->vdim+1, int64_t, &Ap_size) ; if (Ap == NULL || (need_typecast && X_bitmap == NULL)) { // out of memory GB_FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } //---------------------------------------------------------------------- // extract the tuples //---------------------------------------------------------------------- // TODO: pass xcode to GB_convert_bitmap_worker and let it do the // typecasting. This works for now, however. // if A is iso, GB_convert_bitmap_worker expands the iso scalar // into its result, X or X_bitmap GB_OK (GB_convert_bitmap_worker (Ap, (int64_t *) I, (int64_t *) J, (GB_void *) (need_typecast ? X_bitmap : X), NULL, A, Context)) ; //---------------------------------------------------------------------- // typecast X if needed //---------------------------------------------------------------------- if (need_typecast) { // typecast the values from X_bitmap into X ASSERT (X != NULL) ; ASSERT (xcode != acode) ; GB_cast_array ((GB_void *) X, xcode, X_bitmap, acode, NULL, anz, nthreads) ; } } else { //---------------------------------------------------------------------- // sparse, hypersparse, or full case //---------------------------------------------------------------------- //---------------------------------------------------------------------- // extract the row indices //---------------------------------------------------------------------- if (I != NULL) { if (A->i == NULL) { // A is full; construct the row indices int64_t avlen = A->vlen ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { I [p] = (p % avlen) ; } } else { GB_memcpy (I, A->i, anz * sizeof (int64_t), nthreads) ; } } //---------------------------------------------------------------------- // extract the column indices //---------------------------------------------------------------------- if (J != NULL) { GB_OK (GB_extract_vector_list ((int64_t *) J, A, Context)) ; } //---------------------------------------------------------------------- // extract the values //---------------------------------------------------------------------- if (X != NULL) { if (A->iso) { // typecast the scalar and expand it into X size_t xsize = GB_code_size (xcode, asize) ; GB_void scalar [GB_VLA(xsize)] ; GB_cast_scalar (scalar, xcode, A->x, acode, asize) ; GB_iso_expand (X, anz, scalar, xsize, Context) ; } else if (xcode == acode) { // copy the values from A into X, no typecast GB_memcpy (X, A->x, anz * asize, nthreads) ; } else { // typecast the values from A into X ASSERT (X != NULL) ; GB_cast_array ((GB_void *) X, xcode, (GB_void *) A->x, acode, NULL, anz, nthreads) ; } } } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- *p_nvals = anz ; // number of tuples extracted GB_FREE_ALL ; return (GrB_SUCCESS) ; }
opal_test.c
// Copyright 2009-2017 Sandia Corporation. Under the terms // of Contract DE-NA0003525 with Sandia Corporation, the U.S. // Government retains certain rights in this software. // // Copyright (c) 2009-2017, Sandia Corporation // All rights reserved. // // Portions are copyright of other developers: // See the file CONTRIBUTORS.TXT in the top level directory // the distribution for more information. // // This file is part of the SST software package. For license // information, see the LICENSE file in the top level directory of the // distribution. #include <stdio.h> #include <stdlib.h> extern "C" void ariel_enable() { printf("Inside Ariel\n"); } int main(int argc, char* argv[]) { const int LENGTH = 2000; ariel_enable(); printf("Allocating arrays of size %d elements.\n", LENGTH); double* a = (double*) malloc(sizeof(double) * LENGTH); double* b = (double*) malloc(sizeof(double) * LENGTH); double* c = (double*) malloc(sizeof(double) * LENGTH); printf("Done allocating arrays.\n"); int i; for(i = 0; i < LENGTH; ++i) { a[i] = i; b[i] = LENGTH - i; c[i] = 0; } printf("Perfoming the fast_c compute loop...\n"); #pragma omp parallel num_threads(2) for(i = 0; i < LENGTH; ++i) { //printf("issuing a write to: %llu (fast_c)\n", ((unsigned long long int) &fast_c[i])); c[i] = 2.0 * a[i] + 1.5 * b[i]; } double sum = 0; for(i = 0; i < LENGTH; ++i) { sum += c[i]; } printf("Sum of arrays is: %f\n", sum); printf("Freeing arrays...\n"); free(a); free(b); free(c); printf("Done.\n"); }
GB_unaryop__lnot_fp64_fp64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_fp64_fp64 // op(A') function: GB_tran__lnot_fp64_fp64 // C type: double // A type: double // cast: double cij = (double) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ double z = (double) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_fp64_fp64 ( double *restrict Cx, const double *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_fp64_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
tinyexr.h
/* Copyright (c) 2014 - 2019, Syoyo Fujita and many contributors. 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 Syoyo Fujita 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 <COPYRIGHT HOLDER> 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. */ // TinyEXR contains some OpenEXR code, which is licensed under ------------ /////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// // End of OpenEXR license ------------------------------------------------- #ifndef TINYEXR_H_ #define TINYEXR_H_ // // // Do this: // #define TINYEXR_IMPLEMENTATION // before you include this file in *one* C or C++ file to create the // implementation. // // // i.e. it should look like this: // #include ... // #include ... // #include ... // #define TINYEXR_IMPLEMENTATION // #include "tinyexr.h" // // #include <stddef.h> // for size_t #include <stdint.h> // guess stdint.h is available(C99) #ifdef __cplusplus extern "C" { #endif // Use embedded miniz or not to decode ZIP format pixel. Linking with zlib // required if this flas is 0. #ifndef TINYEXR_USE_MINIZ #define TINYEXR_USE_MINIZ (1) #endif // Disable PIZ comporession when applying cpplint. #ifndef TINYEXR_USE_PIZ #define TINYEXR_USE_PIZ (1) #endif #ifndef TINYEXR_USE_ZFP #define TINYEXR_USE_ZFP (0) // TinyEXR extension. // http://computation.llnl.gov/projects/floating-point-compression #endif #ifndef TINYEXR_USE_THREAD #define TINYEXR_USE_THREAD (0) // No threaded loading. // http://computation.llnl.gov/projects/floating-point-compression #endif #ifndef TINYEXR_USE_OPENMP #ifdef _OPENMP #define TINYEXR_USE_OPENMP (1) #else #define TINYEXR_USE_OPENMP (0) #endif #endif #define TINYEXR_SUCCESS (0) #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1) #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2) #define TINYEXR_ERROR_INVALID_ARGUMENT (-3) #define TINYEXR_ERROR_INVALID_DATA (-4) #define TINYEXR_ERROR_INVALID_FILE (-5) #define TINYEXR_ERROR_INVALID_PARAMETER (-6) #define TINYEXR_ERROR_CANT_OPEN_FILE (-7) #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8) #define TINYEXR_ERROR_INVALID_HEADER (-9) #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10) #define TINYEXR_ERROR_CANT_WRITE_FILE (-11) #define TINYEXR_ERROR_SERIALZATION_FAILED (-12) #define TINYEXR_ERROR_LAYER_NOT_FOUND (-13) // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf } // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2 #define TINYEXR_PIXELTYPE_UINT (0) #define TINYEXR_PIXELTYPE_HALF (1) #define TINYEXR_PIXELTYPE_FLOAT (2) #define TINYEXR_MAX_HEADER_ATTRIBUTES (1024) #define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128) #define TINYEXR_COMPRESSIONTYPE_NONE (0) #define TINYEXR_COMPRESSIONTYPE_RLE (1) #define TINYEXR_COMPRESSIONTYPE_ZIPS (2) #define TINYEXR_COMPRESSIONTYPE_ZIP (3) #define TINYEXR_COMPRESSIONTYPE_PIZ (4) #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0) #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1) #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2) #define TINYEXR_TILE_ONE_LEVEL (0) #define TINYEXR_TILE_MIPMAP_LEVELS (1) #define TINYEXR_TILE_RIPMAP_LEVELS (2) #define TINYEXR_TILE_ROUND_DOWN (0) #define TINYEXR_TILE_ROUND_UP (1) typedef struct _EXRVersion { int version; // this must be 2 int tiled; // tile format image int long_name; // long name attribute int non_image; // deep image(EXR 2.0) int multipart; // multi-part(EXR 2.0) } EXRVersion; typedef struct _EXRAttribute { char name[256]; // name and type are up to 255 chars long. char type[256]; unsigned char *value; // uint8_t* int size; int pad0; } EXRAttribute; typedef struct _EXRChannelInfo { char name[256]; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } EXRChannelInfo; typedef struct _EXRTile { int offset_x; int offset_y; int level_x; int level_y; int width; // actual width in a tile. int height; // actual height int a tile. unsigned char **images; // image[channels][pixels] } EXRTile; typedef struct _EXRHeader { float pixel_aspect_ratio; int line_order; int data_window[4]; int display_window[4]; float screen_window_center[2]; float screen_window_width; int chunk_count; // Properties for tiled format(`tiledesc`). int tiled; int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; int long_name; int non_image; int multipart; unsigned int header_len; // Custom attributes(exludes required attributes(e.g. `channels`, // `compression`, etc) int num_custom_attributes; EXRAttribute *custom_attributes; // array of EXRAttribute. size = // `num_custom_attributes`. EXRChannelInfo *channels; // [num_channels] int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for // each channel. This is overwritten with `requested_pixel_types` when // loading. int num_channels; int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*) int *requested_pixel_types; // Filled initially by // ParseEXRHeaderFrom(Meomory|File), then users // can edit it(only valid for HALF pixel type // channel) } EXRHeader; typedef struct _EXRMultiPartHeader { int num_headers; EXRHeader *headers; } EXRMultiPartHeader; typedef struct _EXRImage { EXRTile *tiles; // Tiled pixel data. The application must reconstruct image // from tiles manually. NULL if scanline format. unsigned char **images; // image[channels][pixels]. NULL if tiled format. int width; int height; int num_channels; // Properties for tile format. int num_tiles; } EXRImage; typedef struct _EXRMultiPartImage { int num_images; EXRImage *images; } EXRMultiPartImage; typedef struct _DeepImage { const char **channel_names; float ***image; // image[channels][scanlines][samples] int **offset_table; // offset_table[scanline][offsets] int num_channels; int width; int height; int pad0; } DeepImage; // @deprecated { For backward compatibility. Not recommended to use. } // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel // alpha) or RGB(A) channels. // Application must free image data as returned by `out_rgba` // Result image format is: float x RGBA x width x hight // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err); // Loads single-frame OpenEXR image by specifing layer name. Assume EXR image contains A(single channel // alpha) or RGB(A) channels. // Application must free image data as returned by `out_rgba` // Result image format is: float x RGBA x width x hight // Returns negative value and may set error string in `err` when there's an // error // When the specified layer name is not found in the EXR file, the function will return `TINYEXR_ERROR_LAYER_NOT_FOUND`. extern int LoadEXRWithLayer(float **out_rgba, int *width, int *height, const char *filename, const char *layer_name, const char **err); // // Get layer infos from EXR file. // // @param[out] layer_names List of layer names. Application must free memory after using this. // @param[out] num_layers The number of layers // @param[out] err Error string(wll be filled when the function returns error code). Free it using FreeEXRErrorMessage after using this value. // // @return TINYEXR_SUCCEES upon success. // extern int EXRLayers(const char *filename, const char **layer_names[], int *num_layers, const char **err); // @deprecated { to be removed. } // Simple wrapper API for ParseEXRHeaderFromFile. // checking given file is a EXR file(by just look up header) // @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for // others extern int IsEXR(const char *filename); // @deprecated { to be removed. } // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels. // components must be 1(Grayscale), 3(RGB) or 4(RGBA). // Input image format is: `float x width x height`, or `float x RGB(A) x width x // hight` // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero // value. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0. // Use ZIP compression by default. // Returns negative value and may set error string in `err` when there's an // error extern int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename, const char **err); // Initialize EXRHeader struct extern void InitEXRHeader(EXRHeader *exr_header); // Initialize EXRImage struct extern void InitEXRImage(EXRImage *exr_image); // Free's internal data of EXRHeader struct extern int FreeEXRHeader(EXRHeader *exr_header); // Free's internal data of EXRImage struct extern int FreeEXRImage(EXRImage *exr_image); // Free's error message extern void FreeEXRErrorMessage(const char *msg); // Parse EXR version header of a file. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename); // Parse EXR version header from memory-mapped EXR data. extern int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size); // Parse single-part OpenEXR header from a file and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version, const char *filename, const char **err); // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromMemory(EXRHeader *header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*` // array. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const char *filename, const char **err); // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*` // array // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Loads single-part OpenEXR image from a file. // Application must setup `ParseEXRHeaderFromFile` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header, const char *filename, const char **err); // Loads single-part OpenEXR image from a memory. // Application must setup `EXRHeader` with // `ParseEXRHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header, const unsigned char *memory, const size_t size, const char **err); // Loads multi-part OpenEXR image from a file. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this // function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromFile(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const char *filename, const char **err); // Loads multi-part OpenEXR image from a memory. // Application must setup `EXRHeader*` array with // `ParseEXRMultipartHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromMemory(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err); // Saves multi-channel, single-frame OpenEXR image to a file. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int SaveEXRImageToFile(const EXRImage *image, const EXRHeader *exr_header, const char *filename, const char **err); // Saves multi-channel, single-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // Return the number of bytes if success. // Return zero and will set error string in `err` when there's an // error. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern size_t SaveEXRImageToMemory(const EXRImage *image, const EXRHeader *exr_header, unsigned char **memory, const char **err); // Loads single-frame OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadDeepEXR(DeepImage *out_image, const char *filename, const char **err); // NOT YET IMPLEMENTED: // Saves single-frame OpenEXR deep image. // Returns negative value and may set error string in `err` when there's an // error // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename, // const char **err); // NOT YET IMPLEMENTED: // Loads multi-part OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const // char *filename, // const char **err); // For emscripten. // Loads single-frame OpenEXR image from memory. Assume EXR image contains // RGB(A) channels. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err); #ifdef __cplusplus } #endif #endif // TINYEXR_H_ #ifdef TINYEXR_IMPLEMENTATION #ifndef TINYEXR_IMPLEMENTATION_DEIFNED #define TINYEXR_IMPLEMENTATION_DEIFNED #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> // #include <iostream> // debug #include <limits> #include <string> #include <vector> #if __cplusplus > 199711L // C++11 #include <cstdint> #if TINYEXR_USE_THREAD #include <atomic> #include <thread> #endif #endif // __cplusplus > 199711L #if TINYEXR_USE_OPENMP #include <omp.h> #endif #if TINYEXR_USE_MINIZ #else // Issue #46. Please include your own zlib-compatible API header before // including `tinyexr.h` //#include "zlib.h" #endif #if TINYEXR_USE_ZFP #include "zfp.h" #endif namespace tinyexr { #if __cplusplus > 199711L // C++11 typedef uint64_t tinyexr_uint64; typedef int64_t tinyexr_int64; #else // Although `long long` is not a standard type pre C++11, assume it is defined // as a compiler's extension. #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #endif typedef unsigned long long tinyexr_uint64; typedef long long tinyexr_int64; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #if TINYEXR_USE_MINIZ namespace miniz { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #pragma clang diagnostic ignored "-Wundef" #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" #endif #if __has_warning("-Wmacro-redefined") #pragma clang diagnostic ignored "-Wmacro-redefined" #endif #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #if __has_warning("-Wtautological-constant-compare") #pragma clang diagnostic ignored "-Wtautological-constant-compare" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED //#include <stdlib.h> // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be // CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on // stdio for file I/O. //#define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able // to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be // called. // The current downside is the times written to your archives will be from 1979. #define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. #define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive // API's. //#define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression // API's. //#define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent // conflicts against stock zlib. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom // user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's // which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and // tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc // on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) //#include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ defined(__i386) || defined(__i486__) || defined(__i486) || \ defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient // integer loads and stores from unaligned addresses. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \ 0 // disable to suppress compiler warnings #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are // reasonably fast (and don't involve compiler generated calls to helper // functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() // unless you've modified the MZ_MALLOC macro) to release a block allocated from // the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with // ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with // ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: // items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The // other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best // possible compression (not zlib compatible, and may be very slow), // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been // optimized purely for performance, not ratio. // (This special func. is currently only enabled when // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no // header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input // and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or // MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not // available, and/or there's more output to be written but the output buffer // is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been // written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or // output buffers are empty. (Fill up the input buffer or free up some output // space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of // data that could be generated by deflate(), assuming flush is set to only // MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on // failure. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of // data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that // controls the window size and whether or not the stream has been wrapped with // a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or // -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the // input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output // buffers are both sized large enough to decompress the entire stream in a // single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside // what's already in the input buffer, and that the output buffer is large // enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or // there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes // have been written. For zlib streams, the adler-32 of the decompressed data // has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is // empty but the inflater needs more input to continue, or if the output // buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when // using single call decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on // failure. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the // error code is invalid. const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used // as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you // use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional // expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is // 0 this function returns the number of bytes needed to fully store the // filename. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and // modified times. // This function only extracts files, not archive directory records. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive // file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient // in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the // archive's filename so it can be reopened for writing. If the file can't be // reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be // growable using the realloc callback (which defaults to realloc unless you've // overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's // user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what // you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record // the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a // forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records // the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no // recompression), along with its full filename, extra data, and comment fields. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by // the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive // struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be // valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if // mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) // appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the // input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available // beyond the end of the supplied input buffer. If clear, the input buffer // contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large // enough to hold the entire decompressed stream. If clear, the output buffer is // at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the // decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data // to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer // needed. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block // in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes // written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an // internal 32KB buffer, and a user provided callback function will be called to // flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) \ do { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function // actually needed for decompression. All the other functions are just // high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any // desired higher level decompression API. In the limit case, it can be called // once per every byte input or output. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly // slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 // tdefl_init() compression flags logically OR'd together (low 12 bits contain // the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap // compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before // the deflate data, and the Adler-32 of the source data at the end. Otherwise, // you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even // when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more // efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's // initialization time to the minimum, but the output may vary from run to run // given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per // dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against // the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in // memory. // Returns 0 on failure. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be // 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost // pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL // apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be // larger than *pLen_out) when it's no longer needed. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The // above helpers use this function internally. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed // output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper // functions aren't flexible enough. The low-level functions don't make any heap // allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1 } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not // dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified // callback. In this case, the user should call the tdefl_compress_buffer() API // for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() // API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, // etc.) tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer // as possible, and writing as much compressed data to the specified output // buffer as possible. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a // non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't // defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be // much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, // MZ_RLE, or MZ_FIXED mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want // the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; //#include <assert.h> //#include <string.h> #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C // implementation that balances processor cache usage against speed": // http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c}; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } // static void *def_realloc_func(void *opaque, void *address, size_t items, // size_t size) { // (void)opaque, (void)address, (void)items, (void)size; // return MZ_REALLOC(address, items * size); //} const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty // tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are // large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; // Stream is corrupted (there could be some // uncompressed data left in the output dictionary - // oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; // Signal caller that we can't make forward progress // without supplying more input or by setting flush // to MZ_FINISH. else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data // when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's // at least 1 more byte on the way. If there's no more room left in the // output buffer then something is wrong. else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = {{MZ_OK, ""}, {MZ_STREAM_END, "stream end"}, {MZ_NEED_DICT, "need dictionary"}, {MZ_ERRNO, "file error"}, {MZ_STREAM_ERROR, "stream error"}, {MZ_DATA_ERROR, "data error"}, {MZ_MEM_ERROR, "out of memory"}, {MZ_BUF_ERROR, "buf error"}, {MZ_VERSION_ERROR, "version error"}, {MZ_PARAM_ERROR, "parameter error"}}; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif // MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all // compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ switch (r->m_state) { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ do { \ status = result; \ r->m_state = state_index; \ goto common_exit; \ case state_index:; \ } \ MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do { \ for (;;) { \ TINFL_CR_RETURN(state_index, result); \ } \ } \ MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt // to read beyond the input buf, then something is wrong with the input because // the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of // the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) \ do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for (;;) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else \ c = *pIn_buf_cur++; \ } \ MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) \ do { \ mz_uint c; \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ b = bit_buf & ((1 << (n)) - 1); \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes // remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode // the next Huffman code (and absolutely no more). It works by trying to fully // decode a // Huffman code by using whatever bits are currently present in the bit buffer. // If this fails, it reads another byte, and tries again until it succeeds or // until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); \ if (temp >= 0) break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex // than you would initially expect because the zlib API expects the decompressor // to never read // beyond the final byte of the deflate stream. (In other words, when this macro // wants to read another byte from the input, it REALLY needs another byte in // order to fully // decode the next Huffman code.) Handling this properly is particularly // important on raw deflate (non-zlib) streams, which aren't followed by a byte // aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ do { \ int temp; \ mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ pIn_buf_cur += 2; \ num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while (temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ num_bits -= code_len; \ } \ MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static const int s_min_table_sizes[3] = {257, 1, 4}; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer // is large enough to hold the entire output file (in which case it doesn't // matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (;;) { mz_uint8 *pSrc; for (;;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for (;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression // API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285}; static const mz_uint8 s_tdefl_len_extra[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0}; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17}; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted // values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq *t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, // alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n == 0) return; else if (n == 1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next = 1; next < n - 1; next++) { if (leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n - 2].m_key = 0; for (next = n - 3; next >= 0; next--) A[next].m_key = A[A[next].m_key].m_key + 1; avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; while (avbl > 0) { while (root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } while (avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2 * used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) \ do { \ mz_uint bits = b; \ mz_uint len = l; \ MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); \ d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } \ MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() \ { \ if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)( \ d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) \ packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 16; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_repeat_count - 3); \ } \ rle_repeat_count = 0; \ } \ } #define TDEFL_RLE_ZERO_CODE_SIZE() \ { \ if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = \ (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 17; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 18; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 11); \ } \ rle_z_count = 0; \ } \ } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) \ { \ bit_buffer |= (((mz_uint64)(b)) << bits_in); \ bits_in += (l); \ } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && // MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output // buffer and send a raw block instead. if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS( d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed // block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN( (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const mz_uint16 *)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && \ (d->m_dict[probe_pos + match_len - 1] == c1)) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better // register utilization. Intended for applications where raw throughput is // valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to // TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output // buffer. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; // level may actually range from [0,10] (10 is a "hidden" max level, where we // want a bit more compression and it's fine if throughput to fall off a cliff // on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #endif // MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public // domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files // generated by this function pass pngcheck. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was // defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data tdefl_init( pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41, 0x54}; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); for (i = 0; i < 4; ++i, c <<= 8) ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter( "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); for (i = 0; i < 4; ++i, c <<= 8) (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's // where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #error "No arvhive APIs" #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE *pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler // alignment and platform endian issues, miniz.c doesn't use structs for any of // this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) \ do { \ mz_uint32 t = a; \ a = b; \ b = t; \ } \ MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), // but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename( mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for (;;) { if ((child = (root << 1) + 1) >= size) break; child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (;;) { if ((child = (root << 1) + 1) >= end) break; child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first // 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; // Find the end of central directory record by scanning the file from the end // towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE; pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another // heap block to hold the unsorted central dir file record offsets, and // another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return MZ_FALSE; // Now create an index into the central directory file records, do some // basic sanity checking on each record, and check for zip64 entries (which // are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return MZ_FALSE; n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh( mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } // Bugfix: This code was also checking if the internal attribute was non-zero, // which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the // low 16-bits, so check for the DOS directory flag and ignore the source OS // ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) return MZ_TRUE; return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) return MZ_FALSE; // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare( const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) l = m + 1; else h = m - 1; } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); name_len = strlen(pName); if (name_len > 0xFFFF) return -1; comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) return MZ_FALSE; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return MZ_FALSE; return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input // buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) return NULL; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; // Decompress the file either directly from memory or from a file input // buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32( file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; status = mz_zip_reader_extract_to_callback( pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc( pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; // No sense in trying to write to an archive that's already at the support max // size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is // NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can // resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the // user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; // Start writing new files at the archive's current central directory // location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir( mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_central_dir_header( pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start // with a forward slash, cannot contain a drive letter, and cannot use // DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment( mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return MZ_FALSE; // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) return MZ_FALSE; } // Try to do any allocations before writing to the archive, so if an // allocation fails the file remains unmodified. (A good idea if we're doing // an in-place modification.) if ((!mz_zip_array_ensure_room( pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) return MZ_FALSE; pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return MZ_FALSE; MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for (;;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; uncomp_crc32 = (mz_uint32)mz_crc32( uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer( pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) return MZ_FALSE; while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE; orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back( pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE; #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE; if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid // central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) return NULL; MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #ifdef _MSC_VER #pragma warning(pop) #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */ // ---------------------- end of miniz ---------------------------------------- #ifdef __clang__ #pragma clang diagnostic pop #endif } // namespace miniz #else // Reuse MINIZ_LITTE_ENDIAN macro #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #endif // TINYEXR_USE_MINIZ // static bool IsBigEndian(void) { // union { // unsigned int i; // char c[4]; // } bint = {0x01020304}; // // return bint.c[0] == 1; //} static void SetErrorMessage(const std::string &msg, const char **err) { if (err) { #ifdef _WIN32 (*err) = _strdup(msg.c_str()); #else (*err) = strdup(msg.c_str()); #endif } } static const int kEXRVersionSize = 8; static void cpy2(unsigned short *dst_val, const unsigned short *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; } static void swap2(unsigned short *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned short tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[1]; dst[1] = src[0]; #endif } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif static void cpy4(int *dst_val, const int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(unsigned int *dst_val, const unsigned int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(float *dst_val, const float *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __GNUC__ #pragma GCC diagnostic pop #endif static void swap4(unsigned int *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } #if 0 static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; } #endif static void swap8(tinyexr::tinyexr_uint64 *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else tinyexr::tinyexr_uint64 tmp = (*val); unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; #endif } // https://gist.github.com/rygorous/2156668 // Reuse MINIZ_LITTLE_ENDIAN flag from miniz. union FP32 { unsigned int u; float f; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 23; unsigned int Exponent : 8; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 8; unsigned int Mantissa : 23; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif union FP16 { unsigned short u; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 10; unsigned int Exponent : 5; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 5; unsigned int Mantissa : 10; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic pop #endif static FP32 half_to_float(FP16 h) { static const FP32 magic = {113 << 23}; static const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift FP32 o; o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits unsigned int exp_ = shifted_exp & o.u; // just the exponent o.u += (127 - 15) << 23; // exponent adjust // handle exponent special cases if (exp_ == shifted_exp) // Inf/NaN? o.u += (128 - 16) << 23; // extra exp adjust else if (exp_ == 0) // Zero/Denormal? { o.u += 1 << 23; // extra exp adjust o.f -= magic.f; // renormalize } o.u |= (h.u & 0x8000U) << 16U; // sign bit return o; } static FP16 float_to_half_full(FP32 f) { FP16 o = {0}; // Based on ISPC reference code (with minor modifications) if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow) o.s.Exponent = 0; else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set) { o.s.Exponent = 31; o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf } else // Normalized number { // Exponent unbias the single, then bias the halfp int newexp = f.s.Exponent - 127 + 15; if (newexp >= 31) // Overflow, return signed infinity o.s.Exponent = 31; else if (newexp <= 0) // Underflow { if ((14 - newexp) <= 24) // Mantissa might be non-zero { unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit o.s.Mantissa = mant >> (14 - newexp); if ((mant >> (13 - newexp)) & 1) // Check for rounding o.u++; // Round, might overflow into exp bit, but this is OK } } else { o.s.Exponent = static_cast<unsigned int>(newexp); o.s.Mantissa = f.s.Mantissa >> 13; if (f.s.Mantissa & 0x1000) // Check for rounding o.u++; // Round, might overflow to inf, this is OK } } o.s.Sign = f.s.Sign; return o; } // NOTE: From OpenEXR code // #define IMF_INCREASING_Y 0 // #define IMF_DECREASING_Y 1 // #define IMF_RAMDOM_Y 2 // // #define IMF_NO_COMPRESSION 0 // #define IMF_RLE_COMPRESSION 1 // #define IMF_ZIPS_COMPRESSION 2 // #define IMF_ZIP_COMPRESSION 3 // #define IMF_PIZ_COMPRESSION 4 // #define IMF_PXR24_COMPRESSION 5 // #define IMF_B44_COMPRESSION 6 // #define IMF_B44A_COMPRESSION 7 #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #endif static const char *ReadString(std::string *s, const char *ptr, size_t len) { // Read untile NULL(\0). const char *p = ptr; const char *q = ptr; while ((size_t(q - ptr) < len) && (*q) != 0) { q++; } if (size_t(q - ptr) >= len) { (*s) = std::string(); return NULL; } (*s) = std::string(p, q); return q + 1; // skip '\0' } static bool ReadAttribute(std::string *name, std::string *type, std::vector<unsigned char> *data, size_t *marker_size, const char *marker, size_t size) { size_t name_len = strnlen(marker, size); if (name_len == size) { // String does not have a terminating character. return false; } *name = std::string(marker, name_len); marker += name_len + 1; size -= name_len + 1; size_t type_len = strnlen(marker, size); if (type_len == size) { return false; } *type = std::string(marker, type_len); marker += type_len + 1; size -= type_len + 1; if (size < sizeof(uint32_t)) { return false; } uint32_t data_len; memcpy(&data_len, marker, sizeof(uint32_t)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len == 0) { if ((*type).compare("string") == 0) { // Accept empty string attribute. marker += sizeof(uint32_t); size -= sizeof(uint32_t); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t); data->resize(1); (*data)[0] = '\0'; return true; } else { return false; } } marker += sizeof(uint32_t); size -= sizeof(uint32_t); if (size < data_len) { return false; } data->resize(static_cast<size_t>(data_len)); memcpy(&data->at(0), marker, static_cast<size_t>(data_len)); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len; return true; } static void WriteAttributeToMemory(std::vector<unsigned char> *out, const char *name, const char *type, const unsigned char *data, int len) { out->insert(out->end(), name, name + strlen(name) + 1); out->insert(out->end(), type, type + strlen(type) + 1); int outLen = len; tinyexr::swap4(reinterpret_cast<unsigned int *>(&outLen)); out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen), reinterpret_cast<unsigned char *>(&outLen) + sizeof(int)); out->insert(out->end(), data, data + len); } typedef struct { std::string name; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } ChannelInfo; typedef struct { std::vector<tinyexr::ChannelInfo> channels; std::vector<EXRAttribute> attributes; int data_window[4]; int line_order; int display_window[4]; float screen_window_center[2]; float screen_window_width; float pixel_aspect_ratio; int chunk_count; // Tiled format int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; unsigned int header_len; int compression_type; void clear() { channels.clear(); attributes.clear(); data_window[0] = 0; data_window[1] = 0; data_window[2] = 0; data_window[3] = 0; line_order = 0; display_window[0] = 0; display_window[1] = 0; display_window[2] = 0; display_window[3] = 0; screen_window_center[0] = 0.0f; screen_window_center[1] = 0.0f; screen_window_width = 0.0f; pixel_aspect_ratio = 0.0f; chunk_count = 0; // Tiled format tile_size_x = 0; tile_size_y = 0; tile_level_mode = 0; tile_rounding_mode = 0; header_len = 0; compression_type = 0; } } HeaderInfo; static bool ReadChannelInfo(std::vector<ChannelInfo> &channels, const std::vector<unsigned char> &data) { const char *p = reinterpret_cast<const char *>(&data.at(0)); for (;;) { if ((*p) == 0) { break; } ChannelInfo info; tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) - (p - reinterpret_cast<const char *>(data.data())); if (data_len < 0) { return false; } p = ReadString(&info.name, p, size_t(data_len)); if ((p == NULL) && (info.name.empty())) { // Buffer overrun. Issue #51. return false; } const unsigned char *data_end = reinterpret_cast<const unsigned char *>(p) + 16; if (data_end >= (data.data() + data.size())) { return false; } memcpy(&info.pixel_type, p, sizeof(int)); p += 4; info.p_linear = static_cast<unsigned char>(p[0]); // uchar p += 1 + 3; // reserved: uchar[3] memcpy(&info.x_sampling, p, sizeof(int)); // int p += 4; memcpy(&info.y_sampling, p, sizeof(int)); // int p += 4; tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.y_sampling)); channels.push_back(info); } return true; } static void WriteChannelInfo(std::vector<unsigned char> &data, const std::vector<ChannelInfo> &channels) { size_t sz = 0; // Calculate total size. for (size_t c = 0; c < channels.size(); c++) { sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0 sz += 16; // 4 * int } data.resize(sz + 1); unsigned char *p = &data.at(0); for (size_t c = 0; c < channels.size(); c++) { memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str())); p += strlen(channels[c].name.c_str()); (*p) = '\0'; p++; int pixel_type = channels[c].pixel_type; int x_sampling = channels[c].x_sampling; int y_sampling = channels[c].y_sampling; tinyexr::swap4(reinterpret_cast<unsigned int *>(&pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y_sampling)); memcpy(p, &pixel_type, sizeof(int)); p += sizeof(int); (*p) = channels[c].p_linear; p += 4; memcpy(p, &x_sampling, sizeof(int)); p += sizeof(int); memcpy(p, &y_sampling, sizeof(int)); p += sizeof(int); } (*p) = '\0'; } static void CompressZip(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } #if TINYEXR_USE_MINIZ // // Compress the data using miniz // miniz::mz_ulong outSize = miniz::mz_compressBound(src_size); int ret = miniz::mz_compress( dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)), src_size); assert(ret == miniz::MZ_OK); (void)ret; compressedSize = outSize; #else uLong outSize = compressBound(static_cast<uLong>(src_size)); int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)), src_size); assert(ret == Z_OK); compressedSize = outSize; #endif // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressZip(unsigned char *dst, unsigned long *uncompressed_size /* inout */, const unsigned char *src, unsigned long src_size) { if ((*uncompressed_size) == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } std::vector<unsigned char> tmpBuf(*uncompressed_size); #if TINYEXR_USE_MINIZ int ret = miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (miniz::MZ_OK != ret) { return false; } #else int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (Z_OK != ret) { return false; } #endif // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size); while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (*uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + (*uncompressed_size); for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } // RLE code from OpenEXR -------------------------------------- #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif const int MIN_RUN_LENGTH = 3; const int MAX_RUN_LENGTH = 127; // // Compress an array of bytes, using run-length encoding, // and return the length of the compressed data. // static int rleCompress(int inLength, const char in[], signed char out[]) { const char *inEnd = in + inLength; const char *runStart = in; const char *runEnd = in + 1; signed char *outWrite = out; while (runStart < inEnd) { while (runEnd < inEnd && *runStart == *runEnd && runEnd - runStart - 1 < MAX_RUN_LENGTH) { ++runEnd; } if (runEnd - runStart >= MIN_RUN_LENGTH) { // // Compressable run // *outWrite++ = static_cast<char>(runEnd - runStart) - 1; *outWrite++ = *(reinterpret_cast<const signed char *>(runStart)); runStart = runEnd; } else { // // Uncompressable run // while (runEnd < inEnd && ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) || (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) && runEnd - runStart < MAX_RUN_LENGTH) { ++runEnd; } *outWrite++ = static_cast<char>(runStart - runEnd); while (runStart < runEnd) { *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++)); } } ++runEnd; } return static_cast<int>(outWrite - out); } // // Uncompress an array of bytes compressed with rleCompress(). // Returns the length of the oncompressed data, or 0 if the // length of the uncompressed data would be more than maxLength. // static int rleUncompress(int inLength, int maxLength, const signed char in[], char out[]) { char *outStart = out; while (inLength > 0) { if (*in < 0) { int count = -(static_cast<int>(*in++)); inLength -= count + 1; // Fixes #116: Add bounds check to in buffer. if ((0 > (maxLength -= count)) || (inLength < 0)) return 0; memcpy(out, in, count); out += count; in += count; } else { int count = *in++; inLength -= 2; if (0 > (maxLength -= count + 1)) return 0; memset(out, *reinterpret_cast<const char *>(in), count + 1); out += count + 1; in++; } } return static_cast<int>(out - outStart); } #ifdef __clang__ #pragma clang diagnostic pop #endif // End of RLE code from OpenEXR ----------------------------------- static void CompressRle(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } // outSize will be (srcSiz * 3) / 2 at max. int outSize = rleCompress(static_cast<int>(src_size), reinterpret_cast<const char *>(&tmpBuf.at(0)), reinterpret_cast<signed char *>(dst)); assert(outSize > 0); compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressRle(unsigned char *dst, const unsigned long uncompressed_size, const unsigned char *src, unsigned long src_size) { if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } // Workaround for issue #112. // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`. if (src_size <= 2) { return false; } std::vector<unsigned char> tmpBuf(uncompressed_size); int ret = rleUncompress(static_cast<int>(src_size), static_cast<int>(uncompressed_size), reinterpret_cast<const signed char *>(src), reinterpret_cast<char *>(&tmpBuf.at(0))); if (ret != static_cast<int>(uncompressed_size)) { return false; } // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + uncompressed_size; while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + uncompressed_size; for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } #if TINYEXR_USE_PIZ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif // // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp // // ----------------------------------------------------------------- // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC) // (3 clause BSD license) // struct PIZChannelData { unsigned short *start; unsigned short *end; int nx; int ny; int ys; int size; }; //----------------------------------------------------------------------------- // // 16-bit Haar Wavelet encoding and decoding // // The source code in this file is derived from the encoding // and decoding routines written by Christian Rouet for his // PIZ image file format. // //----------------------------------------------------------------------------- // // Wavelet basis functions without modulo arithmetic; they produce // the best compression ratios when the wavelet-transformed data are // Huffman-encoded, but the wavelet transform works only for 14-bit // data (untransformed data values must be less than (1 << 14)). // inline void wenc14(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { short as = static_cast<short>(a); short bs = static_cast<short>(b); short ms = (as + bs) >> 1; short ds = as - bs; l = static_cast<unsigned short>(ms); h = static_cast<unsigned short>(ds); } inline void wdec14(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { short ls = static_cast<short>(l); short hs = static_cast<short>(h); int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); short as = static_cast<short>(ai); short bs = static_cast<short>(ai - hi); a = static_cast<unsigned short>(as); b = static_cast<unsigned short>(bs); } // // Wavelet basis functions with modulo arithmetic; they work with full // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't // compress the data quite as well. // const int NBITS = 16; const int A_OFFSET = 1 << (NBITS - 1); const int M_OFFSET = 1 << (NBITS - 1); const int MOD_MASK = (1 << NBITS) - 1; inline void wenc16(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { int ao = (a + A_OFFSET) & MOD_MASK; int m = ((ao + b) >> 1); int d = ao - b; if (d < 0) m = (m + M_OFFSET) & MOD_MASK; d &= MOD_MASK; l = static_cast<unsigned short>(m); h = static_cast<unsigned short>(d); } inline void wdec16(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; b = static_cast<unsigned short>(bb); a = static_cast<unsigned short>(aa); } // // 2D Wavelet encoding: // static void wav2Encode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; // == 1 << level int p2 = 2; // == 1 << (level+1) // // Hierachical loop on smaller dimension n // while (p2 <= n) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet encoding // if (w14) { wenc14(*px, *p01, i00, i01); wenc14(*p10, *p11, i10, i11); wenc14(i00, i10, *px, *p10); wenc14(i01, i11, *p01, *p11); } else { wenc16(*px, *p01, i00, i01); wenc16(*p10, *p11, i10, i11); wenc16(i00, i10, *px, *p10); wenc16(i01, i11, *p01, *p11); } } // // Encode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wenc14(*px, *p10, i00, *p10); else wenc16(*px, *p10, i00, *p10); *px = i00; } } // // Encode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wenc14(*px, *p01, i00, *p01); else wenc16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p = p2; p2 <<= 1; } } // // 2D Wavelet decoding: // static void wav2Decode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; // // Search max level // while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; // // Hierarchical loop on smaller dimension n // while (p >= 1) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet decoding // if (w14) { wdec14(*px, *p10, i00, i10); wdec14(*p01, *p11, i01, i11); wdec14(i00, i01, *px, *p01); wdec14(i10, i11, *p10, *p11); } else { wdec16(*px, *p10, i00, i10); wdec16(*p01, *p11, i01, i11); wdec16(i00, i01, *px, *p01); wdec16(i10, i11, *p10, *p11); } } // // Decode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wdec14(*px, *p10, i00, *p10); else wdec16(*px, *p10, i00, *p10); *px = i00; } } // // Decode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wdec14(*px, *p01, i00, *p01); else wdec16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p2 = p; p >>= 1; } } //----------------------------------------------------------------------------- // // 16-bit Huffman compression and decompression. // // The source code in this file is derived from the 8-bit // Huffman compression and decompression routines written // by Christian Rouet for his PIZ image file format. // //----------------------------------------------------------------------------- // Adds some modification for tinyexr. const int HUF_ENCBITS = 16; // literal (value) bit length const int HUF_DECBITS = 14; // decoding bit size (>= 8) const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size const int HUF_DECMASK = HUF_DECSIZE - 1; struct HufDec { // short code long code //------------------------------- int len : 8; // code length 0 int lit : 24; // lit p size int *p; // 0 lits }; inline long long hufLength(long long code) { return code & 63; } inline long long hufCode(long long code) { return code >> 6; } inline void outputBits(int nBits, long long bits, long long &c, int &lc, char *&out) { c <<= nBits; lc += nBits; c |= bits; while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8))); } inline long long getBits(int nBits, long long &c, int &lc, const char *&in) { while (lc < nBits) { c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++)); lc += 8; } lc -= nBits; return (c >> lc) & ((1 << nBits) - 1); } // // ENCODING TABLE BUILDING & (UN)PACKING // // // Build a "canonical" Huffman code table: // - for each (uncompressed) symbol, hcode contains the length // of the corresponding code (in the compressed data) // - canonical codes are computed and stored in hcode // - the rules for constructing canonical codes are as follows: // * shorter codes (if filled with zeroes to the right) // have a numerically higher value than longer codes // * for codes with the same length, numerical values // increase with numerical symbol values // - because the canonical code table can be constructed from // symbol lengths alone, the code table can be transmitted // without sending the actual code values // - see http://www.compressconsult.com/huffman/ // static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) { long long n[59]; // // For each i from 0 through 58, count the // number of different codes of length i, and // store the count in n[i]. // for (int i = 0; i <= 58; ++i) n[i] = 0; for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; // // For each i from 58 through 1, compute the // numerically lowest code with length i, and // store that code in n[i]. // long long c = 0; for (int i = 58; i > 0; --i) { long long nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } // // hcode[i] contains the length, l, of the // code for symbol i. Assign the next available // code of length l to the symbol and store both // l and the code in hcode[i]. // for (int i = 0; i < HUF_ENCSIZE; ++i) { int l = static_cast<int>(hcode[i]); if (l > 0) hcode[i] = l | (n[l]++ << 6); } } // // Compute Huffman codes (based on frq input) and store them in frq: // - code structure is : [63:lsb - 6:msb] | [5-0: bit length]; // - max code length is 58 bits; // - codes outside the range [im-iM] have a null length (unused values); // - original frequencies are destroyed; // - encoding tables are used by hufEncode() and hufBuildDecTable(); // struct FHeapCompare { bool operator()(long long *a, long long *b) { return *a > *b; } }; static void hufBuildEncTable( long long *frq, // io: input frequencies [HUF_ENCSIZE], output table int *im, // o: min frq index int *iM) // o: max frq index { // // This function assumes that when it is called, array frq // indicates the frequency of all possible symbols in the data // that are to be Huffman-encoded. (frq[i] contains the number // of occurrences of symbol i in the data.) // // The loop below does three things: // // 1) Finds the minimum and maximum indices that point // to non-zero entries in frq: // // frq[im] != 0, and frq[i] == 0 for all i < im // frq[iM] != 0, and frq[i] == 0 for all i > iM // // 2) Fills array fHeap with pointers to all non-zero // entries in frq. // // 3) Initializes array hlink such that hlink[i] == i // for all array entries. // std::vector<int> hlink(HUF_ENCSIZE); std::vector<long long *> fHeap(HUF_ENCSIZE); *im = 0; while (!frq[*im]) (*im)++; int nf = 0; for (int i = *im; i < HUF_ENCSIZE; i++) { hlink[i] = i; if (frq[i]) { fHeap[nf] = &frq[i]; nf++; *iM = i; } } // // Add a pseudo-symbol, with a frequency count of 1, to frq; // adjust the fHeap and hlink array accordingly. Function // hufEncode() uses the pseudo-symbol for run-length encoding. // (*iM)++; frq[*iM] = 1; fHeap[nf] = &frq[*iM]; nf++; // // Build an array, scode, such that scode[i] contains the number // of bits assigned to symbol i. Conceptually this is done by // constructing a tree whose leaves are the symbols with non-zero // frequency: // // Make a heap that contains all symbols with a non-zero frequency, // with the least frequent symbol on top. // // Repeat until only one symbol is left on the heap: // // Take the two least frequent symbols off the top of the heap. // Create a new node that has first two nodes as children, and // whose frequency is the sum of the frequencies of the first // two nodes. Put the new node back into the heap. // // The last node left on the heap is the root of the tree. For each // leaf node, the distance between the root and the leaf is the length // of the code for the corresponding symbol. // // The loop below doesn't actually build the tree; instead we compute // the distances of the leaves from the root on the fly. When a new // node is added to the heap, then that node's descendants are linked // into a single linear list that starts at the new node, and the code // lengths of the descendants (that is, their distance from the root // of the tree) are incremented by one. // std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); std::vector<long long> scode(HUF_ENCSIZE); memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE); while (nf > 1) { // // Find the indices, mm and m, of the two smallest non-zero frq // values in fHeap, add the smallest frq to the second-smallest // frq, and remove the smallest frq value from fHeap. // int mm = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); --nf; int m = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); frq[m] += frq[mm]; std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); // // The entries in scode are linked into lists with the // entries in hlink serving as "next" pointers and with // the end of a list marked by hlink[j] == j. // // Traverse the lists that start at scode[m] and scode[mm]. // For each element visited, increment the length of the // corresponding code by one bit. (If we visit scode[j] // during the traversal, then the code for symbol j becomes // one bit longer.) // // Merge the lists that start at scode[m] and scode[mm] // into a single list that starts at scode[m]. // // // Add a bit to all codes in the first list. // for (int j = m;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) { // // Merge the two lists. // hlink[j] = mm; break; } } // // Add a bit to all codes in the second list // for (int j = mm;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) break; } } // // Build a canonical Huffman code table, replacing the code // lengths in scode with (code, code length) pairs. Copy the // code table from scode into frq. // hufCanonicalCodeTable(scode.data()); memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE); } // // Pack an encoding table: // - only code lengths, not actual codes, are stored // - runs of zeroes are compressed as follows: // // unpacked packed // -------------------------------- // 1 zero 0 (6 bits) // 2 zeroes 59 // 3 zeroes 60 // 4 zeroes 61 // 5 zeroes 62 // n zeroes (6 or more) 63 n-6 (6 + 8 bits) // const int SHORT_ZEROCODE_RUN = 59; const int LONG_ZEROCODE_RUN = 63; const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN; static void hufPackEncTable( const long long *hcode, // i : encoding table [HUF_ENCSIZE] int im, // i : min hcode index int iM, // i : max hcode index char **pcode) // o: ptr to packed table (updated) { char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { int l = hufLength(hcode[im]); if (l == 0) { int zerun = 1; while ((im < iM) && (zerun < LONGEST_LONG_RUN)) { if (hufLength(hcode[im + 1]) > 0) break; im++; zerun++; } if (zerun >= 2) { if (zerun >= SHORTEST_LONG_RUN) { outputBits(6, LONG_ZEROCODE_RUN, c, lc, p); outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p); } else { outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p); } continue; } } outputBits(6, l, c, lc, p); } if (lc > 0) *p++ = (unsigned char)(c << (8 - lc)); *pcode = p; } // // Unpack an encoding table packed by hufPackEncTable(): // static bool hufUnpackEncTable( const char **pcode, // io: ptr to packed table (updated) int ni, // i : input size (in bytes) int im, // i : min hcode index int iM, // i : max hcode index long long *hcode) // o: encoding table [HUF_ENCSIZE] { memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE); const char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { if (p - *pcode >= ni) { return false; } long long l = hcode[im] = getBits(6, c, lc, p); // code length if (l == (long long)LONG_ZEROCODE_RUN) { if (p - *pcode > ni) { return false; } int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } else if (l >= (long long)SHORT_ZEROCODE_RUN) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } } *pcode = const_cast<char *>(p); hufCanonicalCodeTable(hcode); return true; } // // DECODING TABLE BUILDING // // // Clear a newly allocated decoding table so that it contains only zeroes. // static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller) // decoding table [HUF_DECSIZE] { for (int i = 0; i < HUF_DECSIZE; i++) { hdecod[i].len = 0; hdecod[i].lit = 0; hdecod[i].p = NULL; } // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE); } // // Build a decoding hash table based on the encoding table hcode: // - short codes (<= HUF_DECBITS) are resolved with a single table access; // - long code entry allocations are not optimized, because long codes are // unfrequent; // - decoding tables are used by hufDecode(); // static bool hufBuildDecTable(const long long *hcode, // i : encoding table int im, // i : min index in hcode int iM, // i : max index in hcode HufDec *hdecod) // o: (allocated by caller) // decoding table [HUF_DECSIZE] { // // Init hashtable & loop on all codes. // Assumes that hufClearDecTable(hdecod) has already been called. // for (; im <= iM; im++) { long long c = hufCode(hcode[im]); int l = hufLength(hcode[im]); if (c >> l) { // // Error: c is supposed to be an l-bit code, // but c contains a value that is greater // than the largest l-bit number. // // invalidTableEntry(); return false; } if (l > HUF_DECBITS) { // // Long code: add a secondary entry // HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) { // // Error: a short code has already // been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->lit++; if (pl->p) { int *p = pl->p; pl->p = new int[pl->lit]; for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i]; delete[] p; } else { pl->p = new int[1]; } pl->p[pl->lit - 1] = im; } else if (l) { // // Short code: init all primary entries // HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) { // // Error: a short code or a long code has // already been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->len = l; pl->lit = im; } } } return true; } // // Free the long code entries of a decoding table built by hufBuildDecTable() // static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table { for (int i = 0; i < HUF_DECSIZE; i++) { if (hdecod[i].p) { delete[] hdecod[i].p; hdecod[i].p = 0; } } } // // ENCODING // inline void outputCode(long long code, long long &c, int &lc, char *&out) { outputBits(hufLength(code), hufCode(code), c, lc, out); } inline void sendCode(long long sCode, int runCount, long long runCode, long long &c, int &lc, char *&out) { // // Output a run of runCount instances of the symbol sCount. // Output the symbols explicitly, or if that is shorter, output // the sCode symbol once followed by a runCode symbol and runCount // expressed as an 8-bit number. // if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) { outputCode(sCode, c, lc, out); outputCode(runCode, c, lc, out); outputBits(8, runCount, c, lc, out); } else { while (runCount-- >= 0) outputCode(sCode, c, lc, out); } } // // Encode (compress) ni values based on the Huffman encoding table hcode: // static int hufEncode // return: output size (in bits) (const long long *hcode, // i : encoding table const unsigned short *in, // i : uncompressed input buffer const int ni, // i : input buffer size (in bytes) int rlc, // i : rl code char *out) // o: compressed output buffer { char *outStart = out; long long c = 0; // bits not yet written to out int lc = 0; // number of valid bits in c (LSB) int s = in[0]; int cs = 0; // // Loop on input values // for (int i = 1; i < ni; i++) { // // Count same values or send code // if (s == in[i] && cs < 255) { cs++; } else { sendCode(hcode[s], cs, hcode[rlc], c, lc, out); cs = 0; } s = in[i]; } // // Send remaining code // sendCode(hcode[s], cs, hcode[rlc], c, lc, out); if (lc) *out = (c << (8 - lc)) & 0xff; return (out - outStart) * 8 + lc; } // // DECODING // // // In order to force the compiler to inline them, // getChar() and getCode() are implemented as macros // instead of "inline" functions. // #define getChar(c, lc, in) \ { \ c = (c << 8) | *(unsigned char *)(in++); \ lc += 8; \ } #if 0 #define getCode(po, rlc, c, lc, in, out, ob, oe) \ { \ if (po == rlc) { \ if (lc < 8) getChar(c, lc, in); \ \ lc -= 8; \ \ unsigned char cs = (c >> lc); \ \ if (out + cs > oe) return false; \ \ /* TinyEXR issue 78 */ \ unsigned short s = out[-1]; \ \ while (cs-- > 0) *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return false; \ } \ } #else static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in, const char *in_end, unsigned short *&out, const unsigned short *ob, const unsigned short *oe) { (void)ob; if (po == rlc) { if (lc < 8) { /* TinyEXR issue 78 */ if ((in + 1) >= in_end) { return false; } getChar(c, lc, in); } lc -= 8; unsigned char cs = (c >> lc); if (out + cs > oe) return false; // Bounds check for safety // Issue 100. if ((out - 1) < ob) return false; unsigned short s = out[-1]; while (cs-- > 0) *out++ = s; } else if (out < oe) { *out++ = po; } else { return false; } return true; } #endif // // Decode (uncompress) ni bits based on encoding & decoding tables: // static bool hufDecode(const long long *hcode, // i : encoding table const HufDec *hdecod, // i : decoding table const char *in, // i : compressed input buffer int ni, // i : input size (in bits) int rlc, // i : run-length code int no, // i : expected output size (in bytes) unsigned short *out) // o: uncompressed output buffer { long long c = 0; int lc = 0; unsigned short *outb = out; // begin unsigned short *oe = out + no; // end const char *ie = in + (ni + 7) / 8; // input byte size // // Loop on input bytes // while (in < ie) { getChar(c, lc, in); // // Access decoding table // while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { // // Get short code // lc -= pl.len; // std::cout << "lit = " << pl.lit << std::endl; // std::cout << "rlc = " << rlc << std::endl; // std::cout << "c = " << c << std::endl; // std::cout << "lc = " << lc << std::endl; // std::cout << "in = " << in << std::endl; // std::cout << "out = " << out << std::endl; // std::cout << "oe = " << oe << std::endl; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { if (!pl.p) { return false; } // invalidCode(); // wrong code // // Search long code // int j; for (j = 0; j < pl.lit; j++) { int l = hufLength(hcode[pl.p[j]]); while (lc < l && in < ie) // get more bits getChar(c, lc, in); if (lc >= l) { if (hufCode(hcode[pl.p[j]]) == ((c >> (lc - l)) & (((long long)(1) << l) - 1))) { // // Found : get long code // lc -= l; if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) { return false; } break; } } } if (j == pl.lit) { return false; // invalidCode(); // Not found } } } } // // Get remaining (short) codes // int i = (8 - ni) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { return false; // invalidCode(); // wrong (long) code } } if (out - outb != no) { return false; } // notEnoughData (); return true; } static void countFrequencies(std::vector<long long> &freq, const unsigned short data[/*n*/], int n) { for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0; for (int i = 0; i < n; ++i) ++freq[data[i]]; } static void writeUInt(char buf[4], unsigned int i) { unsigned char *b = (unsigned char *)buf; b[0] = i; b[1] = i >> 8; b[2] = i >> 16; b[3] = i >> 24; } static unsigned int readUInt(const char buf[4]) { const unsigned char *b = (const unsigned char *)buf; return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) | ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000); } // // EXTERNAL INTERFACE // static int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) { if (nRaw == 0) return 0; std::vector<long long> freq(HUF_ENCSIZE); countFrequencies(freq, raw, nRaw); int im = 0; int iM = 0; hufBuildEncTable(freq.data(), &im, &iM); char *tableStart = compressed + 20; char *tableEnd = tableStart; hufPackEncTable(freq.data(), im, iM, &tableEnd); int tableLength = tableEnd - tableStart; char *dataStart = tableEnd; int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart); int data_length = (nBits + 7) / 8; writeUInt(compressed, im); writeUInt(compressed + 4, iM); writeUInt(compressed + 8, tableLength); writeUInt(compressed + 12, nBits); writeUInt(compressed + 16, 0); // room for future extensions return dataStart + data_length - compressed; } static bool hufUncompress(const char compressed[], int nCompressed, std::vector<unsigned short> *raw) { if (nCompressed == 0) { if (raw->size() != 0) return false; return false; } int im = readUInt(compressed); int iM = readUInt(compressed + 4); // int tableLength = readUInt (compressed + 8); int nBits = readUInt(compressed + 12); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false; const char *ptr = compressed + 20; // // Fast decoder needs at least 2x64-bits of compressed data, and // needs to be run-able on this platform. Otherwise, fall back // to the original decoder // // if (FastHufDecoder::enabled() && nBits > 128) //{ // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); //} // else { std::vector<long long> freq(HUF_ENCSIZE); std::vector<HufDec> hdec(HUF_DECSIZE); hufClearDecTable(&hdec.at(0)); hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM, &freq.at(0)); { if (nBits > 8 * (nCompressed - (ptr - compressed))) { return false; } hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0)); hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(), raw->data()); } // catch (...) //{ // hufFreeDecTable (hdec); // throw; //} hufFreeDecTable(&hdec.at(0)); } return true; } // // Functions to compress the range of values in the pixel data // const int USHORT_RANGE = (1 << 16); const int BITMAP_SIZE = (USHORT_RANGE >> 3); static void bitmapFromData(const unsigned short data[/*nData*/], int nData, unsigned char bitmap[BITMAP_SIZE], unsigned short &minNonZero, unsigned short &maxNonZero) { for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0; for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7)); bitmap[0] &= ~1; // zero is not explicitly stored in // the bitmap; we assume that the // data always contain zeroes minNonZero = BITMAP_SIZE - 1; maxNonZero = 0; for (int i = 0; i < BITMAP_SIZE; ++i) { if (bitmap[i]) { if (minNonZero > i) minNonZero = i; if (maxNonZero < i) maxNonZero = i; } } } static unsigned short forwardLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[i] = k++; else lut[i] = 0; } return k - 1; // maximum value stored in lut[], } // i.e. number of ones in bitmap minus 1 static unsigned short reverseLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; } int n = k - 1; while (k < USHORT_RANGE) lut[k++] = 0; return n; // maximum k where lut[k] is non-zero, } // i.e. number of ones in bitmap minus 1 static void applyLut(const unsigned short lut[USHORT_RANGE], unsigned short data[/*nData*/], int nData) { for (int i = 0; i < nData; ++i) data[i] = lut[data[i]]; } #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #ifdef _MSC_VER #pragma warning(pop) #endif static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize, const unsigned char *inPtr, size_t inSize, const std::vector<ChannelInfo> &channelInfo, int data_width, int num_lines) { std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif // Assume `inSize` is multiple of 2 or 4. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short)); std::vector<PIZChannelData> channelData(channelInfo.size()); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t c = 0; c < channelData.size(); c++) { PIZChannelData &cd = channelData[c]; cd.start = tmpBufferEnd; cd.end = cd.start; cd.nx = data_width; cd.ny = num_lines; // cd.ys = c.channel().ySampling; size_t pixelSize = sizeof(int); // UINT and FLOAT if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } cd.size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += cd.nx * cd.ny * cd.size; } const unsigned char *ptr = inPtr; for (int y = 0; y < num_lines; ++y) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(cd.end, ptr, n * sizeof(unsigned short)); ptr += n * sizeof(unsigned short); cd.end += n; } } bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), bitmap.data(), minNonZero, maxNonZero); std::vector<unsigned short> lut(USHORT_RANGE); unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data()); applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size())); // // Store range compression info in _outBuffer // char *buf = reinterpret_cast<char *>(outPtr); memcpy(buf, &minNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); memcpy(buf, &maxNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); if (minNonZero <= maxNonZero) { memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero), maxNonZero - minNonZero + 1); buf += maxNonZero - minNonZero + 1; } // // Apply wavelet encoding // for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Apply Huffman encoding; append the result to _outBuffer // // length header(4byte), then huff data. Initialize length header with zero, // then later fill it by `length`. char *lengthPtr = buf; int zero = 0; memcpy(buf, &zero, sizeof(int)); buf += sizeof(int); int length = hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf); memcpy(lengthPtr, &length, sizeof(int)); (*outSize) = static_cast<unsigned int>( (reinterpret_cast<unsigned char *>(buf) - outPtr) + static_cast<unsigned int>(length)); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if ((*outSize) >= inSize) { (*outSize) = static_cast<unsigned int>(inSize); memcpy(outPtr, inPtr, inSize); } return true; } static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr, size_t tmpBufSize, size_t inLen, int num_channels, const EXRChannelInfo *channels, int data_width, int num_lines) { if (inLen == tmpBufSize) { // Data is not compressed(Issue 40). memcpy(outPtr, inPtr, inLen); return true; } std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif memset(bitmap.data(), 0, BITMAP_SIZE); const unsigned char *ptr = inPtr; // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr)); tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr)); // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2)); tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2)); ptr += 4; if (maxNonZero >= BITMAP_SIZE) { return false; } if (minNonZero <= maxNonZero) { memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr, maxNonZero - minNonZero + 1); ptr += maxNonZero - minNonZero + 1; } std::vector<unsigned short> lut(USHORT_RANGE); memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE); unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data()); // // Huffman decoding // int length; // length = *(reinterpret_cast<const int *>(ptr)); tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr)); ptr += sizeof(int); if (size_t((ptr - inPtr) + length) > inLen) { return false; } std::vector<unsigned short> tmpBuffer(tmpBufSize); hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer); // // Wavelet decoding // std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels)); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) { const EXRChannelInfo &chan = channels[i]; size_t pixelSize = sizeof(int); // UINT and FLOAT if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } channelData[i].start = tmpBufferEnd; channelData[i].end = channelData[i].start; channelData[i].nx = data_width; channelData[i].ny = num_lines; // channelData[i].ys = 1; channelData[i].size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size; } for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Expand the pixel data to their original range // applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize)); for (int y = 0; y < num_lines; y++) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short))); outPtr += n * sizeof(unsigned short); cd.end += n; } } return true; } #endif // TINYEXR_USE_PIZ #if TINYEXR_USE_ZFP struct ZFPCompressionParam { double rate; int precision; double tolerance; int type; // TINYEXR_ZFP_COMPRESSIONTYPE_* ZFPCompressionParam() { type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE; rate = 2.0; precision = 0; tolerance = 0.0f; } }; bool FindZFPCompressionParam(ZFPCompressionParam *param, const EXRAttribute *attributes, int num_attributes) { bool foundType = false; for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionType") == 0) && (attributes[i].size == 1)) { param->type = static_cast<int>(attributes[i].value[0]); foundType = true; } } if (!foundType) { return false; } if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) && (attributes[i].size == 8)) { param->rate = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) && (attributes[i].size == 4)) { param->rate = *(reinterpret_cast<int *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) && (attributes[i].size == 8)) { param->tolerance = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else { assert(0); } return false; } // Assume pixel format is FLOAT for all channels. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines, int num_channels, const unsigned char *src, unsigned long src_size, const ZFPCompressionParam &param) { size_t uncompressed_size = dst_width * dst_num_lines * num_channels; if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); } zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((dst_width % 4) == 0); assert((dst_num_lines % 4) == 0); if ((dst_width & 3U) || (dst_num_lines & 3U)) { return false; } field = zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)), zfp_type_float, dst_width, dst_num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimention */ 2, /* write random access */ 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); std::vector<unsigned char> buf(buf_size); memcpy(&buf.at(0), src, src_size); bitstream *stream = stream_open(&buf.at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); size_t image_size = dst_width * dst_num_lines; for (int c = 0; c < num_channels; c++) { // decompress 4x4 pixel block. for (int y = 0; y < dst_num_lines; y += 4) { for (int x = 0; x < dst_width; x += 4) { float fblock[16]; zfp_decode_block_float_2(zfp, fblock); for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { dst[c * image_size + ((y + j) * dst_width + (x + i))] = fblock[j * 4 + i]; } } } } } zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); return true; } // Assume pixel format is FLOAT for all channels. bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize, const float *inPtr, int width, int num_lines, int num_channels, const ZFPCompressionParam &param) { zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((width % 4) == 0); assert((num_lines % 4) == 0); if ((width & 3U) || (num_lines & 3U)) { return false; } // create input array. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)), zfp_type_float, width, num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); outBuf->resize(buf_size); bitstream *stream = stream_open(&outBuf->at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_field_free(field); size_t image_size = width * num_lines; for (int c = 0; c < num_channels; c++) { // compress 4x4 pixel block. for (int y = 0; y < num_lines; y += 4) { for (int x = 0; x < width; x += 4) { float fblock[16]; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { fblock[j * 4 + i] = inPtr[c * image_size + ((y + j) * width + (x + i))]; } } zfp_encode_block_float_2(zfp, fblock); } } } zfp_stream_flush(zfp); (*outSize) = zfp_stream_compressed_size(zfp); zfp_stream_close(zfp); return true; } #endif // // ----------------------------------------------------------------- // // TODO(syoyo): Refactor function arguments. static bool DecodePixelData(/* out */ unsigned char **out_images, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int width, int height, int x_stride, int y, int line_no, int num_lines, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ #if TINYEXR_USE_PIZ if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) { // Invalid input #90 return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>( static_cast<size_t>(width * num_lines) * pixel_data_size)); size_t tmpBufLen = outBuf.size(); bool ret = tinyexr::DecompressPiz( reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen, data_len, static_cast<int>(num_channels), channels, width, num_lines); if (!ret) { return false; } // For PIZ_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { FP16 hf; // hf.u = line_ptr[u]; // use `cpy` to avoid unaligned memory access when compiler's // optimization is on. tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>(&outBuf.at( v * pixel_data_size * static_cast<size_t>(x_stride) + channel_offset_list[c] * static_cast<size_t>(x_stride))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); } } #else assert(0 && "PIZ is enabled in this build"); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS || compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For ZIP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); if (dstLen == 0) { return false; } if (!tinyexr::DecompressRle( reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For RLE_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; if (!FindZFPCompressionParam(&zfp_compression_param, attributes, num_attributes)) { assert(0); return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = outBuf.size(); assert(dstLen > 0); tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width, num_lines, num_channels, data_ptr, static_cast<unsigned long>(data_len), zfp_compression_param); // For ZFP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } #else (void)attributes; (void)num_attributes; (void)num_channels; assert(0); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { for (size_t c = 0; c < num_channels; c++) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { const unsigned short *line_ptr = reinterpret_cast<const unsigned short *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *outLine = reinterpret_cast<unsigned short *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); outLine[u] = hf.u; } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // address may not be aliged. use byte-wise copy for safety.#76 // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); tinyexr::FP32 f32 = half_to_float(hf); outLine[u] = f32.f; } } else { assert(0); return false; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { const float *line_ptr = reinterpret_cast<const float *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); unsigned int *outLine = reinterpret_cast<unsigned int *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { if (reinterpret_cast<const unsigned char *>(line_ptr + u) >= (data_ptr + data_len)) { // Corrupsed data? return false; } unsigned int val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } } } } return true; } static bool DecodeTiledPixelData( unsigned char **out_images, int *width, int *height, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int data_width, int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x, int tile_size_y, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { assert(tile_offset_x * tile_size_x < data_width); assert(tile_offset_y * tile_size_y < data_height); // Compute actual image size in a tile. if ((tile_offset_x + 1) * tile_size_x >= data_width) { (*width) = data_width - (tile_offset_x * tile_size_x); } else { (*width) = tile_size_x; } if ((tile_offset_y + 1) * tile_size_y >= data_height) { (*height) = data_height - (tile_offset_y * tile_size_y); } else { (*height) = tile_size_y; } // Image size = tile size. return DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len, compression_type, line_order, (*width), tile_size_y, /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0, (*height), pixel_data_size, num_attributes, attributes, num_channels, channels, channel_offset_list); } static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list, int *pixel_data_size, size_t *channel_offset, int num_channels, const EXRChannelInfo *channels) { channel_offset_list->resize(static_cast<size_t>(num_channels)); (*pixel_data_size) = 0; (*channel_offset) = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { (*channel_offset_list)[c] = (*channel_offset); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { (*pixel_data_size) += sizeof(unsigned short); (*channel_offset) += sizeof(unsigned short); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { (*pixel_data_size) += sizeof(float); (*channel_offset) += sizeof(float); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { (*pixel_data_size) += sizeof(unsigned int); (*channel_offset) += sizeof(unsigned int); } else { // ??? return false; } } return true; } static unsigned char **AllocateImage(int num_channels, const EXRChannelInfo *channels, const int *requested_pixel_types, int data_width, int data_height) { unsigned char **images = reinterpret_cast<unsigned char **>(static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(num_channels)))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { size_t data_len = static_cast<size_t>(data_width) * static_cast<size_t>(data_height); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { // pixel_data_size += sizeof(unsigned short); // channel_offset += sizeof(unsigned short); // Alloc internal image for half type. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { images[c] = reinterpret_cast<unsigned char *>(static_cast<unsigned short *>( malloc(sizeof(unsigned short) * data_len))); } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // pixel_data_size += sizeof(float); // channel_offset += sizeof(float); images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { // pixel_data_size += sizeof(unsigned int); // channel_offset += sizeof(unsigned int); images[c] = reinterpret_cast<unsigned char *>( static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len))); } else { assert(0); } } return images; } static int ParseEXRHeader(HeaderInfo *info, bool *empty_header, const EXRVersion *version, std::string *err, const unsigned char *buf, size_t size) { const char *marker = reinterpret_cast<const char *>(&buf[0]); if (empty_header) { (*empty_header) = false; } if (version->multipart) { if (size > 0 && marker[0] == '\0') { // End of header list. if (empty_header) { (*empty_header) = true; } return TINYEXR_SUCCESS; } } // According to the spec, the header of every OpenEXR file must contain at // least the following attributes: // // channels chlist // compression compression // dataWindow box2i // displayWindow box2i // lineOrder lineOrder // pixelAspectRatio float // screenWindowCenter v2f // screenWindowWidth float bool has_channels = false; bool has_compression = false; bool has_data_window = false; bool has_display_window = false; bool has_line_order = false; bool has_pixel_aspect_ratio = false; bool has_screen_window_center = false; bool has_screen_window_width = false; info->data_window[0] = 0; info->data_window[1] = 0; info->data_window[2] = 0; info->data_window[3] = 0; info->line_order = 0; // @fixme info->display_window[0] = 0; info->display_window[1] = 0; info->display_window[2] = 0; info->display_window[3] = 0; info->screen_window_center[0] = 0.0f; info->screen_window_center[1] = 0.0f; info->screen_window_width = -1.0f; info->pixel_aspect_ratio = -1.0f; info->tile_size_x = -1; info->tile_size_y = -1; info->tile_level_mode = -1; info->tile_rounding_mode = -1; info->attributes.clear(); // Read attributes size_t orig_size = size; for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) { if (0 == size) { if (err) { (*err) += "Insufficient data size for attributes.\n"; } return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { if (err) { (*err) += "Failed to read attribute.\n"; } return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (version->tiled && attr_name.compare("tiles") == 0) { unsigned int x_size, y_size; unsigned char tile_mode; assert(data.size() == 9); memcpy(&x_size, &data.at(0), sizeof(int)); memcpy(&y_size, &data.at(4), sizeof(int)); tile_mode = data[8]; tinyexr::swap4(&x_size); tinyexr::swap4(&y_size); info->tile_size_x = static_cast<int>(x_size); info->tile_size_y = static_cast<int>(y_size); // mode = levelMode + roundingMode * 16 info->tile_level_mode = tile_mode & 0x3; info->tile_rounding_mode = (tile_mode >> 4) & 0x1; } else if (attr_name.compare("compression") == 0) { bool ok = false; if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) { ok = true; } if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ ok = true; #else if (err) { (*err) = "PIZ compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP ok = true; #else if (err) { (*err) = "ZFP compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (!ok) { if (err) { (*err) = "Unknown compression type."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->compression_type = static_cast<int>(data[0]); has_compression = true; } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!ReadChannelInfo(info->channels, data)) { if (err) { (*err) += "Failed to parse channel info.\n"; } return TINYEXR_ERROR_INVALID_DATA; } if (info->channels.size() < 1) { if (err) { (*err) += "# of channels is zero.\n"; } return TINYEXR_ERROR_INVALID_DATA; } has_channels = true; } else if (attr_name.compare("dataWindow") == 0) { if (data.size() >= 16) { memcpy(&info->data_window[0], &data.at(0), sizeof(int)); memcpy(&info->data_window[1], &data.at(4), sizeof(int)); memcpy(&info->data_window[2], &data.at(8), sizeof(int)); memcpy(&info->data_window[3], &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3])); has_data_window = true; } } else if (attr_name.compare("displayWindow") == 0) { if (data.size() >= 16) { memcpy(&info->display_window[0], &data.at(0), sizeof(int)); memcpy(&info->display_window[1], &data.at(4), sizeof(int)); memcpy(&info->display_window[2], &data.at(8), sizeof(int)); memcpy(&info->display_window[3], &data.at(12), sizeof(int)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[3])); has_display_window = true; } } else if (attr_name.compare("lineOrder") == 0) { if (data.size() >= 1) { info->line_order = static_cast<int>(data[0]); has_line_order = true; } } else if (attr_name.compare("pixelAspectRatio") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->pixel_aspect_ratio)); has_pixel_aspect_ratio = true; } } else if (attr_name.compare("screenWindowCenter") == 0) { if (data.size() >= 8) { memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float)); memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[1])); has_screen_window_center = true; } } else if (attr_name.compare("screenWindowWidth") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->screen_window_width, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_width)); has_screen_window_width = true; } } else if (attr_name.compare("chunkCount") == 0) { if (data.size() >= sizeof(int)) { memcpy(&info->chunk_count, &data.at(0), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->chunk_count)); } } else { // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES) if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) { EXRAttribute attrib; #ifdef _MSC_VER strncpy_s(attrib.name, attr_name.c_str(), 255); strncpy_s(attrib.type, attr_type.c_str(), 255); #else strncpy(attrib.name, attr_name.c_str(), 255); strncpy(attrib.type, attr_type.c_str(), 255); #endif attrib.name[255] = '\0'; attrib.type[255] = '\0'; attrib.size = static_cast<int>(data.size()); attrib.value = static_cast<unsigned char *>(malloc(data.size())); memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0), data.size()); info->attributes.push_back(attrib); } } } // Check if required attributes exist { std::stringstream ss_err; if (!has_compression) { ss_err << "\"compression\" attribute not found in the header." << std::endl; } if (!has_channels) { ss_err << "\"channels\" attribute not found in the header." << std::endl; } if (!has_line_order) { ss_err << "\"lineOrder\" attribute not found in the header." << std::endl; } if (!has_display_window) { ss_err << "\"displayWindow\" attribute not found in the header." << std::endl; } if (!has_data_window) { ss_err << "\"dataWindow\" attribute not found in the header or invalid." << std::endl; } if (!has_pixel_aspect_ratio) { ss_err << "\"pixelAspectRatio\" attribute not found in the header." << std::endl; } if (!has_screen_window_width) { ss_err << "\"screenWindowWidth\" attribute not found in the header." << std::endl; } if (!has_screen_window_center) { ss_err << "\"screenWindowCenter\" attribute not found in the header." << std::endl; } if (!(ss_err.str().empty())) { if (err) { (*err) += ss_err.str(); } return TINYEXR_ERROR_INVALID_HEADER; } } info->header_len = static_cast<unsigned int>(orig_size - size); return TINYEXR_SUCCESS; } // C++ HeaderInfo to C EXRHeader conversion. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) { exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio; exr_header->screen_window_center[0] = info.screen_window_center[0]; exr_header->screen_window_center[1] = info.screen_window_center[1]; exr_header->screen_window_width = info.screen_window_width; exr_header->chunk_count = info.chunk_count; exr_header->display_window[0] = info.display_window[0]; exr_header->display_window[1] = info.display_window[1]; exr_header->display_window[2] = info.display_window[2]; exr_header->display_window[3] = info.display_window[3]; exr_header->data_window[0] = info.data_window[0]; exr_header->data_window[1] = info.data_window[1]; exr_header->data_window[2] = info.data_window[2]; exr_header->data_window[3] = info.data_window[3]; exr_header->line_order = info.line_order; exr_header->compression_type = info.compression_type; exr_header->tile_size_x = info.tile_size_x; exr_header->tile_size_y = info.tile_size_y; exr_header->tile_level_mode = info.tile_level_mode; exr_header->tile_rounding_mode = info.tile_rounding_mode; exr_header->num_channels = static_cast<int>(info.channels.size()); exr_header->channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { #ifdef _MSC_VER strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #else strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #endif // manually add '\0' for safety. exr_header->channels[c].name[255] = '\0'; exr_header->channels[c].pixel_type = info.channels[c].pixel_type; exr_header->channels[c].p_linear = info.channels[c].p_linear; exr_header->channels[c].x_sampling = info.channels[c].x_sampling; exr_header->channels[c].y_sampling = info.channels[c].y_sampling; } exr_header->pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->pixel_types[c] = info.channels[c].pixel_type; } // Initially fill with values of `pixel_types` exr_header->requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->requested_pixel_types[c] = info.channels[c].pixel_type; } exr_header->num_custom_attributes = static_cast<int>(info.attributes.size()); if (exr_header->num_custom_attributes > 0) { // TODO(syoyo): Report warning when # of attributes exceeds // `TINYEXR_MAX_CUSTOM_ATTRIBUTES` if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) { exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES; } exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc( sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes))); for (size_t i = 0; i < info.attributes.size(); i++) { memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name, 256); memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type, 256); exr_header->custom_attributes[i].size = info.attributes[i].size; // Just copy poiner exr_header->custom_attributes[i].value = info.attributes[i].value; } } else { exr_header->custom_attributes = NULL; } exr_header->header_len = info.header_len; } static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header, const std::vector<tinyexr::tinyexr_uint64> &offsets, const unsigned char *head, const size_t size, std::string *err) { int num_channels = exr_header->num_channels; int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1; int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1; if ((data_width < 0) || (data_height < 0)) { if (err) { std::stringstream ss; ss << "Invalid data width or data height: " << data_width << ", " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if ((data_width > threshold) || (data_height > threshold)) { if (err) { std::stringstream ss; ss << "data_with or data_height too large. data_width: " << data_width << ", " << "data_height = " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } } size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels)) { if (err) { (*err) += "Failed to compute channel layout.\n"; } return TINYEXR_ERROR_INVALID_DATA; } bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety. if (exr_header->tiled) { // value check if (exr_header->tile_size_x < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } if (exr_header->tile_size_y < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } size_t num_tiles = offsets.size(); // = # of blocks exr_image->tiles = static_cast<EXRTile *>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); int err_code = TINYEXR_SUCCESS; #if (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<size_t> tile_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_tiles)) { num_threads = int(num_tiles); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { size_t tile_idx = 0; while ((tile_idx = tile_count++) < num_tiles) { #else for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) { #endif // Allocate memory for each tile. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, exr_header->tile_size_x, exr_header->tile_size_y); // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) if (offsets[tile_idx] + sizeof(int) * 5 > size) { // TODO(LTE): atomic if (err) { (*err) += "Insufficient data size.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; break; } size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]); int tile_coordinates[4]; memcpy(tile_coordinates, data_ptr, sizeof(int) * 4); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[3])); // @todo{ LoD } if (tile_coordinates[2] != 0) { err_code = TINYEXR_ERROR_UNSUPPORTED_FEATURE; break; } if (tile_coordinates[3] != 0) { err_code = TINYEXR_ERROR_UNSUPPORTED_FEATURE; break; } int data_len; memcpy(&data_len, data_ptr + 16, sizeof(int)); // 16 = sizeof(tile_coordinates) tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len < 4 || size_t(data_len) > data_size) { // TODO(LTE): atomic if (err) { (*err) += "Insufficient data length.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; break; } // Move to data addr: 20 = 16 + 4; data_ptr += 20; bool ret = tinyexr::DecodeTiledPixelData( exr_image->tiles[tile_idx].images, &(exr_image->tiles[tile_idx].width), &(exr_image->tiles[tile_idx].height), exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list); if (!ret) { // TODO(LTE): atomic if (err) { (*err) += "Failed to decode tile data.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; } exr_image->tiles[tile_idx].offset_x = tile_coordinates[0]; exr_image->tiles[tile_idx].offset_y = tile_coordinates[1]; exr_image->tiles[tile_idx].level_x = tile_coordinates[2]; exr_image->tiles[tile_idx].level_y = tile_coordinates[3]; #if (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) } })); } // num_thread loop for (auto &t : workers) { t.join(); } #else } #endif if (err_code != TINYEXR_SUCCESS) { return err_code; } exr_image->num_tiles = static_cast<int>(num_tiles); } else { // scanline format // Don't allow too large image(256GB * pixel_data_size or more). Workaround // for #104. size_t total_data_len = size_t(data_width) * size_t(data_height) * size_t(num_channels); const bool total_data_len_overflown = sizeof(void *) == 8 ? (total_data_len >= 0x4000000000) : false; if ((total_data_len == 0) || total_data_len_overflown) { if (err) { std::stringstream ss; ss << "Image data size is zero or too large: width = " << data_width << ", height = " << data_height << ", channels = " << num_channels << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } exr_image->images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); #if (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<int> y_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_blocks)) { num_threads = int(num_blocks); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int y = 0; while ((y = y_count++) < int(num_blocks)) { #else #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int y = 0; y < static_cast<int>(num_blocks); y++) { #endif size_t y_idx = static_cast<size_t>(y); if (offsets[y_idx] + sizeof(int) * 2 > size) { invalid_data = true; } else { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed or compressed) size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y_idx]); int line_no; memcpy(&line_no, data_ptr, sizeof(int)); int data_len; memcpy(&data_len, data_ptr + 4, sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (size_t(data_len) > data_size) { invalid_data = true; } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) { // Too large value. Assume this is invalid // 2**20 = 1048576 = heuristic value. invalid_data = true; } else if (data_len == 0) { // TODO(syoyo): May be ok to raise the threshold for example // `data_len < 4` invalid_data = true; } else { // line_no may be negative. int end_line_no = (std::min)(line_no + num_scanline_blocks, (exr_header->data_window[3] + 1)); int num_lines = end_line_no - line_no; if (num_lines <= 0) { invalid_data = true; } else { // Move to data addr: 8 = 4 + 4; data_ptr += 8; // Adjust line_no with data_window.bmin.y // overflow check tinyexr_int64 lno = static_cast<tinyexr_int64>(line_no) - static_cast<tinyexr_int64>(exr_header->data_window[1]); if (lno > std::numeric_limits<int>::max()) { line_no = -1; // invalid } else if (lno < -std::numeric_limits<int>::max()) { line_no = -1; // invalid } else { line_no -= exr_header->data_window[1]; } if (line_no < 0) { invalid_data = true; } else { if (!tinyexr::DecodePixelData( exr_image->images, exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, data_width, y, line_no, num_lines, static_cast<size_t>(pixel_data_size), static_cast<size_t>( exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list)) { invalid_data = true; } } } } } #if (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) } })); } for (auto &t : workers) { t.join(); } #else } // omp parallel #endif } if (invalid_data) { if (err) { std::stringstream ss; (*err) += "Invalid data found when decoding pixels.\n"; } return TINYEXR_ERROR_INVALID_DATA; } // Overwrite `pixel_type` with `requested_pixel_type`. { for (int c = 0; c < exr_header->num_channels; c++) { exr_header->pixel_types[c] = exr_header->requested_pixel_types[c]; } } { exr_image->num_channels = num_channels; exr_image->width = data_width; exr_image->height = data_height; } return TINYEXR_SUCCESS; } static bool ReconstructLineOffsets( std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n, const unsigned char *head, const unsigned char *marker, const size_t size) { assert(head < marker); assert(offsets->size() == n); for (size_t i = 0; i < n; i++) { size_t offset = static_cast<size_t>(marker - head); // Offset should not exceed whole EXR file/data size. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) { return false; } int y; unsigned int data_len; memcpy(&y, marker, sizeof(int)); memcpy(&data_len, marker + 4, sizeof(unsigned int)); if (data_len >= size) { return false; } tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); (*offsets)[i] = offset; marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len) } return true; } static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *head, const unsigned char *marker, const size_t size, const char **err) { if (exr_image == NULL || exr_header == NULL || head == NULL || marker == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0]; if (data_width >= std::numeric_limits<int>::max()) { // Issue 63 tinyexr::SetErrorMessage("Invalid data width value", err); return TINYEXR_ERROR_INVALID_DATA; } data_width++; int data_height = exr_header->data_window[3] - exr_header->data_window[1]; if (data_height >= std::numeric_limits<int>::max()) { tinyexr::SetErrorMessage("Invalid data height value", err); return TINYEXR_ERROR_INVALID_DATA; } data_height++; if ((data_width < 0) || (data_height < 0)) { tinyexr::SetErrorMessage("data width or data height is negative.", err); return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if (data_width > threshold) { tinyexr::SetErrorMessage("data width too large.", err); return TINYEXR_ERROR_INVALID_DATA; } if (data_height > threshold) { tinyexr::SetErrorMessage("data height too large.", err); return TINYEXR_ERROR_INVALID_DATA; } } // Read offset tables. size_t num_blocks = 0; if (exr_header->chunk_count > 0) { // Use `chunkCount` attribute. num_blocks = static_cast<size_t>(exr_header->chunk_count); } else if (exr_header->tiled) { // @todo { LoD } size_t num_x_tiles = static_cast<size_t>(data_width) / static_cast<size_t>(exr_header->tile_size_x); if (num_x_tiles * static_cast<size_t>(exr_header->tile_size_x) < static_cast<size_t>(data_width)) { num_x_tiles++; } size_t num_y_tiles = static_cast<size_t>(data_height) / static_cast<size_t>(exr_header->tile_size_y); if (num_y_tiles * static_cast<size_t>(exr_header->tile_size_y) < static_cast<size_t>(data_height)) { num_y_tiles++; } num_blocks = num_x_tiles * num_y_tiles; } else { num_blocks = static_cast<size_t>(data_height) / static_cast<size_t>(num_scanline_blocks); if (num_blocks * static_cast<size_t>(num_scanline_blocks) < static_cast<size_t>(data_height)) { num_blocks++; } } std::vector<tinyexr::tinyexr_uint64> offsets(num_blocks); for (size_t y = 0; y < num_blocks; y++) { tinyexr::tinyexr_uint64 offset; // Issue #81 if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) { tinyexr::SetErrorMessage("Insufficient data size in offset table.", err); return TINYEXR_ERROR_INVALID_DATA; } memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } marker += sizeof(tinyexr::tinyexr_uint64); // = 8 offsets[y] = offset; } // If line offsets are invalid, we try to reconstruct it. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details. for (size_t y = 0; y < num_blocks; y++) { if (offsets[y] <= 0) { // TODO(syoyo) Report as warning? // if (err) { // stringstream ss; // ss << "Incomplete lineOffsets." << std::endl; // (*err) += ss.str(); //} bool ret = ReconstructLineOffsets(&offsets, num_blocks, head, marker, size); if (ret) { // OK break; } else { tinyexr::SetErrorMessage( "Cannot reconstruct lineOffset table in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } } } { std::string e; int ret = DecodeChunk(exr_image, exr_header, offsets, head, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } #if 1 FreeEXRImage(exr_image); #else // release memory(if exists) if ((exr_header->num_channels > 0) && exr_image && exr_image->images) { for (size_t c = 0; c < size_t(exr_header->num_channels); c++) { if (exr_image->images[c]) { free(exr_image->images[c]); exr_image->images[c] = NULL; } } free(exr_image->images); exr_image->images = NULL; } #endif } return ret; } } static void GetLayers(const EXRHeader& exr_header, std::vector<std::string>& layer_names) { // Naive implementation // Group channels by layers // go over all channel names, split by periods // collect unique names layer_names.clear(); for (int c = 0; c < exr_header.num_channels; c++) { std::string full_name(exr_header.channels[c].name); const size_t pos = full_name.find_last_of('.'); if (pos != std::string::npos && pos != 0 && pos + 1 < full_name.size()) { full_name.erase(pos); if (std::find(layer_names.begin(), layer_names.end(), full_name) == layer_names.end()) layer_names.push_back(full_name); } } } struct LayerChannel { explicit LayerChannel (size_t i, std::string n) : index(i) , name(n) {} size_t index; std::string name; }; static void ChannelsInLayer(const EXRHeader& exr_header, const std::string layer_name, std::vector<LayerChannel>& channels) { channels.clear(); for (int c = 0; c < exr_header.num_channels; c++) { std::string ch_name(exr_header.channels[c].name); if (layer_name.empty()) { const size_t pos = ch_name.find_last_of('.'); if (pos != std::string::npos && pos < ch_name.size()) { ch_name = ch_name.substr(pos + 1); } } else { const size_t pos = ch_name.find(layer_name + '.'); if (pos == std::string::npos) continue; if (pos == 0) { ch_name = ch_name.substr(layer_name.size() + 1); } } LayerChannel ch(size_t(c), ch_name); channels.push_back(ch); } } } // namespace tinyexr int EXRLayers(const char *filename, const char **layer_names[], int *num_layers, const char **err) { EXRVersion exr_version; EXRHeader exr_header; InitEXRHeader(&exr_header); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage("Invalid EXR header.", err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } std::vector<std::string> layer_vec; tinyexr::GetLayers(exr_header, layer_vec); (*num_layers) = int(layer_vec.size()); (*layer_names) = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(layer_vec.size()))); for (size_t c = 0; c < static_cast<size_t>(layer_vec.size()); c++) { #ifdef _MSC_VER (*layer_names)[c] = _strdup(layer_vec[c].c_str()); #else (*layer_names)[c] = strdup(layer_vec[c].c_str()); #endif } FreeEXRHeader(&exr_header); return TINYEXR_SUCCESS; } int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err) { return LoadEXRWithLayer(out_rgba, width, height, filename, /* layername */NULL, err); } int LoadEXRWithLayer(float **out_rgba, int *width, int *height, const char *filename, const char *layername, const char **err) { if (out_rgba == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); InitEXRImage(&exr_image); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { std::stringstream ss; ss << "Failed to open EXR file or read version info from EXR file. code(" << ret << ")"; tinyexr::SetErrorMessage(ss.str(), err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } { int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } // TODO: Probably limit loading to layers (channels) selected by layer index { int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; std::vector<std::string> layer_names; tinyexr::GetLayers(exr_header, layer_names); std::vector<tinyexr::LayerChannel> channels; tinyexr::ChannelsInLayer(exr_header, layername == NULL ? "" : std::string(layername), channels); if (channels.size() < 1) { tinyexr::SetErrorMessage("Layer Not Found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_LAYER_NOT_FOUND; } size_t ch_count = channels.size() < 4 ? channels.size() : 4; for (size_t c = 0; c < ch_count; c++) { const tinyexr::LayerChannel &ch = channels[c]; if (ch.name == "R") { idxR = int(ch.index); } else if (ch.name == "G") { idxG = int(ch.index); } else if (ch.name == "B") { idxB = int(ch.index); } else if (ch.name == "A") { idxA = int(ch.index); } } if (channels.size() == 1) { int chIdx = int(channels.front().index); // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // Assume RGB(A) if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int IsEXR(const char *filename) { EXRVersion exr_version; int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { return ret; } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_header == NULL) { tinyexr::SetErrorMessage( "Invalid argument. `memory` or `exr_header` argument is null in " "ParseEXRHeaderFromMemory()", err); // Invalid argument return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Insufficient header/data size.\n", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; tinyexr::HeaderInfo info; info.clear(); std::string err_str; int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { if (err && !err_str.empty()) { tinyexr::SetErrorMessage(err_str, err); } } ConvertHeader(exr_header, info); // transfoer `tiled` from version. exr_header->tiled = version->tiled; return ret; } int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err) { if (out_rgba == NULL || memory == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); int ret = ParseEXRVersionFromMemory(&exr_version, memory, size); if (ret != TINYEXR_SUCCESS) { std::stringstream ss; ss << "Failed to parse EXR version. code(" << ret << ")"; tinyexr::SetErrorMessage(ss.str(), err); return ret; } ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } InitEXRImage(&exr_image); ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } // TODO(syoyo): Refactor removing same code as used in LoadEXR(). if (exr_header.num_channels == 1) { // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[0][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // TODO(syoyo): Support non RGBA image. if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize < 16) { tinyexr::SetErrorMessage("File size too short " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize, err); } int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *memory, const size_t size, const char **err) { if (exr_image == NULL || memory == NULL || (size < tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } const unsigned char *head = memory; const unsigned char *marker = reinterpret_cast<const unsigned char *>( memory + exr_header->header_len + 8); // +8 for magic number + version header. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size, err); } size_t SaveEXRImageToMemory(const EXRImage *exr_image, const EXRHeader *exr_header, unsigned char **memory_out, const char **err) { if (exr_image == NULL || memory_out == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToMemory", err); return 0; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return 0; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return 0; } #endif #if TINYEXR_USE_ZFP for (size_t i = 0; i < static_cast<size_t>(exr_header->num_channels); i++) { if (exr_header->requested_pixel_types[i] != TINYEXR_PIXELTYPE_FLOAT) { tinyexr::SetErrorMessage("Pixel type must be FLOAT for ZFP compression", err); return 0; } } #endif std::vector<unsigned char> memory; // Header { const char header[] = {0x76, 0x2f, 0x31, 0x01}; memory.insert(memory.end(), header, header + 4); } // Version, scanline. { char marker[] = {2, 0, 0, 0}; /* @todo if (exr_header->tiled) { marker[1] |= 0x2; } if (exr_header->long_name) { marker[1] |= 0x4; } if (exr_header->non_image) { marker[1] |= 0x8; } if (exr_header->multipart) { marker[1] |= 0x10; } */ memory.insert(memory.end(), marker, marker + 4); } int num_scanlines = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanlines = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanlines = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanlines = 16; } // Write attributes. std::vector<tinyexr::ChannelInfo> channels; { std::vector<unsigned char> data; for (int c = 0; c < exr_header->num_channels; c++) { tinyexr::ChannelInfo info; info.p_linear = 0; info.pixel_type = exr_header->requested_pixel_types[c]; info.x_sampling = 1; info.y_sampling = 1; info.name = std::string(exr_header->channels[c].name); channels.push_back(info); } tinyexr::WriteChannelInfo(data, channels); tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0), static_cast<int>(data.size())); } { int comp = exr_header->compression_type; tinyexr::swap4(reinterpret_cast<unsigned int *>(&comp)); tinyexr::WriteAttributeToMemory( &memory, "compression", "compression", reinterpret_cast<const unsigned char *>(&comp), 1); } { int data[4] = {0, 0, exr_image->width - 1, exr_image->height - 1}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[3])); tinyexr::WriteAttributeToMemory( &memory, "dataWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); tinyexr::WriteAttributeToMemory( &memory, "displayWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); } { unsigned char line_order = 0; // @fixme { read line_order from EXRHeader } tinyexr::WriteAttributeToMemory(&memory, "lineOrder", "lineOrder", &line_order, 1); } { float aspectRatio = 1.0f; tinyexr::swap4(reinterpret_cast<unsigned int *>(&aspectRatio)); tinyexr::WriteAttributeToMemory( &memory, "pixelAspectRatio", "float", reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float)); } { float center[2] = {0.0f, 0.0f}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[1])); tinyexr::WriteAttributeToMemory( &memory, "screenWindowCenter", "v2f", reinterpret_cast<const unsigned char *>(center), 2 * sizeof(float)); } { float w = static_cast<float>(exr_image->width); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::WriteAttributeToMemory(&memory, "screenWindowWidth", "float", reinterpret_cast<const unsigned char *>(&w), sizeof(float)); } // Custom attributes if (exr_header->num_custom_attributes > 0) { for (int i = 0; i < exr_header->num_custom_attributes; i++) { tinyexr::WriteAttributeToMemory( &memory, exr_header->custom_attributes[i].name, exr_header->custom_attributes[i].type, reinterpret_cast<const unsigned char *>( exr_header->custom_attributes[i].value), exr_header->custom_attributes[i].size); } } { // end of header unsigned char e = 0; memory.push_back(e); } int num_blocks = exr_image->height / num_scanlines; if (num_blocks * num_scanlines < exr_image->height) { num_blocks++; } std::vector<tinyexr::tinyexr_uint64> offsets(static_cast<size_t>(num_blocks)); size_t headerSize = memory.size(); tinyexr::tinyexr_uint64 offset = headerSize + static_cast<size_t>(num_blocks) * sizeof( tinyexr::tinyexr_int64); // sizeof(header) + sizeof(offsetTable) std::vector<std::vector<unsigned char> > data_list( static_cast<size_t>(num_blocks)); std::vector<size_t> channel_offset_list( static_cast<size_t>(exr_header->num_channels)); int pixel_data_size = 0; size_t channel_offset = 0; for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { channel_offset_list[c] = channel_offset; if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { pixel_data_size += sizeof(unsigned short); channel_offset += sizeof(unsigned short); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { pixel_data_size += sizeof(float); channel_offset += sizeof(float); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { pixel_data_size += sizeof(unsigned int); channel_offset += sizeof(unsigned int); } else { assert(0); } } #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; // Use ZFP compression parameter from custom attributes(if such a parameter // exists) { bool ret = tinyexr::FindZFPCompressionParam( &zfp_compression_param, exr_header->custom_attributes, exr_header->num_custom_attributes); if (!ret) { // Use predefined compression parameter. zfp_compression_param.type = 0; zfp_compression_param.rate = 2; } } #endif // TOOD(LTE): C++11 thread // Use signed int since some OpenMP compiler doesn't allow unsigned type for // `parallel for` #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_blocks; i++) { size_t ii = static_cast<size_t>(i); int start_y = num_scanlines * i; int endY = (std::min)(num_scanlines * (i + 1), exr_image->height); int h = endY - start_y; std::vector<unsigned char> buf( static_cast<size_t>(exr_image->width * h * pixel_data_size)); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP16 h16; h16.u = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP32 f32 = half_to_float(h16); tinyexr::swap4(reinterpret_cast<unsigned int *>(&f32.f)); // line_ptr[x] = f32.f; tinyexr::cpy4(line_ptr + x, &(f32.f)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned short val = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap2(&val); // line_ptr[x] = val; tinyexr::cpy2(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP32 f32; f32.f = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP16 h16; h16 = float_to_half_full(f32); tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u)); // line_ptr[x] = h16.u; tinyexr::cpy2(line_ptr + x, &(h16.u)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { float val = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned int val = reinterpret_cast<unsigned int **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(&val); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } } if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(buf.size()); memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), buf.begin(), buf.begin() + data_len); } else if ((exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #if TINYEXR_USE_MINIZ std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound( static_cast<unsigned long>(buf.size()))); #else std::vector<unsigned char> block( compressBound(static_cast<uLong>(buf.size()))); #endif tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressZip(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // (buf.size() * 3) / 2 would be enough. std::vector<unsigned char> block((buf.size() * 3) / 2); tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressRle(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ unsigned int bufLen = 8192 + static_cast<unsigned int>( 2 * static_cast<unsigned int>( buf.size())); // @fixme { compute good bound. } std::vector<unsigned char> block(bufLen); unsigned int outSize = static_cast<unsigned int>(block.size()); CompressPiz(&block.at(0), &outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), buf.size(), channels, exr_image->width, h); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP std::vector<unsigned char> block; unsigned int outSize; tinyexr::CompressZfp( &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)), exr_image->width, h, exr_header->num_channels, zfp_compression_param); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else { assert(0); } } // omp parallel for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { offsets[i] = offset; tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i])); offset += data_list[i].size(); } size_t totalSize = static_cast<size_t>(offset); { memory.insert( memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)), reinterpret_cast<unsigned char *>(&offsets.at(0)) + sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks)); } if (memory.size() == 0) { tinyexr::SetErrorMessage("Output memory size is zero", err); return 0; } (*memory_out) = static_cast<unsigned char *>(malloc(totalSize)); memcpy((*memory_out), &memory.at(0), memory.size()); unsigned char *memory_ptr = *memory_out + memory.size(); for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { memcpy(memory_ptr, &data_list[i].at(0), data_list[i].size()); memory_ptr += data_list[i].size(); } return totalSize; // OK } int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL || filename == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "wb"); #else FILE *fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err); if (mem_size == 0) { return TINYEXR_ERROR_SERIALZATION_FAILED; } size_t written_size = 0; if ((mem_size > 0) && mem) { written_size = fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); if (written_size != mem_size) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } return TINYEXR_SUCCESS; } int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) { if (deep_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _MSC_VER FILE *fp = NULL; errno_t errcode = fopen_s(&fp, filename, "rb"); if ((0 != errcode) || (!fp)) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else FILE *fp = fopen(filename, "rb"); if (!fp) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #endif size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize == 0) { fclose(fp); tinyexr::SetErrorMessage("File size is zero : " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); (void)ret; } fclose(fp); const char *head = &buf[0]; const char *marker = &buf[0]; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { tinyexr::SetErrorMessage("Invalid magic number", err); return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } // Version, scanline. { // ver 2.0, scanline, deep bit on(0x800) // must be [2, 0, 0, 0] if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) { tinyexr::SetErrorMessage("Unsupported version or scanline", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } marker += 4; } int dx = -1; int dy = -1; int dw = -1; int dh = -1; int num_scanline_blocks = 1; // 16 for ZIP compression. int compression_type = -1; int num_channels = -1; std::vector<tinyexr::ChannelInfo> channels; // Read attributes size_t size = filesize - tinyexr::kEXRVersionSize; for (;;) { if (0 == size) { return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { marker++; size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { std::stringstream ss; ss << "Failed to parse attribute\n"; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (attr_name.compare("compression") == 0) { compression_type = data[0]; if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) { std::stringstream ss; ss << "Unsupported compression type : " << compression_type; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!tinyexr::ReadChannelInfo(channels, data)) { tinyexr::SetErrorMessage("Failed to parse channel info", err); return TINYEXR_ERROR_INVALID_DATA; } num_channels = static_cast<int>(channels.size()); if (num_channels < 1) { tinyexr::SetErrorMessage("Invalid channels format", err); return TINYEXR_ERROR_INVALID_DATA; } } else if (attr_name.compare("dataWindow") == 0) { memcpy(&dx, &data.at(0), sizeof(int)); memcpy(&dy, &data.at(4), sizeof(int)); memcpy(&dw, &data.at(8), sizeof(int)); memcpy(&dh, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dx)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dy)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dw)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dh)); } else if (attr_name.compare("displayWindow") == 0) { int x; int y; int w; int h; memcpy(&x, &data.at(0), sizeof(int)); memcpy(&y, &data.at(4), sizeof(int)); memcpy(&w, &data.at(8), sizeof(int)); memcpy(&h, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&h)); } } assert(dx >= 0); assert(dy >= 0); assert(dw >= 0); assert(dh >= 0); assert(num_channels >= 1); int data_width = dw - dx + 1; int data_height = dh - dy + 1; std::vector<float> image( static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA // Read offset tables. int num_blocks = data_height / num_scanline_blocks; if (num_blocks * num_scanline_blocks < data_height) { num_blocks++; } std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks)); for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { tinyexr::tinyexr_int64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset)); marker += sizeof(tinyexr::tinyexr_int64); // = 8 offsets[y] = offset; } #if TINYEXR_USE_PIZ if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) || (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) { #else if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #endif // OK } else { tinyexr::SetErrorMessage("Unsupported compression format", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } deep_image->image = static_cast<float ***>( malloc(sizeof(float **) * static_cast<size_t>(num_channels))); for (int c = 0; c < num_channels; c++) { deep_image->image[c] = static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { } } deep_image->offset_table = static_cast<int **>( malloc(sizeof(int *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { deep_image->offset_table[y] = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(data_width))); } for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y]); // int: y coordinate // int64: packed size of pixel offset table // int64: packed size of sample data // int64: unpacked size of sample data // compressed pixel offset table // compressed sample data int line_no; tinyexr::tinyexr_int64 packedOffsetTableSize; tinyexr::tinyexr_int64 packedSampleDataSize; tinyexr::tinyexr_int64 unpackedSampleDataSize; memcpy(&line_no, data_ptr, sizeof(int)); memcpy(&packedOffsetTableSize, data_ptr + 4, sizeof(tinyexr::tinyexr_int64)); memcpy(&packedSampleDataSize, data_ptr + 12, sizeof(tinyexr::tinyexr_int64)); memcpy(&unpackedSampleDataSize, data_ptr + 20, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize)); std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width)); // decode pixel offset table. { unsigned long dstLen = static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int)); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)), &dstLen, data_ptr + 28, static_cast<unsigned long>(packedOffsetTableSize))) { return false; } assert(dstLen == pixelOffsetTable.size() * sizeof(int)); for (size_t i = 0; i < static_cast<size_t>(data_width); i++) { deep_image->offset_table[y][i] = pixelOffsetTable[i]; } } std::vector<unsigned char> sample_data( static_cast<size_t>(unpackedSampleDataSize)); // decode sample data. { unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize); if (dstLen) { if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen, data_ptr + 28 + packedOffsetTableSize, static_cast<unsigned long>(packedSampleDataSize))) { return false; } assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize)); } } // decode sample int sampleSize = -1; std::vector<int> channel_offset_list(static_cast<size_t>(num_channels)); { int channel_offset = 0; for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) { channel_offset_list[i] = channel_offset; if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT channel_offset += 4; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half channel_offset += 2; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // float channel_offset += 4; } else { assert(0); } } sampleSize = channel_offset; } assert(sampleSize >= 2); assert(static_cast<size_t>( pixelOffsetTable[static_cast<size_t>(data_width - 1)] * sampleSize) == sample_data.size()); int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize; // // Alloc memory // // // pixel data is stored as image[channels][pixel_samples] // { tinyexr::tinyexr_uint64 data_offset = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { deep_image->image[c][y] = static_cast<float *>( malloc(sizeof(float) * static_cast<size_t>(samples_per_line))); if (channels[c].pixel_type == 0) { // UINT for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { unsigned int ui; unsigned int *src_ptr = reinterpret_cast<unsigned int *>( &sample_data.at(size_t(data_offset) + x * sizeof(int))); tinyexr::cpy4(&ui, src_ptr); deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme } data_offset += sizeof(unsigned int) * static_cast<size_t>(samples_per_line); } else if (channels[c].pixel_type == 1) { // half for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { tinyexr::FP16 f16; const unsigned short *src_ptr = reinterpret_cast<unsigned short *>( &sample_data.at(size_t(data_offset) + x * sizeof(short))); tinyexr::cpy2(&(f16.u), src_ptr); tinyexr::FP32 f32 = half_to_float(f16); deep_image->image[c][y][x] = f32.f; } data_offset += sizeof(short) * static_cast<size_t>(samples_per_line); } else { // float for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { float f; const float *src_ptr = reinterpret_cast<float *>( &sample_data.at(size_t(data_offset) + x * sizeof(float))); tinyexr::cpy4(&f, src_ptr); deep_image->image[c][y][x] = f; } data_offset += sizeof(float) * static_cast<size_t>(samples_per_line); } } } } // y deep_image->width = data_width; deep_image->height = data_height; deep_image->channel_names = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(num_channels))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { #ifdef _WIN32 deep_image->channel_names[c] = _strdup(channels[c].name.c_str()); #else deep_image->channel_names[c] = strdup(channels[c].name.c_str()); #endif } deep_image->num_channels = num_channels; return TINYEXR_SUCCESS; } void InitEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return; } exr_image->width = 0; exr_image->height = 0; exr_image->num_channels = 0; exr_image->images = NULL; exr_image->tiles = NULL; exr_image->num_tiles = 0; } void FreeEXRErrorMessage(const char *msg) { if (msg) { free(reinterpret_cast<void *>(const_cast<char *>(msg))); } return; } void InitEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return; } memset(exr_header, 0, sizeof(EXRHeader)); } int FreeEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->channels) { free(exr_header->channels); } if (exr_header->pixel_types) { free(exr_header->pixel_types); } if (exr_header->requested_pixel_types) { free(exr_header->requested_pixel_types); } for (int i = 0; i < exr_header->num_custom_attributes; i++) { if (exr_header->custom_attributes[i].value) { free(exr_header->custom_attributes[i].value); } } if (exr_header->custom_attributes) { free(exr_header->custom_attributes); } return TINYEXR_SUCCESS; } int FreeEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->images && exr_image->images[i]) { free(exr_image->images[i]); } } if (exr_image->images) { free(exr_image->images); } if (exr_image->tiles) { for (int tid = 0; tid < exr_image->num_tiles; tid++) { for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) { free(exr_image->tiles[tid].images[i]); } } if (exr_image->tiles[tid].images) { free(exr_image->tiles[tid].images); } } free(exr_image->tiles); } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_header == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("fread() error on " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize, err); } int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_headers == NULL || num_headers == NULL || exr_version == NULL) { // Invalid argument tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Data size too short", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; std::vector<tinyexr::HeaderInfo> infos; for (;;) { tinyexr::HeaderInfo info; info.clear(); std::string err_str; bool empty_header = false; int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage(err_str, err); return ret; } if (empty_header) { marker += 1; // skip '\0' break; } // `chunkCount` must exist in the header. if (info.chunk_count == 0) { tinyexr::SetErrorMessage( "`chunkCount' attribute is not found in the header.", err); return TINYEXR_ERROR_INVALID_DATA; } infos.push_back(info); // move to next header. marker += info.header_len; size -= info.header_len; } // allocate memory for EXRHeader and create array of EXRHeader pointers. (*exr_headers) = static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size())); for (size_t i = 0; i < infos.size(); i++) { EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader))); ConvertHeader(exr_header, infos[i]); // transfoer `tiled` from version. exr_header->tiled = exr_version->tiled; (*exr_headers)[i] = exr_header; } (*num_headers) = static_cast<int>(infos.size()); return TINYEXR_SUCCESS; } int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_headers == NULL || num_headers == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromFile()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRMultipartHeaderFromMemory( exr_headers, num_headers, exr_version, &buf.at(0), filesize, err); } int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size) { if (version == NULL || memory == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } version->tiled = false; version->long_name = false; version->non_image = false; version->multipart = false; // Parse version header. { // must be 2 if (marker[0] != 2) { return TINYEXR_ERROR_INVALID_EXR_VERSION; } if (version == NULL) { return TINYEXR_SUCCESS; // May OK } version->version = 2; if (marker[1] & 0x2) { // 9th bit version->tiled = true; } if (marker[1] & 0x4) { // 10th bit version->long_name = true; } if (marker[1] & 0x8) { // 11th bit version->non_image = true; // (deep image) } if (marker[1] & 0x10) { // 12th bit version->multipart = true; } } return TINYEXR_SUCCESS; } int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) { if (filename == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t file_size; // Compute size fseek(fp, 0, SEEK_END); file_size = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (file_size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } unsigned char buf[tinyexr::kEXRVersionSize]; size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp); fclose(fp); if (ret != tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize); } int LoadEXRMultipartImageFromMemory(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromMemory()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } // compute total header size. size_t total_header_size = 0; for (unsigned int i = 0; i < num_parts; i++) { if (exr_headers[i]->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } total_header_size += exr_headers[i]->header_len; } const char *marker = reinterpret_cast<const char *>( memory + total_header_size + 4 + 4); // +8 for magic number and version header. marker += 1; // Skip empty header. // NOTE 1: // In multipart image, There is 'part number' before chunk data. // 4 byte : part number // 4+ : chunk // // NOTE 2: // EXR spec says 'part number' is 'unsigned long' but actually this is // 'unsigned int(4 bytes)' in OpenEXR implementation... // http://www.openexr.com/openexrfilelayout.pdf // Load chunk offset table. std::vector<std::vector<tinyexr::tinyexr_uint64> > chunk_offset_table_list; for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> offset_table( static_cast<size_t>(exr_headers[i]->chunk_count)); for (size_t c = 0; c < offset_table.size(); c++) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, 8); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } offset_table[c] = offset + 4; // +4 to skip 'part number' marker += 8; } chunk_offset_table_list.push_back(offset_table); } // Decode image. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> &offset_table = chunk_offset_table_list[i]; // First check 'part number' is identitical to 'i' for (size_t c = 0; c < offset_table.size(); c++) { const unsigned char *part_number_addr = memory + offset_table[c] - 4; // -4 to move to 'part number' field. unsigned int part_no; memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4 tinyexr::swap4(&part_no); if (part_no != i) { tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } } std::string e; int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table, memory, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } return ret; } } return TINYEXR_SUCCESS; } int LoadEXRMultipartImageFromFile(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts, &buf.at(0), filesize, err); } int SaveEXR(const float *data, int width, int height, int components, const int save_as_fp16, const char *outfilename, const char **err) { if ((components == 1) || components == 3 || components == 4) { // OK } else { std::stringstream ss; ss << "Unsupported component value : " << components << std::endl; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRHeader header; InitEXRHeader(&header); if ((width < 16) && (height < 16)) { // No compression for small image. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE; } else { header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP; } EXRImage image; InitEXRImage(&image); image.num_channels = components; std::vector<float> images[4]; if (components == 1) { images[0].resize(static_cast<size_t>(width * height)); memcpy(images[0].data(), data, sizeof(float) * size_t(width * height)); } else { images[0].resize(static_cast<size_t>(width * height)); images[1].resize(static_cast<size_t>(width * height)); images[2].resize(static_cast<size_t>(width * height)); images[3].resize(static_cast<size_t>(width * height)); // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers for (size_t i = 0; i < static_cast<size_t>(width * height); i++) { images[0][i] = data[static_cast<size_t>(components) * i + 0]; images[1][i] = data[static_cast<size_t>(components) * i + 1]; images[2][i] = data[static_cast<size_t>(components) * i + 2]; if (components == 4) { images[3][i] = data[static_cast<size_t>(components) * i + 3]; } } } float *image_ptr[4] = {0, 0, 0, 0}; if (components == 4) { image_ptr[0] = &(images[3].at(0)); // A image_ptr[1] = &(images[2].at(0)); // B image_ptr[2] = &(images[1].at(0)); // G image_ptr[3] = &(images[0].at(0)); // R } else if (components == 3) { image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R } else if (components == 1) { image_ptr[0] = &(images[0].at(0)); // A } image.images = reinterpret_cast<unsigned char **>(image_ptr); image.width = width; image.height = height; header.num_channels = components; header.channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels))); // Must be (A)BGR order, since most of EXR viewers expect this channel order. if (components == 4) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); strncpy_s(header.channels[1].name, "B", 255); strncpy_s(header.channels[2].name, "G", 255); strncpy_s(header.channels[3].name, "R", 255); #else strncpy(header.channels[0].name, "A", 255); strncpy(header.channels[1].name, "B", 255); strncpy(header.channels[2].name, "G", 255); strncpy(header.channels[3].name, "R", 255); #endif header.channels[0].name[strlen("A")] = '\0'; header.channels[1].name[strlen("B")] = '\0'; header.channels[2].name[strlen("G")] = '\0'; header.channels[3].name[strlen("R")] = '\0'; } else if (components == 3) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "B", 255); strncpy_s(header.channels[1].name, "G", 255); strncpy_s(header.channels[2].name, "R", 255); #else strncpy(header.channels[0].name, "B", 255); strncpy(header.channels[1].name, "G", 255); strncpy(header.channels[2].name, "R", 255); #endif header.channels[0].name[strlen("B")] = '\0'; header.channels[1].name[strlen("G")] = '\0'; header.channels[2].name[strlen("R")] = '\0'; } else { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); #else strncpy(header.channels[0].name, "A", 255); #endif header.channels[0].name[strlen("A")] = '\0'; } header.pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); header.requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image if (save_as_fp16 > 0) { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format } else { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e. // no precision reduction) } } int ret = SaveEXRImageToFile(&image, &header, outfilename, err); if (ret != TINYEXR_SUCCESS) { return ret; } free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); return ret; } #ifdef __clang__ // zero-as-null-ppinter-constant #pragma clang diagnostic pop #endif #endif // TINYEXR_IMPLEMENTATION_DEIFNED #endif // TINYEXR_IMPLEMENTATION
rose_matrixmultiply.c
/* Naive matrix-matrix multiplication(mmm) By C. Liao */ #define N 1000 #define M 1000 #define K 1000 #include "omp.h" int i; int j; int k; double a[1000][1000]; double b[1000][1000]; double c[1000][1000]; int mmm() { //#pragma omp parallel for private(i,j,k) shared(a,b,c) #pragma omp parallel for private (i,j,k) for (i = 0; i <= 999; i += 1) { #pragma omp parallel for private (j,k) for (j = 0; j <= 999; j += 1) { for (k = 0; k <= 999; k += 1) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } } return 0; }
main.c
//=============================================================================================================================================================================================================== //=============================================================================================================================================================================================================== // DEFINE / INCLUDE //=============================================================================================================================================================================================================== //=============================================================================================================================================================================================================== #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> #include "AVI/avilib.h" #include "AVI/avimod.h" #include <omp.h> //#include "define.c" #include "kernel.c" //===============================================================================================================================================================================================================200 // WRITE DATA FUNCTION //===============================================================================================================================================================================================================200 #include <omp.h> void write_data(char *filename,int frameNo,int frames_processed,int endoPoints,int *input_a,int *input_b,int epiPoints,int *input_2a,int *input_2b) { //================================================================================80 // VARIABLES //================================================================================80 FILE *fid; int i; int j; char c; //================================================================================80 // OPEN FILE FOR READING //================================================================================80 fid = fopen(filename,"w+"); if (fid == ((void *)0)) { printf("The file was not opened for writing\n"); return ; } //================================================================================80 // WRITE VALUES TO THE FILE //================================================================================80 fprintf(fid,"Total AVI Frames: %d\n",frameNo); fprintf(fid,"Frames Processed: %d\n",frames_processed); fprintf(fid,"endoPoints: %d\n",endoPoints); fprintf(fid,"epiPoints: %d",epiPoints); for (j = 0; j <= frames_processed - 1; j += 1) { fprintf(fid,"\n---Frame %d---",j); fprintf(fid,"\n--endo--\n",j); for (i = 0; i <= endoPoints - 1; i += 1) { fprintf(fid,"%d\t",input_a[j + i * frameNo]); } fprintf(fid,"\n"); for (i = 0; i <= endoPoints - 1; i += 1) { // if(input_b[j*size+i] > 2000) input_b[j*size+i]=0; fprintf(fid,"%d\t",input_b[j + i * frameNo]); } fprintf(fid,"\n--epi--\n",j); for (i = 0; i <= epiPoints - 1; i += 1) { //if(input_2a[j*size_2+i] > 2000) input_2a[j*size_2+i]=0; fprintf(fid,"%d\t",input_2a[j + i * frameNo]); } fprintf(fid,"\n"); for (i = 0; i <= epiPoints - 1; i += 1) { //if(input_2b[j*size_2+i] > 2000) input_2b[j*size_2+i]=0; fprintf(fid,"%d\t",input_2b[j + i * frameNo]); } } // ================================================================================80 // CLOSE FILE // ================================================================================80 fclose(fid); } //=============================================================================================================================================================================================================== //=============================================================================================================================================================================================================== // MAIN FUNCTION //=============================================================================================================================================================================================================== //=============================================================================================================================================================================================================== int main(int argc,char *argv[]) { //====================================================================================================================================================== // VARIABLES //====================================================================================================================================================== // counters int i; int frames_processed; // parameters public_struct public; private_struct private[51]; //====================================================================================================================================================== // FRAMES //====================================================================================================================================================== if (argc != 4) { printf("ERROR: usage: heartwall <inputfile> <num of frames> <num of threads>\n"); exit(1); } char *video_file_name; video_file_name = argv[1]; // added casting avi_t *d_frames = (avi_t *)(AVI_open_input_file(video_file_name,1)); if (d_frames == ((void *)0)) { AVI_print_error((char *)"Error with AVI_open_input_file"); return - 1; } public . d_frames = d_frames; public . frames = (AVI_video_frames(public . d_frames)); public . frame_rows = AVI_video_height(public . d_frames); public . frame_cols = AVI_video_width(public . d_frames); public . frame_elem = public . frame_rows * public . frame_cols; public . frame_mem = (sizeof(float ) * public . frame_elem); //====================================================================================================================================================== // CHECK INPUT ARGUMENTS //====================================================================================================================================================== frames_processed = atoi(argv[2]); if (frames_processed < 0 || frames_processed > public . frames) { printf("ERROR: %d is an incorrect number of frames specified, select in the range of 0-%d\n",frames_processed,public . frames); return 0; } int omp_num_threads; omp_num_threads = atoi(argv[3]); if (omp_num_threads <= 0) { printf("num of threads must be a positive integer"); return 0; } printf("num of threads: %d\n",omp_num_threads); //====================================================================================================================================================== // INPUTS //====================================================================================================================================================== //==================================================================================================== // ENDO POINTS //==================================================================================================== public . endoPoints = 20; public . d_endo_mem = (sizeof(int ) * public . endoPoints); public . d_endoRow = ((int *)(malloc(public . d_endo_mem))); public . d_endoRow[0] = 369; public . d_endoRow[1] = 400; public . d_endoRow[2] = 429; public . d_endoRow[3] = 452; public . d_endoRow[4] = 476; public . d_endoRow[5] = 486; public . d_endoRow[6] = 479; public . d_endoRow[7] = 458; public . d_endoRow[8] = 433; public . d_endoRow[9] = 404; public . d_endoRow[10] = 374; public . d_endoRow[11] = 346; public . d_endoRow[12] = 318; public . d_endoRow[13] = 294; public . d_endoRow[14] = 277; public . d_endoRow[15] = 269; public . d_endoRow[16] = 275; public . d_endoRow[17] = 287; public . d_endoRow[18] = 311; public . d_endoRow[19] = 339; public . d_endoCol = ((int *)(malloc(public . d_endo_mem))); public . d_endoCol[0] = 408; public . d_endoCol[1] = 406; public . d_endoCol[2] = 397; public . d_endoCol[3] = 383; public . d_endoCol[4] = 354; public . d_endoCol[5] = 322; public . d_endoCol[6] = 294; public . d_endoCol[7] = 270; public . d_endoCol[8] = 250; public . d_endoCol[9] = 237; public . d_endoCol[10] = 235; public . d_endoCol[11] = 241; public . d_endoCol[12] = 254; public . d_endoCol[13] = 273; public . d_endoCol[14] = 300; public . d_endoCol[15] = 328; public . d_endoCol[16] = 356; public . d_endoCol[17] = 383; public . d_endoCol[18] = 401; public . d_endoCol[19] = 411; public . d_tEndoRowLoc = ((int *)(malloc((public . d_endo_mem * public . frames)))); public . d_tEndoColLoc = ((int *)(malloc((public . d_endo_mem * public . frames)))); //==================================================================================================== // EPI POINTS //==================================================================================================== public . epiPoints = 31; public . d_epi_mem = (sizeof(int ) * public . epiPoints); public . d_epiRow = ((int *)(malloc(public . d_epi_mem))); public . d_epiRow[0] = 390; public . d_epiRow[1] = 419; public . d_epiRow[2] = 448; public . d_epiRow[3] = 474; public . d_epiRow[4] = 501; public . d_epiRow[5] = 519; public . d_epiRow[6] = 535; public . d_epiRow[7] = 542; public . d_epiRow[8] = 543; public . d_epiRow[9] = 538; public . d_epiRow[10] = 528; public . d_epiRow[11] = 511; public . d_epiRow[12] = 491; public . d_epiRow[13] = 466; public . d_epiRow[14] = 438; public . d_epiRow[15] = 406; public . d_epiRow[16] = 376; public . d_epiRow[17] = 347; public . d_epiRow[18] = 318; public . d_epiRow[19] = 291; public . d_epiRow[20] = 275; public . d_epiRow[21] = 259; public . d_epiRow[22] = 256; public . d_epiRow[23] = 252; public . d_epiRow[24] = 252; public . d_epiRow[25] = 257; public . d_epiRow[26] = 266; public . d_epiRow[27] = 283; public . d_epiRow[28] = 305; public . d_epiRow[29] = 331; public . d_epiRow[30] = 360; public . d_epiCol = ((int *)(malloc(public . d_epi_mem))); public . d_epiCol[0] = 457; public . d_epiCol[1] = 454; public . d_epiCol[2] = 446; public . d_epiCol[3] = 431; public . d_epiCol[4] = 411; public . d_epiCol[5] = 388; public . d_epiCol[6] = 361; public . d_epiCol[7] = 331; public . d_epiCol[8] = 301; public . d_epiCol[9] = 273; public . d_epiCol[10] = 243; public . d_epiCol[11] = 218; public . d_epiCol[12] = 196; public . d_epiCol[13] = 178; public . d_epiCol[14] = 166; public . d_epiCol[15] = 157; public . d_epiCol[16] = 155; public . d_epiCol[17] = 165; public . d_epiCol[18] = 177; public . d_epiCol[19] = 197; public . d_epiCol[20] = 218; public . d_epiCol[21] = 248; public . d_epiCol[22] = 276; public . d_epiCol[23] = 304; public . d_epiCol[24] = 333; public . d_epiCol[25] = 361; public . d_epiCol[26] = 391; public . d_epiCol[27] = 415; public . d_epiCol[28] = 434; public . d_epiCol[29] = 448; public . d_epiCol[30] = 455; public . d_tEpiRowLoc = ((int *)(malloc((public . d_epi_mem * public . frames)))); public . d_tEpiColLoc = ((int *)(malloc((public . d_epi_mem * public . frames)))); //==================================================================================================== // ALL POINTS //==================================================================================================== public . allPoints = 51; //====================================================================================================================================================== // CONSTANTS //====================================================================================================================================================== public . tSize = 25; public . sSize = 40; public . maxMove = 10; public . alpha = 0.87; //====================================================================================================================================================== // SUMS //====================================================================================================================================================== for (i = 0; i <= public . allPoints - 1; i += 1) { private[i] . in_partial_sum = ((float *)(malloc(sizeof(float ) * 2 * public . tSize + 1))); private[i] . in_sqr_partial_sum = ((float *)(malloc(sizeof(float ) * 2 * public . tSize + 1))); private[i] . par_max_val = ((float *)(malloc(sizeof(float ) * (2 * public . tSize + 2 * public . sSize + 1)))); private[i] . par_max_coo = ((int *)(malloc(sizeof(int ) * (2 * public . tSize + 2 * public . sSize + 1)))); } //====================================================================================================================================================== // INPUT 2 (SAMPLE AROUND POINT) //====================================================================================================================================================== public . in2_rows = 2 * public . sSize + 1; public . in2_cols = 2 * public . sSize + 1; public . in2_elem = public . in2_rows * public . in2_cols; public . in2_mem = (sizeof(float ) * public . in2_elem); for (i = 0; i <= public . allPoints - 1; i += 1) { private[i] . d_in2 = ((float *)(malloc(public . in2_mem))); private[i] . d_in2_sqr = ((float *)(malloc(public . in2_mem))); } //====================================================================================================================================================== // INPUT (POINT TEMPLATE) //====================================================================================================================================================== public . in_mod_rows = public . tSize + 1 + public . tSize; public . in_mod_cols = public . in_mod_rows; public . in_mod_elem = public . in_mod_rows * public . in_mod_cols; public . in_mod_mem = (sizeof(float ) * public . in_mod_elem); for (i = 0; i <= public . allPoints - 1; i += 1) { private[i] . d_in_mod = ((float *)(malloc(public . in_mod_mem))); private[i] . d_in_sqr = ((float *)(malloc(public . in_mod_mem))); } //====================================================================================================================================================== // ARRAY OF TEMPLATES FOR ALL POINTS //====================================================================================================================================================== public . d_endoT = ((float *)(malloc((public . in_mod_mem * public . endoPoints)))); public . d_epiT = ((float *)(malloc((public . in_mod_mem * public . epiPoints)))); //====================================================================================================================================================== // SETUP private POINTERS TO ROWS, COLS AND TEMPLATE //====================================================================================================================================================== #pragma omp parallel for private (i) for (i = 0; i <= public . endoPoints - 1; i += 1) { private[i] . point_no = i; private[i] . in_pointer = private[i] . point_no * public . in_mod_elem; // original row coordinates private[i] . d_Row = public . d_endoRow; // original col coordinates private[i] . d_Col = public . d_endoCol; // updated row coordinates private[i] . d_tRowLoc = public . d_tEndoRowLoc; // updated row coordinates private[i] . d_tColLoc = public . d_tEndoColLoc; // templates private[i] . d_T = public . d_endoT; } #pragma omp parallel for private (i) for (i = public . endoPoints; i <= public . allPoints - 1; i += 1) { private[i] . point_no = i - public . endoPoints; private[i] . in_pointer = private[i] . point_no * public . in_mod_elem; private[i] . d_Row = public . d_epiRow; private[i] . d_Col = public . d_epiCol; private[i] . d_tRowLoc = public . d_tEpiRowLoc; private[i] . d_tColLoc = public . d_tEpiColLoc; private[i] . d_T = public . d_epiT; } //====================================================================================================================================================== // CONVOLUTION //====================================================================================================================================================== public . ioffset = 0; public . joffset = 0; // number of rows in I public . conv_rows = public . in_mod_rows + public . in2_rows - 1; // number of columns in I public . conv_cols = public . in_mod_cols + public . in2_cols - 1; // number of elements public . conv_elem = public . conv_rows * public . conv_cols; public . conv_mem = (sizeof(float ) * public . conv_elem); for (i = 0; i <= public . allPoints - 1; i += 1) { private[i] . d_conv = ((float *)(malloc(public . conv_mem))); } //====================================================================================================================================================== // CUMULATIVE SUM //====================================================================================================================================================== //==================================================================================================== // PAD ARRAY //==================================================================================================== //==================================================================================================== // VERTICAL CUMULATIVE SUM //==================================================================================================== public . in2_pad_add_rows = public . in_mod_rows; public . in2_pad_add_cols = public . in_mod_cols; public . in2_pad_rows = public . in2_rows + 2 * public . in2_pad_add_rows; public . in2_pad_cols = public . in2_cols + 2 * public . in2_pad_add_cols; public . in2_pad_elem = public . in2_pad_rows * public . in2_pad_cols; public . in2_pad_mem = (sizeof(float ) * public . in2_pad_elem); for (i = 0; i <= public . allPoints - 1; i += 1) { private[i] . d_in2_pad = ((float *)(malloc(public . in2_pad_mem))); } //==================================================================================================== // SELECTION, SELECTION 2, SUBTRACTION //==================================================================================================== //==================================================================================================== // HORIZONTAL CUMULATIVE SUM //==================================================================================================== // (1 to n+1) public . in2_pad_cumv_sel_rowlow = 1 + public . in_mod_rows; public . in2_pad_cumv_sel_rowhig = public . in2_pad_rows - 1; public . in2_pad_cumv_sel_collow = 1; public . in2_pad_cumv_sel_colhig = public . in2_pad_cols; public . in2_pad_cumv_sel2_rowlow = 1; public . in2_pad_cumv_sel2_rowhig = public . in2_pad_rows - public . in_mod_rows - 1; public . in2_pad_cumv_sel2_collow = 1; public . in2_pad_cumv_sel2_colhig = public . in2_pad_cols; public . in2_sub_rows = public . in2_pad_cumv_sel_rowhig - public . in2_pad_cumv_sel_rowlow + 1; public . in2_sub_cols = public . in2_pad_cumv_sel_colhig - public . in2_pad_cumv_sel_collow + 1; public . in2_sub_elem = public . in2_sub_rows * public . in2_sub_cols; public . in2_sub_mem = (sizeof(float ) * public . in2_sub_elem); for (i = 0; i <= public . allPoints - 1; i += 1) { private[i] . d_in2_sub = ((float *)(malloc(public . in2_sub_mem))); } //==================================================================================================== // SELECTION, SELECTION 2, SUBTRACTION, SQUARE, NUMERATOR //==================================================================================================== public . in2_sub_cumh_sel_rowlow = 1; public . in2_sub_cumh_sel_rowhig = public . in2_sub_rows; public . in2_sub_cumh_sel_collow = 1 + public . in_mod_cols; public . in2_sub_cumh_sel_colhig = public . in2_sub_cols - 1; public . in2_sub_cumh_sel2_rowlow = 1; public . in2_sub_cumh_sel2_rowhig = public . in2_sub_rows; public . in2_sub_cumh_sel2_collow = 1; public . in2_sub_cumh_sel2_colhig = public . in2_sub_cols - public . in_mod_cols - 1; public . in2_sub2_sqr_rows = public . in2_sub_cumh_sel_rowhig - public . in2_sub_cumh_sel_rowlow + 1; public . in2_sub2_sqr_cols = public . in2_sub_cumh_sel_colhig - public . in2_sub_cumh_sel_collow + 1; public . in2_sub2_sqr_elem = public . in2_sub2_sqr_rows * public . in2_sub2_sqr_cols; public . in2_sub2_sqr_mem = (sizeof(float ) * public . in2_sub2_sqr_elem); for (i = 0; i <= public . allPoints - 1; i += 1) { private[i] . d_in2_sub2_sqr = ((float *)(malloc(public . in2_sub2_sqr_mem))); } //====================================================================================================================================================== // CUMULATIVE SUM 2 //====================================================================================================================================================== //==================================================================================================== // PAD ARRAY //==================================================================================================== //==================================================================================================== // VERTICAL CUMULATIVE SUM //==================================================================================================== //==================================================================================================== // SELECTION, SELECTION 2, SUBTRACTION //==================================================================================================== //==================================================================================================== // HORIZONTAL CUMULATIVE SUM //==================================================================================================== //==================================================================================================== // SELECTION, SELECTION 2, SUBTRACTION, DIFFERENTIAL LOCAL SUM, DENOMINATOR A, DENOMINATOR, CORRELATION //==================================================================================================== //====================================================================================================================================================== // TEMPLATE MASK CREATE //====================================================================================================================================================== public . tMask_rows = public . in_mod_rows + (public . sSize + 1 + public . sSize) - 1; public . tMask_cols = public . tMask_rows; public . tMask_elem = public . tMask_rows * public . tMask_cols; public . tMask_mem = (sizeof(float ) * public . tMask_elem); for (i = 0; i <= public . allPoints - 1; i += 1) { private[i] . d_tMask = ((float *)(malloc(public . tMask_mem))); } //====================================================================================================================================================== // POINT MASK INITIALIZE //====================================================================================================================================================== public . mask_rows = public . maxMove; public . mask_cols = public . mask_rows; public . mask_elem = public . mask_rows * public . mask_cols; public . mask_mem = (sizeof(float ) * public . mask_elem); //====================================================================================================================================================== // MASK CONVOLUTION //====================================================================================================================================================== // number of rows in I public . mask_conv_rows = public . tMask_rows; // number of columns in I public . mask_conv_cols = public . tMask_cols; // number of elements public . mask_conv_elem = public . mask_conv_rows * public . mask_conv_cols; public . mask_conv_mem = (sizeof(float ) * public . mask_conv_elem); public . mask_conv_ioffset = (public . mask_rows - 1) / 2; if (((public . mask_rows - 1) % 2) > 0.5) { public . mask_conv_ioffset = public . mask_conv_ioffset + 1; } public . mask_conv_joffset = (public . mask_cols - 1) / 2; if (((public . mask_cols - 1) % 2) > 0.5) { public . mask_conv_joffset = public . mask_conv_joffset + 1; } for (i = 0; i <= public . allPoints - 1; i += 1) { private[i] . d_mask_conv = ((float *)(malloc(public . mask_conv_mem))); } //====================================================================================================================================================== // PRINT FRAME PROGRESS START //====================================================================================================================================================== printf("frame progress: "); fflush(((void *)0)); //====================================================================================================================================================== // KERNEL //====================================================================================================================================================== for (public . frame_no = 0; public . frame_no < frames_processed; public . frame_no++) { //==================================================================================================== // GETTING FRAME //==================================================================================================== // Extract a cropped version of the first frame from the video file // pointer to video file public . d_frame = get_frame(public . d_frames,public . frame_no,0,0,1); // number of frame that needs to be returned // cropped? // scaled? // converted //==================================================================================================== // PROCESSING //==================================================================================================== omp_set_num_threads(omp_num_threads); for (i = 0; i <= public . allPoints - 1; i += 1) { kernel(public,private[i]); } //==================================================================================================== // FREE MEMORY FOR FRAME //==================================================================================================== // free frame after each loop iteration, since AVI library allocates memory for every frame fetched free(public . d_frame); //==================================================================================================== // PRINT FRAME PROGRESS //==================================================================================================== printf("%d ",public . frame_no); fflush(((void *)0)); } //====================================================================================================================================================== // PRINT FRAME PROGRESS END //====================================================================================================================================================== printf("\n"); fflush(((void *)0)); //====================================================================================================================================================== // DEALLOCATION //====================================================================================================================================================== //==================================================50 // DUMP DATA TO FILE //==================================================50 #ifdef OUTPUT #endif //==================================================================================================== // COMMON //==================================================================================================== free(public . d_endoRow); free(public . d_endoCol); free(public . d_tEndoRowLoc); free(public . d_tEndoColLoc); free(public . d_endoT); free(public . d_epiRow); free(public . d_epiCol); free(public . d_tEpiRowLoc); free(public . d_tEpiColLoc); free(public . d_epiT); //==================================================================================================== // POINTERS //==================================================================================================== for (i = 0; i <= public . allPoints - 1; i += 1) { free(private[i] . in_partial_sum); free(private[i] . in_sqr_partial_sum); free(private[i] . par_max_val); free(private[i] . par_max_coo); free(private[i] . d_in2); free(private[i] . d_in2_sqr); free(private[i] . d_in_mod); free(private[i] . d_in_sqr); free(private[i] . d_conv); free(private[i] . d_in2_pad); free(private[i] . d_in2_sub); free(private[i] . d_in2_sub2_sqr); free(private[i] . d_tMask); free(private[i] . d_mask_conv); } } //======================================================================================================================================================================================================== //======================================================================================================================================================================================================== // END OF FILE //======================================================================================================================================================================================================== //========================================================================================================================================================================================================
3d7pt.c
/* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 16; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k]) + beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] + A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
GB_binop__rdiv_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__rdiv_int32 // A.*B function (eWiseMult): GB_AemultB__rdiv_int32 // A*D function (colscale): GB_AxD__rdiv_int32 // D*A function (rowscale): GB_DxB__rdiv_int32 // C+=B function (dense accum): GB_Cdense_accumB__rdiv_int32 // C+=b function (dense accum): GB_Cdense_accumb__rdiv_int32 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__rdiv_int32 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__rdiv_int32 // C=scalar+B GB_bind1st__rdiv_int32 // C=scalar+B' GB_bind1st_tran__rdiv_int32 // C=A+scalar GB_bind2nd__rdiv_int32 // C=A'+scalar GB_bind2nd_tran__rdiv_int32 // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = GB_IDIV_SIGNED (bij, aij, 32) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_IDIV_SIGNED (y, x, 32) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_RDIV || GxB_NO_INT32 || GxB_NO_RDIV_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__rdiv_int32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__rdiv_int32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__rdiv_int32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__rdiv_int32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__rdiv_int32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = (int32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__rdiv_int32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__rdiv_int32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__rdiv_int32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__rdiv_int32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int32_t bij = Bx [p] ; Cx [p] = GB_IDIV_SIGNED (bij, x, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__rdiv_int32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = Ax [p] ; Cx [p] = GB_IDIV_SIGNED (y, aij, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_SIGNED (aij, x, 32) ; \ } GrB_Info GB_bind1st_tran__rdiv_int32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_SIGNED (y, aij, 32) ; \ } GrB_Info GB_bind2nd_tran__rdiv_int32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
lsh_index.h
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * 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. *************************************************************************/ /*********************************************************************** * Author: Vincent Rabaud *************************************************************************/ #ifndef FLANN_LSH_INDEX_H_ #define FLANN_LSH_INDEX_H_ #include <sstream> #include <algorithm> #include <cassert> #include <cstring> #include <map> #include <vector> #include "flann/general.h" #include "flann/algorithms/nn_index.h" #include "flann/util/matrix.h" #include "flann/util/result_set.h" #include "flann/util/heap.h" #include "flann/util/lsh_table.h" #include "flann/util/allocator.h" #include <PrintProgress.hpp> #include "flann/util/random.h" #include "flann/util/saving.h" #include <flann/algorithms/dist.h> namespace flann { struct LshIndexParams : public IndexParams { LshIndexParams(unsigned int table_number = 12, unsigned int key_size = 20, unsigned int multi_probe_level = 2) { (* this)["algorithm"] = FLANN_INDEX_LSH; // The number of hash tables to use (*this)["table_number"] = table_number; // The length of the key in the hash tables (*this)["key_size"] = key_size; // Number of levels to use in multi-probe (0 for standard LSH) (*this)["multi_probe_level"] = multi_probe_level; } }; /** * Locality-sensitive hashing index * * Contains the tables and other information for indexing a set of points * for nearest-neighbor matching. */ template<typename Distance> class LshIndex : public NNIndex<Distance> { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; typedef NNIndex<Distance> BaseClass; /** Constructor * @param params parameters passed to the LSH algorithm * @param d the distance used */ LshIndex(const IndexParams& params = LshIndexParams(), Distance d = Distance()) : BaseClass(params, d) { table_number_ = get_param<unsigned int>(index_params_,"table_number",12); key_size_ = get_param<unsigned int>(index_params_,"key_size",20); multi_probe_level_ = get_param<unsigned int>(index_params_,"multi_probe_level",2); fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); } /** Constructor * @param input_data dataset with the input features * @param params parameters passed to the LSH algorithm * @param d the distance used */ LshIndex(const Matrix<ElementType>& input_data, const IndexParams& params = LshIndexParams(), Distance d = Distance()) : BaseClass(params, d) { table_number_ = get_param<unsigned int>(index_params_,"table_number",12); key_size_ = get_param<unsigned int>(index_params_,"key_size",20); multi_probe_level_ = get_param<unsigned int>(index_params_,"multi_probe_level",2); fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); setDataset(input_data); } LshIndex(const LshIndex& other) : BaseClass(other), tables_(other.tables_), table_number_(other.table_number_), key_size_(other.key_size_), multi_probe_level_(other.multi_probe_level_), xor_masks_(other.xor_masks_) { } LshIndex& operator=(LshIndex other) { this->swap(other); return *this; } virtual ~LshIndex() { freeIndex(); } BaseClass* clone() const { return new LshIndex(*this); } using BaseClass::buildIndex; void addPoints(const Matrix<ElementType>& points, float rebuild_threshold = 2) { assert(points.cols==veclen_); size_t old_size = size_; extendDataset(points); if (rebuild_threshold>1 && size_at_build_*rebuild_threshold<size_) { buildIndex(); } else { for (unsigned int i = 0; i < table_number_; ++i) { lsh::LshTable<ElementType>& table = tables_[i]; for (size_t i=old_size;i<size_;++i) { table.add(i, points_[i]); } } } } flann_algorithm_t getType() const { return FLANN_INDEX_LSH; } template<typename Archive> void serialize(Archive& ar) { ar.setObject(this); ar & *static_cast<NNIndex<Distance>*>(this); ar & table_number_; ar & key_size_; ar & multi_probe_level_; ar & xor_masks_; ar & tables_; if (Archive::is_loading::value) { index_params_["algorithm"] = getType(); index_params_["table_number"] = table_number_; index_params_["key_size"] = key_size_; index_params_["multi_probe_level"] = multi_probe_level_; } } void saveIndex(FILE* stream) { serialization::SaveArchive sa(stream); sa & *this; } void loadIndex(FILE* stream) { serialization::LoadArchive la(stream); la & *this; } /** * Computes the index memory usage * Returns: memory used by the index */ int usedMemory() const { return size_ * sizeof(int); } /** * \brief Perform k-nearest neighbor search * \param[in] queries The query points for which to find the nearest neighbors * \param[out] indices The indices of the nearest neighbors found * \param[out] dists Distances to the nearest neighbors found * \param[in] knn Number of nearest neighbors to return * \param[in] params Search parameters */ int knnSearch(const Matrix<ElementType>& queries, Matrix<size_t>& indices, Matrix<DistanceType>& dists, size_t knn, const SearchParams& params) const { assert(queries.cols == veclen_); assert(indices.rows >= queries.rows); assert(dists.rows >= queries.rows); assert(indices.cols >= knn); assert(dists.cols >= knn); int count = 0; if (params.use_heap==FLANN_True) { #pragma omp parallel num_threads(params.cores) { KNNUniqueResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); resultSet.copy(indices[i], dists[i], n, params.sorted); indices_to_ids(indices[i], indices[i], n); count += n; } } } else { #pragma omp parallel num_threads(params.cores) { KNNResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { /* if (i % 100 == 0 || i == queries.rows - 1) { PrintProgress::printProgress(1.0 * (i + 1) / queries.rows); } */ resultSet.clear(); clock_t startTime = clock(); findNeighbors(resultSet, queries[i], params); //printf("%d/%d, findNeighbors, %d ms\n", i+1, queries.rows, 1000L*(clock()-startTime)/CLOCKS_PER_SEC); size_t n = std::min(resultSet.size(), knn); resultSet.copy(indices[i], dists[i], n, params.sorted); indices_to_ids(indices[i], indices[i], n); count += n; } printf("\n"); } } return count; } /** * \brief Perform k-nearest neighbor search * \param[in] queries The query points for which to find the nearest neighbors * \param[out] indices The indices of the nearest neighbors found * \param[out] dists Distances to the nearest neighbors found * \param[in] knn Number of nearest neighbors to return * \param[in] params Search parameters */ int knnSearch(const Matrix<ElementType>& queries, std::vector< std::vector<size_t> >& indices, std::vector<std::vector<DistanceType> >& dists, size_t knn, const SearchParams& params) const { assert(queries.cols == veclen_); if (indices.size() < queries.rows ) indices.resize(queries.rows); if (dists.size() < queries.rows ) dists.resize(queries.rows); int count = 0; if (params.use_heap==FLANN_True) { #pragma omp parallel num_threads(params.cores) { KNNUniqueResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params, knn); size_t n = std::min(resultSet.size(), knn); indices[i].resize(n); dists[i].resize(n); if (n > 0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } count += n; } } } else { #pragma omp parallel num_threads(params.cores) { KNNResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); indices[i].resize(n); dists[i].resize(n); if (n > 0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } count += n; } } } return count; } /** * Find set of nearest neighbors to vec. Their indices are stored inside * the result object. * * Params: * result = the result object in which the indices of the nearest-neighbors are stored * vec = the vector for which to search the nearest neighbors * maxCheck = the maximum number of restarts (in a best-bin-first manner) * knn = the count of neighbors need to find */ void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& /*searchParams*/) const { getNeighbors(vec, result); } protected: /** * Builds the index */ void buildIndexImpl() { tables_.resize(table_number_); std::vector<std::pair<size_t,ElementType*> > features; features.reserve(points_.size()); for (size_t i=0;i<points_.size();++i) { features.push_back(std::make_pair(i, points_[i])); } for (unsigned int i = 0; i < table_number_; ++i) { lsh::LshTable<ElementType>& table = tables_[i]; table = lsh::LshTable<ElementType>(veclen_, key_size_); // Add the features to the table table.add(features); } } void freeIndex() { /* nothing to do here */ } private: /** Defines the comparator on score and index */ typedef std::pair<float, unsigned int> ScoreIndexPair; struct SortScoreIndexPairOnSecond { bool operator()(const ScoreIndexPair& left, const ScoreIndexPair& right) const { return left.second < right.second; } }; /** Fills the different xor masks to use when getting the neighbors in multi-probe LSH * @param key the key we build neighbors from * @param lowest_index the lowest index of the bit set * @param level the multi-probe level we are at * @param xor_masks all the xor mask */ void fill_xor_mask(lsh::BucketKey key, int lowest_index, unsigned int level, std::vector<lsh::BucketKey>& xor_masks) { xor_masks.push_back(key); if (level == 0) return; for (int index = lowest_index - 1; index >= 0; --index) { // Create a new key lsh::BucketKey new_key = key | (lsh::BucketKey(1) << index); fill_xor_mask(new_key, index, level - 1, xor_masks); } } /** Performs the approximate nearest-neighbor search. * This is a slower version than the above as it uses the ResultSet * @param vec the feature to analyze */ void getNeighbors(const ElementType* vec, ResultSet<DistanceType>& result) const { typename std::vector<lsh::LshTable<ElementType> >::const_iterator table = tables_.begin(); typename std::vector<lsh::LshTable<ElementType> >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); std::vector<lsh::BucketKey>::const_iterator xor_mask = xor_masks_.begin(); std::vector<lsh::BucketKey>::const_iterator xor_mask_end = xor_masks_.end(); for (; xor_mask != xor_mask_end; ++xor_mask) { size_t sub_key = key ^ (*xor_mask); const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); if (bucket == 0) continue; // Go over each descriptor index std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin(); std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end(); DistanceType hamming_distance; // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { if (removed_ && removed_points_.test(*training_index)) continue; // Compute the Hamming distance hamming_distance = distance_(vec, points_[*training_index], veclen_); result.addPoint(hamming_distance, *training_index); } } } } void swap(LshIndex& other) { BaseClass::swap(other); std::swap(tables_, other.tables_); std::swap(size_at_build_, other.size_at_build_); std::swap(table_number_, other.table_number_); std::swap(key_size_, other.key_size_); std::swap(multi_probe_level_, other.multi_probe_level_); std::swap(xor_masks_, other.xor_masks_); } /** The different hash tables */ std::vector<lsh::LshTable<ElementType> > tables_; /** table number */ unsigned int table_number_; /** key size */ unsigned int key_size_; /** How far should we look for neighbors in multi-probe LSH */ unsigned int multi_probe_level_; /** The XOR masks to apply to a key to get the neighboring buckets */ std::vector<lsh::BucketKey> xor_masks_; USING_BASECLASS_SYMBOLS }; template<> void LshIndex<L2_Simple<float>>::getNeighbors(const float* vec, ResultSet<float>& result) const { typename std::vector<lsh::LshTable<float> >::const_iterator table = tables_.begin(); typename std::vector<lsh::LshTable<float> >::const_iterator table_end = tables_.end(); for (; table != table_end; ++table) { size_t key = table->getKey(vec); //printf("key:%d\n", key); const lsh::Bucket* bucket = table->getBucketFromKey(key); if (bucket == 0) continue; // Go over each descriptor index std::vector<lsh::FeatureIndex>::const_iterator training_index = bucket->begin(); std::vector<lsh::FeatureIndex>::const_iterator last_training_index = bucket->end(); // Process the rest of the candidates for (; training_index < last_training_index; ++training_index) { // Compute the Euclidean distance float euclidean_distance = distance_(vec, points_[*training_index], veclen_); //printf("euclidean_distance:%f\n", euclidean_distance); result.addPoint(euclidean_distance, *training_index); } } } } #endif //FLANN_LSH_INDEX_H_
LAGraph_grread.c
//------------------------------------------------------------------------------ // LAGraph_grread: read a matrix from a binary file //------------------------------------------------------------------------------ /* LAGraph: graph algorithms based on GraphBLAS Copyright 2019 LAGraph Contributors. (see Contributors.txt for a full list of Contributors; see ContributionInstructions.txt for information on how you can Contribute to this project). All Rights Reserved. NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. Released under a BSD license, please see the LICENSE file distributed with this Software or contact permission@sei.cmu.edu for full terms. Created, in part, with funding and support from the United States Government. (see Acknowledgments.txt file). This program includes and/or can make use of certain third party source code, object code, documentation and other files ("Third Party Software"). See LICENSE file for more details. */ //------------------------------------------------------------------------------ // LAGraph_grread: read a matrix from a binary file. // Contributed by Tim Davis, Texas A&M, based on the Galois graph reader // file format. // The file format consists of a header, with the following content: // uint64_t version : either 1 or 2. 1: nodes are 2^32, 2: nodes are // 64 bit. This value is returned to the caller, but is otherwise // unused. // uint64_t esize : the size of the edge weight, as sizeof (edgetype). // For example, if the file contains edge weights of type int32_t, // esize is sizeof (int32_t) == 4. The caller must specify the // corresponding GrB_Type, and its size must match esize. // uint64_t n : the number of node in the graph. The GrB_Matrix is // n-by-n. Rectangular matrices are not supported by this format. // uint64_t e : the number of edges in the graph // This header is followed by a matrix in CSR format: // Gp : an array of size ((n+1) * sizeof (uint64_t)) bytes, but Gp [0] = 0 // does not appear in the file. This section of the file is thus // (n * sizeof (uint64_t)) bytes in length. // Gj : an array of size (e * sizeof (int32_t)), containing the adjaceny // lists. Note that the indices are 32 bit, not 64 bit, and thus // this format is limited to graphs with n < 2^32. // Gx : an array of size (e * esize), containing the edge weights. // LAgraph_grread returns its status: GrB_SUCCESS if succesful, // GrB_OUT_OF_MEMORY if out of memory, GrB_INVALID_VALUE if a file I/O error // occurs or the edge size is not what was expected. #include "LAGraph_internal.h" //------------------------------------------------------------------------------ // gr_header //------------------------------------------------------------------------------ // The gr_header specifies the first 4 * sizeof(uint64_t) bytes of the file. typedef struct { uint64_t version ; // either 1 or 2. // 1: node id's are in the range 0 to 2^32 // 2: node id's are in the range 0 to 2^64 uint64_t esize ; // sizeof (edgetype) uint64_t n ; // # of nodes in the graph uint64_t e ; // # of edges in the graph } gr_header ; //------------------------------------------------------------------------------ // LAGraph_binary_read //------------------------------------------------------------------------------ // Read a block of binary data from a file. Returns GrB_SUCCESS if successful, // GrB_INVALID_VALUE otherwise. static GrB_Info LAGraph_binary_read ( char *name, // name of array being read in FILE *fp, // file to read from void *buffer, // buffer of size nbytes to read into size_t n, // # of elements to read size_t size // size of each element ) { if (fp == NULL) { fprintf (stderr, "LAGraph_grread: file I/O error\n") ; return (GrB_INVALID_VALUE) ; } size_t n_read = fread (buffer, size, n, fp) ; if (n_read != n) { fprintf (stderr, "LAGraph_grread: file I/O error; expected %g items" ", got %g, object %s, size %g\n", (double) n_read, (double) n, name, (double) size) ; return (GrB_INVALID_VALUE) ; } return (GrB_SUCCESS) ; } //------------------------------------------------------------------------------ // LAGRAPH_FREE_ALL //------------------------------------------------------------------------------ // Free all allocated space; used only for error return. #define LAGRAPH_FREE_ALL \ { \ GrB_free (G) ; \ LAGRAPH_FREE (Gp) ; \ LAGRAPH_FREE (Gj) ; \ LAGRAPH_FREE (Gj_32) ; \ LAGRAPH_FREE (Gx) ; \ if (fp != NULL) fclose (fp) ; \ fp = NULL ; \ } //------------------------------------------------------------------------------ // LAGraph_grread //------------------------------------------------------------------------------ GrB_Info LAGraph_grread // read a matrix from a binary file ( GrB_Matrix *G, // handle of matrix to create uint64_t *G_version, // the version in the file const char *filename, // name of file to open GrB_Type gtype // type of matrix to read, NULL if no edge weights // (in that case, G has type GrB_BOOL with all // edge weights equal to 1). ) { #if defined ( GxB_SUITESPARSE_GRAPHBLAS ) && ( GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) ) printf ("v5.0.0 not supported\n") ; return (GrB_PANIC) ; #else //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; GrB_Index *Gp = NULL ; int32_t *Gj_32 = NULL ; GrB_Index *Gj = NULL ; void *Gx = NULL ; FILE *fp = NULL ; if (G == NULL || G_version == NULL || filename == NULL) { LAGRAPH_ERROR ("invalid input arguments", GrB_NULL_POINTER) ; } (*G) = NULL ; (*G_version) = 0 ; //-------------------------------------------------------------------------- // open the file //-------------------------------------------------------------------------- fp = fopen (filename, "r") ; if (fp == NULL) { fprintf (stderr, "LAGraph_grread: file not found: %s\n", filename) ; LAGRAPH_ERROR ("input file not found", GrB_INVALID_VALUE) ; } //-------------------------------------------------------------------------- // open the file and read the gr_header //-------------------------------------------------------------------------- gr_header header ; LAGRAPH_OK (LAGraph_binary_read ("header", fp, &header, 1, sizeof (gr_header))) ; uint64_t version = header.version ; // version, 1 or 2 uint64_t esize = header.esize ; // sizeof (edge type) uint64_t n = header.n ; // # of nodes uint64_t e = header.e ; // # of edges (*G_version) = version ; size_t esize_expected = 0 ; if (gtype != NULL) { LAGRAPH_OK (GxB_Type_size (&esize_expected, gtype)) ; } if (esize != esize_expected) { fprintf (stderr, "LAGraph_grread: esize in file (%g) does not match" " gtype size (%g)\n", (double) esize, (double) esize_expected) ; LAGRAPH_ERROR ("unexpected edge size", GrB_INVALID_VALUE) ; } if (! (version == 1 || version == 2)) { LAGRAPH_ERROR ("invalid version, must be 1 or 2", GrB_INVALID_VALUE) ; } if (version == 1 && n > UINT32_MAX) { LAGRAPH_ERROR ("problem too large", GrB_INVALID_VALUE) ; } //-------------------------------------------------------------------------- // allocate and read in the pointers //-------------------------------------------------------------------------- Gp = LAGraph_malloc (n+1, sizeof (GrB_Index)) ; if (Gp == NULL) { LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ; } Gp [0] = 0 ; LAGRAPH_OK (LAGraph_binary_read ("pointers", fp, Gp+1, n, sizeof (GrB_Index))) ; //-------------------------------------------------------------------------- // allocate and read in the indices //-------------------------------------------------------------------------- Gj = LAGraph_malloc (e, sizeof (GrB_Index)) ; if (Gj == NULL) { LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ; } if (version == 1) { //---------------------------------------------------------------------- // indices are in 32-bit format in the file //---------------------------------------------------------------------- // allocate workspace for a single chunk #define CHUNK (10 * 1024 * 1024) int64_t chunk = LAGRAPH_MIN (CHUNK, e) ; Gj_32 = LAGraph_malloc (chunk, sizeof (int32_t)) ; if (Gj_32 == NULL) { LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ; } // read in the indices one chunk at a time for (int64_t k = 0 ; k < e ; k += CHUNK) { // read in the next chunk int64_t chunk = LAGRAPH_MIN (CHUNK, e-k) ; LAGRAPH_OK (LAGraph_binary_read ("indices", fp, Gj_32, chunk, sizeof (int32_t))) ; // convert the chunk to 64-bit #pragma omp parallel for schedule(static) for (GrB_Index p = 0 ; p < chunk ; p++) { Gj [k + p] = (GrB_Index) Gj_32 [p] ; } } LAGRAPH_FREE (Gj_32) ; } else { //---------------------------------------------------------------------- // indices are in 64-bit format in the file //---------------------------------------------------------------------- LAGRAPH_OK (LAGraph_binary_read ("indices", fp, Gj, e, sizeof (GrB_Index))) ; } //-------------------------------------------------------------------------- // read in the values //-------------------------------------------------------------------------- bool no_edge_weights = (gtype == NULL) ; if (no_edge_weights) { // the input file has no edge weights gtype = GrB_BOOL ; esize = sizeof (bool) ; } Gx = LAGraph_malloc (e, esize) ; if (Gx == NULL) LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ; if (no_edge_weights) { // set all edge weights to boolean true bool *Gbool = (bool *) Gx ; #pragma omp parallel for schedule(static) for (GrB_Index p = 0 ; p < e ; p++) { Gbool [p] = true ; } } else { // read in the edge weights LAGRAPH_OK (LAGraph_binary_read ("edgeweights", fp, Gx, e, esize)) ; } //-------------------------------------------------------------------------- // import the data into the GrB_Matrix //-------------------------------------------------------------------------- #if GxB_IMPLEMENTATION >= GxB_VERSION (4,0,1) LAGRAPH_OK (GxB_Matrix_import_CSR (G, gtype, n, n, &Gp, &Gj, &Gx, n+1, e, e, false, NULL)) ; #elif GxB_IMPLEMENTATION == GxB_VERSION (4,0,0) LAGRAPH_OK (GxB_Matrix_import_CSR (G, gtype, n, n, e, false, -1, &Gp, &Gj, &Gx, NULL)) ; #else LAGRAPH_OK (GxB_Matrix_import_CSR (G, gtype, n, n, e, -1, &Gp, &Gj, &Gx, NULL)) ; #endif //-------------------------------------------------------------------------- // close the file and return result //-------------------------------------------------------------------------- fclose (fp) ; return (GrB_SUCCESS) ; #endif }
THZTensorMath.c
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #ifndef THZ_GENERIC_FILE #define THZ_GENERIC_FILE "generic/THZTensorMath.c" #else #define THZ_OMP_OVERHEAD_THZRESHOLD 100000 void THZTensor_(fill)(THZTensor *r_, real value) { TH_TENSOR_APPLY(real, r_, THZVector_(fill)(r__data, value, r__size); break;); } void THZTensor_(zero)(THZTensor *r_) { TH_TENSOR_APPLY(real, r_, THZVector_(fill)(r__data, 0, r__size); break;); } void THZTensor_(maskedFill)(THZTensor *tensor, THByteTensor *mask, real value) { TH_TENSOR_APPLY2(real, tensor, unsigned char, mask, if (*mask_data > 1) THError("Mask tensor can take 0 and 1 values only"); else if (*mask_data == 1) *tensor_data = value;); } void THZTensor_(maskedCopy)(THZTensor *tensor, THByteTensor *mask, THZTensor* src ) { THZTensor *srct = THZTensor_(newContiguous)(src); real *src_data = THZTensor_(data)(srct); long cntr = 0; long nelem = THZTensor_(nElement)(srct); TH_TENSOR_APPLY2(real, tensor, unsigned char, mask, if (*mask_data > 1) { THError("Mask tensor can take 0 and 1 values only"); } else if (*mask_data == 1) { *tensor_data = *src_data; src_data++; cntr++; if (cntr > nelem) THError("Number of elements of src != mask"); }); if (cntr != nelem) THError("Number of elements of src != mask"); THZTensor_(free)(srct); } void THZTensor_(maskedSelect)(THZTensor *tensor, THZTensor *src, THByteTensor *mask) { long numel = THByteTensor_sumall(mask); real *tensor_data; THZTensor_(resize1d)(tensor,numel); tensor_data = THZTensor_(data)(tensor); TH_TENSOR_APPLY2(real, src, unsigned char, mask, if (*mask_data > 1) { THError("Mask tensor can take 0 and 1 values only"); } else if (*mask_data == 1) { *tensor_data = *src_data; tensor_data++; }); } void THZTensor_(indexSelect)(THZTensor *tensor, THZTensor *src, int dim, THLongTensor *index) { long i, numel; THLongStorage *newSize; THZTensor *tSlice, *sSlice; long *index_data; THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < src->nDimension,4,"Indexing dim is out of bounds"); THArgCheck(src->nDimension > 0,2,"Source tensor is empty"); numel = THLongTensor_nElement(index); newSize = THLongStorage_newWithSize(src->nDimension); THLongStorage_rawCopy(newSize,src->size); newSize->data[dim] = numel; THZTensor_(resize)(tensor,newSize,NULL); THLongStorage_free(newSize); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); for (i=0; i<numel; i++) { if (src->nDimension > 1) { tSlice = THZTensor_(new)(); sSlice = THZTensor_(new)(); THZTensor_(select)(tSlice, tensor, dim, i); THZTensor_(select)(sSlice, src, dim, index_data[i]-1); THZTensor_(copy)(tSlice, sSlice); THZTensor_(free)(tSlice); THZTensor_(free)(sSlice); } else { THZTensor_(set1d)(tensor,i,THZTensor_(get1d)(src,index_data[i]-1)); } } THLongTensor_free(index); } void THZTensor_(indexCopy)(THZTensor *tensor, int dim, THLongTensor *index, THZTensor *src) { long i, numel; THZTensor *tSlice, *sSlice; long *index_data; numel = THLongTensor_nElement(index); THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < src->nDimension,4,"Indexing dim is out of bounds"); THArgCheck(numel == src->size[dim],4,"Number of indices should be equal to source:size(dim)"); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); for (i=0; i<numel; i++) { if (tensor->nDimension > 1 ) { tSlice = THZTensor_(new)(); sSlice = THZTensor_(new)(); THZTensor_(select)(tSlice, tensor, dim, index_data[i]-1); THZTensor_(select)(sSlice, src, dim, i); THZTensor_(copy)(tSlice, sSlice); THZTensor_(free)(tSlice); THZTensor_(free)(sSlice); } else { THZTensor_(set1d)(tensor,index_data[i]-1,THZTensor_(get1d)(src,i)); } } THLongTensor_free(index); } void THZTensor_(indexFill)(THZTensor *tensor, int dim, THLongTensor *index, real val) { long i, numel; THZTensor *tSlice; long *index_data; numel = THLongTensor_nElement(index); THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < tensor->nDimension,4,"Indexing dim is out of bounds"); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); for (i=0; i<numel; i++) { if (tensor->nDimension > 1 ) { tSlice = THZTensor_(new)(); THZTensor_(select)(tSlice, tensor,dim,index_data[i]-1); THZTensor_(fill)(tSlice, val); THZTensor_(free)(tSlice); } else { THZTensor_(set1d)(tensor,index_data[i]-1,val); } } THLongTensor_free(index); } accreal THZTensor_(dot)(THZTensor *tensor, THZTensor *src) { accreal sum = 0; /* we use a trick here. careful with that. */ TH_TENSOR_APPLY2(real, tensor, real, src, long sz = (tensor_size-tensor_i < src_size-src_i ? tensor_size-tensor_i : src_size-src_i); sum += THZBlas_(dot)(sz, src_data, src_stride, tensor_data, tensor_stride); tensor_i += sz; src_i += sz; tensor_data += sz*tensor_stride; src_data += sz*src_stride; break;); return sum; } real THZTensor_(minall)(THZTensor *tensor) { real theMin; THArgCheck(tensor->nDimension > 0, 1, "tensor must have one dimension"); theMin = THZTensor_(data)(tensor)[0]; TH_TENSOR_APPLY(real, tensor, if(CABS(*tensor_data) < CABS(theMin)) theMin = *tensor_data;); return theMin; } real THZTensor_(maxall)(THZTensor *tensor) { real theMax; THArgCheck(tensor->nDimension > 0, 1, "tensor must have one dimension"); theMax = THZTensor_(data)(tensor)[0]; TH_TENSOR_APPLY(real, tensor, if(CABS(*tensor_data) > CABS(theMax)) theMax = *tensor_data;); return theMax; } accreal THZTensor_(sumall)(THZTensor *tensor) { accreal sum = 0; TH_TENSOR_APPLY(real, tensor, sum += *tensor_data;); return sum; } void THZTensor_(add)(THZTensor *r_, THZTensor *t, real value) { THZTensor_(resizeAs)(r_, t); if (THZTensor_(isContiguous)(r_) && THZTensor_(isContiguous)(t) && THZTensor_(nElement)(r_) == THZTensor_(nElement)(t)) { real *tp = THZTensor_(data)(t); real *rp = THZTensor_(data)(r_); long sz = THZTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > THZ_OMP_OVERHEAD_THZRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = tp[i] + value; } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data + value;); } } void THZTensor_(mul)(THZTensor *r_, THZTensor *t, real value) { THZTensor_(resizeAs)(r_, t); if (THZTensor_(isContiguous)(r_) && THZTensor_(isContiguous)(t) && THZTensor_(nElement)(r_) == THZTensor_(nElement)(t)) { real *tp = THZTensor_(data)(t); real *rp = THZTensor_(data)(r_); long sz = THZTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > THZ_OMP_OVERHEAD_THZRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = tp[i] * value; } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data * value;); } } void THZTensor_(div)(THZTensor *r_, THZTensor *t, real value) { THZTensor_(resizeAs)(r_, t); if (THZTensor_(isContiguous)(r_) && THZTensor_(isContiguous)(t) && THZTensor_(nElement)(r_) == THZTensor_(nElement)(t)) { real *tp = THZTensor_(data)(t); real *rp = THZTensor_(data)(r_); long sz = THZTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > THZ_OMP_OVERHEAD_THZRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = tp[i] / value; } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data / value;); } } void THZTensor_(cadd)(THZTensor *r_, THZTensor *t, real value, THZTensor *src) { THZTensor_(resizeAs)(r_, t); if (THZTensor_(isContiguous)(r_) && THZTensor_(isContiguous)(t) && THZTensor_(isContiguous)(src) && THZTensor_(nElement)(r_) == THZTensor_(nElement)(src)) { if(r_ == t) { THZBlas_(axpy)(THZTensor_(nElement)(t), value, THZTensor_(data)(src), 1, THZTensor_(data)(r_), 1); } else { real *tp = THZTensor_(data)(t); real *sp = THZTensor_(data)(src); real *rp = THZTensor_(data)(r_); long sz = THZTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > THZ_OMP_OVERHEAD_THZRESHOLD) private(i) for (i=0; i< sz; i++) rp[i] = tp[i] + value * sp[i]; } } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data + value * *src_data;); } } void THZTensor_(cmul)(THZTensor *r_, THZTensor *t, THZTensor *src) { THZTensor_(resizeAs)(r_, t); if (THZTensor_(isContiguous)(r_) && THZTensor_(isContiguous)(t) && THZTensor_(isContiguous)(src) && THZTensor_(nElement)(r_) == THZTensor_(nElement)(src)) { real *tp = THZTensor_(data)(t); real *sp = THZTensor_(data)(src); real *rp = THZTensor_(data)(r_); long sz = THZTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > THZ_OMP_OVERHEAD_THZRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = tp[i] * sp[i]; } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data * *src_data;); } } void THZTensor_(cdiv)(THZTensor *r_, THZTensor *t, THZTensor *src) { THZTensor_(resizeAs)(r_, t); if (THZTensor_(isContiguous)(r_) && THZTensor_(isContiguous)(t) && THZTensor_(isContiguous)(src) && THZTensor_(nElement)(r_) == THZTensor_(nElement)(src)) { real *tp = THZTensor_(data)(t); real *sp = THZTensor_(data)(src); real *rp = THZTensor_(data)(r_); long sz = THZTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > THZ_OMP_OVERHEAD_THZRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = tp[i] / sp[i]; } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data / *src_data;); } } void THZTensor_(addcmul)(THZTensor *r_, THZTensor *t, real value, THZTensor *src1, THZTensor *src2) { if(r_ != t) { THZTensor_(resizeAs)(r_, t); THZTensor_(copy)(r_, t); } TH_TENSOR_APPLY3(real, r_, real, src1, real, src2, *r__data += value * *src1_data * *src2_data;); } void THZTensor_(addcdiv)(THZTensor *r_, THZTensor *t, real value, THZTensor *src1, THZTensor *src2) { if(r_ != t) { THZTensor_(resizeAs)(r_, t); THZTensor_(copy)(r_, t); } TH_TENSOR_APPLY3(real, r_, real, src1, real, src2, *r__data += value * *src1_data / *src2_data;); } void THZTensor_(addmv)(THZTensor *r_, real beta, THZTensor *t, real alpha, THZTensor *mat, THZTensor *vec) { if( (mat->nDimension != 2) || (vec->nDimension != 1) ) THError("matrix and vector expected"); if( mat->size[1] != vec->size[0] ) THError("size mismatch"); if(t->nDimension != 1) THError("size mismatch"); if(t->size[0] != mat->size[0]) THError("size mismatch"); if(r_ != t) { THZTensor_(resizeAs)(r_, t); THZTensor_(copy)(r_, t); } if(mat->stride[0] == 1) { THZBlas_(gemv)('n', mat->size[0], mat->size[1], alpha, THZTensor_(data)(mat), mat->stride[1], THZTensor_(data)(vec), vec->stride[0], beta, THZTensor_(data)(r_), r_->stride[0]); } else if(mat->stride[1] == 1) { THZBlas_(gemv)('t', mat->size[1], mat->size[0], alpha, THZTensor_(data)(mat), mat->stride[0], THZTensor_(data)(vec), vec->stride[0], beta, THZTensor_(data)(r_), r_->stride[0]); } else { THZTensor *cmat = THZTensor_(newContiguous)(mat); THZBlas_(gemv)('t', mat->size[1], mat->size[0], alpha, THZTensor_(data)(cmat), cmat->stride[0], THZTensor_(data)(vec), vec->stride[0], beta, THZTensor_(data)(r_), r_->stride[0]); THZTensor_(free)(cmat); } } void THZTensor_(addmm)(THZTensor *r_, real beta, THZTensor *t, real alpha, THZTensor *m1, THZTensor *m2) { char transpose_r, transpose_m1, transpose_m2; THZTensor *r__, *m1_, *m2_; if( (m1->nDimension != 2) || (m2->nDimension != 2) ) THError("matrix and matrix expected"); if(t->nDimension != 2) THError("size mismatch"); if( (t->size[0] != m1->size[0]) || (t->size[1] != m2->size[1]) || (m1->size[1] != m2->size[0]) ) THError("size mismatch"); if(t != r_) { THZTensor_(resizeAs)(r_, t); THZTensor_(copy)(r_, t); } /* printf("%ldx%ld = %ldx%ld X %ldx%ld\n", r_->size[0], r_->size[1], m1->size[0], m1->size[1], m2->size[0], m2->size[1]); */ /* r_ */ if(r_->stride[0] == 1) { transpose_r = 'n'; r__ = r_; } else if(r_->stride[1] == 1) { THZTensor *swap = m2; m2 = m1; m1 = swap; transpose_r = 't'; r__ = r_; } else { transpose_r = 'n'; r__ = THZTensor_(newWithSize2d)(r_->size[1], r_->size[0]); THZTensor_(copy)(r__, r_); THZTensor_(transpose)(r__, NULL, 0, 1); } /* m1 */ if(m1->stride[(transpose_r == 'n' ? 0 : 1)] == 1) { transpose_m1 = 'n'; m1_ = m1; } else if(m1->stride[(transpose_r == 'n' ? 1 : 0)] == 1) { transpose_m1 = 't'; m1_ = m1; } else { transpose_m1 = (transpose_r == 'n' ? 't' : 'n'); m1_ = THZTensor_(newContiguous)(m1); } /* m2 */ if(m2->stride[(transpose_r == 'n' ? 0 : 1)] == 1) { transpose_m2 = 'n'; m2_ = m2; } else if(m2->stride[(transpose_r == 'n' ? 1 : 0)] == 1) { transpose_m2 = 't'; m2_ = m2; } else { transpose_m2 = (transpose_r == 'n' ? 't' : 'n'); m2_ = THZTensor_(newContiguous)(m2); } /* do the operation */ THZBlas_(gemm)(transpose_m1, transpose_m2, r__->size[(transpose_r == 'n' ? 0 : 1)], r__->size[(transpose_r == 'n' ? 1 : 0)], m1_->size[(transpose_r == 'n' ? 1 : 0)], alpha, THZTensor_(data)(m1_), (transpose_m1 == 'n' ? m1_->stride[(transpose_r == 'n' ? 1 : 0)] : m1_->stride[(transpose_r == 'n' ? 0 : 1)]), THZTensor_(data)(m2_), (transpose_m2 == 'n' ? m2_->stride[(transpose_r == 'n' ? 1 : 0)] : m2_->stride[(transpose_r == 'n' ? 0 : 1)]), beta, THZTensor_(data)(r__), r__->stride[(transpose_r == 'n' ? 1 : 0)]); /* free intermediate variables */ if(m1_ != m1) THZTensor_(free)(m1_); if(m2_ != m2) THZTensor_(free)(m2_); if(r__ != r_) THZTensor_(freeCopyTo)(r__, r_); } void THZTensor_(addr)(THZTensor *r_, real beta, THZTensor *t, real alpha, THZTensor *vec1, THZTensor *vec2) { if( (vec1->nDimension != 1) || (vec2->nDimension != 1) ) THError("vector and vector expected"); if(t->nDimension != 2) THError("size mismatch"); if( (t->size[0] != vec1->size[0]) || (t->size[1] != vec2->size[0]) ) THError("size mismatch"); if(r_ != t) { THZTensor_(resizeAs)(r_, t); THZTensor_(copy)(r_, t); } if(beta != 1) THZTensor_(mul)(r_, r_, beta); if(r_->stride[0] == 1) { THZBlas_(gerc)(vec1->size[0], vec2->size[0], alpha, THZTensor_(data)(vec1), vec1->stride[0], THZTensor_(data)(vec2), vec2->stride[0], THZTensor_(data)(r_), r_->stride[1]); } else { THZTensor *cr = r_; if(r_->stride[1] != 1) cr = THZTensor_(newClone)(r_); THZTensor *cvec2 = THZTensor_(new)(); THZTensor_(conj)(cvec2, vec2); THZBlas_(geru)(cvec2->size[0], vec1->size[0], alpha, THZTensor_(data)(cvec2), cvec2->stride[0], THZTensor_(data)(vec1), vec1->stride[0], THZTensor_(data)(cr), cr->stride[0]); THZTensor_(free)(cvec2); if (cr != r_) THZTensor_(freeCopyTo)(cr, r_); } } void THZTensor_(addru)(THZTensor *r_, real beta, THZTensor *t, real alpha, THZTensor *vec1, THZTensor *vec2) { if( (vec1->nDimension != 1) || (vec2->nDimension != 1) ) THError("vector and vector expected"); if(t->nDimension != 2) THError("size mismatch"); if( (t->size[0] != vec1->size[0]) || (t->size[1] != vec2->size[0]) ) THError("size mismatch"); if(r_ != t) { THZTensor_(resizeAs)(r_, t); THZTensor_(copy)(r_, t); } if(beta != 1) THZTensor_(mul)(r_, r_, beta); if(r_->stride[0] == 1) { THZBlas_(geru)(vec1->size[0], vec2->size[0], alpha, THZTensor_(data)(vec1), vec1->stride[0], THZTensor_(data)(vec2), vec2->stride[0], THZTensor_(data)(r_), r_->stride[1]); } else if(r_->stride[0] == 1) { THZBlas_(geru)(vec2->size[0], vec1->size[0], alpha, THZTensor_(data)(vec2), vec2->stride[0], THZTensor_(data)(vec1), vec1->stride[0], THZTensor_(data)(r_), r_->stride[0]); } else { THZTensor *cr = THZTensor_(newClone)(r_); THZBlas_(geru)(vec2->size[0], vec1->size[0], alpha, THZTensor_(data)(vec2), vec2->stride[0], THZTensor_(data)(vec1), vec1->stride[0], THZTensor_(data)(cr), cr->stride[0]); THZTensor_(freeCopyTo)(cr, r_); } } long THZTensor_(numel)(THZTensor *t) { return THZTensor_(nElement)(t); } void THZTensor_(max)(THZTensor *values_, THLongTensor *indices_, THZTensor *t, int dimension) { THLongStorage *dim; long i; THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 2, "dimension out of range"); dim = THZTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THZTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, long theIndex = 0; real theMax = t_data[0]; for(i = 1; i < t_size; i++) { if(CABS(t_data[i*t_stride]) > CABS(theMax)) { theIndex = i; theMax = t_data[i*t_stride]; } } *indices__data = theIndex; *values__data = theMax;); } void THZTensor_(min)(THZTensor *values_, THLongTensor *indices_, THZTensor *t, int dimension) { THLongStorage *dim; long i; THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 2, "dimension out of range"); dim = THZTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THZTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, long theIndex = 0; real theMin = t_data[0]; for(i = 1; i < t_size; i++) { if(CABS(t_data[i*t_stride]) < CABS(theMin)) { theIndex = i; theMin = t_data[i*t_stride]; } } *indices__data = theIndex; *values__data = theMin;); } void THZTensor_(sum)(THZTensor *r_, THZTensor *t, int dimension) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 2, "dimension out of range"); dim = THZTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THZTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) sum += t_data[i*t_stride]; *r__data = (real)sum;); } void THZTensor_(prod)(THZTensor *r_, THZTensor *t, int dimension) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 2, "dimension out of range"); dim = THZTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THZTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal prod = 1; long i; for(i = 0; i < t_size; i++) prod *= t_data[i*t_stride]; *r__data = (real)prod;); } void THZTensor_(cumsum)(THZTensor *r_, THZTensor *t, int dimension) { THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 2, "dimension out of range"); THZTensor_(resizeAs)(r_, t); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal cumsum = 0; long i; for(i = 0; i < t_size; i++) { cumsum += t_data[i*t_stride]; r__data[i*r__stride] = (real)cumsum; }); } void THZTensor_(cumprod)(THZTensor *r_, THZTensor *t, int dimension) { THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 2, "dimension out of range"); THZTensor_(resizeAs)(r_, t); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal cumprod = 1; long i; for(i = 0; i < t_size; i++) { cumprod *= t_data[i*t_stride]; r__data[i*r__stride] = (real)cumprod; }); } accreal THZTensor_(trace)(THZTensor *t) { real *t_data = THZTensor_(data)(t); accreal sum = 0; long i = 0; long t_stride_0, t_stride_1, t_diag_size; THArgCheck(THZTensor_(nDimension)(t) == 2, 1, "not a matrix"); t_stride_0 = THZTensor_(stride)(t, 0); t_stride_1 = THZTensor_(stride)(t, 1); t_diag_size = THMin(THZTensor_(size)(t, 0), THZTensor_(size)(t, 1)); while(i < t_diag_size) { sum += t_data[i*(t_stride_0+t_stride_1)]; i++; } return sum; } void THZTensor_(cross)(THZTensor *r_, THZTensor *a, THZTensor *b, int dimension) { int i; if(THZTensor_(nDimension)(a) != THZTensor_(nDimension)(b)) THError("inconsitent tensor sizes"); for(i = 0; i < THZTensor_(nDimension)(a); i++) { if(THZTensor_(size)(a, i) != THZTensor_(size)(b, i)) THError("inconsistent tensor sizes"); } if(dimension < 0) { for(i = 0; i < THZTensor_(nDimension)(a); i++) { if(THZTensor_(size)(a, i) == 3) { dimension = i; break; } } if(dimension < 0) THError("no dimension of size 3"); } THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(a), 3, "dimension out of range"); THArgCheck(THZTensor_(size)(a, dimension) == 3, 3, "dimension size is not 3"); THZTensor_(resizeAs)(r_, a); TH_TENSOR_DIM_APPLY3(real, a, real, b, real, r_, dimension, r__data[0*r__stride] = a_data[1*a_stride]*b_data[2*b_stride] - a_data[2*a_stride]*b_data[1*b_stride]; r__data[1*r__stride] = a_data[2*a_stride]*b_data[0*b_stride] - a_data[0*a_stride]*b_data[2*b_stride]; r__data[2*r__stride] = a_data[0*a_stride]*b_data[1*b_stride] - a_data[1*a_stride]*b_data[0*b_stride];); } void THZTensor_(zeros)(THZTensor *r_, THLongStorage *size) { THZTensor_(resize)(r_, size, NULL); THZTensor_(zero)(r_); } void THZTensor_(ones)(THZTensor *r_, THLongStorage *size) { THZTensor_(resize)(r_, size, NULL); THZTensor_(fill)(r_, 1); } void THZTensor_(diag)(THZTensor *r_, THZTensor *t, int k) { THArgCheck(THZTensor_(nDimension)(t) == 1 || THZTensor_(nDimension)(t) == 2, 1, "matrix or a vector expected"); if(THZTensor_(nDimension)(t) == 1) { real *t_data = THZTensor_(data)(t); long t_stride_0 = THZTensor_(stride)(t, 0); long t_size = THZTensor_(size)(t, 0); long sz = t_size + (k >= 0 ? k : -k); real *r__data; long r__stride_0; long r__stride_1; long i; THZTensor_(resize2d)(r_, sz, sz); THZTensor_(zero)(r_); r__data = THZTensor_(data)(r_); r__stride_0 = THZTensor_(stride)(r_, 0); r__stride_1 = THZTensor_(stride)(r_, 1); r__data += (k >= 0 ? k*r__stride_1 : -k*r__stride_0); for(i = 0; i < t_size; i++) r__data[i*(r__stride_0+r__stride_1)] = t_data[i*t_stride_0]; } else { real *t_data = THZTensor_(data)(t); long t_stride_0 = THZTensor_(stride)(t, 0); long t_stride_1 = THZTensor_(stride)(t, 1); long sz; real *r__data; long r__stride_0; long i; if(k >= 0) sz = THMin(THZTensor_(size)(t, 0), THZTensor_(size)(t, 1)-k); else sz = THMin(THZTensor_(size)(t, 0)+k, THZTensor_(size)(t, 1)); THZTensor_(resize1d)(r_, sz); r__data = THZTensor_(data)(r_); r__stride_0 = THZTensor_(stride)(r_, 0); t_data += (k >= 0 ? k*t_stride_1 : -k*t_stride_0); for(i = 0; i < sz; i++) r__data[i*r__stride_0] = t_data[i*(t_stride_0+t_stride_1)]; } } void THZTensor_(eye)(THZTensor *r_, long n, long m) { real *r__data; long i, sz; THArgCheck(n > 0, 1, "invalid argument"); if(m <= 0) m = n; THZTensor_(resize2d)(r_, n, m); THZTensor_(zero)(r_); i = 0; r__data = THZTensor_(data)(r_); sz = THMin(THZTensor_(size)(r_, 0), THZTensor_(size)(r_, 1)); for(i = 0; i < sz; i++) r__data[i*(r_->stride[0]+r_->stride[1])] = 1; } void THZTensor_(reshape)(THZTensor *r_, THZTensor *t, THLongStorage *size) { THZTensor_(resize)(r_, size, NULL); THZTensor_(copy)(r_, t); } /* I cut and pasted (slightly adapted) the quicksort code from http://www.alienryderflex.com/quicksort/ This public-domain C implementation by Darel Rex Finley. Thanks man :) Updated Oct 16 2013: change choice of pivot to avoid worst-case being a pre-sorted input - Daniel and Julien Updated Oct 24 2013: change pivot comparison to strict inequality to avoid worst-case on constant input, see Sedgewick, Algorithms in C, Addison Wesley, 1990, p. 120 - Julien */ #define MAX_LEVELS 300 static void THZTensor_(quicksortascend)(real *arr, long *idx, long elements, long stride) { long beg[MAX_LEVELS], end[MAX_LEVELS], i=0, L, R, P, swap, pid; real rswap, piv; beg[0]=0; end[0]=elements; while (i>=0) { L=beg[i]; R=end[i]-1; if (L<R) { P=(L+R)>>1; /* Choose pivot as middle element of the current block */ piv=arr[P*stride]; pid=idx[P*stride]; rswap=arr[L*stride]; swap=idx[L*stride]; arr[L*stride]=piv; idx[L*stride]=pid; arr[P*stride]=rswap; idx[P*stride]=swap; while (L<R) { while (CABS(arr[R*stride])>CABS(piv) && L<R) R--; if (L<R) { idx[L*stride]=idx[R*stride]; arr[L*stride]=arr[R*stride]; L++; } while (CABS(arr[L*stride])<CABS(piv) && L<R) L++; if (L<R) { idx[R*stride]=idx[L*stride]; arr[R*stride]=arr[L*stride]; R--; } } idx[L*stride]=pid; arr[L*stride]=piv; beg[i+1]=L+1; end[i+1]=end[i]; end[i++]=L; if (end[i]-beg[i]>end[i-1]-beg[i-1]) { swap=beg[i]; beg[i]=beg[i-1]; beg[i-1]=swap; swap=end[i]; end[i]=end[i-1]; end[i-1]=swap; } } else { i--; } } } static void THZTensor_(quicksortdescend)(real *arr, long *idx, long elements, long stride) { long beg[MAX_LEVELS], end[MAX_LEVELS], i=0, L, R, P, swap, pid; real rswap, piv; beg[0]=0; end[0]=elements; while (i>=0) { L=beg[i]; R=end[i]-1; if (L<R) { P=(L+R)>>1; /* Choose pivot as middle element of the current block */ piv=arr[P*stride]; pid=idx[P*stride]; rswap=arr[L*stride]; swap=idx[L*stride]; arr[L*stride]=piv; idx[L*stride]=pid; arr[P*stride]=rswap; idx[P*stride]=swap; while (L<R) { while (CABS(arr[R*stride])<CABS(piv) && L<R) R--; if (L<R) { idx[L*stride]=idx[R*stride]; arr[L*stride]=arr[R*stride]; L++; } while (CABS(arr[L*stride])>CABS(piv) && L<R) L++; if (L<R) { idx[R*stride]=idx[L*stride]; arr[R*stride]=arr[L*stride]; R--; } } idx[L*stride]=pid; arr[L*stride]=piv; beg[i+1]=L+1; end[i+1]=end[i]; end[i++]=L; if (end[i]-beg[i]>end[i-1]-beg[i-1]) { swap=beg[i]; beg[i]=beg[i-1]; beg[i-1]=swap; swap=end[i]; end[i]=end[i-1]; end[i-1]=swap; } } else { i--; } } } void THZTensor_(sort)(THZTensor *rt_, THLongTensor *ri_, THZTensor *t, int dimension, int descendingOrder) { THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 2, "invalid dimension"); THZTensor_(resizeAs)(rt_, t); THZTensor_(copy)(rt_, t); { THLongStorage *size = THZTensor_(newSizeOf)(t); THLongTensor_resize(ri_, size, NULL); THLongStorage_free(size); } if(descendingOrder) { TH_TENSOR_DIM_APPLY2(real, rt_, long, ri_, dimension, long i; for(i = 0; i < ri__size; i++) ri__data[i*ri__stride] = i; THZTensor_(quicksortdescend)(rt__data, ri__data, rt__size, rt__stride);) } else { TH_TENSOR_DIM_APPLY2(real, rt_, long, ri_, dimension, long i; for(i = 0; i < ri__size; i++) ri__data[i*ri__stride] = i; THZTensor_(quicksortascend)(rt__data, ri__data, rt__size, rt__stride);) } } void THZTensor_(tril)(THZTensor *r_, THZTensor *t, long k) { long t_size_0, t_size_1; long t_stride_0, t_stride_1; long r__stride_0, r__stride_1; real *t_data, *r__data; long r, c; THArgCheck(THZTensor_(nDimension)(t) == 2, 1, "not a matrix"); THZTensor_(resizeAs)(r_, t); t_size_0 = THZTensor_(size)(t, 0); t_size_1 = THZTensor_(size)(t, 1); t_stride_0 = THZTensor_(stride)(t, 0); t_stride_1 = THZTensor_(stride)(t, 1); r__stride_0 = THZTensor_(stride)(r_, 0); r__stride_1 = THZTensor_(stride)(r_, 1); r__data = THZTensor_(data)(r_); t_data = THZTensor_(data)(t); for(r = 0; r < t_size_0; r++) { long sz = THMin(r+k+1, t_size_1); for(c = THMax(0, r+k); c < t_size_1; c++) r__data[r*r__stride_0+c*r__stride_1] = 0; for(c = 0; c < sz; c++) r__data[r*r__stride_0+c*r__stride_1] = t_data[r*t_stride_0+c*t_stride_1]; } } void THZTensor_(triu)(THZTensor *r_, THZTensor *t, long k) { long t_size_0, t_size_1; long t_stride_0, t_stride_1; long r__stride_0, r__stride_1; real *t_data, *r__data; long r, c; THArgCheck(THZTensor_(nDimension)(t) == 2, 1, "not a matrix"); THZTensor_(resizeAs)(r_, t); t_size_0 = THZTensor_(size)(t, 0); t_size_1 = THZTensor_(size)(t, 1); t_stride_0 = THZTensor_(stride)(t, 0); t_stride_1 = THZTensor_(stride)(t, 1); r__stride_0 = THZTensor_(stride)(r_, 0); r__stride_1 = THZTensor_(stride)(r_, 1); r__data = THZTensor_(data)(r_); t_data = THZTensor_(data)(t); for(r = 0; r < t_size_0; r++) { long sz = THMin(r+k, t_size_1); for(c = THMax(0, r+k); c < t_size_1; c++) r__data[r*r__stride_0+c*r__stride_1] = t_data[r*t_stride_0+c*t_stride_1]; for(c = 0; c < sz; c++) r__data[r*r__stride_0+c*r__stride_1] = 0; } } void THZTensor_(cat)(THZTensor *r_, THZTensor *ta, THZTensor *tb, int dimension) { THLongStorage *size; int i; int ndim = THMax(ta->nDimension, tb->nDimension); ndim = THMax(ndim, dimension+1); THArgCheck(dimension >= 0, 4, "invalid dimension"); size = THLongStorage_newWithSize(ndim); for(i = 0; i < ndim; i++) { int tadi = (i < ta->nDimension ? ta->size[i] : 1); int tbdi = (i < tb->nDimension ? tb->size[i] : 1); if(i == dimension) size->data[i] = tadi+tbdi; else { if(tadi != tbdi) { THLongStorage_free(size); THError("inconsistent tensor sizes"); } size->data[i] = tadi; } } THZTensor_(resize)(r_, size, NULL); THLongStorage_free(size); { THZTensor *nta = THZTensor_(newWithTensor)(r_); THZTensor_(narrow)(nta, NULL, dimension, 0, (dimension < ta->nDimension ? ta->size[dimension] : 1)); THZTensor_(copy)(nta, ta); THZTensor_(free)(nta); } { THZTensor *ntb = THZTensor_(newWithTensor)(r_); THZTensor_(narrow)(ntb, NULL, dimension, (dimension < ta->nDimension ? ta->size[dimension] : 1), (dimension < tb->nDimension ? tb->size[dimension] : 1)); THZTensor_(copy)(ntb, tb); THZTensor_(free)(ntb); } } #define TENSOR_IMPLEMENT_LOGICAL(NAME,OP) \ void THZTensor_(NAME##Value)(THByteTensor *r_, THZTensor* t, real value) \ { \ THLongStorage *tsz = THZTensor_(newSizeOf)(t); \ THByteTensor_resize(r_, tsz, NULL); \ THLongStorage_free(tsz); \ THByteTensor_zero(r_); \ TH_TENSOR_APPLY2(unsigned char, r_, real, t, \ if (CABS(*t_data) OP CABS(value)) *r__data = 1;); \ } \ void THZTensor_(NAME##Tensor)(THByteTensor *r_, THZTensor *ta, THZTensor *tb) \ { \ THLongStorage *tsz = THZTensor_(newSizeOf)(ta); \ THByteTensor_resize(r_, tsz, NULL); \ THLongStorage_free(tsz); \ THByteTensor_zero(r_); \ TH_TENSOR_APPLY3(unsigned char, r_, real, ta, real, tb, \ if(CABS(*ta_data) OP CABS(*tb_data)) *r__data = 1;); \ } \ TENSOR_IMPLEMENT_LOGICAL(lt,<) TENSOR_IMPLEMENT_LOGICAL(gt,>) TENSOR_IMPLEMENT_LOGICAL(le,<=) TENSOR_IMPLEMENT_LOGICAL(ge,>=) TENSOR_IMPLEMENT_LOGICAL(eq,==) TENSOR_IMPLEMENT_LOGICAL(ne,!=) #define LAB_IMPLEMENT_BASIC_FUNCTION(NAME, CFUNC) \ void THZTensor_(NAME)(THZTensor *r_, THZTensor *t) \ { \ THZTensor_(resizeAs)(r_, t); \ TH_TENSOR_APPLY2(real, t, real, r_, *r__data = CFUNC(*t_data);); \ } \ #define LAB_IMPLEMENT_BASIC_FUNCTION_VALUE(NAME, CFUNC) \ void THZTensor_(NAME)(THZTensor *r_, THZTensor *t, real value) \ { \ THZTensor_(resizeAs)(r_, t); \ TH_TENSOR_APPLY2(real, t, real, r_, *r__data = CFUNC(*t_data, value);); \ } \ LAB_IMPLEMENT_BASIC_FUNCTION(log,CLOG) LAB_IMPLEMENT_BASIC_FUNCTION(exp,CEXP) LAB_IMPLEMENT_BASIC_FUNCTION(cos,CCOS) LAB_IMPLEMENT_BASIC_FUNCTION(acos,CACOS) LAB_IMPLEMENT_BASIC_FUNCTION(cosh,CACOSH) LAB_IMPLEMENT_BASIC_FUNCTION(sin,CSIN) LAB_IMPLEMENT_BASIC_FUNCTION(asin,CASIN) LAB_IMPLEMENT_BASIC_FUNCTION(sinh,CSINH) LAB_IMPLEMENT_BASIC_FUNCTION(tan,CTAN) LAB_IMPLEMENT_BASIC_FUNCTION(atan,CATAN) LAB_IMPLEMENT_BASIC_FUNCTION(tanh,CTANH) LAB_IMPLEMENT_BASIC_FUNCTION_VALUE(pow,CPOW) LAB_IMPLEMENT_BASIC_FUNCTION(sqrt,CSQRT) LAB_IMPLEMENT_BASIC_FUNCTION(conj,CONJ) LAB_IMPLEMENT_BASIC_FUNCTION(proj,CPROJ) LAB_IMPLEMENT_BASIC_FUNCTION(zabs,CABS) LAB_IMPLEMENT_BASIC_FUNCTION(zarg,CARG) LAB_IMPLEMENT_BASIC_FUNCTION(zre,CREAL) LAB_IMPLEMENT_BASIC_FUNCTION(zim,CIMAG) #define LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_FLOAT(NAME, CFUNC) \ void THZTensor_(NAME)(THFloatTensor *r, THZTensor *t) \ { \ THLongStorage *tsz = THZTensor_(newSizeOf)(t); \ THFloatTensor_resize(r, tsz, NULL); \ THLongStorage_free(tsz); \ TH_TENSOR_APPLY2(real, t, float, r, *r_data = CFUNC(*t_data);); \ } #define LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_DOUBLE(NAME, CFUNC) \ void THZTensor_(NAME)(THDoubleTensor *r, THZTensor *t) \ { \ THLongStorage *tsz = THZTensor_(newSizeOf)(t); \ THDoubleTensor_resize(r, tsz, NULL); \ THLongStorage_free(tsz); \ TH_TENSOR_APPLY2(real, t, double, r, *r_data = CFUNC(*t_data);); \ } LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_FLOAT(Float_abs,CABS) LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_FLOAT(Float_arg,CARG) LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_FLOAT(Float_re,CREAL) LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_FLOAT(Float_im,CIMAG) LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_DOUBLE(Double_abs,CABS) LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_DOUBLE(Double_arg,CARG) LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_DOUBLE(Double_re,CREAL) LAB_IMPLEMENT_BASIC_FUNCTION_RETURN_DOUBLE(Double_im,CIMAG) void THZTensor_(mean)(THZTensor *r_, THZTensor *t, int dimension) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 2, "invalid dimension"); dim = THZTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THZTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) sum += t_data[i*t_stride]; *r__data = (real)sum/t_size;); } void THZTensor_(std)(THZTensor *r_, THZTensor *t, int dimension, int flag) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 3, "invalid dimension"); dim = THZTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THZTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; accreal sum2 = 0; long i; for(i = 0; i < t_size; i++) { real z = t_data[i*t_stride]; sum += z; sum2 += z*z; } if(flag) { sum /= t_size; sum2 /= t_size; sum2 -= sum*sum; sum2 = (cabs(sum2) < 0 ? 0 : sum2); *r__data = (real)csqrt(sum2); } else { sum /= t_size; sum2 /= t_size-1; sum2 -= ((real)t_size)/((real)(t_size-1))*sum*sum; sum2 = (cabs(sum2) < 0 ? 0 : sum2); *r__data = (real)csqrt(sum2); }); } void THZTensor_(var)(THZTensor *r_, THZTensor *t, int dimension, int flag) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 3, "invalid dimension"); dim = THZTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THZTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; accreal sum2 = 0; long i; for(i = 0; i < t_size; i++) { real z = t_data[i*t_stride]; sum += z; sum2 += z*z; } if(flag) { sum /= t_size; sum2 /= t_size; sum2 -= sum*sum; sum2 = (cabs(sum2) < 0 ? 0 : sum2); *r__data = sum2; } else { sum /= t_size; sum2 /= t_size-1; sum2 -= ((real)t_size)/((real)(t_size-1))*sum*sum; sum2 = (cabs(sum2) < 0 ? 0 : sum2); *r__data = (real)sum2; }); } void THZTensor_(norm)(THZTensor *r_, THZTensor *t, real value, int dimension) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(t), 3, "invalid dimension"); dim = THZTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THZTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); if(value == 0) { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) sum += t_data[i*t_stride] != 0.0; *r__data = sum;) } else { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) sum += pow(CABS(t_data[i*t_stride]), value); *r__data = (real)cpow(sum, 1.0/value);) } } accreal THZTensor_(normall)(THZTensor *tensor, real value) { accreal sum = 0; if(value == 0) { TH_TENSOR_APPLY(real, tensor, sum += *tensor_data != 0.0;); return sum; } else if(value == 1) { TH_TENSOR_APPLY(real, tensor, sum += CABS(*tensor_data);); return sum; } else if(value == 2) { TH_TENSOR_APPLY(real, tensor, accreal z = *tensor_data; sum += z*z;); return csqrt(sum); } else { TH_TENSOR_APPLY(real, tensor, sum += pow(CABS(*tensor_data), value);); return cpow(sum, 1.0/value); } } void THZTensor_(renorm)(THZTensor *res, THZTensor *src, real value, int dimension, real maxnorm) { int i; THZTensor *rowR, *rowS; THArgCheck(dimension >= 0 && dimension < THZTensor_(nDimension)(src), 3, "invalid dimension"); THArgCheck(CABS(value) > 0, 2, "non-positive-norm not supported"); THArgCheck(THZTensor_(nDimension)(src) > 1, 1, "need at least 2 dimensions"); rowR = THZTensor_(new)(); rowS = THZTensor_(new)(); THZTensor_(resizeAs)(res, src); for (i=0; i<src->size[dimension]; i++) { real norm = 0; real new_norm; THZTensor_(select)(rowS, src, dimension, i); THZTensor_(select)(rowR, res, dimension, i); if (value == 1) { TH_TENSOR_APPLY(real, rowS, norm += CABS(*rowS_data);); } else if (value == 2) { TH_TENSOR_APPLY(real, rowS, accreal z = *rowS_data; norm += z*z;); } else { TH_TENSOR_APPLY(real, rowS, norm += pow(CABS(*rowS_data), value);); } norm = CPOW(norm, 1/value); if (CABS(norm) > CABS(maxnorm)) { new_norm = maxnorm / (norm + 1e-7); TH_TENSOR_APPLY2( real, rowR, real, rowS, *rowR_data = (*rowS_data) * new_norm; ) } else THZTensor_(copy)(rowR, rowS); } THZTensor_(free)(rowR); THZTensor_(free)(rowS); } accreal THZTensor_(dist)(THZTensor *tensor, THZTensor *src, real value) { real sum = 0; TH_TENSOR_APPLY2(real, tensor, real, src, sum += pow(CABS(*tensor_data - *src_data), value);) return CPOW(sum, 1.0/value); } accreal THZTensor_(meanall)(THZTensor *tensor) { THArgCheck(tensor->nDimension > 0, 1, "empty Tensor"); return THZTensor_(sumall)(tensor)/THZTensor_(nElement)(tensor); } accreal THZTensor_(varall)(THZTensor *tensor) { accreal mean = THZTensor_(meanall)(tensor); accreal sum = 0; TH_TENSOR_APPLY(real, tensor, sum += (*tensor_data - mean)*(*tensor_data - mean);); sum /= (THZTensor_(nElement)(tensor)-1); return sum; } accreal THZTensor_(stdall)(THZTensor *tensor) { return csqrt(THZTensor_(varall)(tensor)); } #endif
GB_unaryop__lnot_int32_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_int32_uint8 // op(A') function: GB_tran__lnot_int32_uint8 // C type: int32_t // A type: uint8_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint8_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ int32_t z = (int32_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_INT32 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int32_uint8 ( int32_t *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_int32_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 16; tile_size[3] = 2048; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
sectionsModificado.c
#include <stdio.h> #include <omp.h> void funcA() { printf("En funcA: esta sección la ejecuta el thread %d\n", omp_get_thread_num()); } void funcB() { printf("En funcB: esta sección la ejecuta el thread %d\n", omp_get_thread_num()); } main() { #pragma omp parallel sections { #pragma omp section (void) funcA(); #pragma omp section (void) funcB(); } }
bml_introspection_csr.c
#include "../../macros.h" #include "../bml_introspection.h" #include "../bml_logger.h" #include "../bml_logger.h" #include "../bml_types.h" #include "bml_introspection_csr.h" #include "bml_types_csr.h" #include <complex.h> #include <math.h> #include <stdlib.h> /** Return the matrix precision. * * \param A The matrix. * \return The matrix precision. */ bml_matrix_precision_t bml_get_precision_csr( bml_matrix_csr_t * A) { if (A != NULL) { return A->matrix_precision; } else { return precision_uninitialized; } } /** Return the matrix distribution mode. * * \param A The matrix. * \return The matrix distribution mode. */ bml_distribution_mode_t bml_get_distribution_mode_csr( bml_matrix_csr_t * A) { if (A != NULL) { return A->distribution_mode; } else { return -1; } } /** Return the matrix size. * * \param A The matrix. * \return The matrix size. */ int bml_get_N_csr( bml_matrix_csr_t * A) { if (A != NULL) { return A->N_; } else { return -1; } } /** Return the matrix parameter M. * * \param A The matrix. * \return The matrix parameter M. */ int bml_get_M_csr( bml_matrix_csr_t * A) { if (A != NULL) { int max_alloc = 0; const int N = A->N_; for (int i = 0; i < N; i++) { max_alloc = (csr_row_alloc_size(A->data_[i]) > max_alloc ? csr_row_alloc_size(A->data_[i]) : max_alloc); } return max_alloc; } else { return -1; } } /** Return the bandwidth of a row in the matrix. * * \param A The bml matrix. * \param i The row index. * \return The bandwidth of row i. */ int bml_get_row_bandwidth_csr( bml_matrix_csr_t * A, int i) { return csr_row_NNZ(A->data_[i]); } /** Return the bandwidth of a matrix. * * \param A The bml matrix. * \return The bandwidth of A. */ int bml_get_bandwidth_csr( bml_matrix_csr_t * A) { int max_bandwidth = 0; const int N = A->N_; #pragma omp parallel for reduction (max:max_bandwidth) for (int i = 0; i < N; i++) { max_bandwidth = (csr_row_NNZ(A->data_[i]) > max_bandwidth ? csr_row_NNZ(A->data_[i]) : max_bandwidth); } return max_bandwidth; } /** Return the sparsity of a matrix. * * Note that the the sparsity of a matrix is defined * as (1 - NumberOfZeroes/N*N) where N is the matrix dimension. * The density of matrix A will be defined as 1-sparsity(A) * * \ingroup introspection_group_C * * \param A The bml matrix. * \param threshold The threshold used to compute the sparsity. * \return The sparsity of A. */ double bml_get_sparsity_csr( bml_matrix_csr_t * A, double threshold) { switch (bml_get_precision_csr(A)) { case single_real: return bml_get_sparsity_csr_single_real(A, threshold); break; case double_real: return bml_get_sparsity_csr_double_real(A, threshold); break; case single_complex: return bml_get_sparsity_csr_single_complex(A, threshold); break; case double_complex: return bml_get_sparsity_csr_double_complex(A, threshold); break; case precision_uninitialized: LOG_ERROR("precision not initialized"); break; default: LOG_ERROR("fatal logic error\n"); break; } return -1; }
phonon.c
/* Copyright (C) 2015 Atsushi Togo */ /* All rights reserved. */ /* This file is part of phonopy. */ /* 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 phonopy project 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. */ #include <math.h> #include <string.h> #include <stddef.h> #include "dynmat.h" #include "phonon.h" #include "lapack_wrapper.h" static long collect_undone_grid_points(long *undone, char *phonon_done, const long num_grid_points, const long *grid_points); static void get_undone_phonons(double *frequencies, lapack_complex_double *eigenvectors, const long *undone_grid_points, const long num_undone_grid_points, const long (*grid_address)[3], const double QDinv[3][3], const double *fc2, const double(*svecs_fc2)[27][3], const long *multi_fc2, const long num_patom, const long num_satom, const double *masses_fc2, const long *p2s_fc2, const long *s2p_fc2, const double unit_conversion_factor, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const char uplo); static void get_gonze_undone_phonons(double *frequencies, lapack_complex_double *eigenvectors, const long *undone_grid_points, const long num_undone_grid_points, const long (*grid_address)[3], const double QDinv[3][3], const double *fc2, const double(*svecs_fc2)[27][3], const long *multi_fc2, const double (*positions)[3], const long num_patom, const long num_satom, const double *masses_fc2, const long *p2s_fc2, const long *s2p_fc2, const double unit_conversion_factor, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double *dd_q0, const double(*G_list)[3], const long num_G_points, const double lambda, const char uplo); static void get_phonons(lapack_complex_double *eigvecs, const double q[3], const double *fc2, const double *masses, const long *p2s, const long *s2p, const long *multi, const long num_patom, const long num_satom, const double(*svecs)[27][3], const long is_nac, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double unit_conversion_factor); static void get_gonze_phonons(lapack_complex_double *eigvecs, const double q[3], const double *fc2, const double *masses, const long *p2s, const long *s2p, const long *multi, const double (*positions)[3], const long num_patom, const long num_satom, const double(*svecs)[27][3], const long is_nac, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double *dd_q0, const double(*G_list)[3], const long num_G_points, const double lambda); static void get_dynamical_matrix(lapack_complex_double *dynmat, const double q[3], const double *fc2, const double *masses, const long *p2s, const long *s2p, const long *multi, const long num_patom, const long num_satom, const double(*svecs)[27][3], const long is_nac, const double (*born)[3][3], /* Wang NAC unless NULL */ const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor); static void get_charge_sum(double (*charge_sum)[3][3], const long num_patom, const long num_satom, const double q[3], const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor); static long needs_nac(const double (*born)[3][3], const long (*grid_address)[3], const long gp, const double *q_direction); void phn_get_phonons_at_gridpoints(double *frequencies, lapack_complex_double *eigenvectors, char *phonon_done, const long num_phonons, const long *grid_points, const long num_grid_points, const long (*grid_address)[3], const double QDinv[3][3], const double *fc2, const double(*svecs_fc2)[27][3], const long *multi_fc2, const long num_patom, const long num_satom, const double *masses_fc2, const long *p2s_fc2, const long *s2p_fc2, const double unit_conversion_factor, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, /* must be pointer */ const double nac_factor, const char uplo) { long num_undone; long *undone; undone = (long*)malloc(sizeof(long) * num_phonons); num_undone = collect_undone_grid_points(undone, phonon_done, num_grid_points, grid_points); get_undone_phonons(frequencies, eigenvectors, undone, num_undone, grid_address, QDinv, fc2, svecs_fc2, multi_fc2, num_patom, num_satom, masses_fc2, p2s_fc2, s2p_fc2, unit_conversion_factor, born, dielectric, reciprocal_lattice, q_direction, nac_factor, uplo); free(undone); undone = NULL; } void phn_get_gonze_phonons_at_gridpoints(double *frequencies, lapack_complex_double *eigenvectors, char *phonon_done, const long num_phonons, const long *grid_points, const long num_grid_points, const long (*grid_address)[3], const double QDinv[3][3], const double *fc2, const double(*svecs_fc2)[27][3], const long *multi_fc2, const double (*positions)[3], const long num_patom, const long num_satom, const double *masses_fc2, const long *p2s_fc2, const long *s2p_fc2, const double unit_conversion_factor, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, /* pointer */ const double nac_factor, const double *dd_q0, const double(*G_list)[3], const long num_G_points, const double lambda, const char uplo) { long num_undone; long *undone; undone = (long*)malloc(sizeof(long) * num_phonons); num_undone = collect_undone_grid_points(undone, phonon_done, num_grid_points, grid_points); get_gonze_undone_phonons(frequencies, eigenvectors, undone, num_undone, grid_address, QDinv, fc2, svecs_fc2, multi_fc2, positions, num_patom, num_satom, masses_fc2, p2s_fc2, s2p_fc2, unit_conversion_factor, born, dielectric, reciprocal_lattice, q_direction, nac_factor, dd_q0, G_list, num_G_points, lambda, uplo); free(undone); undone = NULL; } static long collect_undone_grid_points(long *undone, char *phonon_done, const long num_grid_points, const long *grid_points) { long i, gp, num_undone; num_undone = 0; for (i = 0; i < num_grid_points; i++) { gp = grid_points[i]; if (phonon_done[gp] == 0) { undone[num_undone] = gp; num_undone++; phonon_done[gp] = 1; } } return num_undone; } static void get_undone_phonons(double *frequencies, lapack_complex_double *eigenvectors, const long *undone_grid_points, const long num_undone_grid_points, const long (*grid_address)[3], const double QDinv[3][3], const double *fc2, const double(*svecs_fc2)[27][3], const long *multi_fc2, const long num_patom, const long num_satom, const double *masses_fc2, const long *p2s_fc2, const long *s2p_fc2, const double unit_conversion_factor, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const char uplo) { long i, j, gp, num_band; long is_nac, info; double q[3]; double *freqs_tmp; num_band = num_patom * 3; #pragma omp parallel for private(j, q, gp, is_nac) for (i = 0; i < num_undone_grid_points; i++) { gp = undone_grid_points[i]; for (j = 0; j < 3; j++) { q[j] = QDinv[j][0] * grid_address[gp][0] + QDinv[j][1] * grid_address[gp][1] + QDinv[j][2] * grid_address[gp][2]; } is_nac = needs_nac(born, grid_address, gp, q_direction); get_phonons(eigenvectors + num_band * num_band * gp, q, fc2, masses_fc2, p2s_fc2, s2p_fc2, multi_fc2, num_patom, num_satom, svecs_fc2, is_nac, born, dielectric, reciprocal_lattice, q_direction, nac_factor, unit_conversion_factor); } /* To avoid multithreaded BLAS in OpenMP loop */ #ifndef MULTITHREADED_BLAS #pragma omp parallel for private(j, gp, freqs_tmp, info) #endif for (i = 0; i < num_undone_grid_points; i++) { gp = undone_grid_points[i]; freqs_tmp = frequencies + num_band * gp; /* Store eigenvalues in freqs array. */ /* Eigenvectors are overwritten on eigvecs array. */ info = phonopy_zheev(freqs_tmp, eigenvectors + num_band * num_band * gp, num_band, uplo); /* Sqrt of eigenvalues are re-stored in freqs array.*/ for (j = 0; j < num_band; j++) { freqs_tmp[j] = sqrt(fabs(freqs_tmp[j])) * ((freqs_tmp[j] > 0) - (freqs_tmp[j] < 0)) * unit_conversion_factor; } } } static void get_gonze_undone_phonons(double *frequencies, lapack_complex_double *eigenvectors, const long *undone_grid_points, const long num_undone_grid_points, const long (*grid_address)[3], const double QDinv[3][3], const double *fc2, const double(*svecs_fc2)[27][3], const long *multi_fc2, const double (*positions)[3], const long num_patom, const long num_satom, const double *masses_fc2, const long *p2s_fc2, const long *s2p_fc2, const double unit_conversion_factor, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double *dd_q0, const double(*G_list)[3], const long num_G_points, const double lambda, const char uplo) { long i, j, gp, num_band; long is_nac, info; double q[3]; double *freqs_tmp; num_band = num_patom * 3; #pragma omp parallel for private(j, q, gp, is_nac) for (i = 0; i < num_undone_grid_points; i++) { gp = undone_grid_points[i]; for (j = 0; j < 3; j++) { q[j] = QDinv[j][0] * grid_address[gp][0] + QDinv[j][1] * grid_address[gp][1] + QDinv[j][2] * grid_address[gp][2]; } is_nac = needs_nac(born, grid_address, gp, q_direction); get_gonze_phonons(eigenvectors + num_band * num_band * gp, q, fc2, masses_fc2, p2s_fc2, s2p_fc2, multi_fc2, positions, num_patom, num_satom, svecs_fc2, is_nac, born, dielectric, reciprocal_lattice, q_direction, nac_factor, dd_q0, G_list, num_G_points, lambda); } /* To avoid multithreaded BLAS in OpenMP loop */ #ifndef MULTITHREADED_BLAS #pragma omp parallel for private(j, gp, freqs_tmp, info) #endif for (i = 0; i < num_undone_grid_points; i++) { gp = undone_grid_points[i]; /* Store eigenvalues in freqs array. */ /* Eigenvectors are overwritten on eigvecs array. */ freqs_tmp = frequencies + num_band * gp; info = phonopy_zheev(freqs_tmp, eigenvectors + num_band * num_band * gp, num_band, uplo); /* Sqrt of eigenvalues are re-stored in freqs array.*/ for (j = 0; j < num_band; j++) { freqs_tmp[j] = sqrt(fabs(freqs_tmp[j])) * ((freqs_tmp[j] > 0) - (freqs_tmp[j] < 0)) * unit_conversion_factor; } } } static void get_phonons(lapack_complex_double *eigvecs, const double q[3], const double *fc2, const double *masses, const long *p2s, const long *s2p, const long *multi, const long num_patom, const long num_satom, const double(*svecs)[27][3], const long is_nac, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double unit_conversion_factor) { /* Store dynamical matrix in eigvecs array. */ get_dynamical_matrix(eigvecs, q, fc2, masses, p2s, s2p, multi, num_patom, num_satom, svecs, is_nac, born, dielectric, reciprocal_lattice, q_direction, nac_factor); } static void get_gonze_phonons(lapack_complex_double *eigvecs, const double q[3], const double *fc2, const double *masses, const long *p2s, const long *s2p, const long *multi, const double (*positions)[3], const long num_patom, const long num_satom, const double(*svecs)[27][3], const long is_nac, const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double *dd_q0, const double(*G_list)[3], const long num_G_points, const double lambda) { long i, j, k, l, adrs, num_band; double mm; double q_cart[3]; double *q_dir_cart; lapack_complex_double *dd; dd = NULL; q_dir_cart = NULL; num_band = num_patom * 3; dym_get_dynamical_matrix_at_q((double*)eigvecs, num_patom, num_satom, fc2, q, svecs, multi, masses, s2p, p2s, NULL, 0); dd = (lapack_complex_double*) malloc(sizeof(lapack_complex_double) * num_band * num_band); for (i = 0; i < 3; i++) { q_cart[i] = 0; for (j = 0; j < 3; j++) { q_cart[i] += reciprocal_lattice[i][j] * q[j]; } } if (q_direction) { q_dir_cart = (double*)malloc(sizeof(double) * 3); for (i = 0; i < 3; i++) { q_dir_cart[i] = 0; for (j = 0; j < 3; j++) { q_dir_cart[i] += reciprocal_lattice[i][j] * q_direction[j]; } } } dym_get_recip_dipole_dipole((double*)dd, dd_q0, G_list, num_G_points, num_patom, q_cart, q_dir_cart, born, dielectric, positions, nac_factor, lambda, 1e-5); if (q_direction) { free(q_dir_cart); q_dir_cart = NULL; } for (i = 0; i < num_patom; i++) { for (j = 0; j < num_patom; j++) { mm = sqrt(masses[i] * masses[j]); for (k = 0; k < 3; k++) { for (l = 0; l < 3; l++) { adrs = i * num_patom * 9 + k * num_patom * 3 + j * 3 + l; eigvecs[adrs] = lapack_make_complex_double( lapack_complex_double_real(eigvecs[adrs]) + lapack_complex_double_real(dd[adrs]) / mm, lapack_complex_double_imag(eigvecs[adrs]) + lapack_complex_double_imag(dd[adrs]) / mm); } } } } free(dd); dd = NULL; } static void get_dynamical_matrix(lapack_complex_double *dynmat, const double q[3], const double *fc2, const double *masses, const long *p2s, const long *s2p, const long *multi, const long num_patom, const long num_satom, const double(*svecs)[27][3], const long is_nac, const double (*born)[3][3], /* Wang NAC unless NULL */ const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor) { double (*charge_sum)[3][3]; charge_sum = NULL; if (is_nac) { charge_sum = (double(*)[3][3]) malloc(sizeof(double[3][3]) * num_patom * num_patom * 9); get_charge_sum(charge_sum, num_patom, num_satom, q, born, dielectric, reciprocal_lattice, q_direction, nac_factor); } dym_get_dynamical_matrix_at_q((double*)dynmat, num_patom, num_satom, fc2, q, svecs, multi, masses, s2p, p2s, charge_sum, 0); if (is_nac) { free(charge_sum); charge_sum = NULL; } } static void get_charge_sum(double (*charge_sum)[3][3], const long num_patom, const long num_satom, const double q[3], const double (*born)[3][3], const double dielectric[3][3], const double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor) { long i, j; double inv_dielectric_factor, dielectric_factor, tmp_val; double q_cart[3]; if (q_direction) { for (i = 0; i < 3; i++) { q_cart[i] = 0.0; for (j = 0; j < 3; j++) { q_cart[i] += reciprocal_lattice[i][j] * q_direction[j]; } } } else { for (i = 0; i < 3; i++) { q_cart[i] = 0.0; for (j = 0; j < 3; j++) { q_cart[i] += reciprocal_lattice[i][j] * q[j]; } } } inv_dielectric_factor = 0.0; for (i = 0; i < 3; i++) { tmp_val = 0.0; for (j = 0; j < 3; j++) { tmp_val += dielectric[i][j] * q_cart[j]; } inv_dielectric_factor += tmp_val * q_cart[i]; } /* N = num_satom / num_patom = number of prim-cell in supercell */ /* N is used for Wang's method. */ dielectric_factor = nac_factor / inv_dielectric_factor / num_satom * num_patom; dym_get_charge_sum(charge_sum, num_patom, dielectric_factor, q_cart, born); } static long needs_nac(const double (*born)[3][3], const long (*grid_address)[3], const long gp, const double *q_direction) { long is_nac; if (born) { if (grid_address[gp][0] == 0 && grid_address[gp][1] == 0 && grid_address[gp][2] == 0 && q_direction == NULL) { is_nac = 0; } else { is_nac = 1; } } else { is_nac = 0; } return is_nac; }
GB_unaryop__abs_bool_int8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_bool_int8 // op(A') function: GB_tran__abs_bool_int8 // C type: bool // A type: int8_t // cast: bool cij = (bool) aij // unaryop: cij = aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, aij) \ bool z = (bool) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_BOOL || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_bool_int8 ( bool *Cx, // Cx and Ax may be aliased int8_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_bool_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__erf_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__erf_fp32_fp32) // op(A') function: GB (_unop_tran__erf_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = erff (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = erff (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = erff (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ERF || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__erf_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = erff (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = erff (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__erf_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nr_numint.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <string.h> #include <assert.h> #include "config.h" #include "gto/grid_ao_drv.h" #include "np_helper/np_helper.h" #include "vhf/fblas.h" #define BOXSIZE 56 int VXCao_empty_blocks(char *empty, unsigned char *non0table, int *shls_slice, int *ao_loc) { if (non0table == NULL || shls_slice == NULL || ao_loc == NULL) { return 0; } const int sh0 = shls_slice[0]; const int sh1 = shls_slice[1]; int bas_id; int box_id = 0; int bound = BOXSIZE; int has0 = 0; empty[box_id] = 1; for (bas_id = sh0; bas_id < sh1; bas_id++) { empty[box_id] &= !non0table[bas_id]; if (ao_loc[bas_id] == bound) { has0 |= empty[box_id]; box_id++; bound += BOXSIZE; empty[box_id] = 1; } else if (ao_loc[bas_id] > bound) { has0 |= empty[box_id]; box_id++; bound += BOXSIZE; empty[box_id] = !non0table[bas_id]; } } return has0; } static void dot_ao_dm(double *vm, double *ao, double *dm, int nao, int nocc, int ngrids, int bgrids, unsigned char *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; char empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D1 = 1; double beta = 0; if (has0) { int box_id, blen, i, j; size_t b0; for (box_id = 0; box_id < nbox; box_id++) { if (!empty[box_id]) { b0 = box_id * BOXSIZE; blen = MIN(nao-b0, BOXSIZE); dgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &blen, &D1, ao+b0*ngrids, &ngrids, dm+b0*nocc, &nocc, &beta, vm, &ngrids); beta = 1.0; } } if (beta == 0) { // all empty for (i = 0; i < nocc; i++) { for (j = 0; j < bgrids; j++) { vm[i*ngrids+j] = 0; } } } } else { dgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &nao, &D1, ao, &ngrids, dm, &nocc, &beta, vm, &ngrids); } } /* vm[nocc,ngrids] = ao[i,ngrids] * dm[i,nocc] */ void VXCdot_ao_dm(double *vm, double *ao, double *dm, int nao, int nocc, int ngrids, int nbas, unsigned char *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; #pragma omp parallel default(none) \ shared(vm, ao, dm, nao, nocc, ngrids, nbas, \ non0table, shls_slice, ao_loc) { int ip, ib; #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_dm(vm+ip, ao+ip, dm, nao, nocc, ngrids, MIN(ngrids-ip, BLKSIZE), non0table+ib*nbas, shls_slice, ao_loc); } } } /* vv[n,m] = ao1[n,ngrids] * ao2[m,ngrids] */ static void dot_ao_ao(double *vv, double *ao1, double *ao2, int nao, int ngrids, int bgrids, int hermi, unsigned char *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; char empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D1 = 1; if (has0) { int ib, jb, leni, lenj; int j1 = nbox; size_t b0i, b0j; for (ib = 0; ib < nbox; ib++) { if (!empty[ib]) { b0i = ib * BOXSIZE; leni = MIN(nao-b0i, BOXSIZE); if (hermi) { j1 = ib + 1; } for (jb = 0; jb < j1; jb++) { if (!empty[jb]) { b0j = jb * BOXSIZE; lenj = MIN(nao-b0j, BOXSIZE); dgemm_(&TRANS_T, &TRANS_N, &lenj, &leni, &bgrids, &D1, ao2+b0j*ngrids, &ngrids, ao1+b0i*ngrids, &ngrids, &D1, vv+b0i*nao+b0j, &nao); } } } } } else { dgemm_(&TRANS_T, &TRANS_N, &nao, &nao, &bgrids, &D1, ao2, &ngrids, ao1, &ngrids, &D1, vv, &nao); } } /* vv[nao,nao] = ao1[i,nao] * ao2[i,nao] */ void VXCdot_ao_ao(double *vv, double *ao1, double *ao2, int nao, int ngrids, int nbas, int hermi, unsigned char *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; memset(vv, 0, sizeof(double) * nao * nao); #pragma omp parallel default(none) \ shared(vv, ao1, ao2, nao, ngrids, nbas, hermi, \ non0table, shls_slice, ao_loc) { int ip, ib; double *v_priv = calloc(nao*nao+2, sizeof(double)); #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_ao(v_priv, ao1+ip, ao2+ip, nao, ngrids, MIN(ngrids-ip, BLKSIZE), hermi, non0table+ib*nbas, shls_slice, ao_loc); } #pragma omp critical { for (ip = 0; ip < nao*nao; ip++) { vv[ip] += v_priv[ip]; } } free(v_priv); } if (hermi != 0) { NPdsymm_triu(nao, vv, hermi); } }
omp_set_wait_policy_test_1.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <omp.h> #include <sys/timeb.h> #include <sys/syscall.h> #include <unistd.h> #include <sys/types.h> #include <signal.h> /**Important: make sure you use num_threads clause in parallel direction and set it to the * number of hardware cores, not the number of cores Linux gives or the default from OpenMP * * cat /proc/cpuinfo and check the processor id, core id and CPU model number so you can look up fron internet * Lennon is Xeon CPU E5-2683 v3 @ 2.00GHz, it has two CPU for total 28 cores, but support upto 56 threads * Paul is Xeon CPU E5-2695 v2 @ 2.40GHz, it has two CPU for total 24 cores, support upto 48 threads * Fornax Intel® Xeon® E5-2699 v3 2.3GHz, it has two CPU for total 36 cores, support upto 72 threads. * * Use -O0 optimization */ int main(int argc, char * argv[]) { int nthreads = 4; if (argc >= 2) nthreads = (atoi(argv[1])); #pragma omp parallel num_threads(nthreads) { int tid = omp_get_thread_num(); } omp_set_wait_policy(OMP_ACTIVE_WAIT); if (omp_get_wait_policy() != OMP_ACTIVE_WAIT) { printf("WAIT policy is not correctly set\n"); } #pragma omp parallel num_threads(nthreads) { int tid = omp_get_thread_num(); } omp_set_wait_policy(OMP_PASSIVE_WAIT); if (omp_get_wait_policy() == OMP_PASSIVE_WAIT) { printf("WAIT policy is not correctly set\n"); } #pragma omp parallel num_threads(nthreads) { omp_set_wait_policy(OMP_PASSIVE_WAIT); /* This is not the "recommended" way to use */ int tid = omp_get_thread_num(); } return 0; }
csr.c
/*! * \file * * \brief Various routines with dealing with CSR matrices * * \author George Karypis * \version\verbatim $Id: csr.c 16297 2014-02-24 20:36:56Z karypis $ \endverbatim */ #include <GKlib.h> #define OMPMINOPS 50000 /*************************************************************************/ /*! Allocate memory for a CSR matrix and initializes it \returns the allocated matrix. The various fields are set to NULL. */ /**************************************************************************/ gk_csr_t *gk_csr_Create() { gk_csr_t *mat; mat = (gk_csr_t *)gk_malloc(sizeof(gk_csr_t), "gk_csr_Create: mat"); gk_csr_Init(mat); return mat; } /*************************************************************************/ /*! Initializes the matrix \param mat is the matrix to be initialized. */ /*************************************************************************/ void gk_csr_Init(gk_csr_t *mat) { memset(mat, 0, sizeof(gk_csr_t)); mat->nrows = mat->ncols = -1; } /*************************************************************************/ /*! Frees all the memory allocated for matrix. \param mat is the matrix to be freed. */ /*************************************************************************/ void gk_csr_Free(gk_csr_t **mat) { if (*mat == NULL) return; gk_csr_FreeContents(*mat); gk_free((void **)mat, LTERM); } /*************************************************************************/ /*! Frees only the memory allocated for the matrix's different fields and sets them to NULL. \param mat is the matrix whose contents will be freed. */ /*************************************************************************/ void gk_csr_FreeContents(gk_csr_t *mat) { gk_free((void *)&mat->rowptr, &mat->rowind, &mat->rowval, &mat->rowids, &mat->colptr, &mat->colind, &mat->colval, &mat->colids, &mat->rnorms, &mat->cnorms, &mat->rsums, &mat->csums, &mat->rsizes, &mat->csizes, &mat->rvols, &mat->cvols, &mat->rwgts, &mat->cwgts, LTERM); } /*************************************************************************/ /*! Returns a copy of a matrix. \param mat is the matrix to be duplicated. \returns the newly created copy of the matrix. */ /**************************************************************************/ gk_csr_t *gk_csr_Dup(gk_csr_t *mat) { gk_csr_t *nmat; nmat = gk_csr_Create(); nmat->nrows = mat->nrows; nmat->ncols = mat->ncols; /* copy the row structure */ if (mat->rowptr) nmat->rowptr = gk_zcopy(mat->nrows+1, mat->rowptr, gk_zmalloc(mat->nrows+1, "gk_csr_Dup: rowptr")); if (mat->rowids) nmat->rowids = gk_icopy(mat->nrows, mat->rowids, gk_imalloc(mat->nrows, "gk_csr_Dup: rowids")); if (mat->rnorms) nmat->rnorms = gk_fcopy(mat->nrows, mat->rnorms, gk_fmalloc(mat->nrows, "gk_csr_Dup: rnorms")); if (mat->rowind) nmat->rowind = gk_icopy(mat->rowptr[mat->nrows], mat->rowind, gk_imalloc(mat->rowptr[mat->nrows], "gk_csr_Dup: rowind")); if (mat->rowval) nmat->rowval = gk_fcopy(mat->rowptr[mat->nrows], mat->rowval, gk_fmalloc(mat->rowptr[mat->nrows], "gk_csr_Dup: rowval")); /* copy the col structure */ if (mat->colptr) nmat->colptr = gk_zcopy(mat->ncols+1, mat->colptr, gk_zmalloc(mat->ncols+1, "gk_csr_Dup: colptr")); if (mat->colids) nmat->colids = gk_icopy(mat->ncols, mat->colids, gk_imalloc(mat->ncols, "gk_csr_Dup: colids")); if (mat->cnorms) nmat->cnorms = gk_fcopy(mat->ncols, mat->cnorms, gk_fmalloc(mat->ncols, "gk_csr_Dup: cnorms")); if (mat->colind) nmat->colind = gk_icopy(mat->colptr[mat->ncols], mat->colind, gk_imalloc(mat->colptr[mat->ncols], "gk_csr_Dup: colind")); if (mat->colval) nmat->colval = gk_fcopy(mat->colptr[mat->ncols], mat->colval, gk_fmalloc(mat->colptr[mat->ncols], "gk_csr_Dup: colval")); return nmat; } /*************************************************************************/ /*! Returns a submatrix containint a set of consecutive rows. \param mat is the original matrix. \param rstart is the starting row. \param nrows is the number of rows from rstart to extract. \returns the row structure of the newly created submatrix. */ /**************************************************************************/ gk_csr_t *gk_csr_ExtractSubmatrix(gk_csr_t *mat, int rstart, int nrows) { ssize_t i; gk_csr_t *nmat; if (rstart+nrows > mat->nrows) return NULL; nmat = gk_csr_Create(); nmat->nrows = nrows; nmat->ncols = mat->ncols; /* copy the row structure */ if (mat->rowptr) nmat->rowptr = gk_zcopy(nrows+1, mat->rowptr+rstart, gk_zmalloc(nrows+1, "gk_csr_ExtractSubmatrix: rowptr")); for (i=nrows; i>=0; i--) nmat->rowptr[i] -= nmat->rowptr[0]; ASSERT(nmat->rowptr[0] == 0); if (mat->rowids) nmat->rowids = gk_icopy(nrows, mat->rowids+rstart, gk_imalloc(nrows, "gk_csr_ExtractSubmatrix: rowids")); if (mat->rnorms) nmat->rnorms = gk_fcopy(nrows, mat->rnorms+rstart, gk_fmalloc(nrows, "gk_csr_ExtractSubmatrix: rnorms")); if (mat->rsums) nmat->rsums = gk_fcopy(nrows, mat->rsums+rstart, gk_fmalloc(nrows, "gk_csr_ExtractSubmatrix: rsums")); ASSERT(nmat->rowptr[nrows] == mat->rowptr[rstart+nrows]-mat->rowptr[rstart]); if (mat->rowind) nmat->rowind = gk_icopy(mat->rowptr[rstart+nrows]-mat->rowptr[rstart], mat->rowind+mat->rowptr[rstart], gk_imalloc(mat->rowptr[rstart+nrows]-mat->rowptr[rstart], "gk_csr_ExtractSubmatrix: rowind")); if (mat->rowval) nmat->rowval = gk_fcopy(mat->rowptr[rstart+nrows]-mat->rowptr[rstart], mat->rowval+mat->rowptr[rstart], gk_fmalloc(mat->rowptr[rstart+nrows]-mat->rowptr[rstart], "gk_csr_ExtractSubmatrix: rowval")); return nmat; } /*************************************************************************/ /*! Returns a submatrix containing a certain set of rows. \param mat is the original matrix. \param nrows is the number of rows to extract. \param rind is the set of row numbers to extract. \returns the row structure of the newly created submatrix. */ /**************************************************************************/ gk_csr_t *gk_csr_ExtractRows(gk_csr_t *mat, int nrows, int *rind) { ssize_t i, ii, j, nnz; gk_csr_t *nmat; nmat = gk_csr_Create(); nmat->nrows = nrows; nmat->ncols = mat->ncols; for (nnz=0, i=0; i<nrows; i++) nnz += mat->rowptr[rind[i]+1]-mat->rowptr[rind[i]]; nmat->rowptr = gk_zmalloc(nmat->nrows+1, "gk_csr_ExtractPartition: rowptr"); nmat->rowind = gk_imalloc(nnz, "gk_csr_ExtractPartition: rowind"); nmat->rowval = gk_fmalloc(nnz, "gk_csr_ExtractPartition: rowval"); nmat->rowptr[0] = 0; for (nnz=0, j=0, ii=0; ii<nrows; ii++) { i = rind[ii]; gk_icopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowind+mat->rowptr[i], nmat->rowind+nnz); gk_fcopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowval+mat->rowptr[i], nmat->rowval+nnz); nnz += mat->rowptr[i+1]-mat->rowptr[i]; nmat->rowptr[++j] = nnz; } ASSERT(j == nmat->nrows); return nmat; } /*************************************************************************/ /*! Returns a submatrix corresponding to a specified partitioning of rows. \param mat is the original matrix. \param part is the partitioning vector of the rows. \param pid is the partition ID that will be extracted. \returns the row structure of the newly created submatrix. */ /**************************************************************************/ gk_csr_t *gk_csr_ExtractPartition(gk_csr_t *mat, int *part, int pid) { ssize_t i, j, nnz; gk_csr_t *nmat; nmat = gk_csr_Create(); nmat->nrows = 0; nmat->ncols = mat->ncols; for (nnz=0, i=0; i<mat->nrows; i++) { if (part[i] == pid) { nmat->nrows++; nnz += mat->rowptr[i+1]-mat->rowptr[i]; } } nmat->rowptr = gk_zmalloc(nmat->nrows+1, "gk_csr_ExtractPartition: rowptr"); nmat->rowind = gk_imalloc(nnz, "gk_csr_ExtractPartition: rowind"); nmat->rowval = gk_fmalloc(nnz, "gk_csr_ExtractPartition: rowval"); nmat->rowptr[0] = 0; for (nnz=0, j=0, i=0; i<mat->nrows; i++) { if (part[i] == pid) { gk_icopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowind+mat->rowptr[i], nmat->rowind+nnz); gk_fcopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowval+mat->rowptr[i], nmat->rowval+nnz); nnz += mat->rowptr[i+1]-mat->rowptr[i]; nmat->rowptr[++j] = nnz; } } ASSERT(j == nmat->nrows); return nmat; } /*************************************************************************/ /*! Splits the matrix into multiple sub-matrices based on the provided color array. \param mat is the original matrix. \param color is an array of size equal to the number of non-zeros in the matrix (row-wise structure). The matrix is split into as many parts as the number of colors. For meaningfull results, the colors should be numbered consecutively starting from 0. \returns an array of matrices for each supplied color number. */ /**************************************************************************/ gk_csr_t **gk_csr_Split(gk_csr_t *mat, int *color) { ssize_t i, j; int nrows, ncolors; ssize_t *rowptr; int *rowind; float *rowval; gk_csr_t **smats; nrows = mat->nrows; rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; ncolors = gk_imax(rowptr[nrows], color, 1)+1; smats = (gk_csr_t **)gk_malloc(sizeof(gk_csr_t *)*ncolors, "gk_csr_Split: smats"); for (i=0; i<ncolors; i++) { smats[i] = gk_csr_Create(); smats[i]->nrows = mat->nrows; smats[i]->ncols = mat->ncols; smats[i]->rowptr = gk_zsmalloc(nrows+1, 0, "gk_csr_Split: smats[i]->rowptr"); } for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) smats[color[j]]->rowptr[i]++; } for (i=0; i<ncolors; i++) MAKECSR(j, nrows, smats[i]->rowptr); for (i=0; i<ncolors; i++) { smats[i]->rowind = gk_imalloc(smats[i]->rowptr[nrows], "gk_csr_Split: smats[i]->rowind"); smats[i]->rowval = gk_fmalloc(smats[i]->rowptr[nrows], "gk_csr_Split: smats[i]->rowval"); } for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { smats[color[j]]->rowind[smats[color[j]]->rowptr[i]] = rowind[j]; smats[color[j]]->rowval[smats[color[j]]->rowptr[i]] = rowval[j]; smats[color[j]]->rowptr[i]++; } } for (i=0; i<ncolors; i++) SHIFTCSR(j, nrows, smats[i]->rowptr); return smats; } /**************************************************************************/ /*! Reads a CSR matrix from the supplied file and stores it the matrix's forward structure. \param filename is the file that stores the data. \param format is either GK_CSR_FMT_METIS, GK_CSR_FMT_CLUTO, GK_CSR_FMT_CSR, GK_CSR_FMT_BINROW, GK_CSR_FMT_BINCOL specifying the type of the input format. The GK_CSR_FMT_CSR does not contain a header line, whereas the GK_CSR_FMT_BINROW is a binary format written by gk_csr_Write() using the same format specifier. \param readvals is either 1 or 0, indicating if the CSR file contains values or it does not. It only applies when GK_CSR_FMT_CSR is used. \param numbering is either 1 or 0, indicating if the numbering of the indices start from 1 or 0, respectively. If they start from 1, they are automatically decreamented during input so that they will start from 0. It only applies when GK_CSR_FMT_CSR is used. \returns the matrix that was read. */ /**************************************************************************/ gk_csr_t *gk_csr_Read(char *filename, int format, int readvals, int numbering) { ssize_t i, k, l; size_t nfields, nrows, ncols, nnz, fmt, ncon; size_t lnlen; ssize_t *rowptr; int *rowind, *iinds, *jinds, ival; float *rowval=NULL, *vals, fval; int readsizes, readwgts; char *line=NULL, *head, *tail, fmtstr[256]; FILE *fpin; gk_csr_t *mat=NULL; if (!gk_fexists(filename)) gk_errexit(SIGERR, "File %s does not exist!\n", filename); switch (format) { case GK_CSR_FMT_BINROW: mat = gk_csr_Create(); fpin = gk_fopen(filename, "rb", "gk_csr_Read: fpin"); if (fread(&(mat->nrows), sizeof(int32_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read the nrows from file %s!\n", filename); if (fread(&(mat->ncols), sizeof(int32_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read the ncols from file %s!\n", filename); mat->rowptr = gk_zmalloc(mat->nrows+1, "gk_csr_Read: rowptr"); if (fread(mat->rowptr, sizeof(ssize_t), mat->nrows+1, fpin) != mat->nrows+1) gk_errexit(SIGERR, "Failed to read the rowptr from file %s!\n", filename); mat->rowind = gk_imalloc(mat->rowptr[mat->nrows], "gk_csr_Read: rowind"); if (fread(mat->rowind, sizeof(int32_t), mat->rowptr[mat->nrows], fpin) != mat->rowptr[mat->nrows]) gk_errexit(SIGERR, "Failed to read the rowind from file %s!\n", filename); if (readvals == 1) { mat->rowval = gk_fmalloc(mat->rowptr[mat->nrows], "gk_csr_Read: rowval"); if (fread(mat->rowval, sizeof(float), mat->rowptr[mat->nrows], fpin) != mat->rowptr[mat->nrows]) gk_errexit(SIGERR, "Failed to read the rowval from file %s!\n", filename); } gk_fclose(fpin); return mat; break; case GK_CSR_FMT_BINCOL: mat = gk_csr_Create(); fpin = gk_fopen(filename, "rb", "gk_csr_Read: fpin"); if (fread(&(mat->nrows), sizeof(int32_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read the nrows from file %s!\n", filename); if (fread(&(mat->ncols), sizeof(int32_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read the ncols from file %s!\n", filename); mat->colptr = gk_zmalloc(mat->ncols+1, "gk_csr_Read: colptr"); if (fread(mat->colptr, sizeof(ssize_t), mat->ncols+1, fpin) != mat->ncols+1) gk_errexit(SIGERR, "Failed to read the colptr from file %s!\n", filename); mat->colind = gk_imalloc(mat->colptr[mat->ncols], "gk_csr_Read: colind"); if (fread(mat->colind, sizeof(int32_t), mat->colptr[mat->ncols], fpin) != mat->colptr[mat->ncols]) gk_errexit(SIGERR, "Failed to read the colind from file %s!\n", filename); if (readvals) { mat->colval = gk_fmalloc(mat->colptr[mat->ncols], "gk_csr_Read: colval"); if (fread(mat->colval, sizeof(float), mat->colptr[mat->ncols], fpin) != mat->colptr[mat->ncols]) gk_errexit(SIGERR, "Failed to read the colval from file %s!\n", filename); } gk_fclose(fpin); return mat; break; case GK_CSR_FMT_IJV: gk_getfilestats(filename, &nrows, &nnz, NULL, NULL); if (readvals == 1 && 3*nrows != nnz) gk_errexit(SIGERR, "Error: The number of numbers (%zd %d) in the input file is not a multiple of 3.\n", nnz, readvals); if (readvals == 0 && 2*nrows != nnz) gk_errexit(SIGERR, "Error: The number of numbers (%zd %d) in the input file is not a multiple of 2.\n", nnz, readvals); nnz = nrows; numbering = (numbering ? - 1 : 0); /* read the data into three arrays */ iinds = gk_i32malloc(nnz, "iinds"); jinds = gk_i32malloc(nnz, "jinds"); vals = (readvals ? gk_fmalloc(nnz, "vals") : NULL); fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin"); for (nrows=0, ncols=0, i=0; i<nnz; i++) { if (readvals) { if (fscanf(fpin, "%d %d %f", &iinds[i], &jinds[i], &vals[i]) != 3) gk_errexit(SIGERR, "Error: Failed to read (i, j, val) for nnz: %zd.\n", i); } else { if (fscanf(fpin, "%d %d", &iinds[i], &jinds[i]) != 2) gk_errexit(SIGERR, "Error: Failed to read (i, j) value for nnz: %zd.\n", i); } iinds[i] += numbering; jinds[i] += numbering; if (nrows < iinds[i]) nrows = iinds[i]; if (ncols < jinds[i]) ncols = jinds[i]; } nrows++; ncols++; gk_fclose(fpin); /* convert (i, j, v) into a CSR matrix */ mat = gk_csr_Create(); mat->nrows = nrows; mat->ncols = ncols; rowptr = mat->rowptr = gk_zsmalloc(nrows+1, 0, "rowptr"); rowind = mat->rowind = gk_i32malloc(nnz, "rowind"); if (readvals) rowval = mat->rowval = gk_fmalloc(nnz, "rowval"); for (i=0; i<nnz; i++) rowptr[iinds[i]]++; MAKECSR(i, nrows, rowptr); for (i=0; i<nnz; i++) { rowind[rowptr[iinds[i]]] = jinds[i]; if (readvals) rowval[rowptr[iinds[i]]] = vals[i]; rowptr[iinds[i]]++; } SHIFTCSR(i, nrows, rowptr); gk_free((void **)&iinds, &jinds, &vals, LTERM); return mat; break; case GK_CSR_FMT_BIJV: mat = gk_csr_Create(); fpin = gk_fopen(filename, "rb", "gk_csr_Read: fpin"); if (fread(&(mat->nrows), sizeof(int32_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read the nrows from file %s!\n", filename); if (fread(&(mat->ncols), sizeof(int32_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read the ncols from file %s!\n", filename); if (fread(&nnz, sizeof(size_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read the nnz from file %s!\n", filename); if (fread(&readvals, sizeof(int32_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read the readvals from file %s!\n", filename); /* read the data into three arrays */ iinds = gk_i32malloc(nnz, "iinds"); jinds = gk_i32malloc(nnz, "jinds"); vals = (readvals ? gk_fmalloc(nnz, "vals") : NULL); for (i=0; i<nnz; i++) { if (fread(&(iinds[i]), sizeof(int32_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read iinds[i] from file %s!\n", filename); if (fread(&(jinds[i]), sizeof(int32_t), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read jinds[i] from file %s!\n", filename); if (readvals) { if (fread(&(vals[i]), sizeof(float), 1, fpin) != 1) gk_errexit(SIGERR, "Failed to read vals[i] from file %s!\n", filename); } //printf("%d %d\n", iinds[i], jinds[i]); } gk_fclose(fpin); /* convert (i, j, v) into a CSR matrix */ rowptr = mat->rowptr = gk_zsmalloc(mat->nrows+1, 0, "rowptr"); rowind = mat->rowind = gk_i32malloc(nnz, "rowind"); if (readvals) rowval = mat->rowval = gk_fmalloc(nnz, "rowval"); for (i=0; i<nnz; i++) rowptr[iinds[i]]++; MAKECSR(i, mat->nrows, rowptr); for (i=0; i<nnz; i++) { rowind[rowptr[iinds[i]]] = jinds[i]; if (readvals) rowval[rowptr[iinds[i]]] = vals[i]; rowptr[iinds[i]]++; } SHIFTCSR(i, mat->nrows, rowptr); gk_free((void **)&iinds, &jinds, &vals, LTERM); return mat; break; /* the following are handled by a common input code, that comes after the switch */ case GK_CSR_FMT_CLUTO: fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin"); do { if (gk_getline(&line, &lnlen, fpin) <= 0) gk_errexit(SIGERR, "Premature end of input file: file:%s\n", filename); } while (line[0] == '%'); if (sscanf(line, "%zu %zu %zu", &nrows, &ncols, &nnz) != 3) gk_errexit(SIGERR, "Header line must contain 3 integers.\n"); readsizes = 0; readwgts = 0; readvals = 1; numbering = 1; break; case GK_CSR_FMT_METIS: fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin"); do { if (gk_getline(&line, &lnlen, fpin) <= 0) gk_errexit(SIGERR, "Premature end of input file: file:%s\n", filename); } while (line[0] == '%'); fmt = ncon = 0; nfields = sscanf(line, "%zu %zu %zu %zu", &nrows, &nnz, &fmt, &ncon); if (nfields < 2) gk_errexit(SIGERR, "Header line must contain at least 2 integers (#vtxs and #edges).\n"); ncols = nrows; nnz *= 2; if (fmt > 111) gk_errexit(SIGERR, "Cannot read this type of file format [fmt=%zu]!\n", fmt); sprintf(fmtstr, "%03zu", fmt%1000); readsizes = (fmtstr[0] == '1'); readwgts = (fmtstr[1] == '1'); readvals = (fmtstr[2] == '1'); numbering = 1; ncon = (ncon == 0 ? 1 : ncon); break; case GK_CSR_FMT_CSR: readsizes = 0; readwgts = 0; gk_getfilestats(filename, &nrows, &nnz, NULL, NULL); if (readvals == 1 && nnz%2 == 1) gk_errexit(SIGERR, "Error: The number of numbers (%zd %d) in the input file is not even.\n", nnz, readvals); if (readvals == 1) nnz = nnz/2; fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin"); break; default: gk_errexit(SIGERR, "Unknown csr format.\n"); return NULL; } mat = gk_csr_Create(); mat->nrows = nrows; rowptr = mat->rowptr = gk_zmalloc(nrows+1, "gk_csr_Read: rowptr"); rowind = mat->rowind = gk_imalloc(nnz, "gk_csr_Read: rowind"); if (readvals != 2) rowval = mat->rowval = gk_fsmalloc(nnz, 1.0, "gk_csr_Read: rowval"); if (readsizes) mat->rsizes = gk_fsmalloc(nrows, 0.0, "gk_csr_Read: rsizes"); if (readwgts) mat->rwgts = gk_fsmalloc(nrows*ncon, 0.0, "gk_csr_Read: rwgts"); /*---------------------------------------------------------------------- * Read the sparse matrix file *---------------------------------------------------------------------*/ numbering = (numbering ? -1 : 0); for (ncols=0, rowptr[0]=0, k=0, i=0; i<nrows; i++) { do { if (gk_getline(&line, &lnlen, fpin) == -1) gk_errexit(SIGERR, "Premature end of input file: file while reading row %d\n", i); } while (line[0] == '%'); head = line; tail = NULL; /* Read vertex sizes */ if (readsizes) { #ifdef __MSC__ mat->rsizes[i] = (float)strtod(head, &tail); #else mat->rsizes[i] = strtof(head, &tail); #endif if (tail == head) gk_errexit(SIGERR, "The line for vertex %zd does not have size information\n", i+1); if (mat->rsizes[i] < 0) errexit("The size for vertex %zd must be >= 0\n", i+1); head = tail; } /* Read vertex weights */ if (readwgts) { for (l=0; l<ncon; l++) { #ifdef __MSC__ mat->rwgts[i*ncon+l] = (float)strtod(head, &tail); #else mat->rwgts[i*ncon+l] = strtof(head, &tail); #endif if (tail == head) errexit("The line for vertex %zd does not have enough weights " "for the %d constraints.\n", i+1, ncon); if (mat->rwgts[i*ncon+l] < 0) errexit("The weight vertex %zd and constraint %zd must be >= 0\n", i+1, l); head = tail; } } /* Read the rest of the row */ while (1) { ival = (int)strtol(head, &tail, 0); if (tail == head) break; head = tail; if ((rowind[k] = ival + numbering) < 0) gk_errexit(SIGERR, "Error: Invalid column number %d at row %zd.\n", ival, i); ncols = gk_max(rowind[k], ncols); if (readvals == 1) { #ifdef __MSC__ fval = (float)strtod(head, &tail); #else fval = strtof(head, &tail); #endif if (tail == head) gk_errexit(SIGERR, "Value could not be found for column! Row:%zd, NNZ:%zd\n", i, k); head = tail; rowval[k] = fval; } k++; } rowptr[i+1] = k; } if (format == GK_CSR_FMT_METIS) { ASSERT(ncols+1 == mat->nrows); mat->ncols = mat->nrows; } else { mat->ncols = ncols+1; } if (k != nnz) gk_errexit(SIGERR, "gk_csr_Read: Something wrong with the number of nonzeros in " "the input file. NNZ=%zd, ActualNNZ=%zd.\n", nnz, k); gk_fclose(fpin); gk_free((void **)&line, LTERM); return mat; } /**************************************************************************/ /*! Writes the row-based structure of a matrix into a file. \param mat is the matrix to be written, \param filename is the name of the output file. \param format is one of: GK_CSR_FMT_CLUTO, GK_CSR_FMT_CSR, GK_CSR_FMT_BINROW, GK_CSR_FMT_BINCOL, GK_CSR_FMT_BIJV. \param writevals is either 1 or 0 indicating if the values will be written or not. This is only applicable when GK_CSR_FMT_CSR is used. \param numbering is either 1 or 0 indicating if the internal 0-based numbering will be shifted by one or not during output. This is only applicable when GK_CSR_FMT_CSR is used. */ /**************************************************************************/ void gk_csr_Write(gk_csr_t *mat, char *filename, int format, int writevals, int numbering) { ssize_t i, j; int32_t edge[2]; FILE *fpout; switch (format) { case GK_CSR_FMT_METIS: if (mat->nrows != mat->ncols || mat->rowptr[mat->nrows]%2 == 1) gk_errexit(SIGERR, "METIS output format requires a square symmetric matrix.\n"); if (filename) fpout = gk_fopen(filename, "w", "gk_csr_Write: fpout"); else fpout = stdout; fprintf(fpout, "%d %zd\n", mat->nrows, mat->rowptr[mat->nrows]/2); for (i=0; i<mat->nrows; i++) { for (j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++) fprintf(fpout, " %d", mat->rowind[j]+1); fprintf(fpout, "\n"); } if (filename) gk_fclose(fpout); break; case GK_CSR_FMT_BINROW: if (filename == NULL) gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n"); fpout = gk_fopen(filename, "wb", "gk_csr_Write: fpout"); fwrite(&(mat->nrows), sizeof(int32_t), 1, fpout); fwrite(&(mat->ncols), sizeof(int32_t), 1, fpout); fwrite(mat->rowptr, sizeof(ssize_t), mat->nrows+1, fpout); fwrite(mat->rowind, sizeof(int32_t), mat->rowptr[mat->nrows], fpout); if (writevals) fwrite(mat->rowval, sizeof(float), mat->rowptr[mat->nrows], fpout); gk_fclose(fpout); return; break; case GK_CSR_FMT_BINCOL: if (filename == NULL) gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n"); fpout = gk_fopen(filename, "wb", "gk_csr_Write: fpout"); fwrite(&(mat->nrows), sizeof(int32_t), 1, fpout); fwrite(&(mat->ncols), sizeof(int32_t), 1, fpout); fwrite(mat->colptr, sizeof(ssize_t), mat->ncols+1, fpout); fwrite(mat->colind, sizeof(int32_t), mat->colptr[mat->ncols], fpout); if (writevals) fwrite(mat->colval, sizeof(float), mat->colptr[mat->ncols], fpout); gk_fclose(fpout); return; break; case GK_CSR_FMT_IJV: if (filename == NULL) gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n"); fpout = gk_fopen(filename, "w", "gk_csr_Write: fpout"); numbering = (numbering ? 1 : 0); for (i=0; i<mat->nrows; i++) { for (j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++) { if (writevals) fprintf(fpout, "%zd %d %.8f\n", i+numbering, mat->rowind[j]+numbering, mat->rowval[j]); else fprintf(fpout, "%zd %d\n", i+numbering, mat->rowind[j]+numbering); } } gk_fclose(fpout); return; break; case GK_CSR_FMT_BIJV: if (filename == NULL) gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n"); fpout = gk_fopen(filename, "wb", "gk_csr_Write: fpout"); fwrite(&(mat->nrows), sizeof(int32_t), 1, fpout); fwrite(&(mat->ncols), sizeof(int32_t), 1, fpout); fwrite(&(mat->rowptr[mat->nrows]), sizeof(size_t), 1, fpout); fwrite(&writevals, sizeof(int32_t), 1, fpout); for (i=0; i<mat->nrows; i++) { edge[0] = i; for (j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++) { edge[1] = mat->rowind[j]; fwrite(edge, sizeof(int32_t), 2, fpout); if (writevals) fwrite(&(mat->rowval[j]), sizeof(float), 1, fpout); } } gk_fclose(fpout); return; break; default: if (filename) fpout = gk_fopen(filename, "w", "gk_csr_Write: fpout"); else fpout = stdout; if (format == GK_CSR_FMT_CLUTO) { fprintf(fpout, "%d %d %zd\n", mat->nrows, mat->ncols, mat->rowptr[mat->nrows]); writevals = 1; numbering = 1; } for (i=0; i<mat->nrows; i++) { for (j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++) { fprintf(fpout, " %d", mat->rowind[j]+(numbering ? 1 : 0)); if (writevals) fprintf(fpout, " %f", mat->rowval[j]); } fprintf(fpout, "\n"); } if (filename) gk_fclose(fpout); } } /*************************************************************************/ /*! Prunes certain rows/columns of the matrix. The prunning takes place by analyzing the row structure of the matrix. The prunning takes place by removing rows/columns but it does not affect the numbering of the remaining rows/columns. \param mat the matrix to be prunned, \param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL) of the matrix will be prunned, \param minf is the minimum number of rows (columns) that a column (row) must be present in order to be kept, \param maxf is the maximum number of rows (columns) that a column (row) must be present at in order to be kept. \returns the prunned matrix consisting only of its row-based structure. The input matrix is not modified. */ /**************************************************************************/ gk_csr_t *gk_csr_Prune(gk_csr_t *mat, int what, int minf, int maxf) { ssize_t i, j, nnz; int nrows, ncols; ssize_t *rowptr, *nrowptr; int *rowind, *nrowind, *collen; float *rowval, *nrowval; gk_csr_t *nmat; nmat = gk_csr_Create(); nrows = nmat->nrows = mat->nrows; ncols = nmat->ncols = mat->ncols; rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_Prune: nrowptr"); nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_Prune: nrowind"); nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_Prune: nrowval"); switch (what) { case GK_CSR_COL: collen = gk_ismalloc(ncols, 0, "gk_csr_Prune: collen"); for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { ASSERT(rowind[j] < ncols); collen[rowind[j]]++; } } for (i=0; i<ncols; i++) collen[i] = (collen[i] >= minf && collen[i] <= maxf ? 1 : 0); nrowptr[0] = 0; for (nnz=0, i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { if (collen[rowind[j]]) { nrowind[nnz] = rowind[j]; nrowval[nnz] = rowval[j]; nnz++; } } nrowptr[i+1] = nnz; } gk_free((void **)&collen, LTERM); break; case GK_CSR_ROW: nrowptr[0] = 0; for (nnz=0, i=0; i<nrows; i++) { if (rowptr[i+1]-rowptr[i] >= minf && rowptr[i+1]-rowptr[i] <= maxf) { for (j=rowptr[i]; j<rowptr[i+1]; j++, nnz++) { nrowind[nnz] = rowind[j]; nrowval[nnz] = rowval[j]; } } nrowptr[i+1] = nnz; } break; default: gk_csr_Free(&nmat); gk_errexit(SIGERR, "Unknown prunning type of %d\n", what); return NULL; } return nmat; } /*************************************************************************/ /*! Eliminates certain entries from the rows/columns of the matrix. The filtering takes place by keeping only the highest weight entries whose sum accounts for a certain fraction of the overall weight of the row/column. \param mat the matrix to be prunned, \param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL) of the matrix will be prunned, \param norm indicates the norm that will be used to aggregate the weights and possible values are 1 or 2, \param fraction is the fraction of the overall norm that will be retained by the kept entries. \returns the filtered matrix consisting only of its row-based structure. The input matrix is not modified. */ /**************************************************************************/ gk_csr_t *gk_csr_LowFilter(gk_csr_t *mat, int what, int norm, float fraction) { ssize_t i, j, nnz; int nrows, ncols, ncand, maxlen=0; ssize_t *rowptr, *colptr, *nrowptr; int *rowind, *colind, *nrowind; float *rowval, *colval, *nrowval, rsum, tsum; gk_csr_t *nmat; gk_fkv_t *cand; nmat = gk_csr_Create(); nrows = nmat->nrows = mat->nrows; ncols = nmat->ncols = mat->ncols; rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; colptr = mat->colptr; colind = mat->colind; colval = mat->colval; nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_LowFilter: nrowptr"); nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_LowFilter: nrowind"); nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_LowFilter: nrowval"); switch (what) { case GK_CSR_COL: if (mat->colptr == NULL) gk_errexit(SIGERR, "Cannot filter columns when column-based structure has not been created.\n"); gk_zcopy(nrows+1, rowptr, nrowptr); for (i=0; i<ncols; i++) maxlen = gk_max(maxlen, colptr[i+1]-colptr[i]); #pragma omp parallel private(i, j, ncand, rsum, tsum, cand) { cand = gk_fkvmalloc(maxlen, "gk_csr_LowFilter: cand"); #pragma omp for schedule(static) for (i=0; i<ncols; i++) { for (tsum=0.0, ncand=0, j=colptr[i]; j<colptr[i+1]; j++, ncand++) { cand[ncand].val = colind[j]; cand[ncand].key = colval[j]; tsum += (norm == 1 ? colval[j] : colval[j]*colval[j]); } gk_fkvsortd(ncand, cand); for (rsum=0.0, j=0; j<ncand && rsum<=fraction*tsum; j++) { rsum += (norm == 1 ? cand[j].key : cand[j].key*cand[j].key); nrowind[nrowptr[cand[j].val]] = i; nrowval[nrowptr[cand[j].val]] = cand[j].key; nrowptr[cand[j].val]++; } } gk_free((void **)&cand, LTERM); } /* compact the nrowind/nrowval */ for (nnz=0, i=0; i<nrows; i++) { for (j=rowptr[i]; j<nrowptr[i]; j++, nnz++) { nrowind[nnz] = nrowind[j]; nrowval[nnz] = nrowval[j]; } nrowptr[i] = nnz; } SHIFTCSR(i, nrows, nrowptr); break; case GK_CSR_ROW: if (mat->rowptr == NULL) gk_errexit(SIGERR, "Cannot filter rows when row-based structure has not been created.\n"); for (i=0; i<nrows; i++) maxlen = gk_max(maxlen, rowptr[i+1]-rowptr[i]); #pragma omp parallel private(i, j, ncand, rsum, tsum, cand) { cand = gk_fkvmalloc(maxlen, "gk_csr_LowFilter: cand"); #pragma omp for schedule(static) for (i=0; i<nrows; i++) { for (tsum=0.0, ncand=0, j=rowptr[i]; j<rowptr[i+1]; j++, ncand++) { cand[ncand].val = rowind[j]; cand[ncand].key = rowval[j]; tsum += (norm == 1 ? rowval[j] : rowval[j]*rowval[j]); } gk_fkvsortd(ncand, cand); for (rsum=0.0, j=0; j<ncand && rsum<=fraction*tsum; j++) { rsum += (norm == 1 ? cand[j].key : cand[j].key*cand[j].key); nrowind[rowptr[i]+j] = cand[j].val; nrowval[rowptr[i]+j] = cand[j].key; } nrowptr[i+1] = rowptr[i]+j; } gk_free((void **)&cand, LTERM); } /* compact nrowind/nrowval */ nrowptr[0] = nnz = 0; for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<nrowptr[i+1]; j++, nnz++) { nrowind[nnz] = nrowind[j]; nrowval[nnz] = nrowval[j]; } nrowptr[i+1] = nnz; } break; default: gk_csr_Free(&nmat); gk_errexit(SIGERR, "Unknown prunning type of %d\n", what); return NULL; } return nmat; } /*************************************************************************/ /*! Eliminates certain entries from the rows/columns of the matrix. The filtering takes place by keeping only the highest weight top-K entries along each row/column and those entries whose weight is greater than a specified value. \param mat the matrix to be prunned, \param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL) of the matrix will be prunned, \param topk is the number of the highest weight entries to keep. \param keepval is the weight of a term above which will be kept. This is used to select additional terms past the first topk. \returns the filtered matrix consisting only of its row-based structure. The input matrix is not modified. */ /**************************************************************************/ gk_csr_t *gk_csr_TopKPlusFilter(gk_csr_t *mat, int what, int topk, float keepval) { ssize_t i, j, k, nnz; int nrows, ncols, ncand; ssize_t *rowptr, *colptr, *nrowptr; int *rowind, *colind, *nrowind; float *rowval, *colval, *nrowval; gk_csr_t *nmat; gk_fkv_t *cand; nmat = gk_csr_Create(); nrows = nmat->nrows = mat->nrows; ncols = nmat->ncols = mat->ncols; rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; colptr = mat->colptr; colind = mat->colind; colval = mat->colval; nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_LowFilter: nrowptr"); nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_LowFilter: nrowind"); nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_LowFilter: nrowval"); switch (what) { case GK_CSR_COL: if (mat->colptr == NULL) gk_errexit(SIGERR, "Cannot filter columns when column-based structure has not been created.\n"); cand = gk_fkvmalloc(nrows, "gk_csr_LowFilter: cand"); gk_zcopy(nrows+1, rowptr, nrowptr); for (i=0; i<ncols; i++) { for (ncand=0, j=colptr[i]; j<colptr[i+1]; j++, ncand++) { cand[ncand].val = colind[j]; cand[ncand].key = colval[j]; } gk_fkvsortd(ncand, cand); k = gk_min(topk, ncand); for (j=0; j<k; j++) { nrowind[nrowptr[cand[j].val]] = i; nrowval[nrowptr[cand[j].val]] = cand[j].key; nrowptr[cand[j].val]++; } for (; j<ncand; j++) { if (cand[j].key < keepval) break; nrowind[nrowptr[cand[j].val]] = i; nrowval[nrowptr[cand[j].val]] = cand[j].key; nrowptr[cand[j].val]++; } } /* compact the nrowind/nrowval */ for (nnz=0, i=0; i<nrows; i++) { for (j=rowptr[i]; j<nrowptr[i]; j++, nnz++) { nrowind[nnz] = nrowind[j]; nrowval[nnz] = nrowval[j]; } nrowptr[i] = nnz; } SHIFTCSR(i, nrows, nrowptr); gk_free((void **)&cand, LTERM); break; case GK_CSR_ROW: if (mat->rowptr == NULL) gk_errexit(SIGERR, "Cannot filter rows when row-based structure has not been created.\n"); cand = gk_fkvmalloc(ncols, "gk_csr_LowFilter: cand"); nrowptr[0] = 0; for (nnz=0, i=0; i<nrows; i++) { for (ncand=0, j=rowptr[i]; j<rowptr[i+1]; j++, ncand++) { cand[ncand].val = rowind[j]; cand[ncand].key = rowval[j]; } gk_fkvsortd(ncand, cand); k = gk_min(topk, ncand); for (j=0; j<k; j++, nnz++) { nrowind[nnz] = cand[j].val; nrowval[nnz] = cand[j].key; } for (; j<ncand; j++, nnz++) { if (cand[j].key < keepval) break; nrowind[nnz] = cand[j].val; nrowval[nnz] = cand[j].key; } nrowptr[i+1] = nnz; } gk_free((void **)&cand, LTERM); break; default: gk_csr_Free(&nmat); gk_errexit(SIGERR, "Unknown prunning type of %d\n", what); return NULL; } return nmat; } /*************************************************************************/ /*! Eliminates certain entries from the rows/columns of the matrix. The filtering takes place by keeping only the terms whose contribution to the total length of the document is greater than a user-splied multiple over the average. This routine assumes that the vectors are normalized to be unit length. \param mat the matrix to be prunned, \param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL) of the matrix will be prunned, \param zscore is the multiplicative factor over the average contribution to the length of the document. \returns the filtered matrix consisting only of its row-based structure. The input matrix is not modified. */ /**************************************************************************/ gk_csr_t *gk_csr_ZScoreFilter(gk_csr_t *mat, int what, float zscore) { ssize_t i, j, nnz; int nrows; ssize_t *rowptr, *nrowptr; int *rowind, *nrowind; float *rowval, *nrowval, avgwgt; gk_csr_t *nmat; nmat = gk_csr_Create(); nmat->nrows = mat->nrows; nmat->ncols = mat->ncols; nrows = mat->nrows; rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_ZScoreFilter: nrowptr"); nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_ZScoreFilter: nrowind"); nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_ZScoreFilter: nrowval"); switch (what) { case GK_CSR_COL: gk_errexit(SIGERR, "This has not been implemented yet.\n"); break; case GK_CSR_ROW: if (mat->rowptr == NULL) gk_errexit(SIGERR, "Cannot filter rows when row-based structure has not been created.\n"); nrowptr[0] = 0; for (nnz=0, i=0; i<nrows; i++) { avgwgt = zscore/(rowptr[i+1]-rowptr[i]); for (j=rowptr[i]; j<rowptr[i+1]; j++) { if (rowval[j] > avgwgt) { nrowind[nnz] = rowind[j]; nrowval[nnz] = rowval[j]; nnz++; } } nrowptr[i+1] = nnz; } break; default: gk_csr_Free(&nmat); gk_errexit(SIGERR, "Unknown prunning type of %d\n", what); return NULL; } return nmat; } /*************************************************************************/ /*! Compacts the column-space of the matrix by removing empty columns. As a result of the compaction, the column numbers are renumbered. The compaction operation is done in place and only affects the row-based representation of the matrix. The new columns are ordered in decreasing frequency. \param mat the matrix whose empty columns will be removed. */ /**************************************************************************/ void gk_csr_CompactColumns(gk_csr_t *mat) { ssize_t i; int nrows, ncols, nncols; ssize_t *rowptr; int *rowind, *colmap; gk_ikv_t *clens; nrows = mat->nrows; ncols = mat->ncols; rowptr = mat->rowptr; rowind = mat->rowind; colmap = gk_imalloc(ncols, "gk_csr_CompactColumns: colmap"); clens = gk_ikvmalloc(ncols, "gk_csr_CompactColumns: clens"); for (i=0; i<ncols; i++) { clens[i].key = 0; clens[i].val = i; } for (i=0; i<rowptr[nrows]; i++) clens[rowind[i]].key++; gk_ikvsortd(ncols, clens); for (nncols=0, i=0; i<ncols; i++) { if (clens[i].key > 0) colmap[clens[i].val] = nncols++; else break; } for (i=0; i<rowptr[nrows]; i++) rowind[i] = colmap[rowind[i]]; mat->ncols = nncols; gk_free((void **)&colmap, &clens, LTERM); } /*************************************************************************/ /*! Sorts the indices in increasing order \param mat the matrix itself, \param what is either GK_CSR_ROW or GK_CSR_COL indicating which set of indices to sort. */ /**************************************************************************/ void gk_csr_SortIndices(gk_csr_t *mat, int what) { int n, nn=0; ssize_t *ptr; int *ind; float *val; switch (what) { case GK_CSR_ROW: if (!mat->rowptr) gk_errexit(SIGERR, "Row-based view of the matrix does not exists.\n"); n = mat->nrows; ptr = mat->rowptr; ind = mat->rowind; val = mat->rowval; break; case GK_CSR_COL: if (!mat->colptr) gk_errexit(SIGERR, "Column-based view of the matrix does not exists.\n"); n = mat->ncols; ptr = mat->colptr; ind = mat->colind; val = mat->colval; break; default: gk_errexit(SIGERR, "Invalid index type of %d.\n", what); return; } #pragma omp parallel if (n > 100) { ssize_t i, j, k; gk_ikv_t *cand; float *tval; #pragma omp single for (i=0; i<n; i++) nn = gk_max(nn, ptr[i+1]-ptr[i]); cand = gk_ikvmalloc(nn, "gk_csr_SortIndices: cand"); tval = gk_fmalloc(nn, "gk_csr_SortIndices: tval"); #pragma omp for schedule(static) for (i=0; i<n; i++) { for (k=0, j=ptr[i]; j<ptr[i+1]; j++) { if (j > ptr[i] && ind[j] < ind[j-1]) k = 1; /* an inversion */ cand[j-ptr[i]].val = j-ptr[i]; cand[j-ptr[i]].key = ind[j]; tval[j-ptr[i]] = val[j]; } if (k) { gk_ikvsorti(ptr[i+1]-ptr[i], cand); for (j=ptr[i]; j<ptr[i+1]; j++) { ind[j] = cand[j-ptr[i]].key; val[j] = tval[cand[j-ptr[i]].val]; } } } gk_free((void **)&cand, &tval, LTERM); } } /*************************************************************************/ /*! Creates a row/column index from the column/row data. \param mat the matrix itself, \param what is either GK_CSR_ROW or GK_CSR_COL indicating which index will be created. */ /**************************************************************************/ void gk_csr_CreateIndex(gk_csr_t *mat, int what) { /* 'f' stands for forward, 'r' stands for reverse */ ssize_t i, j, k, nf, nr; ssize_t *fptr, *rptr; int *find, *rind; float *fval, *rval; switch (what) { case GK_CSR_COL: nf = mat->nrows; fptr = mat->rowptr; find = mat->rowind; fval = mat->rowval; if (mat->colptr) gk_free((void **)&mat->colptr, LTERM); if (mat->colind) gk_free((void **)&mat->colind, LTERM); if (mat->colval) gk_free((void **)&mat->colval, LTERM); nr = mat->ncols; rptr = mat->colptr = gk_zsmalloc(nr+1, 0, "gk_csr_CreateIndex: rptr"); rind = mat->colind = gk_imalloc(fptr[nf], "gk_csr_CreateIndex: rind"); rval = mat->colval = (fval ? gk_fmalloc(fptr[nf], "gk_csr_CreateIndex: rval") : NULL); break; case GK_CSR_ROW: nf = mat->ncols; fptr = mat->colptr; find = mat->colind; fval = mat->colval; if (mat->rowptr) gk_free((void **)&mat->rowptr, LTERM); if (mat->rowind) gk_free((void **)&mat->rowind, LTERM); if (mat->rowval) gk_free((void **)&mat->rowval, LTERM); nr = mat->nrows; rptr = mat->rowptr = gk_zsmalloc(nr+1, 0, "gk_csr_CreateIndex: rptr"); rind = mat->rowind = gk_imalloc(fptr[nf], "gk_csr_CreateIndex: rind"); rval = mat->rowval = (fval ? gk_fmalloc(fptr[nf], "gk_csr_CreateIndex: rval") : NULL); break; default: gk_errexit(SIGERR, "Invalid index type of %d.\n", what); return; } for (i=0; i<nf; i++) { for (j=fptr[i]; j<fptr[i+1]; j++) rptr[find[j]]++; } MAKECSR(i, nr, rptr); if (rptr[nr] > 6*nr) { for (i=0; i<nf; i++) { for (j=fptr[i]; j<fptr[i+1]; j++) rind[rptr[find[j]]++] = i; } SHIFTCSR(i, nr, rptr); if (fval) { for (i=0; i<nf; i++) { for (j=fptr[i]; j<fptr[i+1]; j++) rval[rptr[find[j]]++] = fval[j]; } SHIFTCSR(i, nr, rptr); } } else { if (fval) { for (i=0; i<nf; i++) { for (j=fptr[i]; j<fptr[i+1]; j++) { k = find[j]; rind[rptr[k]] = i; rval[rptr[k]++] = fval[j]; } } } else { for (i=0; i<nf; i++) { for (j=fptr[i]; j<fptr[i+1]; j++) rind[rptr[find[j]]++] = i; } } SHIFTCSR(i, nr, rptr); } } /*************************************************************************/ /*! Normalizes the rows/columns of the matrix to be unit length. \param mat the matrix itself, \param what indicates what will be normalized and is obtained by specifying GK_CSR_ROW, GK_CSR_COL, GK_CSR_ROW|GK_CSR_COL. \param norm indicates what norm is to normalize to, 1: 1-norm, 2: 2-norm */ /**************************************************************************/ void gk_csr_Normalize(gk_csr_t *mat, int what, int norm) { ssize_t i, j; int n; ssize_t *ptr; float *val, sum; if (what&GK_CSR_ROW && mat->rowval) { n = mat->nrows; ptr = mat->rowptr; val = mat->rowval; #pragma omp parallel if (ptr[n] > OMPMINOPS) { #pragma omp for private(j,sum) schedule(static) for (i=0; i<n; i++) { for (sum=0.0, j=ptr[i]; j<ptr[i+1]; j++){ if (norm == 2) sum += val[j]*val[j]; else if (norm == 1) sum += val[j]; /* assume val[j] > 0 */ } if (sum > 0) { if (norm == 2) sum=1.0/sqrt(sum); else if (norm == 1) sum=1.0/sum; for (j=ptr[i]; j<ptr[i+1]; j++) val[j] *= sum; } } } } if (what&GK_CSR_COL && mat->colval) { n = mat->ncols; ptr = mat->colptr; val = mat->colval; #pragma omp parallel if (ptr[n] > OMPMINOPS) { #pragma omp for private(j,sum) schedule(static) for (i=0; i<n; i++) { for (sum=0.0, j=ptr[i]; j<ptr[i+1]; j++) if (norm == 2) sum += val[j]*val[j]; else if (norm == 1) sum += val[j]; if (sum > 0) { if (norm == 2) sum=1.0/sqrt(sum); else if (norm == 1) sum=1.0/sum; for (j=ptr[i]; j<ptr[i+1]; j++) val[j] *= sum; } } } } } /*************************************************************************/ /*! Applies different row scaling methods. \param mat the matrix itself, \param type indicates the type of row scaling. Possible values are: GK_CSR_MAXTF, GK_CSR_SQRT, GK_CSR_LOG, GK_CSR_IDF, GK_CSR_MAXTF2. */ /**************************************************************************/ void gk_csr_Scale(gk_csr_t *mat, int type) { ssize_t i, j; int nrows, ncols, nnzcols, bgfreq; ssize_t *rowptr; int *rowind, *collen; float *rowval, *cscale, maxtf; nrows = mat->nrows; rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; switch (type) { case GK_CSR_MAXTF: /* TF' = .5 + .5*TF/MAX(TF) */ #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { #pragma omp for private(j, maxtf) schedule(static) for (i=0; i<nrows; i++) { maxtf = fabs(rowval[rowptr[i]]); for (j=rowptr[i]; j<rowptr[i+1]; j++) maxtf = (maxtf < fabs(rowval[j]) ? fabs(rowval[j]) : maxtf); for (j=rowptr[i]; j<rowptr[i+1]; j++) rowval[j] = .5 + .5*rowval[j]/maxtf; } } break; case GK_CSR_MAXTF2: /* TF' = .1 + .9*TF/MAX(TF) */ #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { #pragma omp for private(j, maxtf) schedule(static) for (i=0; i<nrows; i++) { maxtf = fabs(rowval[rowptr[i]]); for (j=rowptr[i]; j<rowptr[i+1]; j++) maxtf = (maxtf < fabs(rowval[j]) ? fabs(rowval[j]) : maxtf); for (j=rowptr[i]; j<rowptr[i+1]; j++) rowval[j] = .1 + .9*rowval[j]/maxtf; } } break; case GK_CSR_SQRT: /* TF' = .1+SQRT(TF) */ #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { #pragma omp for private(j) schedule(static) for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { if (rowval[j] != 0.0) rowval[j] = .1+sign(rowval[j], sqrt(fabs(rowval[j]))); } } } break; case GK_CSR_POW25: /* TF' = .1+POW(TF,.25) */ #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { #pragma omp for private(j) schedule(static) for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { if (rowval[j] != 0.0) rowval[j] = .1+sign(rowval[j], sqrt(sqrt(fabs(rowval[j])))); } } } break; case GK_CSR_POW65: /* TF' = .1+POW(TF,.65) */ #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { #pragma omp for private(j) schedule(static) for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { if (rowval[j] != 0.0) rowval[j] = .1+sign(rowval[j], powf(fabs(rowval[j]), .65)); } } } break; case GK_CSR_POW75: /* TF' = .1+POW(TF,.75) */ #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { #pragma omp for private(j) schedule(static) for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { if (rowval[j] != 0.0) rowval[j] = .1+sign(rowval[j], powf(fabs(rowval[j]), .75)); } } } break; case GK_CSR_POW85: /* TF' = .1+POW(TF,.85) */ #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { #pragma omp for private(j) schedule(static) for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { if (rowval[j] != 0.0) rowval[j] = .1+sign(rowval[j], powf(fabs(rowval[j]), .85)); } } } break; case GK_CSR_LOG: /* TF' = 1+log_2(TF) */ #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { double logscale = 1.0/log(2.0); #pragma omp for schedule(static,32) for (i=0; i<rowptr[nrows]; i++) { if (rowval[i] != 0.0) rowval[i] = 1+(rowval[i]>0.0 ? log(rowval[i]) : -log(-rowval[i]))*logscale; } #ifdef XXX #pragma omp for private(j) schedule(static) for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { if (rowval[j] != 0.0) rowval[j] = 1+(rowval[j]>0.0 ? log(rowval[j]) : -log(-rowval[j]))*logscale; //rowval[j] = 1+sign(rowval[j], log(fabs(rowval[j]))*logscale); } } #endif } break; case GK_CSR_IDF: /* TF' = TF*IDF */ ncols = mat->ncols; cscale = gk_fmalloc(ncols, "gk_csr_Scale: cscale"); collen = gk_ismalloc(ncols, 0, "gk_csr_Scale: collen"); for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) collen[rowind[j]]++; } #pragma omp parallel if (ncols > OMPMINOPS) { #pragma omp for schedule(static) for (i=0; i<ncols; i++) cscale[i] = (collen[i] > 0 ? log(1.0*nrows/collen[i]) : 0.0); } #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { #pragma omp for private(j) schedule(static) for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) rowval[j] *= cscale[rowind[j]]; } } gk_free((void **)&cscale, &collen, LTERM); break; case GK_CSR_IDF2: /* TF' = TF*IDF */ ncols = mat->ncols; cscale = gk_fmalloc(ncols, "gk_csr_Scale: cscale"); collen = gk_ismalloc(ncols, 0, "gk_csr_Scale: collen"); for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) collen[rowind[j]]++; } nnzcols = 0; #pragma omp parallel if (ncols > OMPMINOPS) { #pragma omp for schedule(static) reduction(+:nnzcols) for (i=0; i<ncols; i++) nnzcols += (collen[i] > 0 ? 1 : 0); bgfreq = gk_max(10, (ssize_t)(.5*rowptr[nrows]/nnzcols)); #pragma omp master { printf("nnz: %zd, nnzcols: %d, bgfreq: %d\n", rowptr[nrows], nnzcols, bgfreq); } #pragma omp for schedule(static) for (i=0; i<ncols; i++) cscale[i] = (collen[i] > 0 ? log(1.0*(nrows+2*bgfreq)/(bgfreq+collen[i])) : 0.0); } #pragma omp parallel if (rowptr[nrows] > OMPMINOPS) { #pragma omp for private(j) schedule(static) for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) rowval[j] *= cscale[rowind[j]]; } } gk_free((void **)&cscale, &collen, LTERM); break; default: gk_errexit(SIGERR, "Unknown scaling type of %d\n", type); } } /*************************************************************************/ /*! Computes the sums of the rows/columns \param mat the matrix itself, \param what is either GK_CSR_ROW or GK_CSR_COL indicating which sums to compute. */ /**************************************************************************/ void gk_csr_ComputeSums(gk_csr_t *mat, int what) { ssize_t i; int n; ssize_t *ptr; float *val, *sums; switch (what) { case GK_CSR_ROW: n = mat->nrows; ptr = mat->rowptr; val = mat->rowval; if (mat->rsums) gk_free((void **)&mat->rsums, LTERM); sums = mat->rsums = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: sums"); break; case GK_CSR_COL: n = mat->ncols; ptr = mat->colptr; val = mat->colval; if (mat->csums) gk_free((void **)&mat->csums, LTERM); sums = mat->csums = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: sums"); break; default: gk_errexit(SIGERR, "Invalid sum type of %d.\n", what); return; } #pragma omp parallel for if (ptr[n] > OMPMINOPS) schedule(static) for (i=0; i<n; i++) sums[i] = gk_fsum(ptr[i+1]-ptr[i], val+ptr[i], 1); } /*************************************************************************/ /*! Computes the squared of the norms of the rows/columns \param mat the matrix itself, \param what is either GK_CSR_ROW or GK_CSR_COL indicating which squared norms to compute. */ /**************************************************************************/ void gk_csr_ComputeSquaredNorms(gk_csr_t *mat, int what) { ssize_t i; int n; ssize_t *ptr; float *val, *norms; switch (what) { case GK_CSR_ROW: n = mat->nrows; ptr = mat->rowptr; val = mat->rowval; if (mat->rnorms) gk_free((void **)&mat->rnorms, LTERM); norms = mat->rnorms = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: norms"); break; case GK_CSR_COL: n = mat->ncols; ptr = mat->colptr; val = mat->colval; if (mat->cnorms) gk_free((void **)&mat->cnorms, LTERM); norms = mat->cnorms = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: norms"); break; default: gk_errexit(SIGERR, "Invalid norm type of %d.\n", what); return; } #pragma omp parallel for if (ptr[n] > OMPMINOPS) schedule(static) for (i=0; i<n; i++) norms[i] = gk_fdot(ptr[i+1]-ptr[i], val+ptr[i], 1, val+ptr[i], 1); } /*************************************************************************/ /*! Returns a new matrix whose rows/columns are shuffled. \param mat the matrix to be shuffled, \param what indicates if the rows (GK_CSR_ROW), columns (GK_CSR_COL), or both (GK_CSR_ROWCOL) will be shuffled, \param symmetric indicates if the same shuffling will be applied to both rows and columns. This is valid with nrows==ncols and GK_CSR_ROWCOL was specified. \returns the shuffled matrix. The input matrix is not modified. */ /**************************************************************************/ gk_csr_t *gk_csr_Shuffle(gk_csr_t *mat, int what, int symmetric) { ssize_t i, j; int nrows, ncols; ssize_t *rowptr, *nrowptr; int *rowind, *nrowind; int *rperm, *cperm; float *rowval, *nrowval; gk_csr_t *nmat; if (what == GK_CSR_ROWCOL && symmetric && mat->nrows != mat->ncols) gk_errexit(SIGERR, "The matrix is not square for a symmetric rowcol shuffling.\n"); nrows = mat->nrows; ncols = mat->ncols; rowptr = mat->rowptr; rowind = mat->rowind; rowval = mat->rowval; rperm = gk_imalloc(nrows, "gk_csr_Shuffle: rperm"); cperm = gk_imalloc(ncols, "gk_csr_Shuffle: cperm"); switch (what) { case GK_CSR_ROW: gk_RandomPermute(nrows, rperm, 1); for (i=0; i<20; i++) gk_RandomPermute(nrows, rperm, 0); for (i=0; i<ncols; i++) cperm[i] = i; break; case GK_CSR_COL: gk_RandomPermute(ncols, cperm, 1); for (i=0; i<20; i++) gk_RandomPermute(ncols, cperm, 0); for (i=0; i<nrows; i++) rperm[i] = i; break; case GK_CSR_ROWCOL: gk_RandomPermute(nrows, rperm, 1); for (i=0; i<20; i++) gk_RandomPermute(nrows, rperm, 0); if (symmetric) gk_icopy(nrows, rperm, cperm); else { gk_RandomPermute(ncols, cperm, 1); for (i=0; i<20; i++) gk_RandomPermute(ncols, cperm, 0); } break; default: gk_free((void **)&rperm, &cperm, LTERM); gk_errexit(SIGERR, "Unknown shuffling type of %d\n", what); return NULL; } nmat = gk_csr_Create(); nmat->nrows = nrows; nmat->ncols = ncols; nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_Shuffle: nrowptr"); nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_Shuffle: nrowind"); nrowval = nmat->rowval = (rowval ? gk_fmalloc(rowptr[nrows], "gk_csr_Shuffle: nrowval") : NULL) ; for (i=0; i<nrows; i++) nrowptr[rperm[i]] = rowptr[i+1]-rowptr[i]; MAKECSR(i, nrows, nrowptr); for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { nrowind[nrowptr[rperm[i]]] = cperm[rowind[j]]; if (nrowval) nrowval[nrowptr[rperm[i]]] = rowval[j]; nrowptr[rperm[i]]++; } } SHIFTCSR(i, nrows, nrowptr); gk_free((void **)&rperm, &cperm, LTERM); return nmat; } /*************************************************************************/ /*! Computes the similarity between two rows/columns \param mat the matrix itself. The routine assumes that the indices are sorted in increasing order. \param i1 is the first row/column, \param i2 is the second row/column, \param what is either GK_CSR_ROW or GK_CSR_COL indicating the type of objects between the similarity will be computed, \param simtype is the type of similarity and is one of GK_CSR_COS, GK_CSR_JAC, GK_CSR_MIN, GK_CSR_AMIN \returns the similarity between the two rows/columns. */ /**************************************************************************/ float gk_csr_ComputeSimilarity(gk_csr_t *mat, int i1, int i2, int what, int simtype) { int nind1, nind2; int *ind1, *ind2; float *val1, *val2, stat1, stat2, sim; switch (what) { case GK_CSR_ROW: if (!mat->rowptr) gk_errexit(SIGERR, "Row-based view of the matrix does not exists.\n"); nind1 = mat->rowptr[i1+1]-mat->rowptr[i1]; nind2 = mat->rowptr[i2+1]-mat->rowptr[i2]; ind1 = mat->rowind + mat->rowptr[i1]; ind2 = mat->rowind + mat->rowptr[i2]; val1 = mat->rowval + mat->rowptr[i1]; val2 = mat->rowval + mat->rowptr[i2]; break; case GK_CSR_COL: if (!mat->colptr) gk_errexit(SIGERR, "Column-based view of the matrix does not exists.\n"); nind1 = mat->colptr[i1+1]-mat->colptr[i1]; nind2 = mat->colptr[i2+1]-mat->colptr[i2]; ind1 = mat->colind + mat->colptr[i1]; ind2 = mat->colind + mat->colptr[i2]; val1 = mat->colval + mat->colptr[i1]; val2 = mat->colval + mat->colptr[i2]; break; default: gk_errexit(SIGERR, "Invalid index type of %d.\n", what); return 0.0; } switch (simtype) { case GK_CSR_COS: case GK_CSR_JAC: sim = stat1 = stat2 = 0.0; i1 = i2 = 0; while (i1<nind1 && i2<nind2) { if (i1 == nind1) { stat2 += val2[i2]*val2[i2]; i2++; } else if (i2 == nind2) { stat1 += val1[i1]*val1[i1]; i1++; } else if (ind1[i1] < ind2[i2]) { stat1 += val1[i1]*val1[i1]; i1++; } else if (ind1[i1] > ind2[i2]) { stat2 += val2[i2]*val2[i2]; i2++; } else { sim += val1[i1]*val2[i2]; stat1 += val1[i1]*val1[i1]; stat2 += val2[i2]*val2[i2]; i1++; i2++; } } if (simtype == GK_CSR_COS) sim = (stat1*stat2 > 0.0 ? sim/sqrt(stat1*stat2) : 0.0); else sim = (stat1+stat2-sim > 0.0 ? sim/(stat1+stat2-sim) : 0.0); break; case GK_CSR_MIN: sim = stat1 = stat2 = 0.0; i1 = i2 = 0; while (i1<nind1 && i2<nind2) { if (i1 == nind1) { stat2 += val2[i2]; i2++; } else if (i2 == nind2) { stat1 += val1[i1]; i1++; } else if (ind1[i1] < ind2[i2]) { stat1 += val1[i1]; i1++; } else if (ind1[i1] > ind2[i2]) { stat2 += val2[i2]; i2++; } else { sim += gk_min(val1[i1],val2[i2]); stat1 += val1[i1]; stat2 += val2[i2]; i1++; i2++; } } sim = (stat1+stat2-sim > 0.0 ? sim/(stat1+stat2-sim) : 0.0); break; case GK_CSR_AMIN: sim = stat1 = stat2 = 0.0; i1 = i2 = 0; while (i1<nind1 && i2<nind2) { if (i1 == nind1) { stat2 += val2[i2]; i2++; } else if (i2 == nind2) { stat1 += val1[i1]; i1++; } else if (ind1[i1] < ind2[i2]) { stat1 += val1[i1]; i1++; } else if (ind1[i1] > ind2[i2]) { stat2 += val2[i2]; i2++; } else { sim += gk_min(val1[i1],val2[i2]); stat1 += val1[i1]; stat2 += val2[i2]; i1++; i2++; } } sim = (stat1 > 0.0 ? sim/stat1 : 0.0); break; default: gk_errexit(SIGERR, "Unknown similarity measure %d\n", simtype); return -1; } return sim; } /*************************************************************************/ /*! Finds the n most similar rows (neighbors) to the query using cosine similarity. \param mat the matrix itself \param nqterms is the number of columns in the query \param qind is the list of query columns \param qval is the list of correspodning query weights \param simtype is the type of similarity and is one of GK_CSR_COS, GK_CSR_JAC, GK_CSR_MIN, GK_CSR_AMIN \param nsim is the maximum number of requested most similar rows. If -1 is provided, then everything is returned unsorted. \param minsim is the minimum similarity of the requested most similar rows \param hits is the result set. This array should be at least of length nsim. \param i_marker is an array of size equal to the number of rows whose values are initialized to -1. If NULL is provided then this array is allocated and freed internally. \param i_cand is an array of size equal to the number of rows. If NULL is provided then this array is allocated and freed internally. \returns the number of identified most similar rows, which can be smaller than the requested number of nnbrs in those cases in which there are no sufficiently many neighbors. */ /**************************************************************************/ int gk_csr_GetSimilarRows(gk_csr_t *mat, int nqterms, int *qind, float *qval, int simtype, int nsim, float minsim, gk_fkv_t *hits, int *i_marker, gk_fkv_t *i_cand) { ssize_t i, ii, j, k; int nrows, ncols, ncand; ssize_t *colptr; int *colind, *marker; float *colval, *rnorms, mynorm, *rsums, mysum; gk_fkv_t *cand; if (nqterms == 0) return 0; nrows = mat->nrows; ncols = mat->ncols; colptr = mat->colptr; colind = mat->colind; colval = mat->colval; marker = (i_marker ? i_marker : gk_ismalloc(nrows, -1, "gk_csr_SimilarRows: marker")); cand = (i_cand ? i_cand : gk_fkvmalloc(nrows, "gk_csr_SimilarRows: cand")); switch (simtype) { case GK_CSR_COS: for (ncand=0, ii=0; ii<nqterms; ii++) { i = qind[ii]; if (i < ncols) { for (j=colptr[i]; j<colptr[i+1]; j++) { k = colind[j]; if (marker[k] == -1) { cand[ncand].val = k; cand[ncand].key = 0; marker[k] = ncand++; } cand[marker[k]].key += colval[j]*qval[ii]; } } } break; case GK_CSR_JAC: for (ncand=0, ii=0; ii<nqterms; ii++) { i = qind[ii]; if (i < ncols) { for (j=colptr[i]; j<colptr[i+1]; j++) { k = colind[j]; if (marker[k] == -1) { cand[ncand].val = k; cand[ncand].key = 0; marker[k] = ncand++; } cand[marker[k]].key += colval[j]*qval[ii]; } } } rnorms = mat->rnorms; mynorm = gk_fdot(nqterms, qval, 1, qval, 1); for (i=0; i<ncand; i++) cand[i].key = cand[i].key/(rnorms[cand[i].val]+mynorm-cand[i].key); break; case GK_CSR_MIN: for (ncand=0, ii=0; ii<nqterms; ii++) { i = qind[ii]; if (i < ncols) { for (j=colptr[i]; j<colptr[i+1]; j++) { k = colind[j]; if (marker[k] == -1) { cand[ncand].val = k; cand[ncand].key = 0; marker[k] = ncand++; } cand[marker[k]].key += gk_min(colval[j], qval[ii]); } } } rsums = mat->rsums; mysum = gk_fsum(nqterms, qval, 1); for (i=0; i<ncand; i++) cand[i].key = cand[i].key/(rsums[cand[i].val]+mysum-cand[i].key); break; /* Assymetric MIN similarity */ case GK_CSR_AMIN: for (ncand=0, ii=0; ii<nqterms; ii++) { i = qind[ii]; if (i < ncols) { for (j=colptr[i]; j<colptr[i+1]; j++) { k = colind[j]; if (marker[k] == -1) { cand[ncand].val = k; cand[ncand].key = 0; marker[k] = ncand++; } cand[marker[k]].key += gk_min(colval[j], qval[ii]); } } } mysum = gk_fsum(nqterms, qval, 1); for (i=0; i<ncand; i++) cand[i].key = cand[i].key/mysum; break; default: gk_errexit(SIGERR, "Unknown similarity measure %d\n", simtype); return -1; } /* go and prune the hits that are bellow minsim */ for (j=0, i=0; i<ncand; i++) { marker[cand[i].val] = -1; if (cand[i].key >= minsim) cand[j++] = cand[i]; } ncand = j; if (nsim == -1 || nsim >= ncand) { nsim = ncand; } else { nsim = gk_min(nsim, ncand); gk_dfkvkselect(ncand, nsim, cand); gk_fkvsortd(nsim, cand); } gk_fkvcopy(nsim, cand, hits); if (i_marker == NULL) gk_free((void **)&marker, LTERM); if (i_cand == NULL) gk_free((void **)&cand, LTERM); return nsim; } /*************************************************************************/ /*! This function finds the connected components in a graph. \param mat is the graph structure in CSR format \param cptr is the ptr structure of the CSR representation of the components. The length of this vector must be mat->nrows+1. \param cind is the indices structure of the CSR representation of the components. The length of this vector must be mat->nrows. \param cids is an array that stores the component # of each vertex of the graph. The length of this vector must be mat->nrows. \returns the number of components that it found. \note The cptr, cind, and cids parameters can be NULL, in which case only the number of connected components is returned. */ /*************************************************************************/ int gk_csr_FindConnectedComponents(gk_csr_t *mat, int32_t *cptr, int32_t *cind, int32_t *cids) { ssize_t i, ii, j, jj, k, nvtxs, first, last, ntodo, ncmps; ssize_t *xadj; int32_t *adjncy, *pos, *todo; int32_t mustfree_ccsr=0, mustfree_where=0; if (mat->nrows != mat->ncols) { fprintf(stderr, "gk_csr_FindComponents: The matrix needs to be square.\n"); return -1; } nvtxs = mat->nrows; xadj = mat->rowptr; adjncy = mat->rowind; /* Deal with NULL supplied cptr/cind vectors */ if (cptr == NULL) { cptr = gk_i32malloc(nvtxs+1, "gk_csr_FindComponents: cptr"); cind = gk_i32malloc(nvtxs, "gk_csr_FindComponents: cind"); mustfree_ccsr = 1; } /* The list of vertices that have not been touched yet. The valid entries are from [0..ntodo). */ todo = gk_i32incset(nvtxs, 0, gk_i32malloc(nvtxs, "gk_csr_FindComponents: todo")); /* For a vertex that has not been visited, pos[i] is the position in the todo list that this vertex is stored. If a vertex has been visited, pos[i] = -1. */ pos = gk_i32incset(nvtxs, 0, gk_i32malloc(nvtxs, "gk_csr_FindComponents: pos")); /* Find the connected componends */ ncmps = -1; ntodo = nvtxs; /* All vertices have not been visited */ first = last = 0; /* Point to the first and last vertices that have been touched but not explored. These vertices are stored in cind[first]...cind[last-1]. */ while (first < last || ntodo > 0) { if (first == last) { /* Find another starting vertex */ cptr[++ncmps] = first; /* Mark the end of the current CC */ /* put the first vertex in the todo list as the start of the new CC */ ASSERT(pos[todo[0]] != -1); cind[last++] = todo[0]; pos[todo[0]] = -1; todo[0] = todo[--ntodo]; pos[todo[0]] = 0; } i = cind[first++]; /* Get the first visited but unexplored vertex */ for (j=xadj[i]; j<xadj[i+1]; j++) { k = adjncy[j]; if (pos[k] != -1) { cind[last++] = k; /* Remove k from the todo list and put the last item in the todo list at the position that k was so that the todo list will be consequtive. The pos[] array is updated accordingly to keep track the location of the vertices in the todo[] list. */ todo[pos[k]] = todo[--ntodo]; pos[todo[pos[k]]] = pos[k]; pos[k] = -1; } } } cptr[++ncmps] = first; /* see if we need to return cids */ if (cids != NULL) { for (i=0; i<ncmps; i++) { for (j=cptr[i]; j<cptr[i+1]; j++) cids[cind[j]] = i; } } if (mustfree_ccsr) gk_free((void **)&cptr, &cind, LTERM); gk_free((void **)&pos, &todo, LTERM); return (int) ncmps; } /*************************************************************************/ /*! Returns a symmetric version of a square matrix. The symmetric version is constructed by applying an A op A^T operation, where op is one of GK_CSR_SYM_SUM, GK_CSR_SYM_MIN, GK_CSR_SYM_MAX, GK_CSR_SYM_AVG. \param mat the matrix to be symmetrized, \param op indicates the operation to be performed. The possible values are GK_CSR_SYM_SUM, GK_CSR_SYM_MIN, GK_CSR_SYM_MAX, and GK_CSR_SYM_AVG. \returns the symmetrized matrix consisting only of its row-based structure. The input matrix is not modified. */ /**************************************************************************/ gk_csr_t *gk_csr_MakeSymmetric(gk_csr_t *mat, int op) { ssize_t i, j, k, nnz; int nrows, nadj, hasvals; ssize_t *rowptr, *colptr, *nrowptr; int *rowind, *colind, *nrowind, *marker, *ids; float *rowval=NULL, *colval=NULL, *nrowval=NULL, *wgts=NULL; gk_csr_t *nmat; if (mat->nrows != mat->ncols) { fprintf(stderr, "gk_csr_MakeSymmetric: The matrix needs to be square.\n"); return NULL; } hasvals = (mat->rowval != NULL); nrows = mat->nrows; rowptr = mat->rowptr; rowind = mat->rowind; if (hasvals) rowval = mat->rowval; /* create the column view for efficient processing */ colptr = gk_zsmalloc(nrows+1, 0, "colptr"); colind = gk_i32malloc(rowptr[nrows], "colind"); if (hasvals) colval = gk_fmalloc(rowptr[nrows], "colval"); for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) colptr[rowind[j]]++; } MAKECSR(i, nrows, colptr); for (i=0; i<nrows; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { colind[colptr[rowind[j]]] = i; if (hasvals) colval[colptr[rowind[j]]] = rowval[j]; colptr[rowind[j]]++; } } SHIFTCSR(i, nrows, colptr); nmat = gk_csr_Create(); nmat->nrows = mat->nrows; nmat->ncols = mat->ncols; nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_MakeSymmetric: nrowptr"); nrowind = nmat->rowind = gk_imalloc(2*rowptr[nrows], "gk_csr_MakeSymmetric: nrowind"); if (hasvals) nrowval = nmat->rowval = gk_fmalloc(2*rowptr[nrows], "gk_csr_MakeSymmetric: nrowval"); marker = gk_ismalloc(nrows, -1, "marker"); ids = gk_imalloc(nrows, "ids"); if (hasvals) wgts = gk_fmalloc(nrows, "wgts"); nrowptr[0] = nnz = 0; for (i=0; i<nrows; i++) { nadj = 0; /* out-edges */ for (j=rowptr[i]; j<rowptr[i+1]; j++) { ids[nadj] = rowind[j]; if (hasvals) wgts[nadj] = (op == GK_CSR_SYM_AVG ? 0.5*rowval[j] : rowval[j]); marker[rowind[j]] = nadj++; } /* in-edges */ for (j=colptr[i]; j<colptr[i+1]; j++) { if (marker[colind[j]] == -1) { if (op != GK_CSR_SYM_MIN) { ids[nadj] = colind[j]; if (hasvals) wgts[nadj] = (op == GK_CSR_SYM_AVG ? 0.5*colval[j] : colval[j]); nadj++; } } else { if (hasvals) { switch (op) { case GK_CSR_SYM_MAX: wgts[marker[colind[j]]] = gk_max(colval[j], wgts[marker[colind[j]]]); break; case GK_CSR_SYM_MIN: wgts[marker[colind[j]]] = gk_min(colval[j], wgts[marker[colind[j]]]); break; case GK_CSR_SYM_SUM: wgts[marker[colind[j]]] += colval[j]; break; case GK_CSR_SYM_AVG: wgts[marker[colind[j]]] = 0.5*(wgts[marker[colind[j]]] + colval[j]); break; default: errexit("Unsupported op for MakeSymmetric!\n"); } } marker[colind[j]] = -1; } } /* go over out edges again to resolve any edges that were not found in the in * edges */ for (j=rowptr[i]; j<rowptr[i+1]; j++) { if (marker[rowind[j]] != -1) { if (op == GK_CSR_SYM_MIN) ids[marker[rowind[j]]] = -1; marker[rowind[j]] = -1; } } /* put the non '-1' entries in ids[] into i's row */ for (j=0; j<nadj; j++) { if (ids[j] != -1) { nrowind[nnz] = ids[j]; if (hasvals) nrowval[nnz] = wgts[j]; nnz++; } } nrowptr[i+1] = nnz; } gk_free((void **)&colptr, &colind, &colval, &marker, &ids, &wgts, LTERM); return nmat; }
central_difference.h
#include <stdio.h> static inline long long SUB2IND(const long long j, const long long i, const long long k, const long long row_size, const long long col_size, const long long n_channels) { //return ((i + col_size * j) * n_channels) + k; return (i + col_size * j) + (row_size * col_size * k); } template<typename T> void central_difference(const T* in, const long long rows, const long long cols, const long long n_channels, T* out) { const long long n_output_channels = n_channels * 2; long long output_index = 0; #pragma omp for for (long long k = 0; k < n_channels; ++k) { // row-derivative for (long long i = 0; i < cols; ++i) { for (long long j = 0; j < rows; ++j) { if (j == 0) { output_index = SUB2IND(0, i, k, rows, cols, n_output_channels); out[output_index] = in[SUB2IND(1, i, k, rows, cols, n_channels)] - in[SUB2IND(0, i, k, rows, cols, n_channels)]; } else if (j == rows - 1) { output_index = SUB2IND(j, i, k, rows, cols, n_output_channels); out[output_index] = in[SUB2IND(j, i, k, rows, cols, n_channels)] - in[SUB2IND(j - 1, i, k, rows, cols, n_channels)]; } else { output_index = SUB2IND(j, i, k, rows, cols, n_output_channels); out[output_index] = (in[SUB2IND(j + 1, i, k, rows, cols, n_channels)] - in[SUB2IND(j - 1, i, k, rows, cols, n_channels)]) / 2.0; } } } // column-derivative for (long long j = 0; j < rows; ++j) { for (long long i = 0; i < cols; ++i) { if (i == 0) { output_index = SUB2IND(j, 0, n_channels + k , rows, cols, n_output_channels); out[output_index] = in[SUB2IND(j, 1, k, rows, cols, n_channels)] - in[SUB2IND(j, 0, k, rows, cols, n_channels)]; } else if (i == cols - 1) { output_index = SUB2IND(j, cols - 1, n_channels + k, rows, cols, n_output_channels); out[output_index] = in[SUB2IND(j, i, k, rows, cols, n_channels)] - in[SUB2IND(j, i - 1, k, rows, cols, n_channels)]; } else { output_index = SUB2IND(j, i, n_channels + k, rows, cols, n_output_channels); out[output_index] = (in[SUB2IND(j, i + 1, k, rows, cols, n_channels)] - in[SUB2IND(j, i - 1, k, rows, cols, n_channels)]) / 2.0; } } } } }
loop-1.c
int bar (int); int baz (int *); void f1 (int x) { int i = 0, j = 0; #pragma omp for for (i = 0; i < 16; i++) ; #pragma omp for for (i = 0; 16 > i; i++) ; #pragma omp for for (i = 0; i < 16; i = i + 2) ; #pragma omp for for (i = 0; i < 16; i = 2 + i) ; #pragma omp for /* { dg-error "initializer expression refers to iteration variable" } */ for (i = i; i < 16; i++) ; #pragma omp for for (i = 2 * (i & x); i < 16; i++) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for for (i = bar (i); i < 16; i++) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for for (i = baz (&i); i < 16; i++) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for for (i = 5; i < 2 * i + 17; i++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for for (i = 5; 2 * i + 17 > i; i++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for for (i = 5; bar (i) > i; i++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for for (i = 5; i <= baz (&i); i++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for for (i = 5; i <= i; i++) /* { dg-error "invalid controlling predicate|condition expression refers to iteration variable" } */ ; #pragma omp for /* { dg-error "increment expression refers to iteration variable" "" { xfail *-*-* } } */ for (i = 5; i < 16; i += i) /* { dg-bogus "invalid increment expression" "" { xfail *-*-* } } */ ; #pragma omp for for (i = 5; i < 16; i = i + 2 * i) /* { dg-error "invalid increment expression|increment expression refers to iteration variable" } */ ; #pragma omp for /* { dg-error "increment expression refers to iteration variable" "" { xfail *-*-* } } */ for (i = 5; i < 16; i = i + i) /* { dg-bogus "invalid increment expression" "" { xfail *-*-* } } */ ; #pragma omp for for (i = 5; i < 16; i = i + bar (i)) /* { dg-error "increment expression refers to iteration variable" } */ ; #pragma omp for for (i = 5; i < 16; i = baz (&i) + i) /* { dg-error "increment expression refers to iteration variable" } */ ; #pragma omp for for (i = 5; i < 16; i += bar (i)) /* { dg-error "increment expression refers to iteration variable" } */ ; #pragma omp for for (i = 5; i < 16; i += baz (&i)) /* { dg-error "increment expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (i = 0; i < 16; i = i + 2) for (j = 0; j < 16; j += 2) ; #pragma omp for collapse(2) /* { dg-error "initializer expression refers to iteration variable" } */ for (i = j; i < 16; i = i + 2) for (j = 0; j < 16; j++) ; #pragma omp for collapse(2) /* { dg-error "initializer expression refers to iteration variable" } */ for (i = 0; i < 16; i = i + 2) for (j = i; j < 16; j += 2) ; #pragma omp for collapse(2) for (i = 0; i < 16; i = i + 2) for (j = i + 3; j < 16; j += 2) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (i = 0; i < 16; i++) for (j = baz (&i); j < 16; j += 2) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (i = 0; i < 16; i++) for (j = 16; j > (i & x); j--) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (i = 0; i < 16; i++) for (j = 0; j < i; j++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (i = 0; i < 16; i++) for (j = 0; j < i + 4; j++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (i = 0; i < j + 4; i++) /* { dg-error "condition expression refers to iteration variable" } */ for (j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (i = 0; i < j; i++) /* { dg-error "condition expression refers to iteration variable" } */ for (j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (i = 0; i < bar (j); i++) /* { dg-error "condition expression refers to iteration variable" } */ for (j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (i = 0; i < 16; i++) for (j = 0; j < baz (&i); j++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for collapse(2) /* { dg-error "increment expression refers to iteration variable" } */ for (i = 0; i < 16; i += j) for (j = 0; j < 16; j++) ; #pragma omp for collapse(2) /* { dg-error "increment expression refers to iteration variable" } */ for (i = 0; i < 16; i++) for (j = 0; j < 16; j += i) ; #pragma omp for collapse(2) /* { dg-error "increment expression refers to iteration variable" } */ for (i = 0; i < 16; i = j + i) for (j = 0; j < 16; j++) ; #pragma omp for collapse(2) /* { dg-error "increment expression refers to iteration variable" } */ for (i = 0; i < 16; i++) for (j = 0; j < 16; j = j + i) ; #pragma omp for collapse(2) for (i = 0; i < 16; i = bar (j) + i) /* { dg-error "increment expression refers to iteration variable" } */ for (j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (i = 0; i < 16; i++) for (j = 0; j < 16; j = j + baz (&i)) /* { dg-error "increment expression refers to iteration variable" } */ ; } void f2 (int x) { #pragma omp for for (int i = 0; i < 16; i++) ; #pragma omp for for (int i = 0; 16 > i; i++) ; #pragma omp for for (int i = 0; i < 16; i = i + 2) ; #pragma omp for for (int i = 0; i < 16; i = 2 + i) ; #pragma omp for /* { dg-error "initializer expression refers to iteration variable" } */ for (int i = i; i < 16; i++) ; #pragma omp for for (int i = 2 * (i & x); i < 16; i++) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for for (int i = bar (i); i < 16; i++) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for for (int i = baz (&i); i < 16; i++) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for for (int i = 5; i < 2 * i + 17; i++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for for (int i = 5; 2 * i + 17 > i; i++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for for (int i = 5; bar (i) > i; i++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for for (int i = 5; i <= baz (&i); i++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for for (int i = 5; i <= i; i++) /* { dg-error "invalid controlling predicate|condition expression refers to iteration variable" } */ ; #pragma omp for /* { dg-error "increment expression refers to iteration variable" "" { xfail *-*-* } } */ for (int i = 5; i < 16; i += i) /* { dg-bogus "invalid increment expression" "" { xfail *-*-* } } */ ; #pragma omp for for (int i = 5; i < 16; i = i + 2 * i) /* { dg-error "invalid increment expression|increment expression refers to iteration variable" } */ ; #pragma omp for /* { dg-error "increment expression refers to iteration variable" "" { xfail *-*-* } } */ for (int i = 5; i < 16; i = i + i) /* { dg-bogus "invalid increment expression" "" { xfail *-*-* } } */ ; #pragma omp for for (int i = 5; i < 16; i = i + bar (i)) /* { dg-error "increment expression refers to iteration variable" } */ ; #pragma omp for for (int i = 5; i < 16; i = baz (&i) + i) /* { dg-error "increment expression refers to iteration variable" } */ ; #pragma omp for for (int i = 5; i < 16; i += bar (i)) /* { dg-error "increment expression refers to iteration variable" } */ ; #pragma omp for for (int i = 5; i < 16; i += baz (&i)) /* { dg-error "increment expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (int i = 0; i < 16; i = i + 2) for (int j = 0; j < 16; j += 2) ; #pragma omp for collapse(2) /* { dg-error "initializer expression refers to iteration variable" } */ for (int i = 0; i < 16; i = i + 2) for (int j = i; j < 16; j += 2) ; #pragma omp for collapse(2) for (int i = 0; i < 16; i = i + 2) for (int j = i + 3; j < 16; j += 2) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (int i = 0; i < 16; i++) for (int j = baz (&i); j < 16; j += 2) /* { dg-error "initializer expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (int i = 0; i < 16; i++) for (int j = 16; j > (i & x); j--) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (int i = 0; i < 16; i++) for (int j = 0; j < i; j++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (int i = 0; i < 16; i++) for (int j = 0; j < i + 4; j++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for collapse(2) for (int i = 0; i < 16; i++) for (int j = 0; j < baz (&i); j++) /* { dg-error "condition expression refers to iteration variable" } */ ; #pragma omp for collapse(2) /* { dg-error "increment expression refers to iteration variable" } */ for (int i = 0; i < 16; i++) for (int j = 0; j < 16; j += i) ; #pragma omp for collapse(2) /* { dg-error "increment expression refers to iteration variable" } */ for (int i = 0; i < 16; i++) for (int j = 0; j < 16; j = j + i) ; #pragma omp for collapse(2) for (int i = 0; i < 16; i++) for (int j = 0; j < 16; j = j + baz (&i)) /* { dg-error "increment expression refers to iteration variable" } */ ; } void f3 (void) { int j = 0; #pragma omp for collapse(2) for (int i = j; i < 16; i = i + 2) for (int j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (int i = 0; i < j + 4; i++) for (int j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (int i = 0; i < j; i++) for (int j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (int i = 0; i < bar (j); i++) for (int j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (int i = 0; i < 16; i += j) for (int j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (int i = 0; i < 16; i = j + i) for (int j = 0; j < 16; j++) ; #pragma omp for collapse(2) for (int i = 0; i < 16; i = bar (j) + i) for (int j = 0; j < 16; j++) ; }
9e6bc14_so8.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include <stdio.h> #include "omp.h" #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; }; int Kernel(struct dataobj *restrict block_sizes_vec, struct dataobj *restrict damp_vec, const float dt, const float h_x, const float h_y, const float h_z, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict save_src_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict usol_vec, struct dataobj *restrict vp_vec, const int sp_zi_m, const int time_M, const int time_m, struct profiler *timers, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads) { int (*restrict block_sizes) __attribute__ ((aligned (64))) = (int (*)) block_sizes_vec->data; float(*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[damp_vec->size[1]][damp_vec->size[2]])damp_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src)[save_src_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_vec->size[1]])save_src_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; float(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (float(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; float(*restrict usol)[usol_vec->size[1]][usol_vec->size[2]][usol_vec->size[3]] __attribute__((aligned(64))) = (float(*)[usol_vec->size[1]][usol_vec->size[2]][usol_vec->size[3]])usol_vec->data; float(*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[vp_vec->size[1]][vp_vec->size[2]])vp_vec->data; /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); int xb_size = block_sizes[0]; int y0_blk0_size = block_sizes[3]; int x0_blk0_size = block_sizes[2]; int yb_size = block_sizes[1]; printf(" Tiles: %d, %d ::: Blocks %d, %d \n", x0_blk0_size, y0_blk0_size, xb_size, yb_size); int sf = 4; // half the space order int t_blk_size = 2 * sf * (time_M - time_m); struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); for (int t_blk = time_m; t_blk < sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block { for (int xb = x_m; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size + 1) { for (int yb = y_m; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size + 1) { for (int time = t_blk, t0 = (time + 1) % (3), t1 = (time) % (3), t2 = (time + 2) % (3); time <= 1 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1)) + 1) % (3), t1 = (((time / sf) % (time_M - time_m + 1))) % (3), t2 = (((time / sf) % (time_M - time_m + 1)) + 2) % (3)) { int tw = ((time / sf) % (time_M - time_m + 1)); /* Begin section0 */ #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size) { for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size)), (y0_blk0 + y0_blk0_size - 1)); y++) { #pragma omp simd aligned(damp, usol, vp : 32) for (int z = z_m; z <= z_M; z += 1) { float r14 = -2.84722222F * usol[t1][x - time + 8][y - time + 8][z + 8]; float r13 = 1.0 / dt; float r12 = 1.0 / (dt * dt); float r11 = 1.0 / (vp[x - time + 8][y - time + 8][z + 8] * vp[x - time + 8][y - time + 8][z + 8]); usol[t0][x - time + 8][y - time + 8][z + 8] = (r11 * (-r12 * (-2.0F * usol[t1][x - time + 8][y - time + 8][z + 8] + usol[t2][x - time + 8][y - time + 8][z + 8])) + r13 * (damp[x - time + 1][y - time + 1][z + 1] * usol[t1][x - time + 8][y - time + 8][z + 8]) + (r14 - 1.78571429e-3F * (usol[t1][x - time + 8][y - time + 8][z + 4] + usol[t1][x - time + 8][y - time + 8][z + 12]) + 2.53968254e-2F * (usol[t1][x - time + 8][y - time + 8][z + 5] + usol[t1][x - time + 8][y - time + 8][z + 11]) - 2.0e-1F * (usol[t1][x - time + 8][y - time + 8][z + 6] + usol[t1][x - time + 8][y - time + 8][z + 10]) + 1.6F * (usol[t1][x - time + 8][y - time + 8][z + 7] + usol[t1][x - time + 8][y - time + 8][z + 9])) / ((h_z * h_z)) + (r14 - 1.78571429e-3F * (usol[t1][x - time + 8][y - time + 4][z + 8] + usol[t1][x - time + 8][y - time + 12][z + 8]) + 2.53968254e-2F * (usol[t1][x - time + 8][y - time + 5][z + 8] + usol[t1][x - time + 8][y - time + 11][z + 8]) - 2.0e-1F * (usol[t1][x - time + 8][y - time + 6][z + 8] + usol[t1][x - time + 8][y - time + 10][z + 8]) + 1.6F * (usol[t1][x - time + 8][y - time + 7][z + 8] + usol[t1][x - time + 8][y - time + 9][z + 8])) / ((h_y * h_y)) + (r14 - 1.78571429e-3F * (usol[t1][x - time + 4][y - time + 8][z + 8] + usol[t1][x - time + 12][y - time + 8][z + 8]) + 2.53968254e-2F * (usol[t1][x - time + 5][y - time + 8][z + 8] + usol[t1][x - time + 11][y - time + 8][z + 8]) - 2.0e-1F * (usol[t1][x - time + 6][y - time + 8][z + 8] + usol[t1][x - time + 10][y - time + 8][z + 8]) + 1.6F * (usol[t1][x - time + 7][y - time + 8][z + 8] + usol[t1][x - time + 9][y - time + 8][z + 8])) / ((h_x * h_x))) / (r11 * r12 + r13 * damp[x - time + 1][y - time + 1][z + 1]); } #pragma omp simd aligned(damp, usol, vp : 32) for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time]-1; sp_zi += 1) { int zind = sp_source_mask[x - time][y - time][sp_zi]; float r0 = save_src[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; usol[t0][x - time + 8][y - time + 8][zind + 8] += r0; } } } } } } } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000; return 0; }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/OpenMPClause.h" #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; class ObjCTypeParameter; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class ParsingOpenMPDirectiveRAII; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFENVHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// Parsing OpenMP directive mode. bool OpenMPDirectiveParsing = false; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// Handle the annotation token produced for /// #pragma comment... void HandlePragmaMSComment(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static ParsedType getTypeAnnotation(const Token &Tok) { return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, ParsedType T) { Tok.setAnnotationValue(T.getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); bool MightBeCXXScopeToken() { return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super); } bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); } private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { PrevPreferredType = P.PreferredType; PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); virtual void ParseLexedPragmas(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; void ParseLexedPragmas() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; /// Contains the lexed tokens of a pragma with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. class LateParsedPragma : public LateParsedDeclaration { Parser *Self = nullptr; AccessSpecifier AS = AS_none; CachedTokens Toks; public: explicit LateParsedPragma(Parser *P, AccessSpecifier AS) : Self(P), AS(AS) {} void takeToks(CachedTokens &Cached) { Toks.swap(Cached); } const CachedTokens &toks() const { return Toks; } AccessSpecifier getAccessSpecifier() const { return AS; } void ParseLexedPragmas() override; }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; explicit LexedMethod(Parser* P, Decl *MD) : Self(P), D(MD), TemplateScope(false) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser* Self; /// Method - The method declaration. Decl *Method; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), TemplateScope(false), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { } /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class had an associated template /// scope. When true, TagOrTemplate is a template declaration; /// otherwise, it is a tag declaration. bool TemplateScope : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); static void LateTemplateParserCleanupCallback(void *P); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); void ParseLexedPragmas(ParsingClass &Class); void ParseLexedPragma(LateParsedPragma &LP); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; struct ParsedAttributesViewWithRange : ParsedAttributesView { ParsedAttributesViewWithRange() : ParsedAttributesView() {} void clearListOnly() { ParsedAttributesView::clearListOnly(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc is filled with the location of the last token of the simple-asm. ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); ExprResult ParseAsmStringLiteral(bool ForAsmLabel); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); void ParseObjCMethodRequirement(); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); /// Control what ParseCastExpression will parse. enum CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly }; ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<Expr*, 20> ExprListTy; typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C++ Concepts ExprResult ParseRequiresExpression(); void ParseTrailingRequiresClause(Declarator &D); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); ExprResult ParseInitializerWithPotentialDesignator(); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, Decl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Based only on the given token kind, determine whether we know that /// we're at the start of an expression or a type-specifier-seq (which may /// be an expression, in C++). /// /// This routine does not attempt to resolve any of the trick cases, e.g., /// those involving lookup of identifiers. /// /// \returns \c TPR_true if this token starts an expression, \c TPR_false if /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot /// tell. TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 /// 'explicit(bool)' declaration, in earlier language modes where that is an /// extension. TPResult isExplicitBool(); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } void MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) ParseGNUAttributes(attrs, endLoc, LateAttrs); } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } void MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); } } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) ParseMicrosoftDeclSpecs(Attrs, End); } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0 /// or higher. /// \return false if error happens. bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { if (getLangOpts().OpenCL) return ParseOpenCLUnrollHintAttribute(Attrs); return true; } /// Parses opencl_unroll_hint attribute. /// \return false if error happens. bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parses OpenMP context selectors and calls \p Callback for each /// successfully parsed context selector. bool parseOpenMPContextSelectors(SourceLocation Loc, SmallVectorImpl<Sema::OMPCtxSelectorData> &Data); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand = false); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *TailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or ///< lastprivate clause. SmallVector<OpenMPMapModifierKind, OMPMapClause::NumberOfModifiers> MapTypeModifiers; SmallVector<SourceLocation, OMPMapClause::NumberOfModifiers> MapTypeModifiersLoc; bool IsMapTypeImplicit = false; SourceLocation DepLinMapLastLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); TPResult isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); bool isTypeConstraintAnnotation(); bool TryAnnotateTypeConstraint(); NamedDecl * ParseConstrainedTemplateTypeParameter(unsigned Depth, unsigned Position); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true, bool TypeConstraint = false); void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; }; } // end namespace clang #endif
GB_unaryop__abs_int64_uint16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_int64_uint16 // op(A') function: GB_tran__abs_int64_uint16 // C type: int64_t // A type: uint16_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = GB_IABS (aij) #define GB_ATYPE \ uint16_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IABS (x) ; // casting #define GB_CASTING(z, x) \ int64_t z = (int64_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_INT64 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_int64_uint16 ( int64_t *restrict Cx, const uint16_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_int64_uint16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
3d7pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 24; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,4);t1++) { lbp=max(ceild(t1,2),ceild(8*t1-Nt+3,8)); ubp=min(floord(Nt+Nz-4,8),floord(4*t1+Nz+1,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-5,6)),ceild(8*t2-Nz-20,24));t3<=min(min(min(floord(Nt+Ny-4,24),floord(4*t1+Ny+5,24)),floord(8*t2+Ny+4,24)),floord(8*t1-8*t2+Nz+Ny+3,24));t3++) { for (t4=max(max(max(0,ceild(t1-7,8)),ceild(8*t2-Nz-28,32)),ceild(24*t3-Ny-28,32));t4<=min(min(min(min(floord(Nt+Nx-4,32),floord(4*t1+Nx+5,32)),floord(8*t2+Nx+4,32)),floord(24*t3+Nx+20,32)),floord(8*t1-8*t2+Nz+Nx+3,32));t4++) { for (t5=max(max(max(max(max(0,4*t1),8*t1-8*t2+1),8*t2-Nz+2),24*t3-Ny+2),32*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,4*t1+7),8*t2+6),24*t3+22),32*t4+30),8*t1-8*t2+Nz+5);t5++) { for (t6=max(max(8*t2,t5+1),-8*t1+8*t2+2*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(24*t3,t5+1);t7<=min(24*t3+23,t5+Ny-2);t7++) { lbv=max(32*t4,t5+1); ubv=min(32*t4+31,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
omp_simd_aligned2.c
//Variable examples of using simd directives void foo (int n, double *a, double* b) { for (int i=0; i<n; i++) a[i]=b[i]; } void foo2 (int n, double *a, double* b) { for (int i=0; i<n; i++) a[i]=b[i]; } void foo3 (int n, double *a, double* b) { int j=0; for (int i=0; i<n; i++,j++) { a[i]=b[i]+j; } } void foo32 (int n, double *a, double* b) { int j=0, k=0; for (int i=0; i<n; i++,j++,k++) { a[i]=b[i]+j+k; } } void foo33 (int n, double *a, double* b) { int j=0, k=0; for (int i=0; i<n; i++,j++,k++) { a[i]=b[i]+j+k; } } void fooAligned (int n, double *a, double* b) { int j=0, k=0; for (int i=0; i<n; i++,j++,k++) { a[i]=b[i]+j+k; } } void fooAligned2 (int n, double *a, double* b) { int j=0, k=0; #pragma omp simd aligned(j,k:1) for (int i=0; i<n; i++,j++,k++) { a[i]=b[i]+j+k; } } double work( double *a, double *b, int n ) { int i; double tmp, sum; sum = 0.0; for (i = 0; i < n; i++) { tmp = a[i] + b[i]; sum += tmp; } return sum; } #define N 45 int a[N], b[N], c[N]; void foo4(int i, double* P) { int j; for (i = 0; i < 999; ++i) { j = P[i]; } } void work2( double **a, double **b, double **c, int n ) { int i, j; double tmp; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { tmp = a[i][j] + b[i][j]; c[i][j] = tmp; } } } void work3( double **a, double **b, double **c, int n ) { int i, j; double tmp; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { tmp = a[i][j] + b[i][j]; c[i][j] = tmp; } } } // declare simd can show up several times! float bar(int * p) { *p = *p +10; return *p; } // declare simd can show up several times! float bar2(int * p) { *p = *p +10; return *p; }
scheduled-clauseModificado4.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif main(int argc, char **argv) { omp_sched_t kind; int modifier; int i, n=200,chunk,a[n],suma=0; if(argc < 3) { fprintf(stderr,"\nFalta iteraciones o chunk \n"); exit(-1); } n = atoi(argv[1]); if (n>200) n=200; chunk = atoi(argv[2]); for (i=0; i<n; i++) a[i] = i; printf("Dentro de 'parallel'\n"); //omp_set_num_threads(3); #pragma omp parallel { #pragma omp for firstprivate(suma) lastprivate(suma) schedule(dynamic,chunk) for (i=0; i<n; i++){ suma = suma + a[i]; printf(" thread %d suma a[%d]=%d suma=%d \n", omp_get_thread_num(),i,a[i],suma); } #pragma omp master { // imprimir dyn-var printf("\tdyn-var => %d\n", omp_get_dynamic()); // imprimir nthreads-var printf("\tnthreads-var => %d\n", omp_get_max_threads()); // imprimir thread-limit-var printf("\tthread-limit-var => %d\n", omp_get_thread_limit()); // imprimir run-sched-var omp_get_schedule(&kind, &modifier); printf("\trun-sched-var => kind : %d modifier : %d\n", kind, modifier); // imprimir omp_get_num_threads() "numero de threads usadas en una region paralela" printf("\thebras usadas en la region paralela => %d\n", omp_get_num_threads()); // imprimir omp_get_num_procs() "numero de procesadores disponibles para el programa" printf("\tprocesadores disponibles => %d\n", omp_get_num_procs()); // imprimr omp_in_parallel() "true si se llama en un parallel, false en caso contrario" printf("\t¿region paralela? => %d\n", omp_in_parallel()); } } printf("\nFuera de 'parallel' suma=%d\n",suma); // imprimir dyn-var printf("\tdyn-var => %d\n", omp_get_dynamic()); // imprimir nthreads-var printf("\tnthreads-var => %d\n", omp_get_max_threads()); // imprimir thread-limit-var printf("\tthread-limit-var => %d\n", omp_get_thread_limit()); // imprimir run-sched-var omp_get_schedule(&kind, &modifier); printf("\trun-sched-var => kind : %d modifier : %d\n", kind, modifier); // imprimir omp_get_num_threads() "numero de threads usadas en una region paralela" printf("\thebras usadas fuera de la region paralela => %d\n", omp_get_num_threads()); // imprimir omp_get_num_procs() "numero de procesadores disponibles para el programa" printf("\tprocesadores disponibles => %d\n", omp_get_num_procs()); // imprimr omp_in_parallel() "true si se llama en un parallel, false en caso contrario" printf("\t¿region paralela? => %d\n", omp_in_parallel()); }
cnn_builtin_math.c
#include <math.h> #include <string.h> #include <cblas.h> #include "cnn.h" #include "cnn_builtin_math.h" #include "cnn_builtin_math_inline.h" #include "cnn_config.h" #include "cnn_init.h" #include "cnn_macro.h" #ifdef CNN_WITH_CUDA #include <cuda_runtime.h> #include "cnn_builtin_math_cu.h" #endif CNN_ACTIV_DEF((*cnn_activ_list[])) = { cnn_softmax, // cnn_relu, // cnn_swish, // cnn_sigmoid, // cnn_tanh, // cnn_gaussian, // cnn_bent_identity, // cnn_softplus, // cnn_softsign, // cnn_sinc, // cnn_sinusoid, // cnn_identity // }; CNN_ACTIV_GRAD_DEF((*cnn_activ_grad_list[])) = { cnn_softmax_grad, // cnn_relu_grad, // cnn_swish_grad, // cnn_sigmoid_grad, // cnn_tanh_grad, // cnn_gaussian_grad, // cnn_bent_identity_grad, // cnn_softplus_grad, // cnn_softsign_grad, // cnn_sinc_grad, // cnn_sinusoid_grad, // cnn_identity_grad // }; const char* cnn_activ_name[] = { "Softmax", // "ReLU", // "Swish", // "Sigmoid", // "Hyperbolic Tangent", // "Gaussian", // "Bent Identity", // "SoftPlus", // "SoftSign", // "Sinc", // "Sinusoid", // "Identity" // }; CNN_ACTIV_DEF(cnn_softmax) { float max, sum; #ifdef CNN_WITH_CUDA // Find max value cnn_max_gpu(&max, src, len, buf); // Find shifted vector cnn_add_gpu(buf, src, len, -max); // Find exponential vector cnn_exp_gpu(buf, buf, len); // Find sum cnn_sum_gpu(&sum, buf, len, dst); // Find softmax cnn_div_gpu(dst, buf, len, sum); #else int i; // Find max value max = src[0]; for (i = 1; i < len; i++) { if (src[i] > max) { max = src[i]; } } // Find exponential summation sum = 0; for (i = 0; i < len; i++) { dst[i] = src[i] - max; sum += exp(dst[i]); } // Find softmax output for (i = 0; i < len; i++) { dst[i] = exp(dst[i]) / sum; } #endif } CNN_ACTIV_GRAD_DEF(cnn_softmax_grad) { #ifdef CNN_WITH_CUDA float alpha = 1.0; float beta = 0.0; // Find derivative matrix cnn_smax_grad_gpu(buf, cache, len); // Find layer gradient cnn_assert_cu(cublasSgemm(cnnInit.blasHandle, CUBLAS_OP_N, CUBLAS_OP_N, // len, 1, len, // &alpha, // buf, len, // gradIn, len, // &beta, // gradOut, len)); #else int i, j; // Find softmax gradient matrix for (i = 0; i < len; i++) { for (j = 0; j < len; j++) { buf[i * len + j] = cache[i] * ((float)(i == j) - cache[j]); } } // Find layer gradient cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, // 1, len, len, // 1.0, // gradIn, len, // buf, len, // 0.0, // gradOut, len); #endif } CNN_ACTIV_DEF(cnn_relu) { #ifdef CNN_WITH_CUDA cnn_relu_gpu(dst, src, len); #else #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_relu(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_relu_grad) { #ifdef CNN_WITH_CUDA cnn_relu_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find relu gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_relu_grad(gradOut + i, gradIn + i, src + i, NULL); } #endif } CNN_ACTIV_DEF(cnn_swish) { #ifdef CNN_WITH_CUDA cnn_swish_gpu(dst, src, len); #else #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_swish(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_swish_grad) { #ifdef CNN_WITH_CUDA cnn_swish_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find swish gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_swish_grad(gradOut + i, gradIn + i, src + i, cache + i); } #endif } CNN_ACTIV_DEF(cnn_sigmoid) { #ifdef CNN_WITH_CUDA cnn_sigmoid_gpu(dst, src, len); #else #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_sigmoid(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_sigmoid_grad) { #ifdef CNN_WITH_CUDA cnn_sigmoid_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find sigmoid gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_sigmoid_grad(gradOut + i, gradIn + i, NULL, cache + i); } #endif } CNN_ACTIV_DEF(cnn_tanh) { #ifdef CNN_WITH_CUDA cnn_tanh_gpu(dst, src, len); #else #pragma omp parallel for (int i = 0; i < len; i++) { __cnn_tanh(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_tanh_grad) { #ifdef CNN_WITH_CUDA cnn_tanh_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find tanh gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_tanh_grad(gradOut + i, gradIn + i, NULL, cache + i); } #endif } CNN_ACTIV_DEF(cnn_gaussian) { #ifdef CNN_WITH_CUDA cnn_gaussian_gpu(dst, src, len); #else #pragma omp parallel for (int i = 0; i < len; i++) { __cnn_gaussian(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_gaussian_grad) { #ifdef CNN_WITH_CUDA cnn_gaussian_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find gaussian gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_gaussian_grad(gradOut + i, gradIn + i, src + i, cache + i); } #endif } CNN_ACTIV_DEF(cnn_bent_identity) { #ifdef CNN_WITH_CUDA cnn_bent_identity_gpu(dst, src, len); #else #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_bent_identity(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_bent_identity_grad) { #ifdef CNN_WITH_CUDA cnn_bent_identity_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find bent indentity gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_bent_identity_grad(gradOut + i, gradIn + i, src + i, NULL); } #endif } CNN_ACTIV_DEF(cnn_softplus) { #ifdef CNN_WITH_CUDA cnn_softplus_gpu(dst, src, len); #else #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_softplus(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_softplus_grad) { #ifdef CNN_WITH_CUDA cnn_softplus_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find softplus gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_softplus_grad(gradOut + i, gradIn + i, src + i, NULL); } #endif } CNN_ACTIV_DEF(cnn_softsign) { #ifdef CNN_WITH_CUDA cnn_softsign_gpu(dst, src, len); #else #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_softsign(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_softsign_grad) { #ifdef CNN_WITH_CUDA cnn_softsign_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find softsign gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_softsign_grad(gradOut + i, gradIn + i, src + i, NULL); } #endif } CNN_ACTIV_DEF(cnn_sinc) { #ifdef CNN_WITH_CUDA cnn_sinc_gpu(dst, src, len); #else #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_sinc(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_sinc_grad) { #ifdef CNN_WITH_CUDA cnn_sinc_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find sinc gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_sinc_grad(gradOut + i, gradIn + i, src + i, NULL); } #endif } CNN_ACTIV_DEF(cnn_sinusoid) { #ifdef CNN_WITH_CUDA cnn_sin_gpu(dst, src, len); #else #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_sinusoid(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_sinusoid_grad) { #ifdef CNN_WITH_CUDA cnn_sin_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find sinusoid gradient #pragma omp parallel for shared(gradOut, gradIn, src) for (int i = 0; i < len; i++) { __cnn_sinusoid_grad(gradOut + i, gradIn + i, src + i, NULL); } #endif } CNN_ACTIV_DEF(cnn_identity) { #ifdef CNN_WITH_CUDA cnn_identity_gpu(dst, src, len); #else #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_identity(dst + i, src + i); } #endif } CNN_ACTIV_GRAD_DEF(cnn_identity_grad) { #ifdef CNN_WITH_CUDA cnn_identity_grad_gpu(gradOut, gradIn, src, len, cache); #else // Find identity gradient #pragma omp parallel for for (int i = 0; i < len; i++) { __cnn_identity_grad(gradOut + i, gradIn + i, NULL, NULL); } #endif } int cnn_get_activ_id(const char* name) { int i; int ret = CNN_PARSE_FAILED; if (name != NULL) { for (i = 0; i < CNN_ACTIV_AMOUNT; i++) { ret = strcmp(name, cnn_activ_name[i]); if (ret == 0) { ret = i; goto RET; } } } RET: return ret; }
MsnhCVMatOp.h
#ifndef MSNHCVOP_H #define MSNHCVOP_H #include <Msnhnet/cv/MsnhCVMat.h> #include <Msnhnet/utils/MsnhTimeUtil.h> namespace Msnhnet { class MsnhNet_API MatOp { public: static void getROI(Mat &src, Mat &dst, const Vec2I32 &p1, const Vec2I32 &p2); static void setROI(Mat &srcDst, Mat &roi, const Vec2I32 &pos); static void cvtColor(Mat &src, Mat &dst, const CvtColorType& cvtType); static void resize(Mat& src, Mat &dst, const Vec2I32 &outSize, const ResizeType& resizeType=RESIZE_BILINEAR); template<typename T> static void copyMakeBorder(Mat& src, Mat &dst, const int &top ,const int &down, const int &left, const int &right, const T & val) { int array = DataType<T>::array; int fmt = DataType<T>::fmt; src.checkPixelType(array, fmt); int srcWidth = src.getWidth() ; int srcHeight = src.getHeight(); int finalWidth = srcWidth + left + right; int finalHeight = srcHeight + top + down; Mat tmpMat(finalWidth, finalHeight, src.getMatType()); tmpMat.fillPixel<T>(val); #ifdef USE_OMP #pragma omp parallel for num_threads(OMP_THREAD) #endif for (int i = 0; i < srcHeight; ++i) { if(fmt == 'b') { memcpy(tmpMat.getData().u8+(finalWidth*(i+top)+left)*array, src.getData().u8+(srcWidth*i)*array, array*srcWidth); } else if(fmt == 'f') { memcpy(tmpMat.getData().f32+(finalWidth*(i+top)+left)*array, src.getData().f32+(srcWidth*i)*array, array*srcWidth*4); } else if(fmt == 'd') { memcpy(tmpMat.getData().f64+(finalWidth*(i+top)+left)*array, src.getData().f64+(srcWidth*i)*array, array*srcWidth*8); } } dst = tmpMat; } static void flip(Mat &mat, const FlipMode &flipMode=FLIP_V); static double norm(Mat &mat1, Mat &mat2, const NormType& normType = NORM_L2); static double norm(Mat &mat, const NormType& normType = NORM_L2); template<typename T> static void _split(Mat &src, std::vector<Mat> &dst) { dst.clear(); if(src.getChannel()==1) { dst.push_back(src); } else if(src.getChannel()==3) { Mat R; Mat G; Mat B; Mat::createMat<T>(src.getWidth(),src.getHeight(),1,R); Mat::createMat<T>(src.getWidth(),src.getHeight(),1,G); Mat::createMat<T>(src.getWidth(),src.getHeight(),1,B); uint64_t dataLen = src.getHeight()*src.getWidth(); if(dataLen > MIN_OMP_DATA) { #ifdef USE_OMP #pragma omp parallel for num_threads(OMP_THREAD) #endif for (int i = 0; i < src.getHeight(); ++i) { for (int j = 0; j < src.getWidth(); ++j) { reinterpret_cast<T*>(R.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*3 + 0]; reinterpret_cast<T*>(G.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*3 + 1]; reinterpret_cast<T*>(B.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*3 + 2]; } } } else { for (int i = 0; i < src.getHeight(); ++i) { for (int j = 0; j < src.getWidth(); ++j) { reinterpret_cast<T*>(R.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*3 + 0]; reinterpret_cast<T*>(G.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*3 + 1]; reinterpret_cast<T*>(B.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*3 + 2]; } } } dst.push_back(R); dst.push_back(G); dst.push_back(B); } else if(src.getChannel()==4) { Mat R; Mat G; Mat B; Mat A; Mat::createMat<T>(src.getWidth(),src.getHeight(),1,R); Mat::createMat<T>(src.getWidth(),src.getHeight(),1,G); Mat::createMat<T>(src.getWidth(),src.getHeight(),1,B); Mat::createMat<T>(src.getWidth(),src.getHeight(),1,A); uint64_t dataLen = src.getHeight()*src.getWidth(); if(dataLen > MIN_OMP_DATA) { #ifdef USE_OMP #pragma omp parallel for num_threads(OMP_THREAD) #endif for (int i = 0; i < src.getHeight(); ++i) { for (int j = 0; j < src.getWidth(); ++j) { reinterpret_cast<T*>(R.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*4 + 0]; reinterpret_cast<T*>(G.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*4 + 1]; reinterpret_cast<T*>(B.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*4 + 2]; reinterpret_cast<T*>(A.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*4 + 3]; } } } else { for (int i = 0; i < src.getHeight(); ++i) { for (int j = 0; j < src.getWidth(); ++j) { reinterpret_cast<T*>(R.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*4 + 0]; reinterpret_cast<T*>(G.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*4 + 1]; reinterpret_cast<T*>(B.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*4 + 2]; reinterpret_cast<T*>(A.getBytes())[i*src.getWidth() + j] = reinterpret_cast<T*>(src.getBytes())[(i*src.getWidth() + j)*4 + 3]; } } } dst.push_back(R); dst.push_back(G); dst.push_back(B); dst.push_back(A); } } static void split(Mat &src, std::vector<Mat> &dst); template<typename T> static void _merge(std::vector<Mat> &src, Mat &dst) { int width = src[0].getWidth(); int height = src[1].getHeight(); if(src.size()==1) { dst = src[0]; return; } else if(src.size()==3) { Mat::createMat<T>(width,height,3,dst); uint64_t dataLen = width*height; if(dataLen > MIN_OMP_DATA) { #ifdef USE_OMP #pragma omp parallel for num_threads(OMP_THREAD) #endif for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*3 + 0] = reinterpret_cast<T*>(src[0].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*3 + 1] = reinterpret_cast<T*>(src[1].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*3 + 2] = reinterpret_cast<T*>(src[2].getBytes())[i*width + j]; } } } else { for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*3 + 0] = reinterpret_cast<T*>(src[0].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*3 + 1] = reinterpret_cast<T*>(src[1].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*3 + 2] = reinterpret_cast<T*>(src[2].getBytes())[i*width + j]; } } } } else if(src.size()==4) { Mat::createMat<T>(width,height,4,dst); uint64_t dataLen = width*height; if(dataLen > MIN_OMP_DATA) { #ifdef USE_OMP #pragma omp parallel for num_threads(OMP_THREAD) #endif for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*4 + 0] = reinterpret_cast<T*>(src[0].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*4 + 1] = reinterpret_cast<T*>(src[1].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*4 + 2] = reinterpret_cast<T*>(src[2].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*4 + 3] = reinterpret_cast<T*>(src[3].getBytes())[i*width + j]; } } } else { for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*4 + 0] = reinterpret_cast<T*>(src[0].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*4 + 1] = reinterpret_cast<T*>(src[1].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*4 + 2] = reinterpret_cast<T*>(src[2].getBytes())[i*width + j]; reinterpret_cast<T*>(dst.getBytes())[(i*width + j)*4 + 3] = reinterpret_cast<T*>(src[3].getBytes())[i*width + j]; } } } } } static void merge(std::vector<Mat> &src, Mat &dst); static bool checkMatsProps(Mat &mat1, Mat &mat2); static void threshold(Mat &src, Mat &dst, const double& threshold, const double& maxVal, const int &thresholdType); static Mat hContact(const Mat &A, const Mat &B); static Mat vContact(const Mat &A, const Mat &B); static std::vector<int> histogram(Mat &src); static uint8_t getOtsu(Mat &src); private: static void RGB2BGR(const Mat &src, Mat &dst); static void RGB2GRAY(Mat &src, Mat &dst); static void RGBA2GRAY(Mat &src, Mat &dst); static void GRAY2RGB(Mat &src,Mat &dst); static void GRAY2RGBA(Mat &src, Mat &dst); static void RGB2RGBA(Mat &src, Mat &dst); static void RGBA2RGB(Mat &src, Mat &dst); static void flipV(Mat &mat); static void flipH(Mat &mat); }; } #endif
gimple.h
/* Gimple IR definitions. Copyright 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. Contributed by Aldy Hernandez <aldyh@redhat.com> This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef GCC_GIMPLE_H #define GCC_GIMPLE_H #include "pointer-set.h" #include "vec.h" #include "vecprim.h" #include "vecir.h" #include "ggc.h" #include "basic-block.h" #include "tree-ssa-operands.h" #include "tree-ssa-alias.h" #include "internal-fn.h" struct gimple_seq_node_d; typedef struct gimple_seq_node_d *gimple_seq_node; typedef const struct gimple_seq_node_d *const_gimple_seq_node; /* For each block, the PHI nodes that need to be rewritten are stored into these vectors. */ typedef VEC(gimple, heap) *gimple_vec; DEF_VEC_P (gimple_vec); DEF_VEC_ALLOC_P (gimple_vec, heap); enum gimple_code { #define DEFGSCODE(SYM, STRING, STRUCT) SYM, #include "gimple.def" #undef DEFGSCODE LAST_AND_UNUSED_GIMPLE_CODE }; extern const char *const gimple_code_name[]; extern const unsigned char gimple_rhs_class_table[]; /* Error out if a gimple tuple is addressed incorrectly. */ #if defined ENABLE_GIMPLE_CHECKING #define gcc_gimple_checking_assert(EXPR) gcc_assert (EXPR) extern void gimple_check_failed (const_gimple, const char *, int, \ const char *, enum gimple_code, \ enum tree_code) ATTRIBUTE_NORETURN; #define GIMPLE_CHECK(GS, CODE) \ do { \ const_gimple __gs = (GS); \ if (gimple_code (__gs) != (CODE)) \ gimple_check_failed (__gs, __FILE__, __LINE__, __FUNCTION__, \ (CODE), ERROR_MARK); \ } while (0) #else /* not ENABLE_GIMPLE_CHECKING */ #define gcc_gimple_checking_assert(EXPR) ((void)(0 && (EXPR))) #define GIMPLE_CHECK(GS, CODE) (void)0 #endif /* Class of GIMPLE expressions suitable for the RHS of assignments. See get_gimple_rhs_class. */ enum gimple_rhs_class { GIMPLE_INVALID_RHS, /* The expression cannot be used on the RHS. */ GIMPLE_TERNARY_RHS, /* The expression is a ternary operation. */ GIMPLE_BINARY_RHS, /* The expression is a binary operation. */ GIMPLE_UNARY_RHS, /* The expression is a unary operation. */ GIMPLE_SINGLE_RHS /* The expression is a single object (an SSA name, a _DECL, a _REF, etc. */ }; /* Specific flags for individual GIMPLE statements. These flags are always stored in gimple_statement_base.subcode and they may only be defined for statement codes that do not use sub-codes. Values for the masks can overlap as long as the overlapping values are never used in the same statement class. The maximum mask value that can be defined is 1 << 15 (i.e., each statement code can hold up to 16 bitflags). Keep this list sorted. */ enum gf_mask { GF_ASM_INPUT = 1 << 0, GF_ASM_VOLATILE = 1 << 1, GF_CALL_FROM_THUNK = 1 << 0, GF_CALL_RETURN_SLOT_OPT = 1 << 1, GF_CALL_TAILCALL = 1 << 2, GF_CALL_VA_ARG_PACK = 1 << 3, GF_CALL_NOTHROW = 1 << 4, GF_CALL_ALLOCA_FOR_VAR = 1 << 5, GF_CALL_INTERNAL = 1 << 6, GF_OMP_PARALLEL_COMBINED = 1 << 0, /* True on an GIMPLE_OMP_RETURN statement if the return does not require a thread synchronization via some sort of barrier. The exact barrier that would otherwise be emitted is dependent on the OMP statement with which this return is associated. */ GF_OMP_RETURN_NOWAIT = 1 << 0, GF_OMP_SECTION_LAST = 1 << 0, GF_OMP_ATOMIC_NEED_VALUE = 1 << 0, GF_PREDICT_TAKEN = 1 << 15 }; /* Currently, there are only two types of gimple debug stmt. Others are envisioned, for example, to enable the generation of is_stmt notes in line number information, to mark sequence points, etc. This subcode is to be used to tell them apart. */ enum gimple_debug_subcode { GIMPLE_DEBUG_BIND = 0, GIMPLE_DEBUG_SOURCE_BIND = 1 }; /* Masks for selecting a pass local flag (PLF) to work on. These masks are used by gimple_set_plf and gimple_plf. */ enum plf_mask { GF_PLF_1 = 1 << 0, GF_PLF_2 = 1 << 1 }; /* A node in a gimple_seq_d. */ struct GTY((chain_next ("%h.next"), chain_prev ("%h.prev"))) gimple_seq_node_d { gimple stmt; struct gimple_seq_node_d *prev; struct gimple_seq_node_d *next; }; /* A double-linked sequence of gimple statements. */ struct GTY ((chain_next ("%h.next_free"))) gimple_seq_d { /* First and last statements in the sequence. */ gimple_seq_node first; gimple_seq_node last; /* Sequences are created/destroyed frequently. To minimize allocation activity, deallocated sequences are kept in a pool of available sequences. This is the pointer to the next free sequence in the pool. */ gimple_seq next_free; }; /* Return the first node in GIMPLE sequence S. */ static inline gimple_seq_node gimple_seq_first (const_gimple_seq s) { return s ? s->first : NULL; } /* Return the first statement in GIMPLE sequence S. */ static inline gimple gimple_seq_first_stmt (const_gimple_seq s) { gimple_seq_node n = gimple_seq_first (s); return (n) ? n->stmt : NULL; } /* Return the last node in GIMPLE sequence S. */ static inline gimple_seq_node gimple_seq_last (const_gimple_seq s) { return s ? s->last : NULL; } /* Return the last statement in GIMPLE sequence S. */ static inline gimple gimple_seq_last_stmt (const_gimple_seq s) { gimple_seq_node n = gimple_seq_last (s); return (n) ? n->stmt : NULL; } /* Set the last node in GIMPLE sequence S to LAST. */ static inline void gimple_seq_set_last (gimple_seq s, gimple_seq_node last) { s->last = last; } /* Set the first node in GIMPLE sequence S to FIRST. */ static inline void gimple_seq_set_first (gimple_seq s, gimple_seq_node first) { s->first = first; } /* Return true if GIMPLE sequence S is empty. */ static inline bool gimple_seq_empty_p (const_gimple_seq s) { return s == NULL || s->first == NULL; } void gimple_seq_add_stmt (gimple_seq *, gimple); /* Link gimple statement GS to the end of the sequence *SEQ_P. If *SEQ_P is NULL, a new sequence is allocated. This function is similar to gimple_seq_add_stmt, but does not scan the operands. During gimplification, we need to manipulate statement sequences before the def/use vectors have been constructed. */ void gimple_seq_add_stmt_without_update (gimple_seq *, gimple); /* Allocate a new sequence and initialize its first element with STMT. */ static inline gimple_seq gimple_seq_alloc_with_stmt (gimple stmt) { gimple_seq seq = NULL; gimple_seq_add_stmt (&seq, stmt); return seq; } /* Returns the sequence of statements in BB. */ static inline gimple_seq bb_seq (const_basic_block bb) { return (!(bb->flags & BB_RTL) && bb->il.gimple) ? bb->il.gimple->seq : NULL; } /* Sets the sequence of statements in BB to SEQ. */ static inline void set_bb_seq (basic_block bb, gimple_seq seq) { gcc_checking_assert (!(bb->flags & BB_RTL)); bb->il.gimple->seq = seq; } /* Iterator object for GIMPLE statement sequences. */ typedef struct { /* Sequence node holding the current statement. */ gimple_seq_node ptr; /* Sequence and basic block holding the statement. These fields are necessary to handle edge cases such as when statement is added to an empty basic block or when the last statement of a block/sequence is removed. */ gimple_seq seq; basic_block bb; } gimple_stmt_iterator; /* Data structure definitions for GIMPLE tuples. NOTE: word markers are for 64 bit hosts. */ struct GTY(()) gimple_statement_base { /* [ WORD 1 ] Main identifying code for a tuple. */ ENUM_BITFIELD(gimple_code) code : 8; /* Nonzero if a warning should not be emitted on this tuple. */ unsigned int no_warning : 1; /* Nonzero if this tuple has been visited. Passes are responsible for clearing this bit before using it. */ unsigned int visited : 1; /* Nonzero if this tuple represents a non-temporal move. */ unsigned int nontemporal_move : 1; /* Pass local flags. These flags are free for any pass to use as they see fit. Passes should not assume that these flags contain any useful value when the pass starts. Any initial state that the pass requires should be set on entry to the pass. See gimple_set_plf and gimple_plf for usage. */ unsigned int plf : 2; /* Nonzero if this statement has been modified and needs to have its operands rescanned. */ unsigned modified : 1; /* Nonzero if this statement contains volatile operands. */ unsigned has_volatile_ops : 1; /* Nonzero if this statement appears inside a transaction. This bit is calculated on de-mand and has relevant information only after it has been calculated with compute_transaction_bits. */ unsigned in_transaction : 1; /* The SUBCODE field can be used for tuple-specific flags for tuples that do not require subcodes. Note that SUBCODE should be at least as wide as tree codes, as several tuples store tree codes in there. */ unsigned int subcode : 16; /* UID of this statement. This is used by passes that want to assign IDs to statements. It must be assigned and used by each pass. By default it should be assumed to contain garbage. */ unsigned uid; /* [ WORD 2 ] Locus information for debug info. */ location_t location; /* Number of operands in this tuple. */ unsigned num_ops; /* [ WORD 3 ] Basic block holding this statement. */ struct basic_block_def *bb; /* [ WORD 4 ] Lexical block holding this statement. */ tree block; }; /* Base structure for tuples with operands. */ struct GTY(()) gimple_statement_with_ops_base { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5-6 ] SSA operand vectors. NOTE: It should be possible to amalgamate these vectors with the operand vector OP. However, the SSA operand vectors are organized differently and contain more information (like immediate use chaining). */ struct def_optype_d GTY((skip (""))) *def_ops; struct use_optype_d GTY((skip (""))) *use_ops; }; /* Statements that take register operands. */ struct GTY(()) gimple_statement_with_ops { /* [ WORD 1-6 ] */ struct gimple_statement_with_ops_base opbase; /* [ WORD 7 ] Operand vector. NOTE! This must always be the last field of this structure. In particular, this means that this structure cannot be embedded inside another one. */ tree GTY((length ("%h.opbase.gsbase.num_ops"))) op[1]; }; /* Base for statements that take both memory and register operands. */ struct GTY(()) gimple_statement_with_memory_ops_base { /* [ WORD 1-6 ] */ struct gimple_statement_with_ops_base opbase; /* [ WORD 7-8 ] Virtual operands for this statement. The GC will pick them up via the ssa_names array. */ tree GTY((skip (""))) vdef; tree GTY((skip (""))) vuse; }; /* Statements that take both memory and register operands. */ struct GTY(()) gimple_statement_with_memory_ops { /* [ WORD 1-8 ] */ struct gimple_statement_with_memory_ops_base membase; /* [ WORD 9 ] Operand vector. NOTE! This must always be the last field of this structure. In particular, this means that this structure cannot be embedded inside another one. */ tree GTY((length ("%h.membase.opbase.gsbase.num_ops"))) op[1]; }; /* Call statements that take both memory and register operands. */ struct GTY(()) gimple_statement_call { /* [ WORD 1-8 ] */ struct gimple_statement_with_memory_ops_base membase; /* [ WORD 9-12 ] */ struct pt_solution call_used; struct pt_solution call_clobbered; /* [ WORD 13 ] */ union GTY ((desc ("%1.membase.opbase.gsbase.subcode & GF_CALL_INTERNAL"))) { tree GTY ((tag ("0"))) fntype; enum internal_fn GTY ((tag ("GF_CALL_INTERNAL"))) internal_fn; } u; /* [ WORD 14 ] Operand vector. NOTE! This must always be the last field of this structure. In particular, this means that this structure cannot be embedded inside another one. */ tree GTY((length ("%h.membase.opbase.gsbase.num_ops"))) op[1]; }; /* OpenMP statements (#pragma omp). */ struct GTY(()) gimple_statement_omp { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] */ gimple_seq body; }; /* GIMPLE_BIND */ struct GTY(()) gimple_statement_bind { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] Variables declared in this scope. */ tree vars; /* [ WORD 6 ] This is different than the BLOCK field in gimple_statement_base, which is analogous to TREE_BLOCK (i.e., the lexical block holding this statement). This field is the equivalent of BIND_EXPR_BLOCK in tree land (i.e., the lexical scope defined by this bind). See gimple-low.c. */ tree block; /* [ WORD 7 ] */ gimple_seq body; }; /* GIMPLE_CATCH */ struct GTY(()) gimple_statement_catch { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] */ tree types; /* [ WORD 6 ] */ gimple_seq handler; }; /* GIMPLE_EH_FILTER */ struct GTY(()) gimple_statement_eh_filter { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] Filter types. */ tree types; /* [ WORD 6 ] Failure actions. */ gimple_seq failure; }; /* GIMPLE_EH_ELSE */ struct GTY(()) gimple_statement_eh_else { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5,6 ] */ gimple_seq n_body, e_body; }; /* GIMPLE_EH_MUST_NOT_THROW */ struct GTY(()) gimple_statement_eh_mnt { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] Abort function decl. */ tree fndecl; }; /* GIMPLE_PHI */ struct GTY(()) gimple_statement_phi { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] */ unsigned capacity; unsigned nargs; /* [ WORD 6 ] */ tree result; /* [ WORD 7 ] */ struct phi_arg_d GTY ((length ("%h.nargs"))) args[1]; }; /* GIMPLE_RESX, GIMPLE_EH_DISPATCH */ struct GTY(()) gimple_statement_eh_ctrl { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] Exception region number. */ int region; }; /* GIMPLE_TRY */ struct GTY(()) gimple_statement_try { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] Expression to evaluate. */ gimple_seq eval; /* [ WORD 6 ] Cleanup expression. */ gimple_seq cleanup; }; /* Kind of GIMPLE_TRY statements. */ enum gimple_try_flags { /* A try/catch. */ GIMPLE_TRY_CATCH = 1 << 0, /* A try/finally. */ GIMPLE_TRY_FINALLY = 1 << 1, GIMPLE_TRY_KIND = GIMPLE_TRY_CATCH | GIMPLE_TRY_FINALLY, /* Analogous to TRY_CATCH_IS_CLEANUP. */ GIMPLE_TRY_CATCH_IS_CLEANUP = 1 << 2 }; /* GIMPLE_WITH_CLEANUP_EXPR */ struct GTY(()) gimple_statement_wce { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* Subcode: CLEANUP_EH_ONLY. True if the cleanup should only be executed if an exception is thrown, not on normal exit of its scope. This flag is analogous to the CLEANUP_EH_ONLY flag in TARGET_EXPRs. */ /* [ WORD 5 ] Cleanup expression. */ gimple_seq cleanup; }; /* GIMPLE_ASM */ struct GTY(()) gimple_statement_asm { /* [ WORD 1-8 ] */ struct gimple_statement_with_memory_ops_base membase; /* [ WORD 9 ] __asm__ statement. */ const char *string; /* [ WORD 10 ] Number of inputs, outputs, clobbers, labels. */ unsigned char ni; unsigned char no; unsigned char nc; unsigned char nl; /* [ WORD 11 ] Operand vector. NOTE! This must always be the last field of this structure. In particular, this means that this structure cannot be embedded inside another one. */ tree GTY((length ("%h.membase.opbase.gsbase.num_ops"))) op[1]; }; /* GIMPLE_OMP_CRITICAL */ struct GTY(()) gimple_statement_omp_critical { /* [ WORD 1-5 ] */ struct gimple_statement_omp omp; /* [ WORD 6 ] Critical section name. */ tree name; }; struct GTY(()) gimple_omp_for_iter { /* Condition code. */ enum tree_code cond; /* Index variable. */ tree index; /* Initial value. */ tree initial; /* Final value. */ tree final; /* Increment. */ tree incr; }; /* GIMPLE_OMP_FOR */ struct GTY(()) gimple_statement_omp_for { /* [ WORD 1-5 ] */ struct gimple_statement_omp omp; /* [ WORD 6 ] */ tree clauses; /* [ WORD 7 ] Number of elements in iter array. */ size_t collapse; /* [ WORD 8 ] */ struct gimple_omp_for_iter * GTY((length ("%h.collapse"))) iter; /* [ WORD 9 ] Pre-body evaluated before the loop body begins. */ gimple_seq pre_body; }; /* GIMPLE_OMP_PARALLEL */ struct GTY(()) gimple_statement_omp_parallel { /* [ WORD 1-5 ] */ struct gimple_statement_omp omp; /* [ WORD 6 ] Clauses. */ tree clauses; /* [ WORD 7 ] Child function holding the body of the parallel region. */ tree child_fn; /* [ WORD 8 ] Shared data argument. */ tree data_arg; }; /* GIMPLE_OMP_TASK */ struct GTY(()) gimple_statement_omp_task { /* [ WORD 1-8 ] */ struct gimple_statement_omp_parallel par; /* [ WORD 9 ] Child function holding firstprivate initialization if needed. */ tree copy_fn; /* [ WORD 10-11 ] Size and alignment in bytes of the argument data block. */ tree arg_size; tree arg_align; }; /* GIMPLE_OMP_SECTION */ /* Uses struct gimple_statement_omp. */ /* GIMPLE_OMP_SECTIONS */ struct GTY(()) gimple_statement_omp_sections { /* [ WORD 1-5 ] */ struct gimple_statement_omp omp; /* [ WORD 6 ] */ tree clauses; /* [ WORD 7 ] The control variable used for deciding which of the sections to execute. */ tree control; }; /* GIMPLE_OMP_CONTINUE. Note: This does not inherit from gimple_statement_omp, because we do not need the body field. */ struct GTY(()) gimple_statement_omp_continue { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] */ tree control_def; /* [ WORD 6 ] */ tree control_use; }; /* GIMPLE_OMP_SINGLE */ struct GTY(()) gimple_statement_omp_single { /* [ WORD 1-5 ] */ struct gimple_statement_omp omp; /* [ WORD 6 ] */ tree clauses; }; /* GIMPLE_OMP_ATOMIC_LOAD. Note: This is based on gimple_statement_base, not g_s_omp, because g_s_omp contains a sequence, which we don't need here. */ struct GTY(()) gimple_statement_omp_atomic_load { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5-6 ] */ tree rhs, lhs; }; /* GIMPLE_OMP_ATOMIC_STORE. See note on GIMPLE_OMP_ATOMIC_LOAD. */ struct GTY(()) gimple_statement_omp_atomic_store { /* [ WORD 1-4 ] */ struct gimple_statement_base gsbase; /* [ WORD 5 ] */ tree val; }; /* GIMPLE_TRANSACTION. */ /* Bits to be stored in the GIMPLE_TRANSACTION subcode. */ /* The __transaction_atomic was declared [[outer]] or it is __transaction_relaxed. */ #define GTMA_IS_OUTER (1u << 0) #define GTMA_IS_RELAXED (1u << 1) #define GTMA_DECLARATION_MASK (GTMA_IS_OUTER | GTMA_IS_RELAXED) /* The transaction is seen to not have an abort. */ #define GTMA_HAVE_ABORT (1u << 2) /* The transaction is seen to have loads or stores. */ #define GTMA_HAVE_LOAD (1u << 3) #define GTMA_HAVE_STORE (1u << 4) /* The transaction MAY enter serial irrevocable mode in its dynamic scope. */ #define GTMA_MAY_ENTER_IRREVOCABLE (1u << 5) /* The transaction WILL enter serial irrevocable mode. An irrevocable block post-dominates the entire transaction, such that all invocations of the transaction will go serial-irrevocable. In such case, we don't bother instrumenting the transaction, and tell the runtime that it should begin the transaction in serial-irrevocable mode. */ #define GTMA_DOES_GO_IRREVOCABLE (1u << 6) struct GTY(()) gimple_statement_transaction { /* [ WORD 1-10 ] */ struct gimple_statement_with_memory_ops_base gsbase; /* [ WORD 11 ] */ gimple_seq body; /* [ WORD 12 ] */ tree label; }; #define DEFGSSTRUCT(SYM, STRUCT, HAS_TREE_OP) SYM, enum gimple_statement_structure_enum { #include "gsstruct.def" LAST_GSS_ENUM }; #undef DEFGSSTRUCT /* Define the overall contents of a gimple tuple. It may be any of the structures declared above for various types of tuples. */ union GTY ((desc ("gimple_statement_structure (&%h)"), variable_size)) gimple_statement_d { struct gimple_statement_base GTY ((tag ("GSS_BASE"))) gsbase; struct gimple_statement_with_ops GTY ((tag ("GSS_WITH_OPS"))) gsops; struct gimple_statement_with_memory_ops_base GTY ((tag ("GSS_WITH_MEM_OPS_BASE"))) gsmembase; struct gimple_statement_with_memory_ops GTY ((tag ("GSS_WITH_MEM_OPS"))) gsmem; struct gimple_statement_call GTY ((tag ("GSS_CALL"))) gimple_call; struct gimple_statement_omp GTY ((tag ("GSS_OMP"))) omp; struct gimple_statement_bind GTY ((tag ("GSS_BIND"))) gimple_bind; struct gimple_statement_catch GTY ((tag ("GSS_CATCH"))) gimple_catch; struct gimple_statement_eh_filter GTY ((tag ("GSS_EH_FILTER"))) gimple_eh_filter; struct gimple_statement_eh_mnt GTY ((tag ("GSS_EH_MNT"))) gimple_eh_mnt; struct gimple_statement_eh_else GTY ((tag ("GSS_EH_ELSE"))) gimple_eh_else; struct gimple_statement_phi GTY ((tag ("GSS_PHI"))) gimple_phi; struct gimple_statement_eh_ctrl GTY ((tag ("GSS_EH_CTRL"))) gimple_eh_ctrl; struct gimple_statement_try GTY ((tag ("GSS_TRY"))) gimple_try; struct gimple_statement_wce GTY ((tag ("GSS_WCE"))) gimple_wce; struct gimple_statement_asm GTY ((tag ("GSS_ASM"))) gimple_asm; struct gimple_statement_omp_critical GTY ((tag ("GSS_OMP_CRITICAL"))) gimple_omp_critical; struct gimple_statement_omp_for GTY ((tag ("GSS_OMP_FOR"))) gimple_omp_for; struct gimple_statement_omp_parallel GTY ((tag ("GSS_OMP_PARALLEL"))) gimple_omp_parallel; struct gimple_statement_omp_task GTY ((tag ("GSS_OMP_TASK"))) gimple_omp_task; struct gimple_statement_omp_sections GTY ((tag ("GSS_OMP_SECTIONS"))) gimple_omp_sections; struct gimple_statement_omp_single GTY ((tag ("GSS_OMP_SINGLE"))) gimple_omp_single; struct gimple_statement_omp_continue GTY ((tag ("GSS_OMP_CONTINUE"))) gimple_omp_continue; struct gimple_statement_omp_atomic_load GTY ((tag ("GSS_OMP_ATOMIC_LOAD"))) gimple_omp_atomic_load; struct gimple_statement_omp_atomic_store GTY ((tag ("GSS_OMP_ATOMIC_STORE"))) gimple_omp_atomic_store; struct gimple_statement_transaction GTY((tag ("GSS_TRANSACTION"))) gimple_transaction; }; /* In gimple.c. */ /* Offset in bytes to the location of the operand vector. Zero if there is no operand vector for this tuple structure. */ extern size_t const gimple_ops_offset_[]; /* Map GIMPLE codes to GSS codes. */ extern enum gimple_statement_structure_enum const gss_for_code_[]; /* This variable holds the currently expanded gimple statement for purposes of comminucating the profile info to the builtin expanders. */ extern gimple currently_expanding_gimple_stmt; gimple gimple_build_return (tree); gimple gimple_build_assign_stat (tree, tree MEM_STAT_DECL); #define gimple_build_assign(l,r) gimple_build_assign_stat (l, r MEM_STAT_INFO) void extract_ops_from_tree_1 (tree, enum tree_code *, tree *, tree *, tree *); gimple gimple_build_assign_with_ops_stat (enum tree_code, tree, tree, tree, tree MEM_STAT_DECL); #define gimple_build_assign_with_ops(c,o1,o2,o3) \ gimple_build_assign_with_ops_stat (c, o1, o2, o3, NULL_TREE MEM_STAT_INFO) #define gimple_build_assign_with_ops3(c,o1,o2,o3,o4) \ gimple_build_assign_with_ops_stat (c, o1, o2, o3, o4 MEM_STAT_INFO) gimple gimple_build_debug_bind_stat (tree, tree, gimple MEM_STAT_DECL); #define gimple_build_debug_bind(var,val,stmt) \ gimple_build_debug_bind_stat ((var), (val), (stmt) MEM_STAT_INFO) gimple gimple_build_debug_source_bind_stat (tree, tree, gimple MEM_STAT_DECL); #define gimple_build_debug_source_bind(var,val,stmt) \ gimple_build_debug_source_bind_stat ((var), (val), (stmt) MEM_STAT_INFO) gimple gimple_build_call_vec (tree, VEC(tree, heap) *); gimple gimple_build_call (tree, unsigned, ...); gimple gimple_build_call_valist (tree, unsigned, va_list); gimple gimple_build_call_internal (enum internal_fn, unsigned, ...); gimple gimple_build_call_internal_vec (enum internal_fn, VEC(tree, heap) *); gimple gimple_build_call_from_tree (tree); gimple gimplify_assign (tree, tree, gimple_seq *); gimple gimple_build_cond (enum tree_code, tree, tree, tree, tree); gimple gimple_build_label (tree label); gimple gimple_build_goto (tree dest); gimple gimple_build_nop (void); gimple gimple_build_bind (tree, gimple_seq, tree); gimple gimple_build_asm_vec (const char *, VEC(tree,gc) *, VEC(tree,gc) *, VEC(tree,gc) *, VEC(tree,gc) *); gimple gimple_build_catch (tree, gimple_seq); gimple gimple_build_eh_filter (tree, gimple_seq); gimple gimple_build_eh_must_not_throw (tree); gimple gimple_build_eh_else (gimple_seq, gimple_seq); gimple gimple_build_try (gimple_seq, gimple_seq, enum gimple_try_flags); gimple gimple_build_wce (gimple_seq); gimple gimple_build_resx (int); gimple gimple_build_eh_dispatch (int); gimple gimple_build_switch_nlabels (unsigned, tree, tree); gimple gimple_build_switch (unsigned, tree, tree, ...); gimple gimple_build_switch_vec (tree, tree, VEC(tree,heap) *); gimple gimple_build_omp_parallel (gimple_seq, tree, tree, tree); gimple gimple_build_omp_task (gimple_seq, tree, tree, tree, tree, tree, tree); gimple gimple_build_omp_for (gimple_seq, tree, size_t, gimple_seq); gimple gimple_build_omp_critical (gimple_seq, tree); gimple gimple_build_omp_section (gimple_seq); gimple gimple_build_omp_continue (tree, tree); gimple gimple_build_omp_master (gimple_seq); gimple gimple_build_omp_return (bool); gimple gimple_build_omp_ordered (gimple_seq); gimple gimple_build_omp_sections (gimple_seq, tree); gimple gimple_build_omp_sections_switch (void); gimple gimple_build_omp_single (gimple_seq, tree); gimple gimple_build_cdt (tree, tree); gimple gimple_build_omp_atomic_load (tree, tree); gimple gimple_build_omp_atomic_store (tree); gimple gimple_build_transaction (gimple_seq, tree); gimple gimple_build_predict (enum br_predictor, enum prediction); enum gimple_statement_structure_enum gss_for_assign (enum tree_code); void sort_case_labels (VEC(tree,heap) *); void gimple_set_body (tree, gimple_seq); gimple_seq gimple_body (tree); bool gimple_has_body_p (tree); gimple_seq gimple_seq_alloc (void); void gimple_seq_free (gimple_seq); void gimple_seq_add_seq (gimple_seq *, gimple_seq); gimple_seq gimple_seq_copy (gimple_seq); bool gimple_call_same_target_p (const_gimple, const_gimple); int gimple_call_flags (const_gimple); int gimple_call_return_flags (const_gimple); int gimple_call_arg_flags (const_gimple, unsigned); void gimple_call_reset_alias_info (gimple); bool gimple_assign_copy_p (gimple); bool gimple_assign_ssa_name_copy_p (gimple); bool gimple_assign_unary_nop_p (gimple); void gimple_set_bb (gimple, struct basic_block_def *); void gimple_assign_set_rhs_from_tree (gimple_stmt_iterator *, tree); void gimple_assign_set_rhs_with_ops_1 (gimple_stmt_iterator *, enum tree_code, tree, tree, tree); tree gimple_get_lhs (const_gimple); void gimple_set_lhs (gimple, tree); void gimple_replace_lhs (gimple, tree); gimple gimple_copy (gimple); void gimple_set_modified (gimple, bool); void gimple_cond_get_ops_from_tree (tree, enum tree_code *, tree *, tree *); gimple gimple_build_cond_from_tree (tree, tree, tree); void gimple_cond_set_condition_from_tree (gimple, tree); bool gimple_has_side_effects (const_gimple); bool gimple_could_trap_p (gimple); bool gimple_could_trap_p_1 (gimple, bool, bool); bool gimple_assign_rhs_could_trap_p (gimple); void gimple_regimplify_operands (gimple, gimple_stmt_iterator *); bool empty_body_p (gimple_seq); unsigned get_gimple_rhs_num_ops (enum tree_code); #define gimple_alloc(c, n) gimple_alloc_stat (c, n MEM_STAT_INFO) gimple gimple_alloc_stat (enum gimple_code, unsigned MEM_STAT_DECL); const char *gimple_decl_printable_name (tree, int); tree gimple_get_virt_method_for_binfo (HOST_WIDE_INT, tree); void gimple_adjust_this_by_delta (gimple_stmt_iterator *, tree); tree gimple_extract_devirt_binfo_from_cst (tree); /* Returns true iff T is a valid GIMPLE statement. */ extern bool is_gimple_stmt (tree); /* Returns true iff T is a scalar register variable. */ extern bool is_gimple_reg (tree); /* Returns true iff T is any sort of variable. */ extern bool is_gimple_variable (tree); /* Returns true iff T is any sort of symbol. */ extern bool is_gimple_id (tree); /* Returns true iff T is a variable or an INDIRECT_REF (of a variable). */ extern bool is_gimple_min_lval (tree); /* Returns true iff T is something whose address can be taken. */ extern bool is_gimple_addressable (tree); /* Returns true iff T is any valid GIMPLE lvalue. */ extern bool is_gimple_lvalue (tree); /* Returns true iff T is a GIMPLE address. */ bool is_gimple_address (const_tree); /* Returns true iff T is a GIMPLE invariant address. */ bool is_gimple_invariant_address (const_tree); /* Returns true iff T is a GIMPLE invariant address at interprocedural level. */ bool is_gimple_ip_invariant_address (const_tree); /* Returns true iff T is a valid GIMPLE constant. */ bool is_gimple_constant (const_tree); /* Returns true iff T is a GIMPLE restricted function invariant. */ extern bool is_gimple_min_invariant (const_tree); /* Returns true iff T is a GIMPLE restricted interprecodural invariant. */ extern bool is_gimple_ip_invariant (const_tree); /* Returns true iff T is a GIMPLE rvalue. */ extern bool is_gimple_val (tree); /* Returns true iff T is a GIMPLE asm statement input. */ extern bool is_gimple_asm_val (tree); /* Returns true iff T is a valid address operand of a MEM_REF. */ bool is_gimple_mem_ref_addr (tree); /* Returns true iff T is a valid rhs for a MODIFY_EXPR where the LHS is a GIMPLE temporary, a renamed user variable, or something else, respectively. */ extern bool is_gimple_reg_rhs (tree); extern bool is_gimple_mem_rhs (tree); /* Returns true iff T is a valid if-statement condition. */ extern bool is_gimple_condexpr (tree); /* Returns true iff T is a valid call address expression. */ extern bool is_gimple_call_addr (tree); extern void recalculate_side_effects (tree); extern bool gimple_compare_field_offset (tree, tree); extern tree gimple_register_type (tree); extern tree gimple_register_canonical_type (tree); extern void print_gimple_types_stats (void); extern void free_gimple_type_tables (void); extern tree gimple_unsigned_type (tree); extern tree gimple_signed_type (tree); extern alias_set_type gimple_get_alias_set (tree); extern void count_uses_and_derefs (tree, gimple, unsigned *, unsigned *, unsigned *); extern bool walk_stmt_load_store_addr_ops (gimple, void *, bool (*)(gimple, tree, void *), bool (*)(gimple, tree, void *), bool (*)(gimple, tree, void *)); extern bool walk_stmt_load_store_ops (gimple, void *, bool (*)(gimple, tree, void *), bool (*)(gimple, tree, void *)); extern bool gimple_ior_addresses_taken (bitmap, gimple); extern bool gimple_call_builtin_p (gimple, enum built_in_function); extern bool gimple_asm_clobbers_memory_p (const_gimple); /* In gimplify.c */ extern tree create_tmp_var_raw (tree, const char *); extern tree create_tmp_var_name (const char *); extern tree create_tmp_var (tree, const char *); extern tree create_tmp_reg (tree, const char *); extern tree get_initialized_tmp_var (tree, gimple_seq *, gimple_seq *); extern tree get_formal_tmp_var (tree, gimple_seq *); extern void declare_vars (tree, gimple, bool); extern void annotate_all_with_location (gimple_seq, location_t); /* Validation of GIMPLE expressions. Note that these predicates only check the basic form of the expression, they don't recurse to make sure that underlying nodes are also of the right form. */ typedef bool (*gimple_predicate)(tree); /* FIXME we should deduce this from the predicate. */ enum fallback { fb_none = 0, /* Do not generate a temporary. */ fb_rvalue = 1, /* Generate an rvalue to hold the result of a gimplified expression. */ fb_lvalue = 2, /* Generate an lvalue to hold the result of a gimplified expression. */ fb_mayfail = 4, /* Gimplification may fail. Error issued afterwards. */ fb_either= fb_rvalue | fb_lvalue }; typedef int fallback_t; enum gimplify_status { GS_ERROR = -2, /* Something Bad Seen. */ GS_UNHANDLED = -1, /* A langhook result for "I dunno". */ GS_OK = 0, /* We did something, maybe more to do. */ GS_ALL_DONE = 1 /* The expression is fully gimplified. */ }; struct gimplify_ctx { struct gimplify_ctx *prev_context; VEC(gimple,heap) *bind_expr_stack; tree temps; gimple_seq conditional_cleanups; tree exit_label; tree return_temp; VEC(tree,heap) *case_labels; /* The formal temporary table. Should this be persistent? */ htab_t temp_htab; int conditions; bool save_stack; bool into_ssa; bool allow_rhs_cond_expr; bool in_cleanup_point_expr; }; extern enum gimplify_status gimplify_expr (tree *, gimple_seq *, gimple_seq *, bool (*) (tree), fallback_t); extern void gimplify_type_sizes (tree, gimple_seq *); extern void gimplify_one_sizepos (tree *, gimple_seq *); extern bool gimplify_stmt (tree *, gimple_seq *); extern gimple gimplify_body (tree, bool); extern void push_gimplify_context (struct gimplify_ctx *); extern void pop_gimplify_context (gimple); extern void gimplify_and_add (tree, gimple_seq *); /* Miscellaneous helpers. */ extern void gimple_add_tmp_var (tree); extern gimple gimple_current_bind_expr (void); extern VEC(gimple, heap) *gimple_bind_expr_stack (void); extern tree voidify_wrapper_expr (tree, tree); extern tree build_and_jump (tree *); extern tree force_labels_r (tree *, int *, void *); extern enum gimplify_status gimplify_va_arg_expr (tree *, gimple_seq *, gimple_seq *); struct gimplify_omp_ctx; extern void omp_firstprivatize_variable (struct gimplify_omp_ctx *, tree); extern tree gimple_boolify (tree); extern gimple_predicate rhs_predicate_for (tree); extern tree canonicalize_cond_expr_cond (tree); /* In omp-low.c. */ extern tree omp_reduction_init (tree, tree); /* In trans-mem.c. */ extern void diagnose_tm_safe_errors (tree); extern void compute_transaction_bits (void); /* In tree-nested.c. */ extern void lower_nested_functions (tree); extern void insert_field_into_struct (tree, tree); /* In gimplify.c. */ extern void gimplify_function_tree (tree); /* In cfgexpand.c. */ extern tree gimple_assign_rhs_to_tree (gimple); /* In builtins.c */ extern bool validate_gimple_arglist (const_gimple, ...); /* In tree-ssa.c */ extern bool tree_ssa_useless_type_conversion (tree); extern tree tree_ssa_strip_useless_type_conversions (tree); extern bool useless_type_conversion_p (tree, tree); extern bool types_compatible_p (tree, tree); /* Return the code for GIMPLE statement G. */ static inline enum gimple_code gimple_code (const_gimple g) { return g->gsbase.code; } /* Return the GSS code used by a GIMPLE code. */ static inline enum gimple_statement_structure_enum gss_for_code (enum gimple_code code) { gcc_gimple_checking_assert ((unsigned int)code < LAST_AND_UNUSED_GIMPLE_CODE); return gss_for_code_[code]; } /* Return which GSS code is used by GS. */ static inline enum gimple_statement_structure_enum gimple_statement_structure (gimple gs) { return gss_for_code (gimple_code (gs)); } /* Return true if statement G has sub-statements. This is only true for High GIMPLE statements. */ static inline bool gimple_has_substatements (gimple g) { switch (gimple_code (g)) { case GIMPLE_BIND: case GIMPLE_CATCH: case GIMPLE_EH_FILTER: case GIMPLE_EH_ELSE: case GIMPLE_TRY: case GIMPLE_OMP_FOR: case GIMPLE_OMP_MASTER: case GIMPLE_OMP_ORDERED: case GIMPLE_OMP_SECTION: case GIMPLE_OMP_PARALLEL: case GIMPLE_OMP_TASK: case GIMPLE_OMP_SECTIONS: case GIMPLE_OMP_SINGLE: case GIMPLE_OMP_CRITICAL: case GIMPLE_WITH_CLEANUP_EXPR: case GIMPLE_TRANSACTION: return true; default: return false; } } /* Return the basic block holding statement G. */ static inline struct basic_block_def * gimple_bb (const_gimple g) { return g->gsbase.bb; } /* Return the lexical scope block holding statement G. */ static inline tree gimple_block (const_gimple g) { return g->gsbase.block; } /* Set BLOCK to be the lexical scope block holding statement G. */ static inline void gimple_set_block (gimple g, tree block) { g->gsbase.block = block; } /* Return location information for statement G. */ static inline location_t gimple_location (const_gimple g) { return g->gsbase.location; } /* Return pointer to location information for statement G. */ static inline const location_t * gimple_location_ptr (const_gimple g) { return &g->gsbase.location; } /* Set location information for statement G. */ static inline void gimple_set_location (gimple g, location_t location) { g->gsbase.location = location; } /* Return true if G contains location information. */ static inline bool gimple_has_location (const_gimple g) { return gimple_location (g) != UNKNOWN_LOCATION; } /* Return the file name of the location of STMT. */ static inline const char * gimple_filename (const_gimple stmt) { return LOCATION_FILE (gimple_location (stmt)); } /* Return the line number of the location of STMT. */ static inline int gimple_lineno (const_gimple stmt) { return LOCATION_LINE (gimple_location (stmt)); } /* Determine whether SEQ is a singleton. */ static inline bool gimple_seq_singleton_p (gimple_seq seq) { return ((gimple_seq_first (seq) != NULL) && (gimple_seq_first (seq) == gimple_seq_last (seq))); } /* Return true if no warnings should be emitted for statement STMT. */ static inline bool gimple_no_warning_p (const_gimple stmt) { return stmt->gsbase.no_warning; } /* Set the no_warning flag of STMT to NO_WARNING. */ static inline void gimple_set_no_warning (gimple stmt, bool no_warning) { stmt->gsbase.no_warning = (unsigned) no_warning; } /* Set the visited status on statement STMT to VISITED_P. */ static inline void gimple_set_visited (gimple stmt, bool visited_p) { stmt->gsbase.visited = (unsigned) visited_p; } /* Return the visited status for statement STMT. */ static inline bool gimple_visited_p (gimple stmt) { return stmt->gsbase.visited; } /* Set pass local flag PLF on statement STMT to VAL_P. */ static inline void gimple_set_plf (gimple stmt, enum plf_mask plf, bool val_p) { if (val_p) stmt->gsbase.plf |= (unsigned int) plf; else stmt->gsbase.plf &= ~((unsigned int) plf); } /* Return the value of pass local flag PLF on statement STMT. */ static inline unsigned int gimple_plf (gimple stmt, enum plf_mask plf) { return stmt->gsbase.plf & ((unsigned int) plf); } /* Set the UID of statement. */ static inline void gimple_set_uid (gimple g, unsigned uid) { g->gsbase.uid = uid; } /* Return the UID of statement. */ static inline unsigned gimple_uid (const_gimple g) { return g->gsbase.uid; } /* Return true if GIMPLE statement G has register or memory operands. */ static inline bool gimple_has_ops (const_gimple g) { return gimple_code (g) >= GIMPLE_COND && gimple_code (g) <= GIMPLE_RETURN; } /* Return true if GIMPLE statement G has memory operands. */ static inline bool gimple_has_mem_ops (const_gimple g) { return gimple_code (g) >= GIMPLE_ASSIGN && gimple_code (g) <= GIMPLE_RETURN; } /* Return the set of DEF operands for statement G. */ static inline struct def_optype_d * gimple_def_ops (const_gimple g) { if (!gimple_has_ops (g)) return NULL; return g->gsops.opbase.def_ops; } /* Set DEF to be the set of DEF operands for statement G. */ static inline void gimple_set_def_ops (gimple g, struct def_optype_d *def) { gcc_gimple_checking_assert (gimple_has_ops (g)); g->gsops.opbase.def_ops = def; } /* Return the set of USE operands for statement G. */ static inline struct use_optype_d * gimple_use_ops (const_gimple g) { if (!gimple_has_ops (g)) return NULL; return g->gsops.opbase.use_ops; } /* Set USE to be the set of USE operands for statement G. */ static inline void gimple_set_use_ops (gimple g, struct use_optype_d *use) { gcc_gimple_checking_assert (gimple_has_ops (g)); g->gsops.opbase.use_ops = use; } /* Return the set of VUSE operand for statement G. */ static inline use_operand_p gimple_vuse_op (const_gimple g) { struct use_optype_d *ops; if (!gimple_has_mem_ops (g)) return NULL_USE_OPERAND_P; ops = g->gsops.opbase.use_ops; if (ops && USE_OP_PTR (ops)->use == &g->gsmembase.vuse) return USE_OP_PTR (ops); return NULL_USE_OPERAND_P; } /* Return the set of VDEF operand for statement G. */ static inline def_operand_p gimple_vdef_op (const_gimple g) { struct def_optype_d *ops; if (!gimple_has_mem_ops (g)) return NULL_DEF_OPERAND_P; ops = g->gsops.opbase.def_ops; if (ops && DEF_OP_PTR (ops) == &g->gsmembase.vdef) return DEF_OP_PTR (ops); return NULL_DEF_OPERAND_P; } /* Return the single VUSE operand of the statement G. */ static inline tree gimple_vuse (const_gimple g) { if (!gimple_has_mem_ops (g)) return NULL_TREE; return g->gsmembase.vuse; } /* Return the single VDEF operand of the statement G. */ static inline tree gimple_vdef (const_gimple g) { if (!gimple_has_mem_ops (g)) return NULL_TREE; return g->gsmembase.vdef; } /* Return the single VUSE operand of the statement G. */ static inline tree * gimple_vuse_ptr (gimple g) { if (!gimple_has_mem_ops (g)) return NULL; return &g->gsmembase.vuse; } /* Return the single VDEF operand of the statement G. */ static inline tree * gimple_vdef_ptr (gimple g) { if (!gimple_has_mem_ops (g)) return NULL; return &g->gsmembase.vdef; } /* Set the single VUSE operand of the statement G. */ static inline void gimple_set_vuse (gimple g, tree vuse) { gcc_gimple_checking_assert (gimple_has_mem_ops (g)); g->gsmembase.vuse = vuse; } /* Set the single VDEF operand of the statement G. */ static inline void gimple_set_vdef (gimple g, tree vdef) { gcc_gimple_checking_assert (gimple_has_mem_ops (g)); g->gsmembase.vdef = vdef; } /* Return true if statement G has operands and the modified field has been set. */ static inline bool gimple_modified_p (const_gimple g) { return (gimple_has_ops (g)) ? (bool) g->gsbase.modified : false; } /* Return the tree code for the expression computed by STMT. This is only valid for GIMPLE_COND, GIMPLE_CALL and GIMPLE_ASSIGN. For GIMPLE_CALL, return CALL_EXPR as the expression code for consistency. This is useful when the caller needs to deal with the three kinds of computation that GIMPLE supports. */ static inline enum tree_code gimple_expr_code (const_gimple stmt) { enum gimple_code code = gimple_code (stmt); if (code == GIMPLE_ASSIGN || code == GIMPLE_COND) return (enum tree_code) stmt->gsbase.subcode; else { gcc_gimple_checking_assert (code == GIMPLE_CALL); return CALL_EXPR; } } /* Mark statement S as modified, and update it. */ static inline void update_stmt (gimple s) { if (gimple_has_ops (s)) { gimple_set_modified (s, true); update_stmt_operands (s); } } /* Update statement S if it has been optimized. */ static inline void update_stmt_if_modified (gimple s) { if (gimple_modified_p (s)) update_stmt_operands (s); } /* Return true if statement STMT contains volatile operands. */ static inline bool gimple_has_volatile_ops (const_gimple stmt) { if (gimple_has_mem_ops (stmt)) return stmt->gsbase.has_volatile_ops; else return false; } /* Set the HAS_VOLATILE_OPS flag to VOLATILEP. */ static inline void gimple_set_has_volatile_ops (gimple stmt, bool volatilep) { if (gimple_has_mem_ops (stmt)) stmt->gsbase.has_volatile_ops = (unsigned) volatilep; } /* Return true if STMT is in a transaction. */ static inline bool gimple_in_transaction (gimple stmt) { return stmt->gsbase.in_transaction; } /* Set the IN_TRANSACTION flag to TRANSACTIONP. */ static inline void gimple_set_in_transaction (gimple stmt, bool transactionp) { stmt->gsbase.in_transaction = (unsigned) transactionp; } /* Return true if statement STMT may access memory. */ static inline bool gimple_references_memory_p (gimple stmt) { return gimple_has_mem_ops (stmt) && gimple_vuse (stmt); } /* Return the subcode for OMP statement S. */ static inline unsigned gimple_omp_subcode (const_gimple s) { gcc_gimple_checking_assert (gimple_code (s) >= GIMPLE_OMP_ATOMIC_LOAD && gimple_code (s) <= GIMPLE_OMP_SINGLE); return s->gsbase.subcode; } /* Set the subcode for OMP statement S to SUBCODE. */ static inline void gimple_omp_set_subcode (gimple s, unsigned int subcode) { /* We only have 16 bits for the subcode. Assert that we are not overflowing it. */ gcc_gimple_checking_assert (subcode < (1 << 16)); s->gsbase.subcode = subcode; } /* Set the nowait flag on OMP_RETURN statement S. */ static inline void gimple_omp_return_set_nowait (gimple s) { GIMPLE_CHECK (s, GIMPLE_OMP_RETURN); s->gsbase.subcode |= GF_OMP_RETURN_NOWAIT; } /* Return true if OMP return statement G has the GF_OMP_RETURN_NOWAIT flag set. */ static inline bool gimple_omp_return_nowait_p (const_gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_RETURN); return (gimple_omp_subcode (g) & GF_OMP_RETURN_NOWAIT) != 0; } /* Return true if OMP section statement G has the GF_OMP_SECTION_LAST flag set. */ static inline bool gimple_omp_section_last_p (const_gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_SECTION); return (gimple_omp_subcode (g) & GF_OMP_SECTION_LAST) != 0; } /* Set the GF_OMP_SECTION_LAST flag on G. */ static inline void gimple_omp_section_set_last (gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_SECTION); g->gsbase.subcode |= GF_OMP_SECTION_LAST; } /* Return true if OMP parallel statement G has the GF_OMP_PARALLEL_COMBINED flag set. */ static inline bool gimple_omp_parallel_combined_p (const_gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_PARALLEL); return (gimple_omp_subcode (g) & GF_OMP_PARALLEL_COMBINED) != 0; } /* Set the GF_OMP_PARALLEL_COMBINED field in G depending on the boolean value of COMBINED_P. */ static inline void gimple_omp_parallel_set_combined_p (gimple g, bool combined_p) { GIMPLE_CHECK (g, GIMPLE_OMP_PARALLEL); if (combined_p) g->gsbase.subcode |= GF_OMP_PARALLEL_COMBINED; else g->gsbase.subcode &= ~GF_OMP_PARALLEL_COMBINED; } /* Return true if OMP atomic load/store statement G has the GF_OMP_ATOMIC_NEED_VALUE flag set. */ static inline bool gimple_omp_atomic_need_value_p (const_gimple g) { if (gimple_code (g) != GIMPLE_OMP_ATOMIC_LOAD) GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_STORE); return (gimple_omp_subcode (g) & GF_OMP_ATOMIC_NEED_VALUE) != 0; } /* Set the GF_OMP_ATOMIC_NEED_VALUE flag on G. */ static inline void gimple_omp_atomic_set_need_value (gimple g) { if (gimple_code (g) != GIMPLE_OMP_ATOMIC_LOAD) GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_STORE); g->gsbase.subcode |= GF_OMP_ATOMIC_NEED_VALUE; } /* Return the number of operands for statement GS. */ static inline unsigned gimple_num_ops (const_gimple gs) { return gs->gsbase.num_ops; } /* Set the number of operands for statement GS. */ static inline void gimple_set_num_ops (gimple gs, unsigned num_ops) { gs->gsbase.num_ops = num_ops; } /* Return the array of operands for statement GS. */ static inline tree * gimple_ops (gimple gs) { size_t off; /* All the tuples have their operand vector at the very bottom of the structure. Note that those structures that do not have an operand vector have a zero offset. */ off = gimple_ops_offset_[gimple_statement_structure (gs)]; gcc_gimple_checking_assert (off != 0); return (tree *) ((char *) gs + off); } /* Return operand I for statement GS. */ static inline tree gimple_op (const_gimple gs, unsigned i) { if (gimple_has_ops (gs)) { gcc_gimple_checking_assert (i < gimple_num_ops (gs)); return gimple_ops (CONST_CAST_GIMPLE (gs))[i]; } else return NULL_TREE; } /* Return a pointer to operand I for statement GS. */ static inline tree * gimple_op_ptr (const_gimple gs, unsigned i) { if (gimple_has_ops (gs)) { gcc_gimple_checking_assert (i < gimple_num_ops (gs)); return gimple_ops (CONST_CAST_GIMPLE (gs)) + i; } else return NULL; } /* Set operand I of statement GS to OP. */ static inline void gimple_set_op (gimple gs, unsigned i, tree op) { gcc_gimple_checking_assert (gimple_has_ops (gs) && i < gimple_num_ops (gs)); /* Note. It may be tempting to assert that OP matches is_gimple_operand, but that would be wrong. Different tuples accept slightly different sets of tree operands. Each caller should perform its own validation. */ gimple_ops (gs)[i] = op; } /* Return true if GS is a GIMPLE_ASSIGN. */ static inline bool is_gimple_assign (const_gimple gs) { return gimple_code (gs) == GIMPLE_ASSIGN; } /* Determine if expression CODE is one of the valid expressions that can be used on the RHS of GIMPLE assignments. */ static inline enum gimple_rhs_class get_gimple_rhs_class (enum tree_code code) { return (enum gimple_rhs_class) gimple_rhs_class_table[(int) code]; } /* Return the LHS of assignment statement GS. */ static inline tree gimple_assign_lhs (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); return gimple_op (gs, 0); } /* Return a pointer to the LHS of assignment statement GS. */ static inline tree * gimple_assign_lhs_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); return gimple_op_ptr (gs, 0); } /* Set LHS to be the LHS operand of assignment statement GS. */ static inline void gimple_assign_set_lhs (gimple gs, tree lhs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); gimple_set_op (gs, 0, lhs); if (lhs && TREE_CODE (lhs) == SSA_NAME) SSA_NAME_DEF_STMT (lhs) = gs; } /* Return the first operand on the RHS of assignment statement GS. */ static inline tree gimple_assign_rhs1 (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); return gimple_op (gs, 1); } /* Return a pointer to the first operand on the RHS of assignment statement GS. */ static inline tree * gimple_assign_rhs1_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); return gimple_op_ptr (gs, 1); } /* Set RHS to be the first operand on the RHS of assignment statement GS. */ static inline void gimple_assign_set_rhs1 (gimple gs, tree rhs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); gimple_set_op (gs, 1, rhs); } /* Return the second operand on the RHS of assignment statement GS. If GS does not have two operands, NULL is returned instead. */ static inline tree gimple_assign_rhs2 (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); if (gimple_num_ops (gs) >= 3) return gimple_op (gs, 2); else return NULL_TREE; } /* Return a pointer to the second operand on the RHS of assignment statement GS. */ static inline tree * gimple_assign_rhs2_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); return gimple_op_ptr (gs, 2); } /* Set RHS to be the second operand on the RHS of assignment statement GS. */ static inline void gimple_assign_set_rhs2 (gimple gs, tree rhs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); gimple_set_op (gs, 2, rhs); } /* Return the third operand on the RHS of assignment statement GS. If GS does not have two operands, NULL is returned instead. */ static inline tree gimple_assign_rhs3 (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); if (gimple_num_ops (gs) >= 4) return gimple_op (gs, 3); else return NULL_TREE; } /* Return a pointer to the third operand on the RHS of assignment statement GS. */ static inline tree * gimple_assign_rhs3_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); return gimple_op_ptr (gs, 3); } /* Set RHS to be the third operand on the RHS of assignment statement GS. */ static inline void gimple_assign_set_rhs3 (gimple gs, tree rhs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); gimple_set_op (gs, 3, rhs); } /* A wrapper around gimple_assign_set_rhs_with_ops_1, for callers which expect to see only a maximum of two operands. */ static inline void gimple_assign_set_rhs_with_ops (gimple_stmt_iterator *gsi, enum tree_code code, tree op1, tree op2) { gimple_assign_set_rhs_with_ops_1 (gsi, code, op1, op2, NULL); } /* A wrapper around extract_ops_from_tree_1, for callers which expect to see only a maximum of two operands. */ static inline void extract_ops_from_tree (tree expr, enum tree_code *code, tree *op0, tree *op1) { tree op2; extract_ops_from_tree_1 (expr, code, op0, op1, &op2); gcc_assert (op2 == NULL_TREE); } /* Returns true if GS is a nontemporal move. */ static inline bool gimple_assign_nontemporal_move_p (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); return gs->gsbase.nontemporal_move; } /* Sets nontemporal move flag of GS to NONTEMPORAL. */ static inline void gimple_assign_set_nontemporal_move (gimple gs, bool nontemporal) { GIMPLE_CHECK (gs, GIMPLE_ASSIGN); gs->gsbase.nontemporal_move = nontemporal; } /* Return the code of the expression computed on the rhs of assignment statement GS. In case that the RHS is a single object, returns the tree code of the object. */ static inline enum tree_code gimple_assign_rhs_code (const_gimple gs) { enum tree_code code; GIMPLE_CHECK (gs, GIMPLE_ASSIGN); code = (enum tree_code) gs->gsbase.subcode; /* While we initially set subcode to the TREE_CODE of the rhs for GIMPLE_SINGLE_RHS assigns we do not update that subcode to stay in sync when we rewrite stmts into SSA form or do SSA propagations. */ if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS) code = TREE_CODE (gimple_assign_rhs1 (gs)); return code; } /* Set CODE to be the code for the expression computed on the RHS of assignment S. */ static inline void gimple_assign_set_rhs_code (gimple s, enum tree_code code) { GIMPLE_CHECK (s, GIMPLE_ASSIGN); s->gsbase.subcode = code; } /* Return the gimple rhs class of the code of the expression computed on the rhs of assignment statement GS. This will never return GIMPLE_INVALID_RHS. */ static inline enum gimple_rhs_class gimple_assign_rhs_class (const_gimple gs) { return get_gimple_rhs_class (gimple_assign_rhs_code (gs)); } /* Return true if GS is an assignment with a singleton RHS, i.e., there is no operator associated with the assignment itself. Unlike gimple_assign_copy_p, this predicate returns true for any RHS operand, including those that perform an operation and do not have the semantics of a copy, such as COND_EXPR. */ static inline bool gimple_assign_single_p (gimple gs) { return (is_gimple_assign (gs) && gimple_assign_rhs_class (gs) == GIMPLE_SINGLE_RHS); } /* Return true if S is a type-cast assignment. */ static inline bool gimple_assign_cast_p (gimple s) { if (is_gimple_assign (s)) { enum tree_code sc = gimple_assign_rhs_code (s); return CONVERT_EXPR_CODE_P (sc) || sc == VIEW_CONVERT_EXPR || sc == FIX_TRUNC_EXPR; } return false; } /* Return true if S is a clobber statement. */ static inline bool gimple_clobber_p (gimple s) { return gimple_assign_single_p (s) && TREE_CLOBBER_P (gimple_assign_rhs1 (s)); } /* Return true if GS is a GIMPLE_CALL. */ static inline bool is_gimple_call (const_gimple gs) { return gimple_code (gs) == GIMPLE_CALL; } /* Return the LHS of call statement GS. */ static inline tree gimple_call_lhs (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CALL); return gimple_op (gs, 0); } /* Return a pointer to the LHS of call statement GS. */ static inline tree * gimple_call_lhs_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CALL); return gimple_op_ptr (gs, 0); } /* Set LHS to be the LHS operand of call statement GS. */ static inline void gimple_call_set_lhs (gimple gs, tree lhs) { GIMPLE_CHECK (gs, GIMPLE_CALL); gimple_set_op (gs, 0, lhs); if (lhs && TREE_CODE (lhs) == SSA_NAME) SSA_NAME_DEF_STMT (lhs) = gs; } /* Return true if call GS calls an internal-only function, as enumerated by internal_fn. */ static inline bool gimple_call_internal_p (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CALL); return (gs->gsbase.subcode & GF_CALL_INTERNAL) != 0; } /* Return the target of internal call GS. */ static inline enum internal_fn gimple_call_internal_fn (const_gimple gs) { gcc_gimple_checking_assert (gimple_call_internal_p (gs)); return gs->gimple_call.u.internal_fn; } /* Return the function type of the function called by GS. */ static inline tree gimple_call_fntype (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CALL); if (gimple_call_internal_p (gs)) return NULL_TREE; return gs->gimple_call.u.fntype; } /* Set the type of the function called by GS to FNTYPE. */ static inline void gimple_call_set_fntype (gimple gs, tree fntype) { GIMPLE_CHECK (gs, GIMPLE_CALL); gcc_gimple_checking_assert (!gimple_call_internal_p (gs)); gs->gimple_call.u.fntype = fntype; } /* Return the tree node representing the function called by call statement GS. */ static inline tree gimple_call_fn (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CALL); return gimple_op (gs, 1); } /* Return a pointer to the tree node representing the function called by call statement GS. */ static inline tree * gimple_call_fn_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CALL); return gimple_op_ptr (gs, 1); } /* Set FN to be the function called by call statement GS. */ static inline void gimple_call_set_fn (gimple gs, tree fn) { GIMPLE_CHECK (gs, GIMPLE_CALL); gcc_gimple_checking_assert (!gimple_call_internal_p (gs)); gimple_set_op (gs, 1, fn); } /* Set FNDECL to be the function called by call statement GS. */ static inline void gimple_call_set_fndecl (gimple gs, tree decl) { GIMPLE_CHECK (gs, GIMPLE_CALL); gcc_gimple_checking_assert (!gimple_call_internal_p (gs)); gimple_set_op (gs, 1, build_fold_addr_expr_loc (gimple_location (gs), decl)); } /* Set internal function FN to be the function called by call statement GS. */ static inline void gimple_call_set_internal_fn (gimple gs, enum internal_fn fn) { GIMPLE_CHECK (gs, GIMPLE_CALL); gcc_gimple_checking_assert (gimple_call_internal_p (gs)); gs->gimple_call.u.internal_fn = fn; } /* Given a valid GIMPLE_CALL function address return the FUNCTION_DECL associated with the callee if known. Otherwise return NULL_TREE. */ static inline tree gimple_call_addr_fndecl (const_tree fn) { if (fn && TREE_CODE (fn) == ADDR_EXPR) { tree fndecl = TREE_OPERAND (fn, 0); if (TREE_CODE (fndecl) == MEM_REF && TREE_CODE (TREE_OPERAND (fndecl, 0)) == ADDR_EXPR && integer_zerop (TREE_OPERAND (fndecl, 1))) fndecl = TREE_OPERAND (TREE_OPERAND (fndecl, 0), 0); if (TREE_CODE (fndecl) == FUNCTION_DECL) return fndecl; } return NULL_TREE; } /* If a given GIMPLE_CALL's callee is a FUNCTION_DECL, return it. Otherwise return NULL. This function is analogous to get_callee_fndecl in tree land. */ static inline tree gimple_call_fndecl (const_gimple gs) { return gimple_call_addr_fndecl (gimple_call_fn (gs)); } /* Return the type returned by call statement GS. */ static inline tree gimple_call_return_type (const_gimple gs) { tree type = gimple_call_fntype (gs); if (type == NULL_TREE) return TREE_TYPE (gimple_call_lhs (gs)); /* The type returned by a function is the type of its function type. */ return TREE_TYPE (type); } /* Return the static chain for call statement GS. */ static inline tree gimple_call_chain (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CALL); return gimple_op (gs, 2); } /* Return a pointer to the static chain for call statement GS. */ static inline tree * gimple_call_chain_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CALL); return gimple_op_ptr (gs, 2); } /* Set CHAIN to be the static chain for call statement GS. */ static inline void gimple_call_set_chain (gimple gs, tree chain) { GIMPLE_CHECK (gs, GIMPLE_CALL); gimple_set_op (gs, 2, chain); } /* Return the number of arguments used by call statement GS. */ static inline unsigned gimple_call_num_args (const_gimple gs) { unsigned num_ops; GIMPLE_CHECK (gs, GIMPLE_CALL); num_ops = gimple_num_ops (gs); return num_ops - 3; } /* Return the argument at position INDEX for call statement GS. */ static inline tree gimple_call_arg (const_gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_CALL); return gimple_op (gs, index + 3); } /* Return a pointer to the argument at position INDEX for call statement GS. */ static inline tree * gimple_call_arg_ptr (const_gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_CALL); return gimple_op_ptr (gs, index + 3); } /* Set ARG to be the argument at position INDEX for call statement GS. */ static inline void gimple_call_set_arg (gimple gs, unsigned index, tree arg) { GIMPLE_CHECK (gs, GIMPLE_CALL); gimple_set_op (gs, index + 3, arg); } /* If TAIL_P is true, mark call statement S as being a tail call (i.e., a call just before the exit of a function). These calls are candidate for tail call optimization. */ static inline void gimple_call_set_tail (gimple s, bool tail_p) { GIMPLE_CHECK (s, GIMPLE_CALL); if (tail_p) s->gsbase.subcode |= GF_CALL_TAILCALL; else s->gsbase.subcode &= ~GF_CALL_TAILCALL; } /* Return true if GIMPLE_CALL S is marked as a tail call. */ static inline bool gimple_call_tail_p (gimple s) { GIMPLE_CHECK (s, GIMPLE_CALL); return (s->gsbase.subcode & GF_CALL_TAILCALL) != 0; } /* If RETURN_SLOT_OPT_P is true mark GIMPLE_CALL S as valid for return slot optimization. This transformation uses the target of the call expansion as the return slot for calls that return in memory. */ static inline void gimple_call_set_return_slot_opt (gimple s, bool return_slot_opt_p) { GIMPLE_CHECK (s, GIMPLE_CALL); if (return_slot_opt_p) s->gsbase.subcode |= GF_CALL_RETURN_SLOT_OPT; else s->gsbase.subcode &= ~GF_CALL_RETURN_SLOT_OPT; } /* Return true if S is marked for return slot optimization. */ static inline bool gimple_call_return_slot_opt_p (gimple s) { GIMPLE_CHECK (s, GIMPLE_CALL); return (s->gsbase.subcode & GF_CALL_RETURN_SLOT_OPT) != 0; } /* If FROM_THUNK_P is true, mark GIMPLE_CALL S as being the jump from a thunk to the thunked-to function. */ static inline void gimple_call_set_from_thunk (gimple s, bool from_thunk_p) { GIMPLE_CHECK (s, GIMPLE_CALL); if (from_thunk_p) s->gsbase.subcode |= GF_CALL_FROM_THUNK; else s->gsbase.subcode &= ~GF_CALL_FROM_THUNK; } /* Return true if GIMPLE_CALL S is a jump from a thunk. */ static inline bool gimple_call_from_thunk_p (gimple s) { GIMPLE_CHECK (s, GIMPLE_CALL); return (s->gsbase.subcode & GF_CALL_FROM_THUNK) != 0; } /* If PASS_ARG_PACK_P is true, GIMPLE_CALL S is a stdarg call that needs the argument pack in its argument list. */ static inline void gimple_call_set_va_arg_pack (gimple s, bool pass_arg_pack_p) { GIMPLE_CHECK (s, GIMPLE_CALL); if (pass_arg_pack_p) s->gsbase.subcode |= GF_CALL_VA_ARG_PACK; else s->gsbase.subcode &= ~GF_CALL_VA_ARG_PACK; } /* Return true if GIMPLE_CALL S is a stdarg call that needs the argument pack in its argument list. */ static inline bool gimple_call_va_arg_pack_p (gimple s) { GIMPLE_CHECK (s, GIMPLE_CALL); return (s->gsbase.subcode & GF_CALL_VA_ARG_PACK) != 0; } /* Return true if S is a noreturn call. */ static inline bool gimple_call_noreturn_p (gimple s) { GIMPLE_CHECK (s, GIMPLE_CALL); return (gimple_call_flags (s) & ECF_NORETURN) != 0; } /* If NOTHROW_P is true, GIMPLE_CALL S is a call that is known to not throw even if the called function can throw in other cases. */ static inline void gimple_call_set_nothrow (gimple s, bool nothrow_p) { GIMPLE_CHECK (s, GIMPLE_CALL); if (nothrow_p) s->gsbase.subcode |= GF_CALL_NOTHROW; else s->gsbase.subcode &= ~GF_CALL_NOTHROW; } /* Return true if S is a nothrow call. */ static inline bool gimple_call_nothrow_p (gimple s) { GIMPLE_CHECK (s, GIMPLE_CALL); return (gimple_call_flags (s) & ECF_NOTHROW) != 0; } /* If FOR_VAR is true, GIMPLE_CALL S is a call to builtin_alloca that is known to be emitted for VLA objects. Those are wrapped by stack_save/stack_restore calls and hence can't lead to unbounded stack growth even when they occur in loops. */ static inline void gimple_call_set_alloca_for_var (gimple s, bool for_var) { GIMPLE_CHECK (s, GIMPLE_CALL); if (for_var) s->gsbase.subcode |= GF_CALL_ALLOCA_FOR_VAR; else s->gsbase.subcode &= ~GF_CALL_ALLOCA_FOR_VAR; } /* Return true of S is a call to builtin_alloca emitted for VLA objects. */ static inline bool gimple_call_alloca_for_var_p (gimple s) { GIMPLE_CHECK (s, GIMPLE_CALL); return (s->gsbase.subcode & GF_CALL_ALLOCA_FOR_VAR) != 0; } /* Copy all the GF_CALL_* flags from ORIG_CALL to DEST_CALL. */ static inline void gimple_call_copy_flags (gimple dest_call, gimple orig_call) { GIMPLE_CHECK (dest_call, GIMPLE_CALL); GIMPLE_CHECK (orig_call, GIMPLE_CALL); dest_call->gsbase.subcode = orig_call->gsbase.subcode; } /* Return a pointer to the points-to solution for the set of call-used variables of the call CALL. */ static inline struct pt_solution * gimple_call_use_set (gimple call) { GIMPLE_CHECK (call, GIMPLE_CALL); return &call->gimple_call.call_used; } /* Return a pointer to the points-to solution for the set of call-used variables of the call CALL. */ static inline struct pt_solution * gimple_call_clobber_set (gimple call) { GIMPLE_CHECK (call, GIMPLE_CALL); return &call->gimple_call.call_clobbered; } /* Returns true if this is a GIMPLE_ASSIGN or a GIMPLE_CALL with a non-NULL lhs. */ static inline bool gimple_has_lhs (gimple stmt) { return (is_gimple_assign (stmt) || (is_gimple_call (stmt) && gimple_call_lhs (stmt) != NULL_TREE)); } /* Return the code of the predicate computed by conditional statement GS. */ static inline enum tree_code gimple_cond_code (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_COND); return (enum tree_code) gs->gsbase.subcode; } /* Set CODE to be the predicate code for the conditional statement GS. */ static inline void gimple_cond_set_code (gimple gs, enum tree_code code) { GIMPLE_CHECK (gs, GIMPLE_COND); gs->gsbase.subcode = code; } /* Return the LHS of the predicate computed by conditional statement GS. */ static inline tree gimple_cond_lhs (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_COND); return gimple_op (gs, 0); } /* Return the pointer to the LHS of the predicate computed by conditional statement GS. */ static inline tree * gimple_cond_lhs_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_COND); return gimple_op_ptr (gs, 0); } /* Set LHS to be the LHS operand of the predicate computed by conditional statement GS. */ static inline void gimple_cond_set_lhs (gimple gs, tree lhs) { GIMPLE_CHECK (gs, GIMPLE_COND); gimple_set_op (gs, 0, lhs); } /* Return the RHS operand of the predicate computed by conditional GS. */ static inline tree gimple_cond_rhs (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_COND); return gimple_op (gs, 1); } /* Return the pointer to the RHS operand of the predicate computed by conditional GS. */ static inline tree * gimple_cond_rhs_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_COND); return gimple_op_ptr (gs, 1); } /* Set RHS to be the RHS operand of the predicate computed by conditional statement GS. */ static inline void gimple_cond_set_rhs (gimple gs, tree rhs) { GIMPLE_CHECK (gs, GIMPLE_COND); gimple_set_op (gs, 1, rhs); } /* Return the label used by conditional statement GS when its predicate evaluates to true. */ static inline tree gimple_cond_true_label (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_COND); return gimple_op (gs, 2); } /* Set LABEL to be the label used by conditional statement GS when its predicate evaluates to true. */ static inline void gimple_cond_set_true_label (gimple gs, tree label) { GIMPLE_CHECK (gs, GIMPLE_COND); gimple_set_op (gs, 2, label); } /* Set LABEL to be the label used by conditional statement GS when its predicate evaluates to false. */ static inline void gimple_cond_set_false_label (gimple gs, tree label) { GIMPLE_CHECK (gs, GIMPLE_COND); gimple_set_op (gs, 3, label); } /* Return the label used by conditional statement GS when its predicate evaluates to false. */ static inline tree gimple_cond_false_label (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_COND); return gimple_op (gs, 3); } /* Set the conditional COND_STMT to be of the form 'if (1 == 0)'. */ static inline void gimple_cond_make_false (gimple gs) { gimple_cond_set_lhs (gs, boolean_true_node); gimple_cond_set_rhs (gs, boolean_false_node); gs->gsbase.subcode = EQ_EXPR; } /* Set the conditional COND_STMT to be of the form 'if (1 == 1)'. */ static inline void gimple_cond_make_true (gimple gs) { gimple_cond_set_lhs (gs, boolean_true_node); gimple_cond_set_rhs (gs, boolean_true_node); gs->gsbase.subcode = EQ_EXPR; } /* Check if conditional statemente GS is of the form 'if (1 == 1)', 'if (0 == 0)', 'if (1 != 0)' or 'if (0 != 1)' */ static inline bool gimple_cond_true_p (const_gimple gs) { tree lhs = gimple_cond_lhs (gs); tree rhs = gimple_cond_rhs (gs); enum tree_code code = gimple_cond_code (gs); if (lhs != boolean_true_node && lhs != boolean_false_node) return false; if (rhs != boolean_true_node && rhs != boolean_false_node) return false; if (code == NE_EXPR && lhs != rhs) return true; if (code == EQ_EXPR && lhs == rhs) return true; return false; } /* Check if conditional statement GS is of the form 'if (1 != 1)', 'if (0 != 0)', 'if (1 == 0)' or 'if (0 == 1)' */ static inline bool gimple_cond_false_p (const_gimple gs) { tree lhs = gimple_cond_lhs (gs); tree rhs = gimple_cond_rhs (gs); enum tree_code code = gimple_cond_code (gs); if (lhs != boolean_true_node && lhs != boolean_false_node) return false; if (rhs != boolean_true_node && rhs != boolean_false_node) return false; if (code == NE_EXPR && lhs == rhs) return true; if (code == EQ_EXPR && lhs != rhs) return true; return false; } /* Check if conditional statement GS is of the form 'if (var != 0)' or 'if (var == 1)' */ static inline bool gimple_cond_single_var_p (gimple gs) { if (gimple_cond_code (gs) == NE_EXPR && gimple_cond_rhs (gs) == boolean_false_node) return true; if (gimple_cond_code (gs) == EQ_EXPR && gimple_cond_rhs (gs) == boolean_true_node) return true; return false; } /* Set the code, LHS and RHS of GIMPLE_COND STMT from CODE, LHS and RHS. */ static inline void gimple_cond_set_condition (gimple stmt, enum tree_code code, tree lhs, tree rhs) { gimple_cond_set_code (stmt, code); gimple_cond_set_lhs (stmt, lhs); gimple_cond_set_rhs (stmt, rhs); } /* Return the LABEL_DECL node used by GIMPLE_LABEL statement GS. */ static inline tree gimple_label_label (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_LABEL); return gimple_op (gs, 0); } /* Set LABEL to be the LABEL_DECL node used by GIMPLE_LABEL statement GS. */ static inline void gimple_label_set_label (gimple gs, tree label) { GIMPLE_CHECK (gs, GIMPLE_LABEL); gimple_set_op (gs, 0, label); } /* Return the destination of the unconditional jump GS. */ static inline tree gimple_goto_dest (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_GOTO); return gimple_op (gs, 0); } /* Set DEST to be the destination of the unconditonal jump GS. */ static inline void gimple_goto_set_dest (gimple gs, tree dest) { GIMPLE_CHECK (gs, GIMPLE_GOTO); gimple_set_op (gs, 0, dest); } /* Return the variables declared in the GIMPLE_BIND statement GS. */ static inline tree gimple_bind_vars (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_BIND); return gs->gimple_bind.vars; } /* Set VARS to be the set of variables declared in the GIMPLE_BIND statement GS. */ static inline void gimple_bind_set_vars (gimple gs, tree vars) { GIMPLE_CHECK (gs, GIMPLE_BIND); gs->gimple_bind.vars = vars; } /* Append VARS to the set of variables declared in the GIMPLE_BIND statement GS. */ static inline void gimple_bind_append_vars (gimple gs, tree vars) { GIMPLE_CHECK (gs, GIMPLE_BIND); gs->gimple_bind.vars = chainon (gs->gimple_bind.vars, vars); } /* Return the GIMPLE sequence contained in the GIMPLE_BIND statement GS. */ static inline gimple_seq gimple_bind_body (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_BIND); return gs->gimple_bind.body; } /* Set SEQ to be the GIMPLE sequence contained in the GIMPLE_BIND statement GS. */ static inline void gimple_bind_set_body (gimple gs, gimple_seq seq) { GIMPLE_CHECK (gs, GIMPLE_BIND); gs->gimple_bind.body = seq; } /* Append a statement to the end of a GIMPLE_BIND's body. */ static inline void gimple_bind_add_stmt (gimple gs, gimple stmt) { GIMPLE_CHECK (gs, GIMPLE_BIND); gimple_seq_add_stmt (&gs->gimple_bind.body, stmt); } /* Append a sequence of statements to the end of a GIMPLE_BIND's body. */ static inline void gimple_bind_add_seq (gimple gs, gimple_seq seq) { GIMPLE_CHECK (gs, GIMPLE_BIND); gimple_seq_add_seq (&gs->gimple_bind.body, seq); } /* Return the TREE_BLOCK node associated with GIMPLE_BIND statement GS. This is analogous to the BIND_EXPR_BLOCK field in trees. */ static inline tree gimple_bind_block (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_BIND); return gs->gimple_bind.block; } /* Set BLOCK to be the TREE_BLOCK node associated with GIMPLE_BIND statement GS. */ static inline void gimple_bind_set_block (gimple gs, tree block) { GIMPLE_CHECK (gs, GIMPLE_BIND); gcc_gimple_checking_assert (block == NULL_TREE || TREE_CODE (block) == BLOCK); gs->gimple_bind.block = block; } /* Return the number of input operands for GIMPLE_ASM GS. */ static inline unsigned gimple_asm_ninputs (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASM); return gs->gimple_asm.ni; } /* Return the number of output operands for GIMPLE_ASM GS. */ static inline unsigned gimple_asm_noutputs (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASM); return gs->gimple_asm.no; } /* Return the number of clobber operands for GIMPLE_ASM GS. */ static inline unsigned gimple_asm_nclobbers (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASM); return gs->gimple_asm.nc; } /* Return the number of label operands for GIMPLE_ASM GS. */ static inline unsigned gimple_asm_nlabels (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASM); return gs->gimple_asm.nl; } /* Return input operand INDEX of GIMPLE_ASM GS. */ static inline tree gimple_asm_input_op (const_gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.ni); return gimple_op (gs, index); } /* Return a pointer to input operand INDEX of GIMPLE_ASM GS. */ static inline tree * gimple_asm_input_op_ptr (const_gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.ni); return gimple_op_ptr (gs, index); } /* Set IN_OP to be input operand INDEX in GIMPLE_ASM GS. */ static inline void gimple_asm_set_input_op (gimple gs, unsigned index, tree in_op) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.ni && TREE_CODE (in_op) == TREE_LIST); gimple_set_op (gs, index, in_op); } /* Return output operand INDEX of GIMPLE_ASM GS. */ static inline tree gimple_asm_output_op (const_gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.no); return gimple_op (gs, index + gs->gimple_asm.ni); } /* Return a pointer to output operand INDEX of GIMPLE_ASM GS. */ static inline tree * gimple_asm_output_op_ptr (const_gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.no); return gimple_op_ptr (gs, index + gs->gimple_asm.ni); } /* Set OUT_OP to be output operand INDEX in GIMPLE_ASM GS. */ static inline void gimple_asm_set_output_op (gimple gs, unsigned index, tree out_op) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.no && TREE_CODE (out_op) == TREE_LIST); gimple_set_op (gs, index + gs->gimple_asm.ni, out_op); } /* Return clobber operand INDEX of GIMPLE_ASM GS. */ static inline tree gimple_asm_clobber_op (const_gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.nc); return gimple_op (gs, index + gs->gimple_asm.ni + gs->gimple_asm.no); } /* Set CLOBBER_OP to be clobber operand INDEX in GIMPLE_ASM GS. */ static inline void gimple_asm_set_clobber_op (gimple gs, unsigned index, tree clobber_op) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.nc && TREE_CODE (clobber_op) == TREE_LIST); gimple_set_op (gs, index + gs->gimple_asm.ni + gs->gimple_asm.no, clobber_op); } /* Return label operand INDEX of GIMPLE_ASM GS. */ static inline tree gimple_asm_label_op (const_gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.nl); return gimple_op (gs, index + gs->gimple_asm.ni + gs->gimple_asm.nc); } /* Set LABEL_OP to be label operand INDEX in GIMPLE_ASM GS. */ static inline void gimple_asm_set_label_op (gimple gs, unsigned index, tree label_op) { GIMPLE_CHECK (gs, GIMPLE_ASM); gcc_gimple_checking_assert (index <= gs->gimple_asm.nl && TREE_CODE (label_op) == TREE_LIST); gimple_set_op (gs, index + gs->gimple_asm.ni + gs->gimple_asm.nc, label_op); } /* Return the string representing the assembly instruction in GIMPLE_ASM GS. */ static inline const char * gimple_asm_string (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASM); return gs->gimple_asm.string; } /* Return true if GS is an asm statement marked volatile. */ static inline bool gimple_asm_volatile_p (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASM); return (gs->gsbase.subcode & GF_ASM_VOLATILE) != 0; } /* If VOLATLE_P is true, mark asm statement GS as volatile. */ static inline void gimple_asm_set_volatile (gimple gs, bool volatile_p) { GIMPLE_CHECK (gs, GIMPLE_ASM); if (volatile_p) gs->gsbase.subcode |= GF_ASM_VOLATILE; else gs->gsbase.subcode &= ~GF_ASM_VOLATILE; } /* If INPUT_P is true, mark asm GS as an ASM_INPUT. */ static inline void gimple_asm_set_input (gimple gs, bool input_p) { GIMPLE_CHECK (gs, GIMPLE_ASM); if (input_p) gs->gsbase.subcode |= GF_ASM_INPUT; else gs->gsbase.subcode &= ~GF_ASM_INPUT; } /* Return true if asm GS is an ASM_INPUT. */ static inline bool gimple_asm_input_p (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_ASM); return (gs->gsbase.subcode & GF_ASM_INPUT) != 0; } /* Return the types handled by GIMPLE_CATCH statement GS. */ static inline tree gimple_catch_types (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CATCH); return gs->gimple_catch.types; } /* Return a pointer to the types handled by GIMPLE_CATCH statement GS. */ static inline tree * gimple_catch_types_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CATCH); return &gs->gimple_catch.types; } /* Return the GIMPLE sequence representing the body of the handler of GIMPLE_CATCH statement GS. */ static inline gimple_seq gimple_catch_handler (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CATCH); return gs->gimple_catch.handler; } /* Return a pointer to the GIMPLE sequence representing the body of the handler of GIMPLE_CATCH statement GS. */ static inline gimple_seq * gimple_catch_handler_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_CATCH); return &gs->gimple_catch.handler; } /* Set T to be the set of types handled by GIMPLE_CATCH GS. */ static inline void gimple_catch_set_types (gimple gs, tree t) { GIMPLE_CHECK (gs, GIMPLE_CATCH); gs->gimple_catch.types = t; } /* Set HANDLER to be the body of GIMPLE_CATCH GS. */ static inline void gimple_catch_set_handler (gimple gs, gimple_seq handler) { GIMPLE_CHECK (gs, GIMPLE_CATCH); gs->gimple_catch.handler = handler; } /* Return the types handled by GIMPLE_EH_FILTER statement GS. */ static inline tree gimple_eh_filter_types (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_EH_FILTER); return gs->gimple_eh_filter.types; } /* Return a pointer to the types handled by GIMPLE_EH_FILTER statement GS. */ static inline tree * gimple_eh_filter_types_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_EH_FILTER); return &gs->gimple_eh_filter.types; } /* Return the sequence of statement to execute when GIMPLE_EH_FILTER statement fails. */ static inline gimple_seq gimple_eh_filter_failure (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_EH_FILTER); return gs->gimple_eh_filter.failure; } /* Set TYPES to be the set of types handled by GIMPLE_EH_FILTER GS. */ static inline void gimple_eh_filter_set_types (gimple gs, tree types) { GIMPLE_CHECK (gs, GIMPLE_EH_FILTER); gs->gimple_eh_filter.types = types; } /* Set FAILURE to be the sequence of statements to execute on failure for GIMPLE_EH_FILTER GS. */ static inline void gimple_eh_filter_set_failure (gimple gs, gimple_seq failure) { GIMPLE_CHECK (gs, GIMPLE_EH_FILTER); gs->gimple_eh_filter.failure = failure; } /* Get the function decl to be called by the MUST_NOT_THROW region. */ static inline tree gimple_eh_must_not_throw_fndecl (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_EH_MUST_NOT_THROW); return gs->gimple_eh_mnt.fndecl; } /* Set the function decl to be called by GS to DECL. */ static inline void gimple_eh_must_not_throw_set_fndecl (gimple gs, tree decl) { GIMPLE_CHECK (gs, GIMPLE_EH_MUST_NOT_THROW); gs->gimple_eh_mnt.fndecl = decl; } /* GIMPLE_EH_ELSE accessors. */ static inline gimple_seq gimple_eh_else_n_body (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_EH_ELSE); return gs->gimple_eh_else.n_body; } static inline gimple_seq gimple_eh_else_e_body (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_EH_ELSE); return gs->gimple_eh_else.e_body; } static inline void gimple_eh_else_set_n_body (gimple gs, gimple_seq seq) { GIMPLE_CHECK (gs, GIMPLE_EH_ELSE); gs->gimple_eh_else.n_body = seq; } static inline void gimple_eh_else_set_e_body (gimple gs, gimple_seq seq) { GIMPLE_CHECK (gs, GIMPLE_EH_ELSE); gs->gimple_eh_else.e_body = seq; } /* GIMPLE_TRY accessors. */ /* Return the kind of try block represented by GIMPLE_TRY GS. This is either GIMPLE_TRY_CATCH or GIMPLE_TRY_FINALLY. */ static inline enum gimple_try_flags gimple_try_kind (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_TRY); return (enum gimple_try_flags) (gs->gsbase.subcode & GIMPLE_TRY_KIND); } /* Set the kind of try block represented by GIMPLE_TRY GS. */ static inline void gimple_try_set_kind (gimple gs, enum gimple_try_flags kind) { GIMPLE_CHECK (gs, GIMPLE_TRY); gcc_gimple_checking_assert (kind == GIMPLE_TRY_CATCH || kind == GIMPLE_TRY_FINALLY); if (gimple_try_kind (gs) != kind) gs->gsbase.subcode = (unsigned int) kind; } /* Return the GIMPLE_TRY_CATCH_IS_CLEANUP flag. */ static inline bool gimple_try_catch_is_cleanup (const_gimple gs) { gcc_gimple_checking_assert (gimple_try_kind (gs) == GIMPLE_TRY_CATCH); return (gs->gsbase.subcode & GIMPLE_TRY_CATCH_IS_CLEANUP) != 0; } /* Return the sequence of statements used as the body for GIMPLE_TRY GS. */ static inline gimple_seq gimple_try_eval (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_TRY); return gs->gimple_try.eval; } /* Return the sequence of statements used as the cleanup body for GIMPLE_TRY GS. */ static inline gimple_seq gimple_try_cleanup (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_TRY); return gs->gimple_try.cleanup; } /* Set the GIMPLE_TRY_CATCH_IS_CLEANUP flag. */ static inline void gimple_try_set_catch_is_cleanup (gimple g, bool catch_is_cleanup) { gcc_gimple_checking_assert (gimple_try_kind (g) == GIMPLE_TRY_CATCH); if (catch_is_cleanup) g->gsbase.subcode |= GIMPLE_TRY_CATCH_IS_CLEANUP; else g->gsbase.subcode &= ~GIMPLE_TRY_CATCH_IS_CLEANUP; } /* Set EVAL to be the sequence of statements to use as the body for GIMPLE_TRY GS. */ static inline void gimple_try_set_eval (gimple gs, gimple_seq eval) { GIMPLE_CHECK (gs, GIMPLE_TRY); gs->gimple_try.eval = eval; } /* Set CLEANUP to be the sequence of statements to use as the cleanup body for GIMPLE_TRY GS. */ static inline void gimple_try_set_cleanup (gimple gs, gimple_seq cleanup) { GIMPLE_CHECK (gs, GIMPLE_TRY); gs->gimple_try.cleanup = cleanup; } /* Return the cleanup sequence for cleanup statement GS. */ static inline gimple_seq gimple_wce_cleanup (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_WITH_CLEANUP_EXPR); return gs->gimple_wce.cleanup; } /* Set CLEANUP to be the cleanup sequence for GS. */ static inline void gimple_wce_set_cleanup (gimple gs, gimple_seq cleanup) { GIMPLE_CHECK (gs, GIMPLE_WITH_CLEANUP_EXPR); gs->gimple_wce.cleanup = cleanup; } /* Return the CLEANUP_EH_ONLY flag for a WCE tuple. */ static inline bool gimple_wce_cleanup_eh_only (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_WITH_CLEANUP_EXPR); return gs->gsbase.subcode != 0; } /* Set the CLEANUP_EH_ONLY flag for a WCE tuple. */ static inline void gimple_wce_set_cleanup_eh_only (gimple gs, bool eh_only_p) { GIMPLE_CHECK (gs, GIMPLE_WITH_CLEANUP_EXPR); gs->gsbase.subcode = (unsigned int) eh_only_p; } /* Return the maximum number of arguments supported by GIMPLE_PHI GS. */ static inline unsigned gimple_phi_capacity (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_PHI); return gs->gimple_phi.capacity; } /* Return the number of arguments in GIMPLE_PHI GS. This must always be exactly the number of incoming edges for the basic block holding GS. */ static inline unsigned gimple_phi_num_args (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_PHI); return gs->gimple_phi.nargs; } /* Return the SSA name created by GIMPLE_PHI GS. */ static inline tree gimple_phi_result (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_PHI); return gs->gimple_phi.result; } /* Return a pointer to the SSA name created by GIMPLE_PHI GS. */ static inline tree * gimple_phi_result_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_PHI); return &gs->gimple_phi.result; } /* Set RESULT to be the SSA name created by GIMPLE_PHI GS. */ static inline void gimple_phi_set_result (gimple gs, tree result) { GIMPLE_CHECK (gs, GIMPLE_PHI); gs->gimple_phi.result = result; } /* Return the PHI argument corresponding to incoming edge INDEX for GIMPLE_PHI GS. */ static inline struct phi_arg_d * gimple_phi_arg (gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_PHI); gcc_gimple_checking_assert (index <= gs->gimple_phi.capacity); return &(gs->gimple_phi.args[index]); } /* Set PHIARG to be the argument corresponding to incoming edge INDEX for GIMPLE_PHI GS. */ static inline void gimple_phi_set_arg (gimple gs, unsigned index, struct phi_arg_d * phiarg) { GIMPLE_CHECK (gs, GIMPLE_PHI); gcc_gimple_checking_assert (index <= gs->gimple_phi.nargs); gs->gimple_phi.args[index] = *phiarg; } /* Return the region number for GIMPLE_RESX GS. */ static inline int gimple_resx_region (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_RESX); return gs->gimple_eh_ctrl.region; } /* Set REGION to be the region number for GIMPLE_RESX GS. */ static inline void gimple_resx_set_region (gimple gs, int region) { GIMPLE_CHECK (gs, GIMPLE_RESX); gs->gimple_eh_ctrl.region = region; } /* Return the region number for GIMPLE_EH_DISPATCH GS. */ static inline int gimple_eh_dispatch_region (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_EH_DISPATCH); return gs->gimple_eh_ctrl.region; } /* Set REGION to be the region number for GIMPLE_EH_DISPATCH GS. */ static inline void gimple_eh_dispatch_set_region (gimple gs, int region) { GIMPLE_CHECK (gs, GIMPLE_EH_DISPATCH); gs->gimple_eh_ctrl.region = region; } /* Return the number of labels associated with the switch statement GS. */ static inline unsigned gimple_switch_num_labels (const_gimple gs) { unsigned num_ops; GIMPLE_CHECK (gs, GIMPLE_SWITCH); num_ops = gimple_num_ops (gs); gcc_gimple_checking_assert (num_ops > 1); return num_ops - 1; } /* Set NLABELS to be the number of labels for the switch statement GS. */ static inline void gimple_switch_set_num_labels (gimple g, unsigned nlabels) { GIMPLE_CHECK (g, GIMPLE_SWITCH); gimple_set_num_ops (g, nlabels + 1); } /* Return the index variable used by the switch statement GS. */ static inline tree gimple_switch_index (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_SWITCH); return gimple_op (gs, 0); } /* Return a pointer to the index variable for the switch statement GS. */ static inline tree * gimple_switch_index_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_SWITCH); return gimple_op_ptr (gs, 0); } /* Set INDEX to be the index variable for switch statement GS. */ static inline void gimple_switch_set_index (gimple gs, tree index) { GIMPLE_CHECK (gs, GIMPLE_SWITCH); gcc_gimple_checking_assert (SSA_VAR_P (index) || CONSTANT_CLASS_P (index)); gimple_set_op (gs, 0, index); } /* Return the label numbered INDEX. The default label is 0, followed by any labels in a switch statement. */ static inline tree gimple_switch_label (const_gimple gs, unsigned index) { GIMPLE_CHECK (gs, GIMPLE_SWITCH); gcc_gimple_checking_assert (gimple_num_ops (gs) > index + 1); return gimple_op (gs, index + 1); } /* Set the label number INDEX to LABEL. 0 is always the default label. */ static inline void gimple_switch_set_label (gimple gs, unsigned index, tree label) { GIMPLE_CHECK (gs, GIMPLE_SWITCH); gcc_gimple_checking_assert (gimple_num_ops (gs) > index + 1 && (label == NULL_TREE || TREE_CODE (label) == CASE_LABEL_EXPR)); gimple_set_op (gs, index + 1, label); } /* Return the default label for a switch statement. */ static inline tree gimple_switch_default_label (const_gimple gs) { return gimple_switch_label (gs, 0); } /* Set the default label for a switch statement. */ static inline void gimple_switch_set_default_label (gimple gs, tree label) { gimple_switch_set_label (gs, 0, label); } /* Return true if GS is a GIMPLE_DEBUG statement. */ static inline bool is_gimple_debug (const_gimple gs) { return gimple_code (gs) == GIMPLE_DEBUG; } /* Return true if S is a GIMPLE_DEBUG BIND statement. */ static inline bool gimple_debug_bind_p (const_gimple s) { if (is_gimple_debug (s)) return s->gsbase.subcode == GIMPLE_DEBUG_BIND; return false; } /* Return the variable bound in a GIMPLE_DEBUG bind statement. */ static inline tree gimple_debug_bind_get_var (gimple dbg) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_bind_p (dbg)); return gimple_op (dbg, 0); } /* Return the value bound to the variable in a GIMPLE_DEBUG bind statement. */ static inline tree gimple_debug_bind_get_value (gimple dbg) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_bind_p (dbg)); return gimple_op (dbg, 1); } /* Return a pointer to the value bound to the variable in a GIMPLE_DEBUG bind statement. */ static inline tree * gimple_debug_bind_get_value_ptr (gimple dbg) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_bind_p (dbg)); return gimple_op_ptr (dbg, 1); } /* Set the variable bound in a GIMPLE_DEBUG bind statement. */ static inline void gimple_debug_bind_set_var (gimple dbg, tree var) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_bind_p (dbg)); gimple_set_op (dbg, 0, var); } /* Set the value bound to the variable in a GIMPLE_DEBUG bind statement. */ static inline void gimple_debug_bind_set_value (gimple dbg, tree value) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_bind_p (dbg)); gimple_set_op (dbg, 1, value); } /* The second operand of a GIMPLE_DEBUG_BIND, when the value was optimized away. */ #define GIMPLE_DEBUG_BIND_NOVALUE NULL_TREE /* error_mark_node */ /* Remove the value bound to the variable in a GIMPLE_DEBUG bind statement. */ static inline void gimple_debug_bind_reset_value (gimple dbg) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_bind_p (dbg)); gimple_set_op (dbg, 1, GIMPLE_DEBUG_BIND_NOVALUE); } /* Return true if the GIMPLE_DEBUG bind statement is bound to a value. */ static inline bool gimple_debug_bind_has_value_p (gimple dbg) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_bind_p (dbg)); return gimple_op (dbg, 1) != GIMPLE_DEBUG_BIND_NOVALUE; } #undef GIMPLE_DEBUG_BIND_NOVALUE /* Return true if S is a GIMPLE_DEBUG SOURCE BIND statement. */ static inline bool gimple_debug_source_bind_p (const_gimple s) { if (is_gimple_debug (s)) return s->gsbase.subcode == GIMPLE_DEBUG_SOURCE_BIND; return false; } /* Return the variable bound in a GIMPLE_DEBUG source bind statement. */ static inline tree gimple_debug_source_bind_get_var (gimple dbg) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_source_bind_p (dbg)); return gimple_op (dbg, 0); } /* Return the value bound to the variable in a GIMPLE_DEBUG source bind statement. */ static inline tree gimple_debug_source_bind_get_value (gimple dbg) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_source_bind_p (dbg)); return gimple_op (dbg, 1); } /* Return a pointer to the value bound to the variable in a GIMPLE_DEBUG source bind statement. */ static inline tree * gimple_debug_source_bind_get_value_ptr (gimple dbg) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_source_bind_p (dbg)); return gimple_op_ptr (dbg, 1); } /* Set the variable bound in a GIMPLE_DEBUG source bind statement. */ static inline void gimple_debug_source_bind_set_var (gimple dbg, tree var) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_source_bind_p (dbg)); gimple_set_op (dbg, 0, var); } /* Set the value bound to the variable in a GIMPLE_DEBUG source bind statement. */ static inline void gimple_debug_source_bind_set_value (gimple dbg, tree value) { GIMPLE_CHECK (dbg, GIMPLE_DEBUG); gcc_gimple_checking_assert (gimple_debug_source_bind_p (dbg)); gimple_set_op (dbg, 1, value); } /* Return the body for the OMP statement GS. */ static inline gimple_seq gimple_omp_body (gimple gs) { return gs->omp.body; } /* Set BODY to be the body for the OMP statement GS. */ static inline void gimple_omp_set_body (gimple gs, gimple_seq body) { gs->omp.body = body; } /* Return the name associated with OMP_CRITICAL statement GS. */ static inline tree gimple_omp_critical_name (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_CRITICAL); return gs->gimple_omp_critical.name; } /* Return a pointer to the name associated with OMP critical statement GS. */ static inline tree * gimple_omp_critical_name_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_CRITICAL); return &gs->gimple_omp_critical.name; } /* Set NAME to be the name associated with OMP critical statement GS. */ static inline void gimple_omp_critical_set_name (gimple gs, tree name) { GIMPLE_CHECK (gs, GIMPLE_OMP_CRITICAL); gs->gimple_omp_critical.name = name; } /* Return the clauses associated with OMP_FOR GS. */ static inline tree gimple_omp_for_clauses (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); return gs->gimple_omp_for.clauses; } /* Return a pointer to the OMP_FOR GS. */ static inline tree * gimple_omp_for_clauses_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); return &gs->gimple_omp_for.clauses; } /* Set CLAUSES to be the list of clauses associated with OMP_FOR GS. */ static inline void gimple_omp_for_set_clauses (gimple gs, tree clauses) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gs->gimple_omp_for.clauses = clauses; } /* Get the collapse count of OMP_FOR GS. */ static inline size_t gimple_omp_for_collapse (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); return gs->gimple_omp_for.collapse; } /* Return the index variable for OMP_FOR GS. */ static inline tree gimple_omp_for_index (const_gimple gs, size_t i) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); return gs->gimple_omp_for.iter[i].index; } /* Return a pointer to the index variable for OMP_FOR GS. */ static inline tree * gimple_omp_for_index_ptr (gimple gs, size_t i) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); return &gs->gimple_omp_for.iter[i].index; } /* Set INDEX to be the index variable for OMP_FOR GS. */ static inline void gimple_omp_for_set_index (gimple gs, size_t i, tree index) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); gs->gimple_omp_for.iter[i].index = index; } /* Return the initial value for OMP_FOR GS. */ static inline tree gimple_omp_for_initial (const_gimple gs, size_t i) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); return gs->gimple_omp_for.iter[i].initial; } /* Return a pointer to the initial value for OMP_FOR GS. */ static inline tree * gimple_omp_for_initial_ptr (gimple gs, size_t i) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); return &gs->gimple_omp_for.iter[i].initial; } /* Set INITIAL to be the initial value for OMP_FOR GS. */ static inline void gimple_omp_for_set_initial (gimple gs, size_t i, tree initial) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); gs->gimple_omp_for.iter[i].initial = initial; } /* Return the final value for OMP_FOR GS. */ static inline tree gimple_omp_for_final (const_gimple gs, size_t i) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); return gs->gimple_omp_for.iter[i].final; } /* Return a pointer to the final value for OMP_FOR GS. */ static inline tree * gimple_omp_for_final_ptr (gimple gs, size_t i) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); return &gs->gimple_omp_for.iter[i].final; } /* Set FINAL to be the final value for OMP_FOR GS. */ static inline void gimple_omp_for_set_final (gimple gs, size_t i, tree final) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); gs->gimple_omp_for.iter[i].final = final; } /* Return the increment value for OMP_FOR GS. */ static inline tree gimple_omp_for_incr (const_gimple gs, size_t i) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); return gs->gimple_omp_for.iter[i].incr; } /* Return a pointer to the increment value for OMP_FOR GS. */ static inline tree * gimple_omp_for_incr_ptr (gimple gs, size_t i) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); return &gs->gimple_omp_for.iter[i].incr; } /* Set INCR to be the increment value for OMP_FOR GS. */ static inline void gimple_omp_for_set_incr (gimple gs, size_t i, tree incr) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); gs->gimple_omp_for.iter[i].incr = incr; } /* Return the sequence of statements to execute before the OMP_FOR statement GS starts. */ static inline gimple_seq gimple_omp_for_pre_body (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); return gs->gimple_omp_for.pre_body; } /* Set PRE_BODY to be the sequence of statements to execute before the OMP_FOR statement GS starts. */ static inline void gimple_omp_for_set_pre_body (gimple gs, gimple_seq pre_body) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gs->gimple_omp_for.pre_body = pre_body; } /* Return the clauses associated with OMP_PARALLEL GS. */ static inline tree gimple_omp_parallel_clauses (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_PARALLEL); return gs->gimple_omp_parallel.clauses; } /* Return a pointer to the clauses associated with OMP_PARALLEL GS. */ static inline tree * gimple_omp_parallel_clauses_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_PARALLEL); return &gs->gimple_omp_parallel.clauses; } /* Set CLAUSES to be the list of clauses associated with OMP_PARALLEL GS. */ static inline void gimple_omp_parallel_set_clauses (gimple gs, tree clauses) { GIMPLE_CHECK (gs, GIMPLE_OMP_PARALLEL); gs->gimple_omp_parallel.clauses = clauses; } /* Return the child function used to hold the body of OMP_PARALLEL GS. */ static inline tree gimple_omp_parallel_child_fn (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_PARALLEL); return gs->gimple_omp_parallel.child_fn; } /* Return a pointer to the child function used to hold the body of OMP_PARALLEL GS. */ static inline tree * gimple_omp_parallel_child_fn_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_PARALLEL); return &gs->gimple_omp_parallel.child_fn; } /* Set CHILD_FN to be the child function for OMP_PARALLEL GS. */ static inline void gimple_omp_parallel_set_child_fn (gimple gs, tree child_fn) { GIMPLE_CHECK (gs, GIMPLE_OMP_PARALLEL); gs->gimple_omp_parallel.child_fn = child_fn; } /* Return the artificial argument used to send variables and values from the parent to the children threads in OMP_PARALLEL GS. */ static inline tree gimple_omp_parallel_data_arg (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_PARALLEL); return gs->gimple_omp_parallel.data_arg; } /* Return a pointer to the data argument for OMP_PARALLEL GS. */ static inline tree * gimple_omp_parallel_data_arg_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_PARALLEL); return &gs->gimple_omp_parallel.data_arg; } /* Set DATA_ARG to be the data argument for OMP_PARALLEL GS. */ static inline void gimple_omp_parallel_set_data_arg (gimple gs, tree data_arg) { GIMPLE_CHECK (gs, GIMPLE_OMP_PARALLEL); gs->gimple_omp_parallel.data_arg = data_arg; } /* Return the clauses associated with OMP_TASK GS. */ static inline tree gimple_omp_task_clauses (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return gs->gimple_omp_parallel.clauses; } /* Return a pointer to the clauses associated with OMP_TASK GS. */ static inline tree * gimple_omp_task_clauses_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return &gs->gimple_omp_parallel.clauses; } /* Set CLAUSES to be the list of clauses associated with OMP_TASK GS. */ static inline void gimple_omp_task_set_clauses (gimple gs, tree clauses) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); gs->gimple_omp_parallel.clauses = clauses; } /* Return the child function used to hold the body of OMP_TASK GS. */ static inline tree gimple_omp_task_child_fn (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return gs->gimple_omp_parallel.child_fn; } /* Return a pointer to the child function used to hold the body of OMP_TASK GS. */ static inline tree * gimple_omp_task_child_fn_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return &gs->gimple_omp_parallel.child_fn; } /* Set CHILD_FN to be the child function for OMP_TASK GS. */ static inline void gimple_omp_task_set_child_fn (gimple gs, tree child_fn) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); gs->gimple_omp_parallel.child_fn = child_fn; } /* Return the artificial argument used to send variables and values from the parent to the children threads in OMP_TASK GS. */ static inline tree gimple_omp_task_data_arg (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return gs->gimple_omp_parallel.data_arg; } /* Return a pointer to the data argument for OMP_TASK GS. */ static inline tree * gimple_omp_task_data_arg_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return &gs->gimple_omp_parallel.data_arg; } /* Set DATA_ARG to be the data argument for OMP_TASK GS. */ static inline void gimple_omp_task_set_data_arg (gimple gs, tree data_arg) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); gs->gimple_omp_parallel.data_arg = data_arg; } /* Return the clauses associated with OMP_TASK GS. */ static inline tree gimple_omp_taskreg_clauses (const_gimple gs) { if (gimple_code (gs) != GIMPLE_OMP_PARALLEL) GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return gs->gimple_omp_parallel.clauses; } /* Return a pointer to the clauses associated with OMP_TASK GS. */ static inline tree * gimple_omp_taskreg_clauses_ptr (gimple gs) { if (gimple_code (gs) != GIMPLE_OMP_PARALLEL) GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return &gs->gimple_omp_parallel.clauses; } /* Set CLAUSES to be the list of clauses associated with OMP_TASK GS. */ static inline void gimple_omp_taskreg_set_clauses (gimple gs, tree clauses) { if (gimple_code (gs) != GIMPLE_OMP_PARALLEL) GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); gs->gimple_omp_parallel.clauses = clauses; } /* Return the child function used to hold the body of OMP_TASK GS. */ static inline tree gimple_omp_taskreg_child_fn (const_gimple gs) { if (gimple_code (gs) != GIMPLE_OMP_PARALLEL) GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return gs->gimple_omp_parallel.child_fn; } /* Return a pointer to the child function used to hold the body of OMP_TASK GS. */ static inline tree * gimple_omp_taskreg_child_fn_ptr (gimple gs) { if (gimple_code (gs) != GIMPLE_OMP_PARALLEL) GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return &gs->gimple_omp_parallel.child_fn; } /* Set CHILD_FN to be the child function for OMP_TASK GS. */ static inline void gimple_omp_taskreg_set_child_fn (gimple gs, tree child_fn) { if (gimple_code (gs) != GIMPLE_OMP_PARALLEL) GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); gs->gimple_omp_parallel.child_fn = child_fn; } /* Return the artificial argument used to send variables and values from the parent to the children threads in OMP_TASK GS. */ static inline tree gimple_omp_taskreg_data_arg (const_gimple gs) { if (gimple_code (gs) != GIMPLE_OMP_PARALLEL) GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return gs->gimple_omp_parallel.data_arg; } /* Return a pointer to the data argument for OMP_TASK GS. */ static inline tree * gimple_omp_taskreg_data_arg_ptr (gimple gs) { if (gimple_code (gs) != GIMPLE_OMP_PARALLEL) GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return &gs->gimple_omp_parallel.data_arg; } /* Set DATA_ARG to be the data argument for OMP_TASK GS. */ static inline void gimple_omp_taskreg_set_data_arg (gimple gs, tree data_arg) { if (gimple_code (gs) != GIMPLE_OMP_PARALLEL) GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); gs->gimple_omp_parallel.data_arg = data_arg; } /* Return the copy function used to hold the body of OMP_TASK GS. */ static inline tree gimple_omp_task_copy_fn (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return gs->gimple_omp_task.copy_fn; } /* Return a pointer to the copy function used to hold the body of OMP_TASK GS. */ static inline tree * gimple_omp_task_copy_fn_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return &gs->gimple_omp_task.copy_fn; } /* Set CHILD_FN to be the copy function for OMP_TASK GS. */ static inline void gimple_omp_task_set_copy_fn (gimple gs, tree copy_fn) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); gs->gimple_omp_task.copy_fn = copy_fn; } /* Return size of the data block in bytes in OMP_TASK GS. */ static inline tree gimple_omp_task_arg_size (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return gs->gimple_omp_task.arg_size; } /* Return a pointer to the data block size for OMP_TASK GS. */ static inline tree * gimple_omp_task_arg_size_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return &gs->gimple_omp_task.arg_size; } /* Set ARG_SIZE to be the data block size for OMP_TASK GS. */ static inline void gimple_omp_task_set_arg_size (gimple gs, tree arg_size) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); gs->gimple_omp_task.arg_size = arg_size; } /* Return align of the data block in bytes in OMP_TASK GS. */ static inline tree gimple_omp_task_arg_align (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return gs->gimple_omp_task.arg_align; } /* Return a pointer to the data block align for OMP_TASK GS. */ static inline tree * gimple_omp_task_arg_align_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); return &gs->gimple_omp_task.arg_align; } /* Set ARG_SIZE to be the data block align for OMP_TASK GS. */ static inline void gimple_omp_task_set_arg_align (gimple gs, tree arg_align) { GIMPLE_CHECK (gs, GIMPLE_OMP_TASK); gs->gimple_omp_task.arg_align = arg_align; } /* Return the clauses associated with OMP_SINGLE GS. */ static inline tree gimple_omp_single_clauses (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_SINGLE); return gs->gimple_omp_single.clauses; } /* Return a pointer to the clauses associated with OMP_SINGLE GS. */ static inline tree * gimple_omp_single_clauses_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_SINGLE); return &gs->gimple_omp_single.clauses; } /* Set CLAUSES to be the clauses associated with OMP_SINGLE GS. */ static inline void gimple_omp_single_set_clauses (gimple gs, tree clauses) { GIMPLE_CHECK (gs, GIMPLE_OMP_SINGLE); gs->gimple_omp_single.clauses = clauses; } /* Return the clauses associated with OMP_SECTIONS GS. */ static inline tree gimple_omp_sections_clauses (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_SECTIONS); return gs->gimple_omp_sections.clauses; } /* Return a pointer to the clauses associated with OMP_SECTIONS GS. */ static inline tree * gimple_omp_sections_clauses_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_SECTIONS); return &gs->gimple_omp_sections.clauses; } /* Set CLAUSES to be the set of clauses associated with OMP_SECTIONS GS. */ static inline void gimple_omp_sections_set_clauses (gimple gs, tree clauses) { GIMPLE_CHECK (gs, GIMPLE_OMP_SECTIONS); gs->gimple_omp_sections.clauses = clauses; } /* Return the control variable associated with the GIMPLE_OMP_SECTIONS in GS. */ static inline tree gimple_omp_sections_control (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_SECTIONS); return gs->gimple_omp_sections.control; } /* Return a pointer to the clauses associated with the GIMPLE_OMP_SECTIONS GS. */ static inline tree * gimple_omp_sections_control_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_OMP_SECTIONS); return &gs->gimple_omp_sections.control; } /* Set CONTROL to be the set of clauses associated with the GIMPLE_OMP_SECTIONS in GS. */ static inline void gimple_omp_sections_set_control (gimple gs, tree control) { GIMPLE_CHECK (gs, GIMPLE_OMP_SECTIONS); gs->gimple_omp_sections.control = control; } /* Set COND to be the condition code for OMP_FOR GS. */ static inline void gimple_omp_for_set_cond (gimple gs, size_t i, enum tree_code cond) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (TREE_CODE_CLASS (cond) == tcc_comparison && i < gs->gimple_omp_for.collapse); gs->gimple_omp_for.iter[i].cond = cond; } /* Return the condition code associated with OMP_FOR GS. */ static inline enum tree_code gimple_omp_for_cond (const_gimple gs, size_t i) { GIMPLE_CHECK (gs, GIMPLE_OMP_FOR); gcc_gimple_checking_assert (i < gs->gimple_omp_for.collapse); return gs->gimple_omp_for.iter[i].cond; } /* Set the value being stored in an atomic store. */ static inline void gimple_omp_atomic_store_set_val (gimple g, tree val) { GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_STORE); g->gimple_omp_atomic_store.val = val; } /* Return the value being stored in an atomic store. */ static inline tree gimple_omp_atomic_store_val (const_gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_STORE); return g->gimple_omp_atomic_store.val; } /* Return a pointer to the value being stored in an atomic store. */ static inline tree * gimple_omp_atomic_store_val_ptr (gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_STORE); return &g->gimple_omp_atomic_store.val; } /* Set the LHS of an atomic load. */ static inline void gimple_omp_atomic_load_set_lhs (gimple g, tree lhs) { GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_LOAD); g->gimple_omp_atomic_load.lhs = lhs; } /* Get the LHS of an atomic load. */ static inline tree gimple_omp_atomic_load_lhs (const_gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_LOAD); return g->gimple_omp_atomic_load.lhs; } /* Return a pointer to the LHS of an atomic load. */ static inline tree * gimple_omp_atomic_load_lhs_ptr (gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_LOAD); return &g->gimple_omp_atomic_load.lhs; } /* Set the RHS of an atomic load. */ static inline void gimple_omp_atomic_load_set_rhs (gimple g, tree rhs) { GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_LOAD); g->gimple_omp_atomic_load.rhs = rhs; } /* Get the RHS of an atomic load. */ static inline tree gimple_omp_atomic_load_rhs (const_gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_LOAD); return g->gimple_omp_atomic_load.rhs; } /* Return a pointer to the RHS of an atomic load. */ static inline tree * gimple_omp_atomic_load_rhs_ptr (gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_ATOMIC_LOAD); return &g->gimple_omp_atomic_load.rhs; } /* Get the definition of the control variable in a GIMPLE_OMP_CONTINUE. */ static inline tree gimple_omp_continue_control_def (const_gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_CONTINUE); return g->gimple_omp_continue.control_def; } /* The same as above, but return the address. */ static inline tree * gimple_omp_continue_control_def_ptr (gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_CONTINUE); return &g->gimple_omp_continue.control_def; } /* Set the definition of the control variable in a GIMPLE_OMP_CONTINUE. */ static inline void gimple_omp_continue_set_control_def (gimple g, tree def) { GIMPLE_CHECK (g, GIMPLE_OMP_CONTINUE); g->gimple_omp_continue.control_def = def; } /* Get the use of the control variable in a GIMPLE_OMP_CONTINUE. */ static inline tree gimple_omp_continue_control_use (const_gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_CONTINUE); return g->gimple_omp_continue.control_use; } /* The same as above, but return the address. */ static inline tree * gimple_omp_continue_control_use_ptr (gimple g) { GIMPLE_CHECK (g, GIMPLE_OMP_CONTINUE); return &g->gimple_omp_continue.control_use; } /* Set the use of the control variable in a GIMPLE_OMP_CONTINUE. */ static inline void gimple_omp_continue_set_control_use (gimple g, tree use) { GIMPLE_CHECK (g, GIMPLE_OMP_CONTINUE); g->gimple_omp_continue.control_use = use; } /* Return the body for the GIMPLE_TRANSACTION statement GS. */ static inline gimple_seq gimple_transaction_body (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_TRANSACTION); return gs->gimple_transaction.body; } /* Return the label associated with a GIMPLE_TRANSACTION. */ static inline tree gimple_transaction_label (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_TRANSACTION); return gs->gimple_transaction.label; } static inline tree * gimple_transaction_label_ptr (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_TRANSACTION); return &gs->gimple_transaction.label; } /* Return the subcode associated with a GIMPLE_TRANSACTION. */ static inline unsigned int gimple_transaction_subcode (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_TRANSACTION); return gs->gsbase.subcode; } /* Set BODY to be the body for the GIMPLE_TRANSACTION statement GS. */ static inline void gimple_transaction_set_body (gimple gs, gimple_seq body) { GIMPLE_CHECK (gs, GIMPLE_TRANSACTION); gs->gimple_transaction.body = body; } /* Set the label associated with a GIMPLE_TRANSACTION. */ static inline void gimple_transaction_set_label (gimple gs, tree label) { GIMPLE_CHECK (gs, GIMPLE_TRANSACTION); gs->gimple_transaction.label = label; } /* Set the subcode associated with a GIMPLE_TRANSACTION. */ static inline void gimple_transaction_set_subcode (gimple gs, unsigned int subcode) { GIMPLE_CHECK (gs, GIMPLE_TRANSACTION); gs->gsbase.subcode = subcode; } /* Return a pointer to the return value for GIMPLE_RETURN GS. */ static inline tree * gimple_return_retval_ptr (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_RETURN); return gimple_op_ptr (gs, 0); } /* Return the return value for GIMPLE_RETURN GS. */ static inline tree gimple_return_retval (const_gimple gs) { GIMPLE_CHECK (gs, GIMPLE_RETURN); return gimple_op (gs, 0); } /* Set RETVAL to be the return value for GIMPLE_RETURN GS. */ static inline void gimple_return_set_retval (gimple gs, tree retval) { GIMPLE_CHECK (gs, GIMPLE_RETURN); gimple_set_op (gs, 0, retval); } /* Returns true when the gimple statment STMT is any of the OpenMP types. */ #define CASE_GIMPLE_OMP \ case GIMPLE_OMP_PARALLEL: \ case GIMPLE_OMP_TASK: \ case GIMPLE_OMP_FOR: \ case GIMPLE_OMP_SECTIONS: \ case GIMPLE_OMP_SECTIONS_SWITCH: \ case GIMPLE_OMP_SINGLE: \ case GIMPLE_OMP_SECTION: \ case GIMPLE_OMP_MASTER: \ case GIMPLE_OMP_ORDERED: \ case GIMPLE_OMP_CRITICAL: \ case GIMPLE_OMP_RETURN: \ case GIMPLE_OMP_ATOMIC_LOAD: \ case GIMPLE_OMP_ATOMIC_STORE: \ case GIMPLE_OMP_CONTINUE static inline bool is_gimple_omp (const_gimple stmt) { switch (gimple_code (stmt)) { CASE_GIMPLE_OMP: return true; default: return false; } } /* Returns TRUE if statement G is a GIMPLE_NOP. */ static inline bool gimple_nop_p (const_gimple g) { return gimple_code (g) == GIMPLE_NOP; } /* Return true if GS is a GIMPLE_RESX. */ static inline bool is_gimple_resx (const_gimple gs) { return gimple_code (gs) == GIMPLE_RESX; } /* Return the predictor of GIMPLE_PREDICT statement GS. */ static inline enum br_predictor gimple_predict_predictor (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_PREDICT); return (enum br_predictor) (gs->gsbase.subcode & ~GF_PREDICT_TAKEN); } /* Set the predictor of GIMPLE_PREDICT statement GS to PREDICT. */ static inline void gimple_predict_set_predictor (gimple gs, enum br_predictor predictor) { GIMPLE_CHECK (gs, GIMPLE_PREDICT); gs->gsbase.subcode = (gs->gsbase.subcode & GF_PREDICT_TAKEN) | (unsigned) predictor; } /* Return the outcome of GIMPLE_PREDICT statement GS. */ static inline enum prediction gimple_predict_outcome (gimple gs) { GIMPLE_CHECK (gs, GIMPLE_PREDICT); return (gs->gsbase.subcode & GF_PREDICT_TAKEN) ? TAKEN : NOT_TAKEN; } /* Set the outcome of GIMPLE_PREDICT statement GS to OUTCOME. */ static inline void gimple_predict_set_outcome (gimple gs, enum prediction outcome) { GIMPLE_CHECK (gs, GIMPLE_PREDICT); if (outcome == TAKEN) gs->gsbase.subcode |= GF_PREDICT_TAKEN; else gs->gsbase.subcode &= ~GF_PREDICT_TAKEN; } /* Return the type of the main expression computed by STMT. Return void_type_node if the statement computes nothing. */ static inline tree gimple_expr_type (const_gimple stmt) { enum gimple_code code = gimple_code (stmt); if (code == GIMPLE_ASSIGN || code == GIMPLE_CALL) { tree type; /* In general we want to pass out a type that can be substituted for both the RHS and the LHS types if there is a possibly useless conversion involved. That means returning the original RHS type as far as we can reconstruct it. */ if (code == GIMPLE_CALL) type = gimple_call_return_type (stmt); else switch (gimple_assign_rhs_code (stmt)) { case POINTER_PLUS_EXPR: type = TREE_TYPE (gimple_assign_rhs1 (stmt)); break; default: /* As fallback use the type of the LHS. */ type = TREE_TYPE (gimple_get_lhs (stmt)); break; } return type; } else if (code == GIMPLE_COND) return boolean_type_node; else return void_type_node; } /* Return true if TYPE is a suitable type for a scalar register variable. */ static inline bool is_gimple_reg_type (tree type) { return !AGGREGATE_TYPE_P (type); } /* Return a new iterator pointing to GIMPLE_SEQ's first statement. */ static inline gimple_stmt_iterator gsi_start (gimple_seq seq) { gimple_stmt_iterator i; i.ptr = gimple_seq_first (seq); i.seq = seq; i.bb = (i.ptr && i.ptr->stmt) ? gimple_bb (i.ptr->stmt) : NULL; return i; } /* Return a new iterator pointing to the first statement in basic block BB. */ static inline gimple_stmt_iterator gsi_start_bb (basic_block bb) { gimple_stmt_iterator i; gimple_seq seq; seq = bb_seq (bb); i.ptr = gimple_seq_first (seq); i.seq = seq; i.bb = bb; return i; } /* Return a new iterator initially pointing to GIMPLE_SEQ's last statement. */ static inline gimple_stmt_iterator gsi_last (gimple_seq seq) { gimple_stmt_iterator i; i.ptr = gimple_seq_last (seq); i.seq = seq; i.bb = (i.ptr && i.ptr->stmt) ? gimple_bb (i.ptr->stmt) : NULL; return i; } /* Return a new iterator pointing to the last statement in basic block BB. */ static inline gimple_stmt_iterator gsi_last_bb (basic_block bb) { gimple_stmt_iterator i; gimple_seq seq; seq = bb_seq (bb); i.ptr = gimple_seq_last (seq); i.seq = seq; i.bb = bb; return i; } /* Return true if I is at the end of its sequence. */ static inline bool gsi_end_p (gimple_stmt_iterator i) { return i.ptr == NULL; } /* Return true if I is one statement before the end of its sequence. */ static inline bool gsi_one_before_end_p (gimple_stmt_iterator i) { return i.ptr != NULL && i.ptr->next == NULL; } /* Advance the iterator to the next gimple statement. */ static inline void gsi_next (gimple_stmt_iterator *i) { i->ptr = i->ptr->next; } /* Advance the iterator to the previous gimple statement. */ static inline void gsi_prev (gimple_stmt_iterator *i) { i->ptr = i->ptr->prev; } /* Return the current stmt. */ static inline gimple gsi_stmt (gimple_stmt_iterator i) { return i.ptr->stmt; } /* Return a block statement iterator that points to the first non-label statement in block BB. */ static inline gimple_stmt_iterator gsi_after_labels (basic_block bb) { gimple_stmt_iterator gsi = gsi_start_bb (bb); while (!gsi_end_p (gsi) && gimple_code (gsi_stmt (gsi)) == GIMPLE_LABEL) gsi_next (&gsi); return gsi; } /* Advance the iterator to the next non-debug gimple statement. */ static inline void gsi_next_nondebug (gimple_stmt_iterator *i) { do { gsi_next (i); } while (!gsi_end_p (*i) && is_gimple_debug (gsi_stmt (*i))); } /* Advance the iterator to the next non-debug gimple statement. */ static inline void gsi_prev_nondebug (gimple_stmt_iterator *i) { do { gsi_prev (i); } while (!gsi_end_p (*i) && is_gimple_debug (gsi_stmt (*i))); } /* Return a new iterator pointing to the first non-debug statement in basic block BB. */ static inline gimple_stmt_iterator gsi_start_nondebug_bb (basic_block bb) { gimple_stmt_iterator i = gsi_start_bb (bb); if (!gsi_end_p (i) && is_gimple_debug (gsi_stmt (i))) gsi_next_nondebug (&i); return i; } /* Return a new iterator pointing to the last non-debug statement in basic block BB. */ static inline gimple_stmt_iterator gsi_last_nondebug_bb (basic_block bb) { gimple_stmt_iterator i = gsi_last_bb (bb); if (!gsi_end_p (i) && is_gimple_debug (gsi_stmt (i))) gsi_prev_nondebug (&i); return i; } /* Return a pointer to the current stmt. NOTE: You may want to use gsi_replace on the iterator itself, as this performs additional bookkeeping that will not be done if you simply assign through a pointer returned by gsi_stmt_ptr. */ static inline gimple * gsi_stmt_ptr (gimple_stmt_iterator *i) { return &i->ptr->stmt; } /* Return the basic block associated with this iterator. */ static inline basic_block gsi_bb (gimple_stmt_iterator i) { return i.bb; } /* Return the sequence associated with this iterator. */ static inline gimple_seq gsi_seq (gimple_stmt_iterator i) { return i.seq; } enum gsi_iterator_update { GSI_NEW_STMT, /* Only valid when single statement is added, move iterator to it. */ GSI_SAME_STMT, /* Leave the iterator at the same statement. */ GSI_CONTINUE_LINKING /* Move iterator to whatever position is suitable for linking other statements in the same direction. */ }; /* In gimple-iterator.c */ gimple_stmt_iterator gsi_start_phis (basic_block); gimple_seq gsi_split_seq_after (gimple_stmt_iterator); gimple_seq gsi_split_seq_before (gimple_stmt_iterator *); void gsi_replace (gimple_stmt_iterator *, gimple, bool); void gsi_insert_before (gimple_stmt_iterator *, gimple, enum gsi_iterator_update); void gsi_insert_before_without_update (gimple_stmt_iterator *, gimple, enum gsi_iterator_update); void gsi_insert_seq_before (gimple_stmt_iterator *, gimple_seq, enum gsi_iterator_update); void gsi_insert_seq_before_without_update (gimple_stmt_iterator *, gimple_seq, enum gsi_iterator_update); void gsi_insert_after (gimple_stmt_iterator *, gimple, enum gsi_iterator_update); void gsi_insert_after_without_update (gimple_stmt_iterator *, gimple, enum gsi_iterator_update); void gsi_insert_seq_after (gimple_stmt_iterator *, gimple_seq, enum gsi_iterator_update); void gsi_insert_seq_after_without_update (gimple_stmt_iterator *, gimple_seq, enum gsi_iterator_update); void gsi_remove (gimple_stmt_iterator *, bool); gimple_stmt_iterator gsi_for_stmt (gimple); void gsi_move_after (gimple_stmt_iterator *, gimple_stmt_iterator *); void gsi_move_before (gimple_stmt_iterator *, gimple_stmt_iterator *); void gsi_move_to_bb_end (gimple_stmt_iterator *, struct basic_block_def *); void gsi_insert_on_edge (edge, gimple); void gsi_insert_seq_on_edge (edge, gimple_seq); basic_block gsi_insert_on_edge_immediate (edge, gimple); basic_block gsi_insert_seq_on_edge_immediate (edge, gimple_seq); void gsi_commit_one_edge_insert (edge, basic_block *); void gsi_commit_edge_inserts (void); gimple gimple_call_copy_skip_args (gimple, bitmap); /* Convenience routines to walk all statements of a gimple function. Note that this is useful exclusively before the code is converted into SSA form. Once the program is in SSA form, the standard operand interface should be used to analyze/modify statements. */ struct walk_stmt_info { /* Points to the current statement being walked. */ gimple_stmt_iterator gsi; /* Additional data that the callback functions may want to carry through the recursion. */ void *info; /* Pointer map used to mark visited tree nodes when calling walk_tree on each operand. If set to NULL, duplicate tree nodes will be visited more than once. */ struct pointer_set_t *pset; /* Operand returned by the callbacks. This is set when calling walk_gimple_seq. If the walk_stmt_fn or walk_tree_fn callback returns non-NULL, this field will contain the tree returned by the last callback. */ tree callback_result; /* Indicates whether the operand being examined may be replaced with something that matches is_gimple_val (if true) or something slightly more complicated (if false). "Something" technically means the common subset of is_gimple_lvalue and is_gimple_rhs, but we never try to form anything more complicated than that, so we don't bother checking. Also note that CALLBACK should update this flag while walking the sub-expressions of a statement. For instance, when walking the statement 'foo (&var)', the flag VAL_ONLY will initially be set to true, however, when walking &var, the operand of that ADDR_EXPR does not need to be a GIMPLE value. */ BOOL_BITFIELD val_only : 1; /* True if we are currently walking the LHS of an assignment. */ BOOL_BITFIELD is_lhs : 1; /* Optional. Set to true by the callback functions if they made any changes. */ BOOL_BITFIELD changed : 1; /* True if we're interested in location information. */ BOOL_BITFIELD want_locations : 1; /* True if we've removed the statement that was processed. */ BOOL_BITFIELD removed_stmt : 1; }; /* Callback for walk_gimple_stmt. Called for every statement found during traversal. The first argument points to the statement to walk. The second argument is a flag that the callback sets to 'true' if it the callback handled all the operands and sub-statements of the statement (the default value of this flag is 'false'). The third argument is an anonymous pointer to data to be used by the callback. */ typedef tree (*walk_stmt_fn) (gimple_stmt_iterator *, bool *, struct walk_stmt_info *); gimple walk_gimple_seq (gimple_seq, walk_stmt_fn, walk_tree_fn, struct walk_stmt_info *); tree walk_gimple_stmt (gimple_stmt_iterator *, walk_stmt_fn, walk_tree_fn, struct walk_stmt_info *); tree walk_gimple_op (gimple, walk_tree_fn, struct walk_stmt_info *); #ifdef GATHER_STATISTICS /* Enum and arrays used for allocation stats. Keep in sync with gimple.c:gimple_alloc_kind_names. */ enum gimple_alloc_kind { gimple_alloc_kind_assign, /* Assignments. */ gimple_alloc_kind_phi, /* PHI nodes. */ gimple_alloc_kind_cond, /* Conditionals. */ gimple_alloc_kind_seq, /* Sequences. */ gimple_alloc_kind_rest, /* Everything else. */ gimple_alloc_kind_all }; extern int gimple_alloc_counts[]; extern int gimple_alloc_sizes[]; /* Return the allocation kind for a given stmt CODE. */ static inline enum gimple_alloc_kind gimple_alloc_kind (enum gimple_code code) { switch (code) { case GIMPLE_ASSIGN: return gimple_alloc_kind_assign; case GIMPLE_PHI: return gimple_alloc_kind_phi; case GIMPLE_COND: return gimple_alloc_kind_cond; default: return gimple_alloc_kind_rest; } } #endif /* GATHER_STATISTICS */ extern void dump_gimple_statistics (void); /* In gimple-fold.c. */ void gimplify_and_update_call_from_tree (gimple_stmt_iterator *, tree); tree gimple_fold_builtin (gimple); bool fold_stmt (gimple_stmt_iterator *); bool fold_stmt_inplace (gimple_stmt_iterator *); tree get_symbol_constant_value (tree); tree canonicalize_constructor_val (tree); extern tree maybe_fold_and_comparisons (enum tree_code, tree, tree, enum tree_code, tree, tree); extern tree maybe_fold_or_comparisons (enum tree_code, tree, tree, enum tree_code, tree, tree); bool gimple_val_nonnegative_real_p (tree); #endif /* GCC_GIMPLE_H */
convolutiondepthwise_3x3_packn_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convdw3x3s1_packn_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const __fp16* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); vfloat16m1_t _bias0 = bias ? vle16_v_f16m1(bias + g * packn, vl) : vfmv_v_f_f16m1((__fp16)0.f, vl); const __fp16* k0 = kernel.row<const __fp16>(g); __fp16* outptr0 = out.row<__fp16>(0); __fp16* outptr1 = out.row<__fp16>(1); const Mat img0 = bottom_blob.channel(g); const __fp16* r0 = img0.row<const __fp16>(0); const __fp16* r1 = img0.row<const __fp16>(1); const __fp16* r2 = img0.row<const __fp16>(2); const __fp16* r3 = img0.row<const __fp16>(3); vfloat16m1_t _k00 = vle16_v_f16m1(k0, vl); vfloat16m1_t _k01 = vle16_v_f16m1(k0 + packn, vl); vfloat16m1_t _k02 = vle16_v_f16m1(k0 + packn * 2, vl); vfloat16m1_t _k10 = vle16_v_f16m1(k0 + packn * 3, vl); vfloat16m1_t _k11 = vle16_v_f16m1(k0 + packn * 4, vl); vfloat16m1_t _k12 = vle16_v_f16m1(k0 + packn * 5, vl); vfloat16m1_t _k20 = vle16_v_f16m1(k0 + packn * 6, vl); vfloat16m1_t _k21 = vle16_v_f16m1(k0 + packn * 7, vl); vfloat16m1_t _k22 = vle16_v_f16m1(k0 + packn * 8, vl); int i = 0; for (; i + 1 < outh; i += 2) { int j = 0; for (; j + 1 < outw; j += 2) { vfloat16m1_t _sum00 = _bias0; vfloat16m1_t _sum01 = _bias0; vfloat16m1_t _sum10 = _bias0; vfloat16m1_t _sum11 = _bias0; vfloat16m1_t _r00 = vle16_v_f16m1(r0, vl); vfloat16m1_t _r01 = vle16_v_f16m1(r0 + packn, vl); vfloat16m1_t _r02 = vle16_v_f16m1(r0 + packn * 2, vl); vfloat16m1_t _r03 = vle16_v_f16m1(r0 + packn * 3, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k00, _r00, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k01, _r01, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k02, _r02, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k00, _r01, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k01, _r02, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k02, _r03, vl); vfloat16m1_t _r10 = vle16_v_f16m1(r1, vl); vfloat16m1_t _r11 = vle16_v_f16m1(r1 + packn, vl); vfloat16m1_t _r12 = vle16_v_f16m1(r1 + packn * 2, vl); vfloat16m1_t _r13 = vle16_v_f16m1(r1 + packn * 3, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k10, _r10, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k11, _r11, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k12, _r12, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k10, _r11, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k11, _r12, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k12, _r13, vl); _sum10 = vfmacc_vv_f16m1(_sum10, _k00, _r10, vl); _sum10 = vfmacc_vv_f16m1(_sum10, _k01, _r11, vl); _sum10 = vfmacc_vv_f16m1(_sum10, _k02, _r12, vl); _sum11 = vfmacc_vv_f16m1(_sum11, _k00, _r11, vl); _sum11 = vfmacc_vv_f16m1(_sum11, _k01, _r12, vl); _sum11 = vfmacc_vv_f16m1(_sum11, _k02, _r13, vl); vfloat16m1_t _r20 = vle16_v_f16m1(r2, vl); vfloat16m1_t _r21 = vle16_v_f16m1(r2 + packn, vl); vfloat16m1_t _r22 = vle16_v_f16m1(r2 + packn * 2, vl); vfloat16m1_t _r23 = vle16_v_f16m1(r2 + packn * 3, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k20, _r20, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k21, _r21, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k22, _r22, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k20, _r21, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k21, _r22, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k22, _r23, vl); _sum10 = vfmacc_vv_f16m1(_sum10, _k10, _r20, vl); _sum10 = vfmacc_vv_f16m1(_sum10, _k11, _r21, vl); _sum10 = vfmacc_vv_f16m1(_sum10, _k12, _r22, vl); _sum11 = vfmacc_vv_f16m1(_sum11, _k10, _r21, vl); _sum11 = vfmacc_vv_f16m1(_sum11, _k11, _r22, vl); _sum11 = vfmacc_vv_f16m1(_sum11, _k12, _r23, vl); vfloat16m1_t _r30 = vle16_v_f16m1(r3, vl); vfloat16m1_t _r31 = vle16_v_f16m1(r3 + packn, vl); vfloat16m1_t _r32 = vle16_v_f16m1(r3 + packn * 2, vl); vfloat16m1_t _r33 = vle16_v_f16m1(r3 + packn * 3, vl); _sum10 = vfmacc_vv_f16m1(_sum10, _k20, _r30, vl); _sum10 = vfmacc_vv_f16m1(_sum10, _k21, _r31, vl); _sum10 = vfmacc_vv_f16m1(_sum10, _k22, _r32, vl); _sum11 = vfmacc_vv_f16m1(_sum11, _k20, _r31, vl); _sum11 = vfmacc_vv_f16m1(_sum11, _k21, _r32, vl); _sum11 = vfmacc_vv_f16m1(_sum11, _k22, _r33, vl); vse16_v_f16m1(outptr0, _sum00, vl); vse16_v_f16m1(outptr0 + packn, _sum01, vl); vse16_v_f16m1(outptr1, _sum10, vl); vse16_v_f16m1(outptr1 + packn, _sum11, vl); outptr0 += packn * 2; outptr1 += packn * 2; r0 += packn * 2; r1 += packn * 2; r2 += packn * 2; r3 += packn * 2; } for (; j < outw; j++) { vfloat16m1_t _sum0 = _bias0; vfloat16m1_t _sum1 = _bias0; vfloat16m1_t _r00 = vle16_v_f16m1(r0, vl); vfloat16m1_t _r01 = vle16_v_f16m1(r0 + packn, vl); vfloat16m1_t _r02 = vle16_v_f16m1(r0 + packn * 2, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k00, _r00, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k01, _r01, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k02, _r02, vl); vfloat16m1_t _r10 = vle16_v_f16m1(r1, vl); vfloat16m1_t _r11 = vle16_v_f16m1(r1 + packn, vl); vfloat16m1_t _r12 = vle16_v_f16m1(r1 + packn * 2, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k10, _r10, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k11, _r11, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k12, _r12, vl); _sum1 = vfmacc_vv_f16m1(_sum1, _k00, _r10, vl); _sum1 = vfmacc_vv_f16m1(_sum1, _k01, _r11, vl); _sum1 = vfmacc_vv_f16m1(_sum1, _k02, _r12, vl); vfloat16m1_t _r20 = vle16_v_f16m1(r2, vl); vfloat16m1_t _r21 = vle16_v_f16m1(r2 + packn, vl); vfloat16m1_t _r22 = vle16_v_f16m1(r2 + packn * 2, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k20, _r20, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k21, _r21, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k22, _r22, vl); _sum1 = vfmacc_vv_f16m1(_sum1, _k10, _r20, vl); _sum1 = vfmacc_vv_f16m1(_sum1, _k11, _r21, vl); _sum1 = vfmacc_vv_f16m1(_sum1, _k12, _r22, vl); vfloat16m1_t _r30 = vle16_v_f16m1(r3, vl); vfloat16m1_t _r31 = vle16_v_f16m1(r3 + packn, vl); vfloat16m1_t _r32 = vle16_v_f16m1(r3 + packn * 2, vl); _sum1 = vfmacc_vv_f16m1(_sum1, _k20, _r30, vl); _sum1 = vfmacc_vv_f16m1(_sum1, _k21, _r31, vl); _sum1 = vfmacc_vv_f16m1(_sum1, _k22, _r32, vl); vse16_v_f16m1(outptr0, _sum0, vl); vse16_v_f16m1(outptr1, _sum1, vl); outptr0 += packn; outptr1 += packn; r0 += packn; r1 += packn; r2 += packn; r3 += packn; } r0 += 2 * packn + w * packn; r1 += 2 * packn + w * packn; r2 += 2 * packn + w * packn; r3 += 2 * packn + w * packn; outptr0 += outw * packn; outptr1 += outw * packn; } for (; i < outh; i++) { int j = 0; for (; j + 1 < outw; j += 2) { vfloat16m1_t _sum00 = _bias0; vfloat16m1_t _sum01 = _bias0; vfloat16m1_t _r00 = vle16_v_f16m1(r0, vl); vfloat16m1_t _r01 = vle16_v_f16m1(r0 + packn, vl); vfloat16m1_t _r02 = vle16_v_f16m1(r0 + packn * 2, vl); vfloat16m1_t _r03 = vle16_v_f16m1(r0 + packn * 3, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k00, _r00, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k01, _r01, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k02, _r02, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k00, _r01, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k01, _r02, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k02, _r03, vl); vfloat16m1_t _r10 = vle16_v_f16m1(r1, vl); vfloat16m1_t _r11 = vle16_v_f16m1(r1 + packn, vl); vfloat16m1_t _r12 = vle16_v_f16m1(r1 + packn * 2, vl); vfloat16m1_t _r13 = vle16_v_f16m1(r1 + packn * 3, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k10, _r10, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k11, _r11, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k12, _r12, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k10, _r11, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k11, _r12, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k12, _r13, vl); vfloat16m1_t _r20 = vle16_v_f16m1(r2, vl); vfloat16m1_t _r21 = vle16_v_f16m1(r2 + packn, vl); vfloat16m1_t _r22 = vle16_v_f16m1(r2 + packn * 2, vl); vfloat16m1_t _r23 = vle16_v_f16m1(r2 + packn * 3, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k20, _r20, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k21, _r21, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k22, _r22, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k20, _r21, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k21, _r22, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k22, _r23, vl); vse16_v_f16m1(outptr0, _sum00, vl); vse16_v_f16m1(outptr0 + packn, _sum01, vl); outptr0 += packn * 2; r0 += packn * 2; r1 += packn * 2; r2 += packn * 2; } for (; j < outw; j++) { vfloat16m1_t _sum0 = _bias0; vfloat16m1_t _r00 = vle16_v_f16m1(r0, vl); vfloat16m1_t _r01 = vle16_v_f16m1(r0 + packn, vl); vfloat16m1_t _r02 = vle16_v_f16m1(r0 + packn * 2, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k00, _r00, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k01, _r01, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k02, _r02, vl); vfloat16m1_t _r10 = vle16_v_f16m1(r1, vl); vfloat16m1_t _r11 = vle16_v_f16m1(r1 + packn, vl); vfloat16m1_t _r12 = vle16_v_f16m1(r1 + packn * 2, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k10, _r10, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k11, _r11, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k12, _r12, vl); vfloat16m1_t _r20 = vle16_v_f16m1(r2, vl); vfloat16m1_t _r21 = vle16_v_f16m1(r2 + packn, vl); vfloat16m1_t _r22 = vle16_v_f16m1(r2 + packn * 2, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k20, _r20, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k21, _r21, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k22, _r22, vl); vse16_v_f16m1(outptr0, _sum0, vl); outptr0 += packn; r0 += packn; r1 += packn; r2 += packn; } r0 += 2 * packn; r1 += 2 * packn; r2 += 2 * packn; } } } static void convdw3x3s2_packn_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const int tailstep = (w - 2 * outw + w) * packn; const __fp16* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); vfloat16m1_t _bias0 = bias ? vle16_v_f16m1(bias + g * packn, vl) : vfmv_v_f_f16m1((__fp16)0.f, vl); const __fp16* k0 = kernel.row<const __fp16>(g); __fp16* outptr0 = out; const Mat img0 = bottom_blob.channel(g); const __fp16* r0 = img0.row<const __fp16>(0); const __fp16* r1 = img0.row<const __fp16>(1); const __fp16* r2 = img0.row<const __fp16>(2); vfloat16m1_t _k00 = vle16_v_f16m1(k0, vl); vfloat16m1_t _k01 = vle16_v_f16m1(k0 + packn, vl); vfloat16m1_t _k02 = vle16_v_f16m1(k0 + packn * 2, vl); vfloat16m1_t _k10 = vle16_v_f16m1(k0 + packn * 3, vl); vfloat16m1_t _k11 = vle16_v_f16m1(k0 + packn * 4, vl); vfloat16m1_t _k12 = vle16_v_f16m1(k0 + packn * 5, vl); vfloat16m1_t _k20 = vle16_v_f16m1(k0 + packn * 6, vl); vfloat16m1_t _k21 = vle16_v_f16m1(k0 + packn * 7, vl); vfloat16m1_t _k22 = vle16_v_f16m1(k0 + packn * 8, vl); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 1 < outw; j += 2) { vfloat16m1_t _sum00 = _bias0; vfloat16m1_t _sum01 = _bias0; vfloat16m1_t _r00 = vle16_v_f16m1(r0, vl); vfloat16m1_t _r01 = vle16_v_f16m1(r0 + packn, vl); vfloat16m1_t _r02 = vle16_v_f16m1(r0 + packn * 2, vl); vfloat16m1_t _r03 = vle16_v_f16m1(r0 + packn * 3, vl); vfloat16m1_t _r04 = vle16_v_f16m1(r0 + packn * 4, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k00, _r00, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k01, _r01, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k02, _r02, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k00, _r02, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k01, _r03, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k02, _r04, vl); vfloat16m1_t _r10 = vle16_v_f16m1(r1, vl); vfloat16m1_t _r11 = vle16_v_f16m1(r1 + packn, vl); vfloat16m1_t _r12 = vle16_v_f16m1(r1 + packn * 2, vl); vfloat16m1_t _r13 = vle16_v_f16m1(r1 + packn * 3, vl); vfloat16m1_t _r14 = vle16_v_f16m1(r1 + packn * 4, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k10, _r10, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k11, _r11, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k12, _r12, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k10, _r12, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k11, _r13, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k12, _r14, vl); vfloat16m1_t _r20 = vle16_v_f16m1(r2, vl); vfloat16m1_t _r21 = vle16_v_f16m1(r2 + packn, vl); vfloat16m1_t _r22 = vle16_v_f16m1(r2 + packn * 2, vl); vfloat16m1_t _r23 = vle16_v_f16m1(r2 + packn * 3, vl); vfloat16m1_t _r24 = vle16_v_f16m1(r2 + packn * 4, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k20, _r20, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k21, _r21, vl); _sum00 = vfmacc_vv_f16m1(_sum00, _k22, _r22, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k20, _r22, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k21, _r23, vl); _sum01 = vfmacc_vv_f16m1(_sum01, _k22, _r24, vl); vse16_v_f16m1(outptr0, _sum00, vl); vse16_v_f16m1(outptr0 + packn, _sum01, vl); outptr0 += packn * 2; r0 += packn * 4; r1 += packn * 4; r2 += packn * 4; } for (; j < outw; j++) { vfloat16m1_t _sum0 = _bias0; vfloat16m1_t _r00 = vle16_v_f16m1(r0, vl); vfloat16m1_t _r01 = vle16_v_f16m1(r0 + packn, vl); vfloat16m1_t _r02 = vle16_v_f16m1(r0 + packn * 2, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k00, _r00, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k01, _r01, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k02, _r02, vl); vfloat16m1_t _r10 = vle16_v_f16m1(r1, vl); vfloat16m1_t _r11 = vle16_v_f16m1(r1 + packn, vl); vfloat16m1_t _r12 = vle16_v_f16m1(r1 + packn * 2, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k10, _r10, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k11, _r11, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k12, _r12, vl); vfloat16m1_t _r20 = vle16_v_f16m1(r2, vl); vfloat16m1_t _r21 = vle16_v_f16m1(r2 + packn, vl); vfloat16m1_t _r22 = vle16_v_f16m1(r2 + packn * 2, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k20, _r20, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k21, _r21, vl); _sum0 = vfmacc_vv_f16m1(_sum0, _k22, _r22, vl); vse16_v_f16m1(outptr0, _sum0, vl); outptr0 += packn; r0 += packn * 2; r1 += packn * 2; r2 += packn * 2; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } }
missing.c
#include <stdio.h> #include <stdlib.h> #include "grb2.h" #include "wgrib2.h" /* * Public domain: w. ebisuzaki * number of missing data points as determined by bitmap * * v1.1: just faster my dear * v1.2: just faster my dear * v1.3: just faster my dear * */ static unsigned int bitsum[256] = { 8, 7, 7, 6, 7, 6, 6, 5, 7, 6, 6, 5, 6, 5, 5, 4, 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, 4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0}; unsigned int missing_points(unsigned char *bitmap, unsigned int n) { unsigned int count, i, j, rem; if (bitmap == NULL) return 0; /* count = 0; while (n >= 8) { tmp = *bitmap++; n -= 8; count += bitsum[tmp]; } tmp = *bitmap | ((1 << (8 - n)) - 1); count += bitsum[tmp]; */ j = n >> 3; rem = n & 7; count = 0; #pragma omp parallel for private(i) reduction(+:count) for (i = 0; i < j; i++) { count += bitsum[bitmap[i]]; } count += rem ? bitsum[bitmap[j] | ((1 << (8 - rem)) - 1)] : 0; return count; }
collision.c
/* * $Id: collision.c 40659 2011-09-28 15:22:13Z mont29 $ * * ***** BEGIN GPL LICENSE BLOCK ***** * * 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. * * The Original Code is Copyright (C) Blender Foundation * All rights reserved. * * The Original Code is: all of this file. * * Contributor(s): none yet. * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/blenkernel/intern/collision.c * \ingroup bke */ #include "MEM_guardedalloc.h" #include "BKE_cloth.h" #include "DNA_cloth_types.h" #include "DNA_group_types.h" #include "DNA_mesh_types.h" #include "DNA_object_types.h" #include "DNA_object_force.h" #include "DNA_scene_types.h" #include "DNA_meshdata_types.h" #include "BLI_blenlib.h" #include "BLI_math.h" #include "BLI_edgehash.h" #include "BLI_utildefines.h" #include "BLI_ghash.h" #include "BLI_memarena.h" #include "BLI_rand.h" #include "BKE_DerivedMesh.h" #include "BKE_global.h" #include "BKE_scene.h" #include "BKE_mesh.h" #include "BKE_object.h" #include "BKE_modifier.h" #include "BKE_DerivedMesh.h" #ifdef USE_BULLET #include "Bullet-C-Api.h" #endif #include "BLI_kdopbvh.h" #include "BKE_collision.h" #ifdef WITH_ELTOPO #include "eltopo-capi.h" #endif /*********************************** Collision modifier code start ***********************************/ /* step is limited from 0 (frame start position) to 1 (frame end position) */ void collision_move_object ( CollisionModifierData *collmd, float step, float prevstep ) { float tv[3] = {0, 0, 0}; unsigned int i = 0; for ( i = 0; i < collmd->numverts; i++ ) { VECSUB ( tv, collmd->xnew[i].co, collmd->x[i].co ); VECADDS ( collmd->current_x[i].co, collmd->x[i].co, tv, prevstep ); VECADDS ( collmd->current_xnew[i].co, collmd->x[i].co, tv, step ); VECSUB ( collmd->current_v[i].co, collmd->current_xnew[i].co, collmd->current_x[i].co ); } bvhtree_update_from_mvert ( collmd->bvhtree, collmd->mfaces, collmd->numfaces, collmd->current_x, collmd->current_xnew, collmd->numverts, 1 ); } BVHTree *bvhtree_build_from_mvert ( MFace *mfaces, unsigned int numfaces, MVert *x, unsigned int UNUSED(numverts), float epsilon ) { BVHTree *tree; float co[12]; unsigned int i; MFace *tface = mfaces; tree = BLI_bvhtree_new ( numfaces*2, epsilon, 4, 26 ); // fill tree for ( i = 0; i < numfaces; i++, tface++ ) { copy_v3_v3 ( &co[0*3], x[tface->v1].co ); copy_v3_v3 ( &co[1*3], x[tface->v2].co ); copy_v3_v3 ( &co[2*3], x[tface->v3].co ); if ( tface->v4 ) copy_v3_v3 ( &co[3*3], x[tface->v4].co ); BLI_bvhtree_insert ( tree, i, co, ( mfaces->v4 ? 4 : 3 ) ); } // balance tree BLI_bvhtree_balance ( tree ); return tree; } void bvhtree_update_from_mvert ( BVHTree * bvhtree, MFace *faces, int numfaces, MVert *x, MVert *xnew, int UNUSED(numverts), int moving ) { int i; MFace *mfaces = faces; float co[12], co_moving[12]; int ret = 0; if ( !bvhtree ) return; if ( x ) { for ( i = 0; i < numfaces; i++, mfaces++ ) { copy_v3_v3 ( &co[0*3], x[mfaces->v1].co ); copy_v3_v3 ( &co[1*3], x[mfaces->v2].co ); copy_v3_v3 ( &co[2*3], x[mfaces->v3].co ); if ( mfaces->v4 ) copy_v3_v3 ( &co[3*3], x[mfaces->v4].co ); // copy new locations into array if ( moving && xnew ) { // update moving positions copy_v3_v3 ( &co_moving[0*3], xnew[mfaces->v1].co ); copy_v3_v3 ( &co_moving[1*3], xnew[mfaces->v2].co ); copy_v3_v3 ( &co_moving[2*3], xnew[mfaces->v3].co ); if ( mfaces->v4 ) copy_v3_v3 ( &co_moving[3*3], xnew[mfaces->v4].co ); ret = BLI_bvhtree_update_node ( bvhtree, i, co, co_moving, ( mfaces->v4 ? 4 : 3 ) ); } else { ret = BLI_bvhtree_update_node ( bvhtree, i, co, NULL, ( mfaces->v4 ? 4 : 3 ) ); } // check if tree is already full if ( !ret ) break; } BLI_bvhtree_update_tree ( bvhtree ); } } /*********************************** Collision modifier code end ***********************************/ /** * gsl_poly_solve_cubic - * * copied from SOLVE_CUBIC.C --> GSL */ #define mySWAP(a,b) do { double tmp = b ; b = a ; a = tmp ; } while(0) #if 0 /* UNUSED */ static int gsl_poly_solve_cubic (double a, double b, double c, double *x0, double *x1, double *x2) { double q = (a * a - 3 * b); double r = (2 * a * a * a - 9 * a * b + 27 * c); double Q = q / 9; double R = r / 54; double Q3 = Q * Q * Q; double R2 = R * R; double CR2 = 729 * r * r; double CQ3 = 2916 * q * q * q; if (R == 0 && Q == 0) { *x0 = - a / 3 ; *x1 = - a / 3 ; *x2 = - a / 3 ; return 3 ; } else if (CR2 == CQ3) { /* this test is actually R2 == Q3, written in a form suitable for exact computation with integers */ /* Due to finite precision some double roots may be missed, and considered to be a pair of complex roots z = x +/- epsilon i close to the real axis. */ double sqrtQ = sqrt (Q); if (R > 0) { *x0 = -2 * sqrtQ - a / 3; *x1 = sqrtQ - a / 3; *x2 = sqrtQ - a / 3; } else { *x0 = - sqrtQ - a / 3; *x1 = - sqrtQ - a / 3; *x2 = 2 * sqrtQ - a / 3; } return 3 ; } else if (CR2 < CQ3) /* equivalent to R2 < Q3 */ { double sqrtQ = sqrt (Q); double sqrtQ3 = sqrtQ * sqrtQ * sqrtQ; double theta = acos (R / sqrtQ3); double norm = -2 * sqrtQ; *x0 = norm * cos (theta / 3) - a / 3; *x1 = norm * cos ((theta + 2.0 * M_PI) / 3) - a / 3; *x2 = norm * cos ((theta - 2.0 * M_PI) / 3) - a / 3; /* Sort *x0, *x1, *x2 into increasing order */ if (*x0 > *x1) mySWAP(*x0, *x1) ; if (*x1 > *x2) { mySWAP(*x1, *x2) ; if (*x0 > *x1) mySWAP(*x0, *x1) ; } return 3; } else { double sgnR = (R >= 0 ? 1 : -1); double A = -sgnR * pow (fabs (R) + sqrt (R2 - Q3), 1.0/3.0); double B = Q / A ; *x0 = A + B - a / 3; return 1; } } /** * gsl_poly_solve_quadratic * * copied from GSL */ static int gsl_poly_solve_quadratic (double a, double b, double c, double *x0, double *x1) { double disc = b * b - 4 * a * c; if (a == 0) /* Handle linear case */ { if (b == 0) { return 0; } else { *x0 = -c / b; return 1; }; } if (disc > 0) { if (b == 0) { double r = fabs (0.5 * sqrt (disc) / a); *x0 = -r; *x1 = r; } else { double sgnb = (b > 0 ? 1 : -1); double temp = -0.5 * (b + sgnb * sqrt (disc)); double r1 = temp / a ; double r2 = c / temp ; if (r1 < r2) { *x0 = r1 ; *x1 = r2 ; } else { *x0 = r2 ; *x1 = r1 ; } } return 2; } else if (disc == 0) { *x0 = -0.5 * b / a ; *x1 = -0.5 * b / a ; return 2 ; } else { return 0; } } #endif /* UNUSED */ /* * See Bridson et al. "Robust Treatment of Collision, Contact and Friction for Cloth Animation" * page 4, left column */ #if 0 static int cloth_get_collision_time ( double a[3], double b[3], double c[3], double d[3], double e[3], double f[3], double solution[3] ) { int num_sols = 0; // x^0 - checked double g = a[0] * c[1] * e[2] - a[0] * c[2] * e[1] + a[1] * c[2] * e[0] - a[1] * c[0] * e[2] + a[2] * c[0] * e[1] - a[2] * c[1] * e[0]; // x^1 double h = -b[2] * c[1] * e[0] + b[1] * c[2] * e[0] - a[2] * d[1] * e[0] + a[1] * d[2] * e[0] + b[2] * c[0] * e[1] - b[0] * c[2] * e[1] + a[2] * d[0] * e[1] - a[0] * d[2] * e[1] - b[1] * c[0] * e[2] + b[0] * c[1] * e[2] - a[1] * d[0] * e[2] + a[0] * d[1] * e[2] - a[2] * c[1] * f[0] + a[1] * c[2] * f[0] + a[2] * c[0] * f[1] - a[0] * c[2] * f[1] - a[1] * c[0] * f[2] + a[0] * c[1] * f[2]; // x^2 double i = -b[2] * d[1] * e[0] + b[1] * d[2] * e[0] + b[2] * d[0] * e[1] - b[0] * d[2] * e[1] - b[1] * d[0] * e[2] + b[0] * d[1] * e[2] - b[2] * c[1] * f[0] + b[1] * c[2] * f[0] - a[2] * d[1] * f[0] + a[1] * d[2] * f[0] + b[2] * c[0] * f[1] - b[0] * c[2] * f[1] + a[2] * d[0] * f[1] - a[0] * d[2] * f[1] - b[1] * c[0] * f[2] + b[0] * c[1] * f[2] - a[1] * d[0] * f[2] + a[0] * d[1] * f[2]; // x^3 - checked double j = -b[2] * d[1] * f[0] + b[1] * d[2] * f[0] + b[2] * d[0] * f[1] - b[0] * d[2] * f[1] - b[1] * d[0] * f[2] + b[0] * d[1] * f[2]; /* printf("r1: %lf\n", a[0] * c[1] * e[2] - a[0] * c[2] * e[1]); printf("r2: %lf\n", a[1] * c[2] * e[0] - a[1] * c[0] * e[2]); printf("r3: %lf\n", a[2] * c[0] * e[1] - a[2] * c[1] * e[0]); printf("x1 x: %f, y: %f, z: %f\n", a[0], a[1], a[2]); printf("x2 x: %f, y: %f, z: %f\n", c[0], c[1], c[2]); printf("x3 x: %f, y: %f, z: %f\n", e[0], e[1], e[2]); printf("v1 x: %f, y: %f, z: %f\n", b[0], b[1], b[2]); printf("v2 x: %f, y: %f, z: %f\n", d[0], d[1], d[2]); printf("v3 x: %f, y: %f, z: %f\n", f[0], f[1], f[2]); printf("t^3: %lf, t^2: %lf, t^1: %lf, t^0: %lf\n", j, i, h, g); */ // Solve cubic equation to determine times t1, t2, t3, when the collision will occur. if ( ABS ( j ) > DBL_EPSILON ) { i /= j; h /= j; g /= j; num_sols = gsl_poly_solve_cubic ( i, h, g, &solution[0], &solution[1], &solution[2] ); } else { num_sols = gsl_poly_solve_quadratic ( i, h, g, &solution[0], &solution[1] ); solution[2] = -1.0; } // printf("num_sols: %d, sol1: %lf, sol2: %lf, sol3: %lf\n", num_sols, solution[0], solution[1], solution[2]); // Discard negative solutions if ( ( num_sols >= 1 ) && ( solution[0] < DBL_EPSILON ) ) { --num_sols; solution[0] = solution[num_sols]; } if ( ( num_sols >= 2 ) && ( solution[1] < DBL_EPSILON ) ) { --num_sols; solution[1] = solution[num_sols]; } if ( ( num_sols == 3 ) && ( solution[2] < DBL_EPSILON ) ) { --num_sols; } // Sort if ( num_sols == 2 ) { if ( solution[0] > solution[1] ) { double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp; } } else if ( num_sols == 3 ) { // Bubblesort if ( solution[0] > solution[1] ) { double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp; } if ( solution[1] > solution[2] ) { double tmp = solution[1]; solution[1] = solution[2]; solution[2] = tmp; } if ( solution[0] > solution[1] ) { double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp; } } return num_sols; } #endif // w3 is not perfect static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 ) { double tempV1[3], tempV2[3], tempV4[3]; double a,b,c,d,e,f; VECSUB ( tempV1, p1, p3 ); VECSUB ( tempV2, p2, p3 ); VECSUB ( tempV4, pv, p3 ); a = INPR ( tempV1, tempV1 ); b = INPR ( tempV1, tempV2 ); c = INPR ( tempV2, tempV2 ); e = INPR ( tempV1, tempV4 ); f = INPR ( tempV2, tempV4 ); d = ( a * c - b * b ); if ( ABS ( d ) < ALMOST_ZERO ) { *w1 = *w2 = *w3 = 1.0 / 3.0; return; } w1[0] = ( float ) ( ( e * c - b * f ) / d ); if ( w1[0] < 0 ) w1[0] = 0; w2[0] = ( float ) ( ( f - b * ( double ) w1[0] ) / c ); if ( w2[0] < 0 ) w2[0] = 0; w3[0] = 1.0f - w1[0] - w2[0]; } DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 ) { to[0] = to[1] = to[2] = 0; VECADDMUL ( to, v1, w1 ); VECADDMUL ( to, v2, w2 ); VECADDMUL ( to, v3, w3 ); } #ifndef WITH_ELTOPO static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end ) { int result = 0; Cloth *cloth1; float w1, w2, w3, u1, u2, u3; float v1[3], v2[3], relativeVelocity[3]; float magrelVel; float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree ); cloth1 = clmd->clothObject; for ( ; collpair != collision_end; collpair++ ) { // only handle static collisions here if ( collpair->flag & COLLISION_IN_FUTURE ) continue; // compute barycentric coordinates for both collision points collision_compute_barycentric ( collpair->pa, cloth1->verts[collpair->ap1].txold, cloth1->verts[collpair->ap2].txold, cloth1->verts[collpair->ap3].txold, &w1, &w2, &w3 ); // was: txold collision_compute_barycentric ( collpair->pb, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, &u1, &u2, &u3 ); // Calculate relative "velocity". collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 ); collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 ); VECSUB ( relativeVelocity, v2, v1 ); // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal'). magrelVel = INPR ( relativeVelocity, collpair->normal ); // printf("magrelVel: %f\n", magrelVel); // Calculate masses of points. // TODO // If v_n_mag < 0 the edges are approaching each other. if ( magrelVel > ALMOST_ZERO ) { // Calculate Impulse magnitude to stop all motion in normal direction. float magtangent = 0, repulse = 0, d = 0; double impulse = 0.0; float vrel_t_pre[3]; float temp[3], spf; // calculate tangential velocity copy_v3_v3 ( temp, collpair->normal ); mul_v3_fl( temp, magrelVel ); VECSUB ( vrel_t_pre, relativeVelocity, temp ); // Decrease in magnitude of relative tangential velocity due to coulomb friction // in original formula "magrelVel" should be the "change of relative velocity in normal direction" magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) ); // Apply friction impulse. if ( magtangent > ALMOST_ZERO ) { normalize_v3( vrel_t_pre ); impulse = magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // 2.0 * VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse ); VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse ); VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse ); } // Apply velocity stopping impulse // I_c = m * v_N / 2.0 // no 2.0 * magrelVel normally, but looks nicer DG impulse = magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse ); cloth1->verts[collpair->ap1].impulse_count++; VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse ); cloth1->verts[collpair->ap2].impulse_count++; VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse ); cloth1->verts[collpair->ap3].impulse_count++; // Apply repulse impulse if distance too short // I_r = -min(dt*kd, m(0,1d/dt - v_n)) spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale; d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance; if ( ( magrelVel < 0.1*d*spf ) && ( d > ALMOST_ZERO ) ) { repulse = MIN2 ( d*1.0/spf, 0.1*d*spf - magrelVel ); // stay on the safe side and clamp repulse if ( impulse > ALMOST_ZERO ) repulse = MIN2 ( repulse, 5.0*impulse ); repulse = MAX2 ( impulse, repulse ); impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25 VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, impulse ); VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, impulse ); VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, impulse ); } result = 1; } } return result; } #endif /* !WITH_ELTOPO */ #ifdef WITH_ELTOPO typedef struct edgepairkey { int a1, a2, b1, b2; } edgepairkey; unsigned int edgepair_hash(void *vkey) { edgepairkey *key = vkey; int keys[4] = {key->a1, key->a2, key->b1, key->b2}; int i, j; for (i=0; i<4; i++) { for (j=0; j<3; j++) { if (keys[j] >= keys[j+1]) { SWAP(int, keys[j], keys[j+1]); } } } return keys[0]*101 + keys[1]*72 + keys[2]*53 + keys[3]*34; } int edgepair_cmp(const void *va, const void *vb) { edgepairkey *a = va, *b = vb; int keysa[4] = {a->a1, a->a2, a->b1, a->b2}; int keysb[4] = {b->a1, b->a2, b->b1, b->b2}; int i; for (i=0; i<4; i++) { int j, ok=0; for (j=0; j<4; j++) { if (keysa[i] == keysa[j]) { ok = 1; break; } } if (!ok) return -1; } return 0; } static void get_edgepairkey(edgepairkey *key, int a1, int a2, int b1, int b2) { key->a1 = a1; key->a2 = a2; key->b1 = b1; key->b2 = b2; } /*an immense amount of duplication goes on here. . .a major performance hit, I'm sure*/ static CollPair* cloth_edge_collision ( ModifierData *md1, ModifierData *md2, BVHTreeOverlap *overlap, CollPair *collpair, GHash *visithash, MemArena *arena) { ClothModifierData *clmd = ( ClothModifierData * ) md1; CollisionModifierData *collmd = ( CollisionModifierData * ) md2; MFace *face1=NULL, *face2 = NULL; ClothVertex *verts1 = clmd->clothObject->verts; double distance = 0; edgepairkey *key, tstkey; float epsilon1 = clmd->coll_parms->epsilon; float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree ); float no[3], uv[3], t, relnor; int i, i1, i2, i3, i4, i5, i6; Cloth *cloth = clmd->clothObject; float n1[3], n2[3], off[3], v1[2][3], v2[2][3], v3[2][3], v4[2][3], v5[2][3], v6[2][3]; void **verts[] = {v1, v2, v3, v4, v5, v6}; int j, ret, bp1, bp2, bp3, ap1, ap2, ap3, table[6]; face1 = & ( clmd->clothObject->mfaces[overlap->indexA] ); face2 = & ( collmd->mfaces[overlap->indexB] ); // check all 4 possible collisions for ( i = 0; i < 4; i++ ) { if ( i == 0 ) { // fill faceA ap1 = face1->v1; ap2 = face1->v2; ap3 = face1->v3; // fill faceB bp1 = face2->v1; bp2 = face2->v2; bp3 = face2->v3; } else if ( i == 1 ) { if ( face1->v4 ) { // fill faceA ap1 = face1->v1; ap2 = face1->v3; ap3 = face1->v4; // fill faceB bp1 = face2->v1; bp2 = face2->v2; bp3 = face2->v3; } else { continue; } } if ( i == 2 ) { if ( face2->v4 ) { // fill faceA ap1 = face1->v1; ap2 = face1->v2; ap3 = face1->v3; // fill faceB bp1 = face2->v1; bp2 = face2->v3; bp3 = face2->v4; } else { continue; } } else if ( i == 3 ) { if ( face1->v4 && face2->v4 ) { // fill faceA ap1 = face1->v1; ap2 = face1->v3; ap3 = face1->v4; // fill faceB bp1 = face2->v1; bp2 = face2->v3; bp3 = face2->v4; } else { continue; } } copy_v3_v3(v1[0], cloth->verts[ap1].txold); copy_v3_v3(v1[1], cloth->verts[ap1].tx); copy_v3_v3(v2[0], cloth->verts[ap2].txold); copy_v3_v3(v2[1], cloth->verts[ap2].tx); copy_v3_v3(v3[0], cloth->verts[ap3].txold); copy_v3_v3(v3[1], cloth->verts[ap3].tx); copy_v3_v3(v4[0], collmd->current_x[bp1].co); copy_v3_v3(v4[1], collmd->current_xnew[bp1].co); copy_v3_v3(v5[0], collmd->current_x[bp2].co); copy_v3_v3(v5[1], collmd->current_xnew[bp2].co); copy_v3_v3(v6[0], collmd->current_x[bp3].co); copy_v3_v3(v6[1], collmd->current_xnew[bp3].co); normal_tri_v3(n2, v4[1], v5[1], v6[1]); /*offset new positions a bit, to account for margins*/ i1 = ap1; i2 = ap2; i3 = ap3; i4 = bp1; i5 = bp2; i6 = bp3; for (j=0; j<3; j++) { int collp1, collp2, k, j2 = (j+1)%3; table[0] = ap1; table[1] = ap2; table[2] = ap3; table[3] = bp1; table[4] = bp2; table[5] = bp3; for (k=0; k<3; k++) { float p1[3], p2[3]; int k2 = (k+1)%3; get_edgepairkey(&tstkey, table[j], table[j2], table[k+3], table[k2+3]); //if (BLI_ghash_haskey(visithash, &tstkey)) // continue; key = BLI_memarena_alloc(arena, sizeof(edgepairkey)); *key = tstkey; BLI_ghash_insert(visithash, key, NULL); sub_v3_v3v3(p1, verts[j], verts[j2]); sub_v3_v3v3(p2, verts[k+3], verts[k2+3]); cross_v3_v3v3(off, p1, p2); normalize_v3(off); if (dot_v3v3(n2, off) < 0.0) negate_v3(off); mul_v3_fl(off, epsilon1 + epsilon2 + ALMOST_ZERO); copy_v3_v3(p1, verts[k+3]); copy_v3_v3(p2, verts[k2+3]); add_v3_v3(p1, off); add_v3_v3(p2, off); ret = eltopo_line_line_moving_isect_v3v3_f(verts[j], table[j], verts[j2], table[j2], p1, table[k+3], p2, table[k2+3], no, uv, &t, &relnor); /*cloth vert versus coll face*/ if (ret) { collpair->ap1 = table[j]; collpair->ap2 = table[j2]; collpair->bp1 = table[k+3]; collpair->bp2 = table[k2+3]; /*I'm not sure if this is correct, but hopefully it's better then simply ignoring back edges*/ if (dot_v3v3(n2, no) < 0.0) { negate_v3(no); } copy_v3_v3(collpair->normal, no); mul_v3_v3fl(collpair->vector, collpair->normal, relnor); collpair->distance = relnor; collpair->time = t; copy_v2_v2(collpair->bary, uv); collpair->flag = COLLISION_IS_EDGES; collpair++; } } } } return collpair; } static int cloth_edge_collision_response_moving ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end ) { int result = 0; Cloth *cloth1; float w1, w2; float v1[3], v2[3], relativeVelocity[3]; float magrelVel, pimpulse[3]; cloth1 = clmd->clothObject; for ( ; collpair != collision_end; collpair++ ) { if (!(collpair->flag & COLLISION_IS_EDGES)) continue; // was: txold w1 = collpair->bary[0]; w2 = collpair->bary[1]; // Calculate relative "velocity". VECADDFAC(v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, w1); VECADDFAC(v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, w2); VECSUB ( relativeVelocity, v2, v1); // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal'). magrelVel = INPR ( relativeVelocity, collpair->normal ); // If v_n_mag < 0 the edges are approaching each other. if ( magrelVel > ALMOST_ZERO ) { // Calculate Impulse magnitude to stop all motion in normal direction. float magtangent = 0, repulse = 0, d = 0; double impulse = 0.0; float vrel_t_pre[3]; float temp[3], spf; zero_v3(pimpulse); // calculate tangential velocity VECCOPY ( temp, collpair->normal ); mul_v3_fl( temp, magrelVel ); VECSUB ( vrel_t_pre, relativeVelocity, temp ); // Decrease in magnitude of relative tangential velocity due to coulomb friction // in original formula "magrelVel" should be the "change of relative velocity in normal direction" magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) ); // Apply friction impulse. if ( magtangent > ALMOST_ZERO ) { normalize_v3( vrel_t_pre ); impulse = magtangent; VECADDMUL ( pimpulse, vrel_t_pre, impulse); } // Apply velocity stopping impulse // I_c = m * v_N / 2.0 // no 2.0 * magrelVel normally, but looks nicer DG impulse = magrelVel; mul_v3_fl(collpair->normal, 0.5); VECADDMUL ( pimpulse, collpair->normal, impulse); // Apply repulse impulse if distance too short // I_r = -min(dt*kd, m(0,1d/dt - v_n)) spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale; d = collpair->distance; if ( ( magrelVel < 0.1*d*spf && ( d > ALMOST_ZERO ) ) ) { repulse = MIN2 ( d*1.0/spf, 0.1*d*spf - magrelVel ); // stay on the safe side and clamp repulse if ( impulse > ALMOST_ZERO ) repulse = MIN2 ( repulse, 5.0*impulse ); repulse = MAX2 ( impulse, repulse ); impulse = repulse / ( 5.0 ); // original 2.0 / 0.25 VECADDMUL ( pimpulse, collpair->normal, impulse); } w2 = 1.0f-w1; if (w1 < 0.5) w1 *= 2.0; else w2 *= 2.0; VECADDFAC(cloth1->verts[collpair->ap1].impulse, cloth1->verts[collpair->ap1].impulse, pimpulse, w1*2.0); VECADDFAC(cloth1->verts[collpair->ap2].impulse, cloth1->verts[collpair->ap2].impulse, pimpulse, w2*2.0); cloth1->verts[collpair->ap1].impulse_count++; cloth1->verts[collpair->ap2].impulse_count++; result = 1; } } return result; } static int cloth_collision_response_moving ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end ) { int result = 0; Cloth *cloth1; float w1, w2, w3, u1, u2, u3; float v1[3], v2[3], relativeVelocity[3]; float magrelVel; float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree ); cloth1 = clmd->clothObject; for ( ; collpair != collision_end; collpair++ ) { if (collpair->flag & COLLISION_IS_EDGES) continue; if ( collpair->flag & COLLISION_USE_COLLFACE ) { // was: txold w1 = collpair->bary[0]; w2 = collpair->bary[1]; w3 = collpair->bary[2]; // Calculate relative "velocity". collision_interpolateOnTriangle ( v1, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, w1, w2, w3); VECSUB ( relativeVelocity, v1, cloth1->verts[collpair->collp].tv); // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal'). magrelVel = INPR ( relativeVelocity, collpair->normal ); // If v_n_mag < 0 the edges are approaching each other. if ( magrelVel > ALMOST_ZERO ) { // Calculate Impulse magnitude to stop all motion in normal direction. float magtangent = 0, repulse = 0, d = 0; double impulse = 0.0; float vrel_t_pre[3]; float temp[3], spf; // calculate tangential velocity VECCOPY ( temp, collpair->normal ); mul_v3_fl( temp, magrelVel ); VECSUB ( vrel_t_pre, relativeVelocity, temp ); // Decrease in magnitude of relative tangential velocity due to coulomb friction // in original formula "magrelVel" should be the "change of relative velocity in normal direction" magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) ); // Apply friction impulse. if ( magtangent > ALMOST_ZERO ) { normalize_v3( vrel_t_pre ); impulse = magtangent; // 2.0 * VECADDMUL ( cloth1->verts[collpair->collp].impulse, vrel_t_pre, impulse); } // Apply velocity stopping impulse // I_c = m * v_N / 2.0 // no 2.0 * magrelVel normally, but looks nicer DG impulse = magrelVel/2.0; VECADDMUL ( cloth1->verts[collpair->collp].impulse, collpair->normal, impulse); cloth1->verts[collpair->collp].impulse_count++; // Apply repulse impulse if distance too short // I_r = -min(dt*kd, m(0,1d/dt - v_n)) spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale; d = -collpair->distance; if ( ( magrelVel < 0.1*d*spf ) && ( d > ALMOST_ZERO ) ) { repulse = MIN2 ( d*1.0/spf, 0.1*d*spf - magrelVel ); // stay on the safe side and clamp repulse if ( impulse > ALMOST_ZERO ) repulse = MIN2 ( repulse, 5.0*impulse ); repulse = MAX2 ( impulse, repulse ); impulse = repulse / ( 5.0 ); // original 2.0 / 0.25 VECADDMUL ( cloth1->verts[collpair->collp].impulse, collpair->normal, impulse); } result = 1; } } else { w1 = collpair->bary[0]; w2 = collpair->bary[1]; w3 = collpair->bary[2]; // Calculate relative "velocity". collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 ); VECSUB ( relativeVelocity, collmd->current_v[collpair->collp].co, v1); // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal'). magrelVel = INPR ( relativeVelocity, collpair->normal ); // If v_n_mag < 0 the edges are approaching each other. if ( magrelVel > ALMOST_ZERO ) { // Calculate Impulse magnitude to stop all motion in normal direction. float magtangent = 0, repulse = 0, d = 0; double impulse = 0.0; float vrel_t_pre[3], pimpulse[3] = {0.0f, 0.0f, 0.0f}; float temp[3], spf; // calculate tangential velocity VECCOPY ( temp, collpair->normal ); mul_v3_fl( temp, magrelVel ); VECSUB ( vrel_t_pre, relativeVelocity, temp ); // Decrease in magnitude of relative tangential velocity due to coulomb friction // in original formula "magrelVel" should be the "change of relative velocity in normal direction" magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) ); // Apply friction impulse. if ( magtangent > ALMOST_ZERO ) { normalize_v3( vrel_t_pre ); impulse = magtangent; // 2.0 * VECADDMUL ( pimpulse, vrel_t_pre, impulse); } // Apply velocity stopping impulse // I_c = m * v_N / 2.0 // no 2.0 * magrelVel normally, but looks nicer DG impulse = magrelVel/2.0; VECADDMUL ( pimpulse, collpair->normal, impulse); // Apply repulse impulse if distance too short // I_r = -min(dt*kd, m(0,1d/dt - v_n)) spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale; d = -collpair->distance; if ( ( magrelVel < 0.1*d*spf ) && ( d > ALMOST_ZERO ) ) { repulse = MIN2 ( d*1.0/spf, 0.1*d*spf - magrelVel ); // stay on the safe side and clamp repulse if ( impulse > ALMOST_ZERO ) repulse = MIN2 ( repulse, 5.0*impulse ); repulse = MAX2 ( impulse, repulse ); impulse = repulse / ( 2.0 ); // original 2.0 / 0.25 VECADDMUL ( pimpulse, collpair->normal, impulse); } if (w1 < 0.5) w1 *= 2.0; if (w2 < 0.5) w2 *= 2.0; if (w3 < 0.5) w3 *= 2.0; VECADDMUL(cloth1->verts[collpair->ap1].impulse, pimpulse, w1*2.0); VECADDMUL(cloth1->verts[collpair->ap2].impulse, pimpulse, w2*2.0); VECADDMUL(cloth1->verts[collpair->ap3].impulse, pimpulse, w3*2.0); cloth1->verts[collpair->ap1].impulse_count++; cloth1->verts[collpair->ap2].impulse_count++; cloth1->verts[collpair->ap3].impulse_count++; result = 1; } } } return result; } typedef struct tripairkey { int p, a1, a2, a3; } tripairkey; unsigned int tripair_hash(void *vkey) { tripairkey *key = vkey; int keys[4] = {key->p, key->a1, key->a2, key->a3}; int i, j; for (i=0; i<4; i++) { for (j=0; j<3; j++) { if (keys[j] >= keys[j+1]) { SWAP(int, keys[j], keys[j+1]); } } } return keys[0]*101 + keys[1]*72 + keys[2]*53 + keys[3]*34; } int tripair_cmp(const void *va, const void *vb) { tripairkey *a = va, *b = vb; int keysa[4] = {a->p, a->a1, a->a2, a->a3}; int keysb[4] = {b->p, b->a1, b->a2, b->a3}; int i; for (i=0; i<4; i++) { int j, ok=0; for (j=0; j<4; j++) { if (keysa[i] == keysa[j]) { ok = 1; break; } } if (!ok) return -1; } return 0; } static void get_tripairkey(tripairkey *key, int p, int a1, int a2, int a3) { key->a1 = a1; key->a2 = a2; key->a3 = a3; key->p = p; } static int checkvisit(MemArena *arena, GHash *gh, int p, int a1, int a2, int a3) { tripairkey key, *key2; get_tripairkey(&key, p, a1, a2, a3); if (BLI_ghash_haskey(gh, &key)) return 1; key2 = BLI_memarena_alloc(arena, sizeof(*key2)); *key2 = key; BLI_ghash_insert(gh, key2, NULL); return 0; } int cloth_point_tri_moving_v3v3_f(float v1[2][3], int i1, float v2[2][3], int i2, float v3[2][3], int i3, float v4[2][3], int i4, float normal[3], float bary[3], float *t, float *relnor, GHash *gh, MemArena *arena) { if (checkvisit(arena, gh, i1, i2, i3, i4)) return 0; return eltopo_point_tri_moving_v3v3_f(v1, i1, v2, i2, v3, i3, v4, i4, normal, bary, t, relnor); } static CollPair* cloth_collision ( ModifierData *md1, ModifierData *md2, BVHTreeOverlap *overlap, CollPair *collpair, double dt, GHash *gh, MemArena *arena) { ClothModifierData *clmd = ( ClothModifierData * ) md1; CollisionModifierData *collmd = ( CollisionModifierData * ) md2; MFace *face1=NULL, *face2 = NULL; ClothVertex *verts1 = clmd->clothObject->verts; double distance = 0; float epsilon1 = clmd->coll_parms->epsilon; float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree ); float no[3], uv[3], t, relnor; int i, i1, i2, i3, i4, i5, i6; Cloth *cloth = clmd->clothObject; float n1[3], sdis, p[3], l, n2[3], off[3], v1[2][3], v2[2][3], v3[2][3], v4[2][3], v5[2][3], v6[2][3]; int j, ret, bp1, bp2, bp3, ap1, ap2, ap3; face1 = & ( clmd->clothObject->mfaces[overlap->indexA] ); face2 = & ( collmd->mfaces[overlap->indexB] ); // check all 4 possible collisions for ( i = 0; i < 4; i++ ) { if ( i == 0 ) { // fill faceA ap1 = face1->v1; ap2 = face1->v2; ap3 = face1->v3; // fill faceB bp1 = face2->v1; bp2 = face2->v2; bp3 = face2->v3; } else if ( i == 1 ) { if ( face1->v4 ) { // fill faceA ap1 = face1->v1; ap2 = face1->v3; ap3 = face1->v4; // fill faceB bp1 = face2->v1; bp2 = face2->v2; bp3 = face2->v3; } else { continue; } } if ( i == 2 ) { if ( face2->v4 ) { // fill faceA ap1 = face1->v1; ap2 = face1->v2; ap3 = face1->v3; // fill faceB bp1 = face2->v1; bp2 = face2->v3; bp3 = face2->v4; } else { continue; } } else if ( i == 3 ) { if ( face1->v4 && face2->v4 ) { // fill faceA ap1 = face1->v1; ap2 = face1->v3; ap3 = face1->v4; // fill faceB bp1 = face2->v1; bp2 = face2->v3; bp3 = face2->v4; } else { continue; } } copy_v3_v3(v1[0], cloth->verts[ap1].txold); copy_v3_v3(v1[1], cloth->verts[ap1].tx); copy_v3_v3(v2[0], cloth->verts[ap2].txold); copy_v3_v3(v2[1], cloth->verts[ap2].tx); copy_v3_v3(v3[0], cloth->verts[ap3].txold); copy_v3_v3(v3[1], cloth->verts[ap3].tx); copy_v3_v3(v4[0], collmd->current_x[bp1].co); copy_v3_v3(v4[1], collmd->current_xnew[bp1].co); copy_v3_v3(v5[0], collmd->current_x[bp2].co); copy_v3_v3(v5[1], collmd->current_xnew[bp2].co); copy_v3_v3(v6[0], collmd->current_x[bp3].co); copy_v3_v3(v6[1], collmd->current_xnew[bp3].co); normal_tri_v3(n2, v4[1], v5[1], v6[1]); sdis = clmd->coll_parms->distance_repel + epsilon2 + FLT_EPSILON; /*apply a repulsion force, to help the solver along*/ copy_v3_v3(off, n2); negate_v3(off); if (isect_ray_plane_v3(v1[1], off, v4[1], v5[1], v6[1], &l, 0)) { if (l >= 0.0 && l < sdis) { mul_v3_fl(off, (l-sdis)*cloth->verts[ap1].mass*dt*clmd->coll_parms->repel_force*0.1); add_v3_v3(cloth->verts[ap1].tv, off); add_v3_v3(cloth->verts[ap2].tv, off); add_v3_v3(cloth->verts[ap3].tv, off); } } /*offset new positions a bit, to account for margins*/ copy_v3_v3(off, n2); mul_v3_fl(off, epsilon1 + epsilon2 + ALMOST_ZERO); add_v3_v3(v4[1], off); add_v3_v3(v5[1], off); add_v3_v3(v6[1], off); i1 = ap1; i2 = ap2; i3 = ap3; i4 = bp1+cloth->numverts; i5 = bp2+cloth->numverts; i6 = bp3+cloth->numverts; for (j=0; j<6; j++) { int collp; switch (j) { case 0: ret = cloth_point_tri_moving_v3v3_f(v1, i1, v4, i4, v5, i5, v6, i6, no, uv, &t, &relnor, gh, arena); collp = ap1; break; case 1: collp = ap2; ret = cloth_point_tri_moving_v3v3_f(v2, i2, v4, i4, v5, i5, v6, i6, no, uv, &t, &relnor, gh, arena); break; case 2: collp = ap3; ret = cloth_point_tri_moving_v3v3_f(v3, i3, v4, i4, v5, i5, v6, i6, no, uv, &t, &relnor, gh, arena); break; case 3: collp = bp1; ret = cloth_point_tri_moving_v3v3_f(v4, i4, v1, i1, v2, i2, v3, i3, no, uv, &t, &relnor, gh, arena); break; case 4: collp = bp2; ret = cloth_point_tri_moving_v3v3_f(v5, i5, v1, i1, v2, i2, v3, i3, no, uv, &t, &relnor, gh, arena); break; case 5: collp = bp3; ret = cloth_point_tri_moving_v3v3_f(v6, i6, v1, i1, v2, i2, v3, i3, no, uv, &t, &relnor, gh, arena); break; } /*cloth vert versus coll face*/ if (ret && j < 3) { collpair->bp1 = bp1; collpair->bp2 = bp2; collpair->bp3 = bp3; collpair->collp = collp; copy_v3_v3(collpair->normal, no); mul_v3_v3fl(collpair->vector, collpair->normal, relnor); collpair->distance = relnor; collpair->time = t; copy_v3_v3(collpair->bary, uv); collpair->flag = COLLISION_USE_COLLFACE; collpair++; } else if (ret && j >= 3) { /*coll vert versus cloth face*/ collpair->ap1 = ap1; collpair->ap2 = ap2; collpair->ap3 = ap3; collpair->collp = collp; copy_v3_v3(collpair->normal, no); mul_v3_v3fl(collpair->vector, collpair->normal, relnor); collpair->distance = relnor; collpair->time = t; copy_v3_v3(collpair->bary, uv); collpair->flag = 0; collpair++; } } } return collpair; } static void machine_epsilon_offset(Cloth *cloth) { ClothVertex *cv; int i, j; cv = cloth->verts; for (i=0; i<cloth->numverts; i++, cv++) { /*aggrevatingly enough, it's necassary to offset the coordinates by a multiple of the 32-bit floating point epsilon when switching into doubles*/ #define RNDSIGN (float)(-1*(BLI_rand()%2==0)|1) for (j=0; j<3; j++) { cv->tx[j] += FLT_EPSILON*30.0f*RNDSIGN; cv->txold[j] += FLT_EPSILON*30.0f*RNDSIGN; cv->tv[j] += FLT_EPSILON*30.0f*RNDSIGN; } } } #else /* !WITH_ELTOPO */ //Determines collisions on overlap, collisions are written to collpair[i] and collision+number_collision_found is returned static CollPair* cloth_collision ( ModifierData *md1, ModifierData *md2, BVHTreeOverlap *overlap, CollPair *collpair, float dt ) { ClothModifierData *clmd = ( ClothModifierData * ) md1; CollisionModifierData *collmd = ( CollisionModifierData * ) md2; Cloth *cloth = clmd->clothObject; MFace *face1=NULL, *face2 = NULL; #ifdef USE_BULLET ClothVertex *verts1 = clmd->clothObject->verts; #endif double distance = 0; float epsilon1 = clmd->coll_parms->epsilon; float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree ); float n2[3], sdis, l; int i; face1 = & ( clmd->clothObject->mfaces[overlap->indexA] ); face2 = & ( collmd->mfaces[overlap->indexB] ); // check all 4 possible collisions for ( i = 0; i < 4; i++ ) { if ( i == 0 ) { // fill faceA collpair->ap1 = face1->v1; collpair->ap2 = face1->v2; collpair->ap3 = face1->v3; // fill faceB collpair->bp1 = face2->v1; collpair->bp2 = face2->v2; collpair->bp3 = face2->v3; } else if ( i == 1 ) { if ( face1->v4 ) { // fill faceA collpair->ap1 = face1->v1; collpair->ap2 = face1->v4; collpair->ap3 = face1->v3; // fill faceB collpair->bp1 = face2->v1; collpair->bp2 = face2->v2; collpair->bp3 = face2->v3; } else i++; } if ( i == 2 ) { if ( face2->v4 ) { // fill faceA collpair->ap1 = face1->v1; collpair->ap2 = face1->v2; collpair->ap3 = face1->v3; // fill faceB collpair->bp1 = face2->v1; collpair->bp2 = face2->v4; collpair->bp3 = face2->v3; } else break; } else if ( i == 3 ) { if ( face1->v4 && face2->v4 ) { // fill faceA collpair->ap1 = face1->v1; collpair->ap2 = face1->v4; collpair->ap3 = face1->v3; // fill faceB collpair->bp1 = face2->v1; collpair->bp2 = face2->v4; collpair->bp3 = face2->v3; } else break; } normal_tri_v3(n2, collmd->current_xnew[collpair->bp1].co, collmd->current_xnew[collpair->bp2].co, collmd->current_xnew[collpair->bp3].co); sdis = clmd->coll_parms->distance_repel + epsilon2 + FLT_EPSILON; /* apply a repulsion force, to help the solver along. * this is kindof crude, it only tests one vert of the triangle */ if (isect_ray_plane_v3(cloth->verts[collpair->ap1].tx, n2, collmd->current_xnew[collpair->bp1].co, collmd->current_xnew[collpair->bp2].co, collmd->current_xnew[collpair->bp3].co, &l, 0)) { if (l >= 0.0 && l < sdis) { mul_v3_fl(n2, (l-sdis)*cloth->verts[collpair->ap1].mass*dt*clmd->coll_parms->repel_force*0.1); add_v3_v3(cloth->verts[collpair->ap1].tv, n2); add_v3_v3(cloth->verts[collpair->ap2].tv, n2); add_v3_v3(cloth->verts[collpair->ap3].tv, n2); } } #ifdef USE_BULLET // calc distance + normal distance = plNearestPoints ( verts1[collpair->ap1].txold, verts1[collpair->ap2].txold, verts1[collpair->ap3].txold, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, collpair->pa,collpair->pb,collpair->vector ); #else // just be sure that we don't add anything distance = 2.0 * ( epsilon1 + epsilon2 + ALMOST_ZERO ); #endif if ( distance <= ( epsilon1 + epsilon2 + ALMOST_ZERO ) ) { normalize_v3_v3( collpair->normal, collpair->vector ); collpair->distance = distance; collpair->flag = 0; collpair++; }/* else { float w1, w2, w3, u1, u2, u3; float v1[3], v2[3], relativeVelocity[3]; // calc relative velocity // compute barycentric coordinates for both collision points collision_compute_barycentric ( collpair->pa, verts1[collpair->ap1].txold, verts1[collpair->ap2].txold, verts1[collpair->ap3].txold, &w1, &w2, &w3 ); // was: txold collision_compute_barycentric ( collpair->pb, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, &u1, &u2, &u3 ); // Calculate relative "velocity". collision_interpolateOnTriangle ( v1, verts1[collpair->ap1].tv, verts1[collpair->ap2].tv, verts1[collpair->ap3].tv, w1, w2, w3 ); collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 ); VECSUB ( relativeVelocity, v2, v1 ); if(sqrt(INPR(relativeVelocity, relativeVelocity)) >= distance) { // check for collision in the future collpair->flag |= COLLISION_IN_FUTURE; collpair++; } }*/ } return collpair; } #endif /* WITH_ELTOPO */ #if 0 static int cloth_collision_response_moving( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end ) { int result = 0; Cloth *cloth1; float w1, w2, w3, u1, u2, u3; float v1[3], v2[3], relativeVelocity[3]; float magrelVel; cloth1 = clmd->clothObject; for ( ; collpair != collision_end; collpair++ ) { // compute barycentric coordinates for both collision points collision_compute_barycentric ( collpair->pa, cloth1->verts[collpair->ap1].txold, cloth1->verts[collpair->ap2].txold, cloth1->verts[collpair->ap3].txold, &w1, &w2, &w3 ); // was: txold collision_compute_barycentric ( collpair->pb, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, &u1, &u2, &u3 ); // Calculate relative "velocity". collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 ); collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 ); VECSUB ( relativeVelocity, v2, v1 ); // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal'). magrelVel = INPR ( relativeVelocity, collpair->normal ); // printf("magrelVel: %f\n", magrelVel); // Calculate masses of points. // TODO // If v_n_mag < 0 the edges are approaching each other. if ( magrelVel > ALMOST_ZERO ) { // Calculate Impulse magnitude to stop all motion in normal direction. float magtangent = 0; double impulse = 0.0; float vrel_t_pre[3]; float temp[3]; // calculate tangential velocity VECCOPY ( temp, collpair->normal ); mul_v3_fl( temp, magrelVel ); VECSUB ( vrel_t_pre, relativeVelocity, temp ); // Decrease in magnitude of relative tangential velocity due to coulomb friction // in original formula "magrelVel" should be the "change of relative velocity in normal direction" magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) ); // Apply friction impulse. if ( magtangent > ALMOST_ZERO ) { normalize_v3( vrel_t_pre ); impulse = 2.0 * magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse ); VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse ); VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse ); } // Apply velocity stopping impulse // I_c = m * v_N / 2.0 // no 2.0 * magrelVel normally, but looks nicer DG impulse = magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse ); cloth1->verts[collpair->ap1].impulse_count++; VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse ); cloth1->verts[collpair->ap2].impulse_count++; VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse ); cloth1->verts[collpair->ap3].impulse_count++; // Apply repulse impulse if distance too short // I_r = -min(dt*kd, m(0,1d/dt - v_n)) /* d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance; if ( ( magrelVel < 0.1*d*clmd->sim_parms->stepsPerFrame ) && ( d > ALMOST_ZERO ) ) { repulse = MIN2 ( d*1.0/clmd->sim_parms->stepsPerFrame, 0.1*d*clmd->sim_parms->stepsPerFrame - magrelVel ); // stay on the safe side and clamp repulse if ( impulse > ALMOST_ZERO ) repulse = MIN2 ( repulse, 5.0*impulse ); repulse = MAX2 ( impulse, repulse ); impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25 VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, impulse ); VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, impulse ); VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, impulse ); } */ result = 1; } } return result; } #endif #if 0 static float projectPointOntoLine(float *p, float *a, float *b) { float ba[3], pa[3]; VECSUB(ba, b, a); VECSUB(pa, p, a); return INPR(pa, ba) / INPR(ba, ba); } static void calculateEENormal(float *np1, float *np2, float *np3, float *np4,float *out_normal) { float line1[3], line2[3]; float length; VECSUB(line1, np2, np1); VECSUB(line2, np3, np1); // printf("l1: %f, l1: %f, l2: %f, l2: %f\n", line1[0], line1[1], line2[0], line2[1]); cross_v3_v3v3(out_normal, line1, line2); length = normalize_v3(out_normal); if (length <= FLT_EPSILON) { // lines are collinear VECSUB(out_normal, np2, np1); normalize_v3(out_normal); } } static void findClosestPointsEE(float *x1, float *x2, float *x3, float *x4, float *w1, float *w2) { float temp[3], temp2[3]; double a, b, c, e, f; VECSUB(temp, x2, x1); a = INPR(temp, temp); VECSUB(temp2, x4, x3); b = -INPR(temp, temp2); c = INPR(temp2, temp2); VECSUB(temp2, x3, x1); e = INPR(temp, temp2); VECSUB(temp, x4, x3); f = -INPR(temp, temp2); *w1 = (e * c - b * f) / (a * c - b * b); *w2 = (f - b * *w1) / c; } // calculates the distance of 2 edges static float edgedge_distance(float np11[3], float np12[3], float np21[3], float np22[3], float *out_a1, float *out_a2, float *out_normal) { float line1[3], line2[3], cross[3]; float length; float temp[3], temp2[3]; float dist_a1, dist_a2; VECSUB(line1, np12, np11); VECSUB(line2, np22, np21); cross_v3_v3v3(cross, line1, line2); length = INPR(cross, cross); if (length < FLT_EPSILON) { *out_a2 = projectPointOntoLine(np11, np21, np22); if ((*out_a2 >= -FLT_EPSILON) && (*out_a2 <= 1.0 + FLT_EPSILON)) { *out_a1 = 0; calculateEENormal(np11, np12, np21, np22, out_normal); VECSUB(temp, np22, np21); mul_v3_fl(temp, *out_a2); VECADD(temp2, temp, np21); VECADD(temp2, temp2, np11); return INPR(temp2, temp2); } CLAMP(*out_a2, 0.0, 1.0); if (*out_a2 > .5) { // == 1.0 *out_a1 = projectPointOntoLine(np22, np11, np12); if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON)) { calculateEENormal(np11, np12, np21, np22, out_normal); // return (np22 - (np11 + (np12 - np11) * out_a1)).lengthSquared(); VECSUB(temp, np12, np11); mul_v3_fl(temp, *out_a1); VECADD(temp2, temp, np11); VECSUB(temp2, np22, temp2); return INPR(temp2, temp2); } } else { // == 0.0 *out_a1 = projectPointOntoLine(np21, np11, np12); if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON)) { calculateEENormal(np11, np11, np21, np22, out_normal); // return (np21 - (np11 + (np12 - np11) * out_a1)).lengthSquared(); VECSUB(temp, np12, np11); mul_v3_fl(temp, *out_a1); VECADD(temp2, temp, np11); VECSUB(temp2, np21, temp2); return INPR(temp2, temp2); } } CLAMP(*out_a1, 0.0, 1.0); calculateEENormal(np11, np12, np21, np22, out_normal); if(*out_a1 > .5) { if(*out_a2 > .5) { VECSUB(temp, np12, np22); } else { VECSUB(temp, np12, np21); } } else { if(*out_a2 > .5) { VECSUB(temp, np11, np22); } else { VECSUB(temp, np11, np21); } } return INPR(temp, temp); } else { // If the lines aren't parallel (but coplanar) they have to intersect findClosestPointsEE(np11, np12, np21, np22, out_a1, out_a2); // If both points are on the finite edges, we're done. if (*out_a1 >= 0.0 && *out_a1 <= 1.0 && *out_a2 >= 0.0 && *out_a2 <= 1.0) { float p1[3], p2[3]; // p1= np11 + (np12 - np11) * out_a1; VECSUB(temp, np12, np11); mul_v3_fl(temp, *out_a1); VECADD(p1, np11, temp); // p2 = np21 + (np22 - np21) * out_a2; VECSUB(temp, np22, np21); mul_v3_fl(temp, *out_a2); VECADD(p2, np21, temp); calculateEENormal(np11, np12, np21, np22, out_normal); VECSUB(temp, p1, p2); return INPR(temp, temp); } /* * Clamp both points to the finite edges. * The one that moves most during clamping is one part of the solution. */ dist_a1 = *out_a1; CLAMP(dist_a1, 0.0, 1.0); dist_a2 = *out_a2; CLAMP(dist_a2, 0.0, 1.0); // Now project the "most clamped" point on the other line. if (dist_a1 > dist_a2) { /* keep out_a1 */ float p1[3]; // p1 = np11 + (np12 - np11) * out_a1; VECSUB(temp, np12, np11); mul_v3_fl(temp, *out_a1); VECADD(p1, np11, temp); *out_a2 = projectPointOntoLine(p1, np21, np22); CLAMP(*out_a2, 0.0, 1.0); calculateEENormal(np11, np12, np21, np22, out_normal); // return (p1 - (np21 + (np22 - np21) * out_a2)).lengthSquared(); VECSUB(temp, np22, np21); mul_v3_fl(temp, *out_a2); VECADD(temp, temp, np21); VECSUB(temp, p1, temp); return INPR(temp, temp); } else { /* keep out_a2 */ float p2[3]; // p2 = np21 + (np22 - np21) * out_a2; VECSUB(temp, np22, np21); mul_v3_fl(temp, *out_a2); VECADD(p2, np21, temp); *out_a1 = projectPointOntoLine(p2, np11, np12); CLAMP(*out_a1, 0.0, 1.0); calculateEENormal(np11, np12, np21, np22, out_normal); // return ((np11 + (np12 - np11) * out_a1) - p2).lengthSquared(); VECSUB(temp, np12, np11); mul_v3_fl(temp, *out_a1); VECADD(temp, temp, np11); VECSUB(temp, temp, p2); return INPR(temp, temp); } } printf("Error in edgedge_distance: end of function\n"); return 0; } static int cloth_collision_moving_edges ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair ) { EdgeCollPair edgecollpair; Cloth *cloth1=NULL; ClothVertex *verts1=NULL; unsigned int i = 0, k = 0; int numsolutions = 0; double x1[3], v1[3], x2[3], v2[3], x3[3], v3[3]; double solution[3], solution2[3]; MVert *verts2 = collmd->current_x; // old x MVert *velocity2 = collmd->current_v; // velocity float distance = 0; float triA[3][3], triB[3][3]; int result = 0; cloth1 = clmd->clothObject; verts1 = cloth1->verts; for(i = 0; i < 9; i++) { // 9 edge - edge possibilities if(i == 0) // cloth edge: 1-2; coll edge: 1-2 { edgecollpair.p11 = collpair->ap1; edgecollpair.p12 = collpair->ap2; edgecollpair.p21 = collpair->bp1; edgecollpair.p22 = collpair->bp2; } else if(i == 1) // cloth edge: 1-2; coll edge: 2-3 { edgecollpair.p11 = collpair->ap1; edgecollpair.p12 = collpair->ap2; edgecollpair.p21 = collpair->bp2; edgecollpair.p22 = collpair->bp3; } else if(i == 2) // cloth edge: 1-2; coll edge: 1-3 { edgecollpair.p11 = collpair->ap1; edgecollpair.p12 = collpair->ap2; edgecollpair.p21 = collpair->bp1; edgecollpair.p22 = collpair->bp3; } else if(i == 3) // cloth edge: 2-3; coll edge: 1-2 { edgecollpair.p11 = collpair->ap2; edgecollpair.p12 = collpair->ap3; edgecollpair.p21 = collpair->bp1; edgecollpair.p22 = collpair->bp2; } else if(i == 4) // cloth edge: 2-3; coll edge: 2-3 { edgecollpair.p11 = collpair->ap2; edgecollpair.p12 = collpair->ap3; edgecollpair.p21 = collpair->bp2; edgecollpair.p22 = collpair->bp3; } else if(i == 5) // cloth edge: 2-3; coll edge: 1-3 { edgecollpair.p11 = collpair->ap2; edgecollpair.p12 = collpair->ap3; edgecollpair.p21 = collpair->bp1; edgecollpair.p22 = collpair->bp3; } else if(i ==6) // cloth edge: 1-3; coll edge: 1-2 { edgecollpair.p11 = collpair->ap1; edgecollpair.p12 = collpair->ap3; edgecollpair.p21 = collpair->bp1; edgecollpair.p22 = collpair->bp2; } else if(i ==7) // cloth edge: 1-3; coll edge: 2-3 { edgecollpair.p11 = collpair->ap1; edgecollpair.p12 = collpair->ap3; edgecollpair.p21 = collpair->bp2; edgecollpair.p22 = collpair->bp3; } else if(i == 8) // cloth edge: 1-3; coll edge: 1-3 { edgecollpair.p11 = collpair->ap1; edgecollpair.p12 = collpair->ap3; edgecollpair.p21 = collpair->bp1; edgecollpair.p22 = collpair->bp3; } /* if((edgecollpair.p11 == 3) && (edgecollpair.p12 == 16)) printf("Ahier!\n"); if((edgecollpair.p11 == 16) && (edgecollpair.p12 == 3)) printf("Ahier!\n"); */ // if ( !cloth_are_edges_adjacent ( clmd, collmd, &edgecollpair ) ) { // always put coll points in p21/p22 VECSUB ( x1, verts1[edgecollpair.p12].txold, verts1[edgecollpair.p11].txold ); VECSUB ( v1, verts1[edgecollpair.p12].tv, verts1[edgecollpair.p11].tv ); VECSUB ( x2, verts2[edgecollpair.p21].co, verts1[edgecollpair.p11].txold ); VECSUB ( v2, velocity2[edgecollpair.p21].co, verts1[edgecollpair.p11].tv ); VECSUB ( x3, verts2[edgecollpair.p22].co, verts1[edgecollpair.p11].txold ); VECSUB ( v3, velocity2[edgecollpair.p22].co, verts1[edgecollpair.p11].tv ); numsolutions = cloth_get_collision_time ( x1, v1, x2, v2, x3, v3, solution ); if((edgecollpair.p11 == 3 && edgecollpair.p12==16)|| (edgecollpair.p11==16 && edgecollpair.p12==3)) { if(edgecollpair.p21==6 || edgecollpair.p22 == 6) { printf("dist: %f, sol[k]: %f, sol2[k]: %f\n", distance, solution[k], solution2[k]); printf("a1: %f, a2: %f, b1: %f, b2: %f\n", x1[0], x2[0], x3[0], v1[0]); printf("b21: %d, b22: %d\n", edgecollpair.p21, edgecollpair.p22); } } for ( k = 0; k < numsolutions; k++ ) { // printf("sol %d: %lf\n", k, solution[k]); if ( ( solution[k] >= ALMOST_ZERO ) && ( solution[k] <= 1.0 ) && ( solution[k] > ALMOST_ZERO)) { float a,b; float out_normal[3]; float distance; float impulse = 0; float I_mag; // move verts VECADDS(triA[0], verts1[edgecollpair.p11].txold, verts1[edgecollpair.p11].tv, solution[k]); VECADDS(triA[1], verts1[edgecollpair.p12].txold, verts1[edgecollpair.p12].tv, solution[k]); VECADDS(triB[0], collmd->current_x[edgecollpair.p21].co, collmd->current_v[edgecollpair.p21].co, solution[k]); VECADDS(triB[1], collmd->current_x[edgecollpair.p22].co, collmd->current_v[edgecollpair.p22].co, solution[k]); // TODO: check for collisions distance = edgedge_distance(triA[0], triA[1], triB[0], triB[1], &a, &b, out_normal); if ((distance <= clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree ) + ALMOST_ZERO) && (INPR(out_normal, out_normal) > 0)) { float vrel_1_to_2[3], temp[3], temp2[3], out_normalVelocity; float desiredVn; VECCOPY(vrel_1_to_2, verts1[edgecollpair.p11].tv); mul_v3_fl(vrel_1_to_2, 1.0 - a); VECCOPY(temp, verts1[edgecollpair.p12].tv); mul_v3_fl(temp, a); VECADD(vrel_1_to_2, vrel_1_to_2, temp); VECCOPY(temp, verts1[edgecollpair.p21].tv); mul_v3_fl(temp, 1.0 - b); VECCOPY(temp2, verts1[edgecollpair.p22].tv); mul_v3_fl(temp2, b); VECADD(temp, temp, temp2); VECSUB(vrel_1_to_2, vrel_1_to_2, temp); out_normalVelocity = INPR(vrel_1_to_2, out_normal); /* // this correction results in wrong normals sometimes? if(out_normalVelocity < 0.0) { out_normalVelocity*= -1.0; negate_v3(out_normal); } */ /* Inelastic repulsion impulse. */ // Calculate which normal velocity we need. desiredVn = (out_normalVelocity * (float)solution[k] - (.1 * (clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree )) - sqrt(distance)) - ALMOST_ZERO); // Now calculate what impulse we need to reach that velocity. I_mag = (out_normalVelocity - desiredVn) / 2.0; // / (1/m1 + 1/m2); // Finally apply that impulse. impulse = (2.0 * -I_mag) / (a*a + (1.0-a)*(1.0-a) + b*b + (1.0-b)*(1.0-b)); VECADDMUL ( verts1[edgecollpair.p11].impulse, out_normal, (1.0-a) * impulse ); verts1[edgecollpair.p11].impulse_count++; VECADDMUL ( verts1[edgecollpair.p12].impulse, out_normal, a * impulse ); verts1[edgecollpair.p12].impulse_count++; // return true; result = 1; break; } else { // missing from collision.hpp } // mintime = MIN2(mintime, (float)solution[k]); break; } } } } return result; } static int cloth_collision_moving ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end ) { Cloth *cloth1; cloth1 = clmd->clothObject; for ( ; collpair != collision_end; collpair++ ) { // only handle moving collisions here if (!( collpair->flag & COLLISION_IN_FUTURE )) continue; cloth_collision_moving_edges ( clmd, collmd, collpair); // cloth_collision_moving_tris ( clmd, collmd, collpair); } return 1; } #endif static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned int *maxobj, Object *ob, Object *self, int level) { CollisionModifierData *cmd= NULL; if(ob == self) return; /* only get objects with collision modifier */ if(ob->pd && ob->pd->deflect) cmd= (CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision); if(cmd) { /* extend array */ if(*numobj >= *maxobj) { *maxobj *= 2; *objs= MEM_reallocN(*objs, sizeof(Object*)*(*maxobj)); } (*objs)[*numobj] = ob; (*numobj)++; } /* objects in dupli groups, one level only for now */ if(ob->dup_group && level == 0) { GroupObject *go; Group *group= ob->dup_group; /* add objects */ for(go= group->gobject.first; go; go= go->next) add_collision_object(objs, numobj, maxobj, go->ob, self, level+1); } } // return all collision objects in scene // collision object will exclude self Object **get_collisionobjects(Scene *scene, Object *self, Group *group, unsigned int *numcollobj) { Base *base; Object **objs; GroupObject *go; unsigned int numobj= 0, maxobj= 100; objs= MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray"); /* gather all collision objects */ if(group) { /* use specified group */ for(go= group->gobject.first; go; go= go->next) add_collision_object(&objs, &numobj, &maxobj, go->ob, self, 0); } else { Scene *sce_iter; /* add objects in same layer in scene */ for(SETLOOPER(scene, sce_iter, base)) { if(base->lay & self->lay) add_collision_object(&objs, &numobj, &maxobj, base->object, self, 0); } } *numcollobj= numobj; return objs; } static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self, int level) { CollisionModifierData *cmd= NULL; ColliderCache *col; if(ob == self) return; if(ob->pd && ob->pd->deflect) cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision); if(cmd && cmd->bvhtree) { if(*objs == NULL) *objs = MEM_callocN(sizeof(ListBase), "ColliderCache array"); col = MEM_callocN(sizeof(ColliderCache), "ColliderCache"); col->ob = ob; col->collmd = cmd; /* make sure collider is properly set up */ collision_move_object(cmd, 1.0, 0.0); BLI_addtail(*objs, col); } /* objects in dupli groups, one level only for now */ if(ob->dup_group && level == 0) { GroupObject *go; Group *group= ob->dup_group; /* add objects */ for(go= group->gobject.first; go; go= go->next) add_collider_cache_object(objs, go->ob, self, level+1); } } ListBase *get_collider_cache(Scene *scene, Object *self, Group *group) { GroupObject *go; ListBase *objs= NULL; /* add object in same layer in scene */ if(group) { for(go= group->gobject.first; go; go= go->next) add_collider_cache_object(&objs, go->ob, self, 0); } else { Scene *sce_iter; Base *base; /* add objects in same layer in scene */ for(SETLOOPER(scene, sce_iter, base)) { if(!self || (base->lay & self->lay)) add_collider_cache_object(&objs, base->object, self, 0); } } return objs; } void free_collider_cache(ListBase **colliders) { if(*colliders) { BLI_freelistN(*colliders); MEM_freeN(*colliders); *colliders = NULL; } } static void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap, double dt) { int i; #ifdef WITH_ELTOPO GHash *visithash = BLI_ghash_new(edgepair_hash, edgepair_cmp, "visthash, collision.c"); GHash *tri_visithash = BLI_ghash_new(tripair_hash, tripair_cmp, "tri_visthash, collision.c"); MemArena *arena = BLI_memarena_new(1<<16, "edge hash arena, collision.c"); #endif *collisions = ( CollPair* ) MEM_mallocN ( sizeof ( CollPair ) * numresult * 64, "collision array" ); //*4 since cloth_collision_static can return more than 1 collision *collisions_index = *collisions; #ifdef WITH_ELTOPO machine_epsilon_offset(clmd->clothObject); for ( i = 0; i < numresult; i++ ) { *collisions_index = cloth_collision ( ( ModifierData * ) clmd, ( ModifierData * ) collmd, overlap+i, *collisions_index, dt, tri_visithash, arena ); } for ( i = 0; i < numresult; i++ ) { *collisions_index = cloth_edge_collision ( ( ModifierData * ) clmd, ( ModifierData * ) collmd, overlap+i, *collisions_index, visithash, arena ); } BLI_ghash_free(visithash, NULL, NULL); BLI_ghash_free(tri_visithash, NULL, NULL); BLI_memarena_free(arena); #else /* WITH_ELTOPO */ for ( i = 0; i < numresult; i++ ) { *collisions_index = cloth_collision ( ( ModifierData * ) clmd, ( ModifierData * ) collmd, overlap+i, *collisions_index, dt ); } #endif /* WITH_ELTOPO */ } static int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair *collisions, CollPair *collisions_index) { Cloth *cloth = clmd->clothObject; int i=0, j = 0, /*numfaces = 0,*/ numverts = 0; ClothVertex *verts = NULL; int ret = 0; int result = 0; float tnull[3] = {0,0,0}; /*numfaces = clmd->clothObject->numfaces;*/ /*UNUSED*/ numverts = clmd->clothObject->numverts; verts = cloth->verts; // process all collisions (calculate impulses, TODO: also repulses if distance too short) result = 1; for ( j = 0; j < 5; j++ ) // 5 is just a value that ensures convergence { result = 0; if ( collmd->bvhtree ) { #ifdef WITH_ELTOPO result += cloth_collision_response_moving(clmd, collmd, collisions, collisions_index); result += cloth_edge_collision_response_moving(clmd, collmd, collisions, collisions_index); #else result += cloth_collision_response_static ( clmd, collmd, collisions, collisions_index ); #endif #ifdef WITH_ELTOPO { #else // apply impulses in parallel if ( result ) { #endif for ( i = 0; i < numverts; i++ ) { // calculate "velocities" (just xnew = xold + v; no dt in v) if ( verts[i].impulse_count ) { VECADDMUL ( verts[i].tv, verts[i].impulse, 1.0f / verts[i].impulse_count ); copy_v3_v3 ( verts[i].impulse, tnull ); verts[i].impulse_count = 0; ret++; } } } } } return ret; } // cloth - object collisions int cloth_bvh_objcollision (Object *ob, ClothModifierData * clmd, float step, float dt ) { Cloth *cloth= clmd->clothObject; BVHTree *cloth_bvh= cloth->bvhtree; unsigned int i=0, /* numfaces = 0, */ /* UNUSED */ numverts = 0, k, l, j; int rounds = 0; // result counts applied collisions; ic is for debug output; ClothVertex *verts = NULL; int ret = 0, ret2 = 0; Object **collobjs = NULL; unsigned int numcollobj = 0; if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ) || cloth_bvh==NULL) return 0; verts = cloth->verts; /* numfaces = cloth->numfaces; */ /* UNUSED */ numverts = cloth->numverts; //////////////////////////////////////////////////////////// // static collisions //////////////////////////////////////////////////////////// // update cloth bvh bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function) bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function) collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj); if(!collobjs) return 0; do { CollPair **collisions, **collisions_index; ret2 = 0; collisions = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair"); collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair"); // check all collision objects for(i = 0; i < numcollobj; i++) { Object *collob= collobjs[i]; CollisionModifierData *collmd = (CollisionModifierData*)modifiers_findByType(collob, eModifierType_Collision); BVHTreeOverlap *overlap = NULL; unsigned int result = 0; if(!collmd->bvhtree) continue; /* move object to position (step) in time */ collision_move_object ( collmd, step + dt, step ); /* search for overlapping collision pairs */ overlap = BLI_bvhtree_overlap ( cloth_bvh, collmd->bvhtree, &result ); // go to next object if no overlap is there if( result && overlap ) { /* check if collisions really happen (costly near check) */ cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], &collisions_index[i], result, overlap, dt/(float)clmd->coll_parms->loop_count); // resolve nearby collisions ret += cloth_bvh_objcollisions_resolve ( clmd, collmd, collisions[i], collisions_index[i]); ret2 += ret; } if ( overlap ) MEM_freeN ( overlap ); } rounds++; for(i = 0; i < numcollobj; i++) { if ( collisions[i] ) MEM_freeN ( collisions[i] ); } MEM_freeN(collisions); MEM_freeN(collisions_index); //////////////////////////////////////////////////////////// // update positions // this is needed for bvh_calc_DOP_hull_moving() [kdop.c] //////////////////////////////////////////////////////////// // verts come from clmd for ( i = 0; i < numverts; i++ ) { if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) { if ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) { continue; } } VECADD ( verts[i].tx, verts[i].txold, verts[i].tv ); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Test on *simple* selfcollisions //////////////////////////////////////////////////////////// if ( clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF ) { for(l = 0; l < (unsigned int)clmd->coll_parms->self_loop_count; l++) { // TODO: add coll quality rounds again BVHTreeOverlap *overlap = NULL; unsigned int result = 0; // collisions = 1; verts = cloth->verts; // needed for openMP /* numfaces = cloth->numfaces; */ /* UNUSED */ numverts = cloth->numverts; verts = cloth->verts; if ( cloth->bvhselftree ) { // search for overlapping collision pairs overlap = BLI_bvhtree_overlap ( cloth->bvhselftree, cloth->bvhselftree, &result ); // #pragma omp parallel for private(k, i, j) schedule(static) for ( k = 0; k < result; k++ ) { float temp[3]; float length = 0; float mindistance; i = overlap[k].indexA; j = overlap[k].indexB; mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len ); if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) { if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) && ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) ) { continue; } } VECSUB ( temp, verts[i].tx, verts[j].tx ); if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue; // check for adjacent points (i must be smaller j) if ( BLI_edgehash_haskey ( cloth->edgehash, MIN2(i, j), MAX2(i, j) ) ) { continue; } length = normalize_v3( temp ); if ( length < mindistance ) { float correction = mindistance - length; if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) { mul_v3_fl( temp, -correction ); VECADD ( verts[j].tx, verts[j].tx, temp ); } else if ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) { mul_v3_fl( temp, correction ); VECADD ( verts[i].tx, verts[i].tx, temp ); } else { mul_v3_fl( temp, -correction*0.5 ); VECADD ( verts[j].tx, verts[j].tx, temp ); VECSUB ( verts[i].tx, verts[i].tx, temp ); } ret = 1; ret2 += ret; } else { // check for approximated time collisions } } if ( overlap ) MEM_freeN ( overlap ); } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // SELFCOLLISIONS: update velocities //////////////////////////////////////////////////////////// if ( ret2 ) { for ( i = 0; i < cloth->numverts; i++ ) { if ( ! ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) ) { VECSUB ( verts[i].tv, verts[i].tx, verts[i].txold ); } } } //////////////////////////////////////////////////////////// } } while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) ); if(collobjs) MEM_freeN(collobjs); return 1|MIN2 ( ret, 1 ); }
pcg.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include "pcg.h" // Left preconditioned Conjugate Gradient for solving A * x = b void pcg( const int n, const DTYPE tol, const int max_iter, const matvec_fptr Ax, const void *Ax_param, const DTYPE *b, const matvec_fptr invMx, const void *invMx_param, DTYPE *x, int *flag_, DTYPE *relres_, int *iter_, DTYPE *res_vec ) { size_t vec_msize = sizeof(DTYPE) * n; DTYPE *r = (DTYPE*) malloc(vec_msize); DTYPE *z = (DTYPE*) malloc(vec_msize); DTYPE *p = (DTYPE*) malloc(vec_msize); DTYPE *s = (DTYPE*) malloc(vec_msize); assert(r != NULL && z != NULL && p != NULL && s != NULL); // r = b - A * x; Ax(Ax_param, x, r); #pragma omp simd for (int i = 0; i < n; i++) r[i] = b[i] - r[i]; // z = M \ r; if (invMx != NULL) invMx(invMx_param, r, z); else memcpy(z, r, vec_msize); // p = z; memcpy(p, z, vec_msize); // rho = r' * z; DTYPE rho = 0.0; #pragma omp simd for (int i = 0; i < n; i++) rho += r[i] * z[i]; // b_2norm = norm(b, 2); // r_2norm = norm(r, 2); // rn_stop = b_2norm * tol; DTYPE b_2norm = 0.0, r_2norm = 0.0, rn_stop; #pragma omp simd for (int i = 0; i < n; i++) { b_2norm += b[i] * b[i]; r_2norm += r[i] * r[i]; } b_2norm = DSQRT(b_2norm); r_2norm = DSQRT(r_2norm); rn_stop = b_2norm * tol; int iter = 0; DTYPE alpha, beta, rho0, tmp; while (iter < max_iter && r_2norm > rn_stop) { // s = A * p; Ax(Ax_param, p, s); // alpha = rho / (p' * s); tmp = 0.0; #pragma omp simd for (int i = 0; i < n; i++) tmp += p[i] * s[i]; alpha = rho / tmp; // x = x + alpha * p; // r = r - alpha * s; #pragma omp simd for (int i = 0; i < n; i++) { x[i] += alpha * p[i]; r[i] -= alpha * s[i]; } // z = M \ r; if (invMx != NULL) invMx(invMx_param, r, z); else memcpy(z, r, vec_msize); // rho0 = rho; // rho = r' * z; rho0 = rho; rho = 0.0; #pragma omp simd for (int i = 0; i < n; i++) rho += r[i] * z[i]; // beta = rho / rho0; // p = z + beta * p; beta = rho / rho0; #pragma omp simd for (int i = 0; i < n; i++) p[i] = z[i] + beta * p[i]; // r_2norm = norm(r, 2); // resvec(iter) = r_2norm; // iter = iter + 1; r_2norm = 0.0; #pragma omp simd for (int i = 0; i < n; i++) r_2norm += r[i] * r[i]; r_2norm = DSQRT(r_2norm); if (res_vec != NULL) res_vec[iter] = r_2norm; iter++; //printf("%e\n", r_2norm / b_2norm); } // End of while *flag_ = (r_2norm <= rn_stop) ? 0 : 1; *relres_ = r_2norm / b_2norm; *iter_ = iter; free(r); free(z); free(p); free(s); }
cache.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/distribute-cache-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/quantum.h" #include "MagickCore/random_.h" #include "MagickCore/registry.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const Quantum *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static const void *GetVirtualMetacontentFromCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t,Quantum *, ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,Quantum *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), OpenPixelCacheOnDisk(CacheInfo *,const MapMode), ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), ReadPixelCacheMetacontent(CacheInfo *magick_restrict, NexusInfo *magick_restrict,ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), WritePixelCacheMetacontent(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *); static Quantum *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *,const MapMode, const RectangleInfo *,NexusInfo *,ExceptionInfo *) magick_hot_spot; #if defined(MAGICKCORE_OPENCL_SUPPORT) static void CopyOpenCLBuffer(CacheInfo *magick_restrict); #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static volatile MagickBooleanType instantiate_cache = MagickFalse; static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; static ssize_t cache_anonymous_memory = (-1); static time_t cache_epoch = 0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *magick_restrict cache_info; char *value; cache_info=(CacheInfo *) AcquireQuantumMemory(1,sizeof(*cache_info)); if (cache_info == (CacheInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); if (cache_info->nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); value=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } value=GetPolicyValue("cache:synchronize"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } cache_info->semaphore=AcquireSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AcquireSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickCoreSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **magick_restrict nexus_info; register ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory( number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); nexus_info[0]=(NexusInfo *) AcquireQuantumMemory(number_threads, sizeof(**nexus_info)); if (nexus_info[0] == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(nexus_info[0],0,number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) number_threads; i++) { nexus_info[i]=(&nexus_info[0][i]); nexus_info[i]->signature=MagickCoreSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % const void *AcquirePixelCachePixels(const Image *image, % MagickSizeType *length,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate const void *AcquirePixelCachePixels(const Image *image, MagickSizeType *length,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((const void *) NULL); *length=cache_info->length; return((const void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickPrivate MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickPrivate void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); LockSemaphoreInfo(cache_semaphore); instantiate_cache=MagickFalse; UnlockSemaphoreInfo(cache_semaphore); RelinquishSemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate Cache ClonePixelCache(const Cache cache) { CacheInfo *magick_restrict clone_info; const CacheInfo *magick_restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); if (clone_info == (Cache) NULL) return((Cache) NULL); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickPrivate void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *magick_restrict cache_info, *magick_restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickCoreSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClonePixelCacheOnDisk( CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info) { MagickSizeType extent; size_t quantum; ssize_t count; struct stat file_stats; unsigned char *buffer; /* Clone pixel cache on disk with identical morphology. */ if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) || (OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse)) return(MagickFalse); quantum=(size_t) MagickMaxBufferExtent; if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0)) quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); extent=0; while ((count=read(cache_info->file,buffer,quantum)) > 0) { ssize_t number_bytes; number_bytes=write(clone_info->file,buffer,(size_t) count); if (number_bytes != count) break; extent+=number_bytes; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (extent != cache_info->length) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads 2 #define cache_threads(source,destination) \ num_threads(((source)->type == DiskCache) || \ ((destination)->type == DiskCache) || (((source)->rows) < \ (16*GetMagickResourceLimit(ThreadResource))) ? 1 : \ GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \ GetMagickResourceLimit(ThreadResource) : MaxCacheThreads) MagickBooleanType optimize, status; NexusInfo **magick_restrict cache_nexus, **magick_restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); length=cache_info->number_channels*sizeof(*cache_info->channel_map); if ((cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) && (cache_info->metacontent_extent == clone_info->metacontent_extent)) { /* Identical pixel cache morphology. */ if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache))) { (void) memcpy(clone_info->pixels,cache_info->pixels, cache_info->columns*cache_info->number_channels*cache_info->rows* sizeof(*cache_info->pixels)); if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) (void) memcpy(clone_info->metacontent,cache_info->metacontent, cache_info->columns*cache_info->rows* clone_info->metacontent_extent*sizeof(unsigned char)); return(MagickTrue); } if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache)) return(ClonePixelCacheOnDisk(cache_info,clone_info)); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads); clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads); if ((cache_nexus == (NexusInfo **) NULL) || (clone_nexus == (NexusInfo **) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); length=cache_info->number_channels*sizeof(*cache_info->channel_map); optimize=(cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) ? MagickTrue : MagickFalse; length=(size_t) MagickMin(cache_info->columns*cache_info->number_channels, clone_info->columns*clone_info->number_channels); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ cache_threads(cache_info,clone_info) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; RectangleInfo region; register ssize_t x; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region, cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region, clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; (void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); if (optimize != MagickFalse) (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length* sizeof(Quantum)); else { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; /* Mismatched pixel channel map. */ p=cache_nexus[id]->pixels; q=clone_nexus[id]->pixels; for (x=0; x < (ssize_t) cache_info->columns; x++) { register ssize_t i; if (x == (ssize_t) clone_info->columns) break; for (i=0; i < (ssize_t) clone_info->number_channels; i++) { PixelChannel channel; PixelTrait traits; channel=clone_info->channel_map[i].channel; traits=cache_info->channel_map[channel].traits; if (traits != UndefinedPixelTrait) *q=*(p+cache_info->channel_map[channel].offset); q++; } p+=cache_info->number_channels; } } status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) { /* Clone metacontent. */ length=(size_t) MagickMin(cache_info->metacontent_extent, clone_info->metacontent_extent); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ cache_threads(cache_info,clone_info) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region, cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCacheMetacontent(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region, clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; if ((clone_nexus[id]->metacontent != (void *) NULL) && (cache_nexus[id]->metacontent != (void *) NULL)) (void) memcpy(clone_nexus[id]->metacontent, cache_nexus[id]->metacontent,length*sizeof(unsigned char)); status=WritePixelCacheMetacontent(clone_info,clone_nexus[id],exception); } } cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads); clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache == (void *) NULL) return; image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { #if defined(MAGICKCORE_OPENCL_SUPPORT) if (cache_info->opencl != (MagickCLCacheInfo) NULL) { cache_info->opencl=RelinquishMagickCLCacheInfo(cache_info->opencl, MagickTrue); cache_info->pixels=(Quantum *) NULL; break; } #endif if (cache_info->mapped == MagickFalse) cache_info->pixels=(Quantum *) RelinquishAlignedMemory( cache_info->pixels); else (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(Quantum *) NULL; if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->metacontent=(void *) NULL; } MagickPrivate Cache DestroyPixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickCoreSignature); cache_info=(CacheInfo *) RelinquishMagickMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(Quantum *) NULL; nexus_info->pixels=(Quantum *) NULL; nexus_info->metacontent=(void *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickPrivate NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { register ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) number_threads; i++) { if (nexus_info[i]->cache != (Quantum *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickCoreSignature); } nexus_info[0]=(NexusInfo *) RelinquishMagickMemory(nexus_info[0]); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontent() returns the authentic metacontent corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the associated pixels are not available. % % The format of the GetAuthenticMetacontent() method is: % % void *GetAuthenticMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void *GetAuthenticMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) { void *metacontent; metacontent=cache_info->methods. get_authentic_metacontent_from_handler(image); return(metacontent); } assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontentFromCache() returns the meta-content corresponding % with the last call to QueueAuthenticPixelsCache() or % GetAuthenticPixelsCache(). % % The format of the GetAuthenticMetacontentFromCache() method is: % % void *GetAuthenticMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *GetAuthenticMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticOpenCLBuffer() returns an OpenCL buffer used to execute OpenCL % operations. % % The format of the GetAuthenticOpenCLBuffer() method is: % % cl_mem GetAuthenticOpenCLBuffer(const Image *image, % MagickCLDevice device,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o device: the device to use. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate cl_mem GetAuthenticOpenCLBuffer(const Image *image, MagickCLDevice device,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; cl_int status; assert(image != (const Image *) NULL); assert(device != (const MagickCLDevice) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info->type == UndefinedCache) SyncImagePixelCache((Image *) image,exception); if ((cache_info->type != MemoryCache) || (cache_info->mapped != MagickFalse)) return((cl_mem) NULL); if ((cache_info->opencl != (MagickCLCacheInfo) NULL) && (cache_info->opencl->device->context != device->context)) cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); if (cache_info->opencl == (MagickCLCacheInfo) NULL) { assert(cache_info->pixels != (Quantum *) NULL); cache_info->opencl=AcquireMagickCLCacheInfo(device,cache_info->pixels, cache_info->length); if (cache_info->opencl == (MagickCLCacheInfo) NULL) return((cl_mem) NULL); } assert(cache_info->opencl->pixels == cache_info->pixels); return(cache_info->opencl->buffer); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (Quantum *) NULL) return((Quantum *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); if (cache_info->metacontent_extent != 0) if (ReadPixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % Quantum *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static Quantum *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated % corresponding with the last call to QueueAuthenticPixels() or % GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % Quantum *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Quantum *GetAuthenticPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a Quantum array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image has corresponding metacontent,call % GetAuthenticMetacontent() after invoking GetAuthenticPixels() to obtain the % meta-content corresponding to the region. Once the Quantum array has % been updated, the changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % Quantum *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *magick_restrict image) { const CacheInfo *magick_restrict cache_info; const PixelChannelMap *magick_restrict p, *magick_restrict q; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; p=image->channel_map; q=cache_info->channel_map; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->alpha_trait != cache_info->alpha_trait) || (image->read_mask != cache_info->read_mask) || (image->write_mask != cache_info->write_mask) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (image->number_channels != cache_info->number_channels) || (memcmp(p,q,image->number_channels*sizeof(*p)) != 0) || (image->metacontent_extent != cache_info->metacontent_extent) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cache_timelimit = MagickResourceInfinity, cpu_throttle = MagickResourceInfinity, cycles = 0; status=MagickTrue; if (cpu_throttle == MagickResourceInfinity) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != 0) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (cache_epoch == 0) { /* Set the expire time in seconds. */ cache_timelimit=GetMagickResourceLimit(TimeResource); cache_epoch=time((time_t *) NULL); } if ((cache_timelimit != MagickResourceInfinity) && ((MagickSizeType) (time((time_t *) NULL)-cache_epoch) >= cache_timelimit)) { #if defined(ECANCELED) errno=ECANCELED; #endif ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } LockSemaphoreInfo(image->semaphore); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AcquireSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status != MagickFalse) { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status != MagickFalse) { if (cache_info->reference_count == 1) cache_info->nexus_info=(NexusInfo **) NULL; destroy=MagickTrue; image->cache=clone_image.cache; } } RelinquishSemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ image->type=UndefinedType; if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->type == DiskCache) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MemoryCache, MapCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType CopyPixel(const Image *image, const Quantum *source,Quantum *destination) { register ssize_t i; if (source == (const Quantum *) NULL) { destination[RedPixelChannel]=ClampToQuantum(image->background_color.red); destination[GreenPixelChannel]=ClampToQuantum( image->background_color.green); destination[BluePixelChannel]=ClampToQuantum( image->background_color.blue); destination[BlackPixelChannel]=ClampToQuantum( image->background_color.black); destination[AlphaPixelChannel]=ClampToQuantum( image->background_color.alpha); return(MagickFalse); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); destination[channel]=source[i]; } return(MagickTrue); } MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; register Quantum *magick_restrict q; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y, pixel,exception)); q=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,Quantum *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); q=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,cache_info->nexus_info[id], exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelInfo() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixelInfo() method is: % % MagickBooleanType GetOneVirtualPixelInfo(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,PixelInfo *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixelInfo(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelInfo *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); GetPixelInfo(image,pixel); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (p == (const Quantum *) NULL) return(MagickFalse); GetPixelInfoPixel(image,p,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the class type of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheFilename() returns the filename associated with the pixel % cache. % % The format of the GetPixelCacheFilename() method is: % % const char *GetPixelCacheFilename(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetPixelCacheFilename(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->cache_filename); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) ResetMagickMemory(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_metacontent_from_handler= GetVirtualMetacontentFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_metacontent_from_handler= GetAuthenticMetacontentFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated % corresponding with the last call to SetPixelCacheNexusPixels() or % GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickPrivate MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=cache_info->length; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickPrivate ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimized cache tile width in pixels. % % o height: the optimized cache tile height in pixels. % */ MagickPrivate void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *width=2048UL/(cache_info->number_channels*sizeof(Quantum)); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/(cache_info->number_channels*sizeof(Quantum)); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromCache() returns the meta-content corresponding with % the last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualMetacontentFromCache() method is: % % void *GetVirtualMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const void *GetVirtualMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromNexus() returns the meta-content for the specified % cache nexus. % % The format of the GetVirtualMetacontentFromNexus() method is: % % const void *GetVirtualMetacontentFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the meta-content. % */ MagickPrivate const void *GetVirtualMetacontentFromNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((void *) NULL); return(nexus_info->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontent() returns the virtual metacontent corresponding with % the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the meta-content are not available. % % The format of the GetVirtualMetacontent() method is: % % const void *GetVirtualMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const void *GetVirtualMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); metacontent=cache_info->methods.get_virtual_metacontent_from_handler(image); if (metacontent != (void *) NULL) return(metacontent); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsFromNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelsFromNexus() method is: % % Quantum *GetVirtualPixelsFromNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; /* Compute the remainder of dividing offset by extent. It returns not only the quotient (tile the offset falls in) but also the positive remainer within that tile such that 0 <= remainder < extent. This method is essentially a ldiv() using a floored modulo division rather than the normal default truncated modulo division. */ modulo.quotient=offset/(ssize_t) extent; if (offset < 0L) modulo.quotient--; modulo.remainder=offset-modulo.quotient*(ssize_t) extent; return(modulo); } MagickPrivate const Quantum *GetVirtualPixelsFromNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo **magick_restrict virtual_nexus; Quantum *magick_restrict pixels, virtual_pixel[MaxPixelChannels]; RectangleInfo region; register const Quantum *magick_restrict p; register const void *magick_restrict r; register Quantum *magick_restrict q; register ssize_t i, u; register unsigned char *magick_restrict s; ssize_t v; void *magick_restrict virtual_metacontent; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((const Quantum *) NULL); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,nexus_info, exception); if (pixels == (Quantum *) NULL) return((const Quantum *) NULL); q=pixels; offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns) <= (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows) <= (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(q); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); if (cache_info->metacontent_extent != 0) { status=ReadPixelCacheMetacontent(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); } return(q); } /* Pixel request is outside cache extents. */ s=(unsigned char *) nexus_info->metacontent; virtual_nexus=AcquirePixelCacheNexus(1); if (virtual_nexus == (NexusInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "UnableToGetCacheNexus","`%s'",image->filename); return((const Quantum *) NULL); } (void) ResetMagickMemory(virtual_pixel,0,cache_info->number_channels* sizeof(*virtual_pixel)); virtual_metacontent=(void *) NULL; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: case EdgeVirtualPixelMethod: case CheckerTileVirtualPixelMethod: case HorizontalTileVirtualPixelMethod: case VerticalTileVirtualPixelMethod: { if (cache_info->metacontent_extent != 0) { /* Acquire a metacontent buffer. */ virtual_metacontent=(void *) AcquireQuantumMemory(1, cache_info->metacontent_extent); if (virtual_metacontent == (void *) NULL) { virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); (void) ThrowMagickException(exception,GetMagickModule(), CacheError,"UnableToGetCacheNexus","`%s'",image->filename); return((const Quantum *) NULL); } (void) ResetMagickMemory(virtual_metacontent,0, cache_info->metacontent_extent); } switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case GrayVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange/2, virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case TransparentVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,TransparentAlpha,virtual_pixel); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } default: { SetPixelRed(image,ClampToQuantum(image->background_color.red), virtual_pixel); SetPixelGreen(image,ClampToQuantum(image->background_color.green), virtual_pixel); SetPixelBlue(image,ClampToQuantum(image->background_color.blue), virtual_pixel); SetPixelBlack(image,ClampToQuantum(image->background_color.black), virtual_pixel); SetPixelAlpha(image,ClampToQuantum(image->background_color.alpha), virtual_pixel); break; } } break; } default: break; } for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=virtual_pixel; r=virtual_metacontent; break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=virtual_pixel; r=virtual_metacontent; break; } p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } } if (p == (const Quantum *) NULL) break; (void) memcpy(q,p,(size_t) length*cache_info->number_channels* sizeof(*p)); q+=cache_info->number_channels; if ((s != (void *) NULL) && (r != (const void *) NULL)) { (void) memcpy(s,r,(size_t) cache_info->metacontent_extent); s+=cache_info->metacontent_extent; } continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,*virtual_nexus,exception); if (p == (const Quantum *) NULL) break; r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); (void) memcpy(q,p,(size_t) length*cache_info->number_channels*sizeof(*p)); q+=length*cache_info->number_channels; if ((r != (void *) NULL) && (s != (const void *) NULL)) { (void) memcpy(s,r,(size_t) length); s+=length*cache_info->metacontent_extent; } } if (u < (ssize_t) columns) break; } /* Free resources. */ if (virtual_metacontent != (void *) NULL) virtual_metacontent=(void *) RelinquishMagickMemory(virtual_metacontent); virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); if (v < (ssize_t) rows) return((const Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const Quantum *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const Quantum *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const Quantum *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const Quantum *GetVirtualPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % access the meta-content (of type void) corresponding to the the % region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const Quantum *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const Quantum *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated corresponding with the % last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % Quantum *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const Quantum *GetVirtualPixelsCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const Quantum *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickPrivate const Quantum *GetVirtualPixelsNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((Quantum *) NULL); return((const Quantum *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % metacontent, and memory mapping the cache if it is disk based. The cache % nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if defined(SIGBUS) static void CacheSignalHandler(int status) { ThrowFatalException(CacheFatalError,"UnableToExtendPixelCache"); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if ((cache_info->file != -1) && (cache_info->mode == mode)) return(MagickTrue); /* cache already open and in the proper mode */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); cache_info->file=file; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *magick_restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MagickPathExtent], message[MagickPathExtent]; (void) FormatMagickSize(length,MagickFalse,"B",MagickPathExtent,format); (void) FormatLocaleString(message,MagickPathExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (length != (MagickSizeType) ((MagickOffsetType) length)) return(MagickFalse); offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) count=(MagickOffsetType) 1; else { extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); if (count != 1) return(MagickFalse); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) (void) posix_fallocate(cache_info->file,offset+1,extent-offset); #endif #if defined(SIGBUS) (void) signal(SIGBUS,CacheSignalHandler); #endif } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET); if (offset < 0) return(MagickFalse); return(MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (cache_anonymous_memory < 0) { char *value; /* Does the security policy require anonymous mapping for pixel cache? */ cache_anonymous_memory=0; value=GetPolicyValue("pixel-cache-memory"); if (value == (char *) NULL) value=GetPolicyValue("cache:memory-map"); if (LocaleCompare(value,"anonymous") == 0) { #if defined(MAGICKCORE_HAVE_MMAP) && defined(MAP_ANONYMOUS) cache_anonymous_memory=1; #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn", "'%s' (policy requires anonymous memory mapping)",image->filename); #endif } value=DestroyString(value); } if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]", image->filename,(double) GetImageIndexInList(image)); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->read_mask=image->read_mask; cache_info->write_mask=image->write_mask; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); if (cache_info->mode == PersistMode) status=MagickFalse; length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { status=MagickTrue; if (cache_anonymous_memory <= 0) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); } else { cache_info->mapped=MagickTrue; cache_info->pixels=(Quantum *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } if (cache_info->pixels == (Quantum *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ status=MagickTrue; cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode) && (cache_info->mode != PersistMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) { status=MagickTrue; cache_info->type=DiskCache; } else { status=MagickTrue; cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->type=DiskCache; cache_info->pixels=source_info.pixels; } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } RelinquishMagickResource(MapResource,cache_info->length); } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status == 0 ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, *magick_restrict clone_info; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MagickPathExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(MagickTrue); } /* Clone persistent pixel cache. */ clone_info=(CacheInfo *) ClonePixelCache(cache_info); clone_info->type=DiskCache; (void) CopyMagickString(clone_info->cache_filename,filename,MagickPathExtent); clone_info->file=(-1); clone_info->storage_class=cache_info->storage_class; clone_info->colorspace=cache_info->colorspace; clone_info->alpha_trait=cache_info->alpha_trait; clone_info->read_mask=cache_info->read_mask; clone_info->write_mask=cache_info->write_mask; clone_info->rows=cache_info->rows; clone_info->columns=cache_info->columns; clone_info->number_channels=cache_info->number_channels; clone_info->metacontent_extent=cache_info->metacontent_extent; clone_info->mode=PersistMode; clone_info->length=cache_info->length; (void) memcpy(clone_info->channel_map,cache_info->channel_map, MaxPixelChannels*sizeof(*cache_info->channel_map)); clone_info->offset=(*offset); status=ClonePixelCacheRepository(clone_info,cache_info,exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % Quantum *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; Quantum *magick_restrict pixels; RectangleInfo region; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((Quantum *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((Quantum *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((Quantum *) NULL); /* Return pixel cache. */ region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,&region,nexus_info, exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a Quantum array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % obtain the meta-content (of type void) corresponding to the region. % Once the Quantum (and/or Quantum) array has been updated, the % changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.queue_authentic_pixels_handler(image,x,y, columns,rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheMetacontent() reads metacontent from the specified region of % the pixel cache. % % The format of the ReadPixelCacheMetacontent() method is: % % MagickBooleanType ReadPixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the metacontent. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheMetacontent( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register ssize_t y; register unsigned char *magick_restrict q; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; q=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict p; /* Read meta-content from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->metacontent_extent*cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } break; } case DiskCache: { /* Read meta content from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read metacontent from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register Quantum *magick_restrict q; register ssize_t y; size_t number_channels, rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns; if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y) return(MagickFalse); offset+=nexus_info->region.x; number_channels=cache_info->number_channels; length=(MagickSizeType) number_channels*nexus_info->region.width* sizeof(Quantum); if ((length/number_channels/sizeof(Quantum)) != nexus_info->region.width) return(MagickFalse); rows=nexus_info->region.height; extent=length*rows; if ((extent == 0) || ((extent/length) != rows)) return(MagickFalse); y=0; q=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+offset*cache_info->number_channels; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*q),length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickPrivate Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheChannels() resets the pixel cache channels. % % The format of the ResetPixelCacheChannels method is: % % void ResetPixelCacheChannels(Image *) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate void ResetPixelCacheChannels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); cache_info->number_channels=GetPixelChannels(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e E p o c h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheEpoch() resets the pixel cache epoch. % % The format of the ResetPixelCacheEpoch method is: % % void ResetPixelCacheEpoch(void) % */ MagickPrivate void ResetPixelCacheEpoch(void) { cache_epoch=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *magick_restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_metacontent_from_handler != (GetVirtualMetacontentFromHandler) NULL) cache_info->methods.get_virtual_metacontent_from_handler= cache_methods->get_virtual_metacontent_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) cache_info->methods.get_authentic_metacontent_from_handler= cache_methods->get_authentic_metacontent_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % Quantum SetPixelCacheNexusPixels(const CacheInfo *cache_info, % const MapMode mode,const RectangleInfo *region,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o region: A pointer to the RectangleInfo structure that defines the % region of this particular cache nexus. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *magick_restrict cache_info,NexusInfo *nexus_info, ExceptionInfo *exception) { if (nexus_info->length != (MagickSizeType) ((size_t) nexus_info->length)) return(MagickFalse); if (cache_anonymous_memory <= 0) { nexus_info->mapped=MagickFalse; nexus_info->cache=(Quantum *) MagickAssumeAligned(AcquireAlignedMemory(1, (size_t) nexus_info->length)); if (nexus_info->cache != (Quantum *) NULL) (void) ResetMagickMemory(nexus_info->cache,0,(size_t) nexus_info->length); } else { nexus_info->mapped=MagickTrue; nexus_info->cache=(Quantum *) MapBlob(-1,IOMode,0,(size_t) nexus_info->length); } if (nexus_info->cache == (Quantum *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } return(MagickTrue); } static inline MagickBooleanType IsPixelCacheAuthentic( const CacheInfo *magick_restrict cache_info, const NexusInfo *magick_restrict nexus_info) { MagickBooleanType status; MagickOffsetType offset; /* Does nexus pixels point directly to in-core cache pixels or is it buffered? */ if (cache_info->type == PingCache) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; status=nexus_info->pixels == (cache_info->pixels+offset* cache_info->number_channels) ? MagickTrue : MagickFalse; return(status); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels,0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels,1,1); } static Quantum *SetPixelCacheNexusPixels(const CacheInfo *cache_info, const MapMode mode,const RectangleInfo *region,NexusInfo *nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((Quantum *) NULL); nexus_info->region=(*region); if ((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) { ssize_t x, y; x=nexus_info->region.x+(ssize_t) nexus_info->region.width-1; y=nexus_info->region.y+(ssize_t) nexus_info->region.height-1; if (((nexus_info->region.x >= 0) && (x < (ssize_t) cache_info->columns) && (nexus_info->region.y >= 0) && (y < (ssize_t) cache_info->rows)) && ((nexus_info->region.height == 1UL) || ((nexus_info->region.x == 0) && ((nexus_info->region.width == cache_info->columns) || ((nexus_info->region.width % cache_info->columns) == 0))))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; nexus_info->pixels=cache_info->pixels+cache_info->number_channels* offset; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(unsigned char *) cache_info->metacontent+ offset*cache_info->metacontent_extent; PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsPixelCacheAuthentic(cache_info, nexus_info); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; length=number_pixels*cache_info->number_channels*sizeof(Quantum); if (cache_info->metacontent_extent != 0) length+=number_pixels*cache_info->metacontent_extent; if (nexus_info->cache == (Quantum *) NULL) { nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((Quantum *) NULL); } } else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((Quantum *) NULL); } } nexus_info->pixels=nexus_info->cache; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(void *) (nexus_info->pixels+number_pixels* cache_info->number_channels); PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsPixelCacheAuthentic(cache_info, nexus_info); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } status=SyncCacheViewAuthenticPixels(image_view,exception); } image_view=DestroyCacheView(image_view); return(status); } MagickPrivate VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); if ((IsPixelInfoGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); break; } case TransparentVirtualPixelMethod: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); break; } default: break; } return(method); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticOpenCLBuffer() makes sure that all the OpenCL operations have % been completed and updates the host memory. % % The format of the SyncAuthenticOpenCLBuffer() method is: % % void SyncAuthenticOpenCLBuffer(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void CopyOpenCLBuffer(CacheInfo *magick_restrict cache_info) { assert(cache_info != (CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->type != MemoryCache) || (cache_info->opencl == (MagickCLCacheInfo) NULL)) return; /* Ensure single threaded access to OpenCL environment. */ LockSemaphoreInfo(cache_info->semaphore); cache_info->opencl=(MagickCLCacheInfo) CopyMagickCLCacheInfo( cache_info->opencl); UnlockSemaphoreInfo(cache_info->semaphore); } MagickPrivate void SyncAuthenticOpenCLBuffer(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); cache_info=(CacheInfo *) image->cache; CopyOpenCLBuffer(cache_info); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) { image->taint=MagickTrue; return(MagickTrue); } assert(cache_info->signature == MagickCoreSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->metacontent_extent != 0) && (WritePixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (status != MagickFalse) image->taint=MagickTrue; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) { status=cache_info->methods.sync_authentic_pixels_handler(image, exception); return(status); } assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheMetacontent() writes the meta-content to the specified region % of the pixel cache. % % The format of the WritePixelCacheMetacontent() method is: % % MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the meta-content. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const unsigned char *magick_restrict p; register ssize_t y; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=(MagickSizeType) length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict q; /* Write associated pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width*cache_info->metacontent_extent; q+=cache_info->columns*cache_info->metacontent_extent; } break; } case DiskCache: { /* Write associated pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write metacontent to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const Quantum *magick_restrict p; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) cache_info->number_channels*nexus_info->region.width* sizeof(Quantum); extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+offset*cache_info->number_channels; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*nexus_info->region.width; q+=cache_info->columns*cache_info->number_channels; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*p),length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
master.c
#include <stdio.h> #include <omp.h> int main() { #pragma omp parallel { printf("Start of Secret\n"); #pragma omp master { printf("Only Master knows the SECRET\n"); } printf("Secret Delivered\n"); } }
image2pdf.c
/** @file image2pdf.c * * Oyranos is an open source Color Management System * * Copyright (C) 2008-2012 Kai-Uwe Behrmann * */ /** * @brief public Oyranos API's * @internal * @author Kai-Uwe Behrmann <ku.b@gmx.de> * @par License: * new BSD <http://www.opensource.org/licenses/BSD-3-Clause> * @since 2008/09/26 * * A sample application on how to compose a set of camera raw files into a pdf, * while keeping attention to user color settings. * Beside Cairo and Oyranos you need DCraw during runtime. * * Compile: cc -pedantic -Wall -g `oyranos-config --cflags` `oyranos-config --ld_x_flags` `pkg-config --cflags --libs cairo` image2pdf.c -o image2pdf */ # include <stddef.h> #define __USE_POSIX2 1 #include <stdio.h> /* popen() */ FILE *popen ( const char *__command, const char *__modes); #include <math.h> #include <string.h> #include <oyConversion_s.h> #include <oyProfile_s.h> /* Oyranos headers */ #include <oyranos_devices.h> #include <cairo.h> /* Cairo headers */ #include <cairo-pdf.h> #define MIN(a,b) ((a<b)?(a):(b)) #define MAX(a,b) ((a>b)?(a):(b)) int main (int argc, char ** argv) { int result = 0; int i,j,o, error; cairo_t * cr = 0; cairo_surface_t * surface = NULL, * image_surf = NULL; cairo_status_t status; double page_w = 210.0, /* page width in mm */ page_h = 297.0, resolution = 72.0, /* Cairo PDF surface resolution */ scale = 1.0, frame = 0; int pixel_w, pixel_h, /* page size in pixel */ x,y,w=0,h=0, /* image dimensions */ to_moni = 0; size_t size = 0; unsigned char * image_data = 0, rgba[4] = {127,127,127,255}; oyProfile_s * monitor, * print, * output; oyConversion_s * to_output = 0; oyConfig_s * device = 0; uint32_t icc_profile_flags = 0; if(argc < 2) { printf("Merge some CamerRAW images into one output image and use\n"); printf("Oyranos CMS settings to obtain the result.\n"); printf("\n"); printf("Usage of the image2pdf example application:"); printf(" To obtain a PDF (test.pdf):\n"); printf(" image2pdf imageA.raw imageB.raw\n"); printf(" To obtain a monitor preview (test.png):\n"); printf(" image2pdf --monitor imageA.raw imageB.raw\n"); return 1; } o = 1; if(strcmp(argv[o],"--monitor") == 0 || strcmp(argv[o],"-m") == 0) { ++o; to_moni = 1; resolution = 96; } pixel_w = page_w / 25.4 * resolution; pixel_h = page_h / 25.4 * resolution; /* create a surface to place our images on */ if(to_moni) surface = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, pixel_w,pixel_h); else surface = cairo_pdf_surface_create( "test.pdf", pixel_w, pixel_h ); status = cairo_surface_status( surface ); if(status) return 1; /* select profiles matching actual capabilities */ icc_profile_flags = oyICCProfileSelectionFlagsFromOptions( OY_CMM_STD, "//" OY_TYPE_STD "/icc_color", NULL, 0 ); /* The monitor profile is located in the Xserver. For details see: * http://www.freedesktop.org/wiki/Specifications/icc_profiles_in_x_spec */ error = oyDeviceGet( OY_TYPE_STD, "monitor", 0, 0, &device ); error = oyDeviceGetProfile( device, 0, &monitor ); if(error > 0) fprintf(stderr, "oyDeviceGetProfile error: %d\n", error); printf("monitor: %s\n", oyProfile_GetText( monitor, oyNAME_DESCRIPTION ) ); /* The output profile is equal to sRGB, as output profiles are curently not * supported in Cairo. */ print = oyProfile_FromStd( oyASSUMED_WEB, icc_profile_flags, 0 ); printf("print: %s\n", oyProfile_GetText( print, oyNAME_DESCRIPTION )); cr = cairo_create( surface ); cairo_set_source_rgba( cr, rgba[0]/255., rgba[1]/255., rgba[2]/255., 1.0 ); cairo_rectangle( cr, 0, 0, pixel_w, pixel_h ); cairo_fill( cr ); for ( i=0; i < argc-o; ++i ) { const char * filename = argv[i+o]; oyOptions_s * options = NULL; oyImage_s * in = NULL, * out = NULL; error = oyImage_FromFile( filename, icc_profile_flags, &in, NULL ); w = oyImage_GetWidth( in ); h = oyImage_GetHeight( in ); if(!(w && h)) { oyImage_Release( &in ); continue; } /* create a Cairo image */ image_surf = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, w, h ); status = cairo_surface_status( image_surf ); if(status) return 1; /* write our dcraw stream on the Cairo image */ image_data = cairo_image_surface_get_data( image_surf ); size = w*h; /* build the color context */ if( to_moni ) { output = oyProfile_Copy( monitor, 0 ); } else { output = oyProfile_Copy( print, 0 ); } out = oyImage_Create( w, h, image_data, oyChannels_m(oyProfile_GetChannelsCount(output)+1) | oyDataType_m(oyUINT8), output, 0 ); /* create a processing graph to convert from one image to an other */ to_output = oyConversion_CreateBasicPixels( in, out, options, 0 ); /* tell Oyranos to apply defaults */ oyConversion_Correct( to_output, "//" OY_TYPE_STD "/icc_color", oyOPTIONATTRIBUTE_ADVANCED, 0 ); /* transform colors */ oyConversion_RunPixels( to_output, NULL ); oyConversion_Release( &to_output ); /*oyImage_WritePPM( out, "test_out.ppm", "out" );*/ oyImage_Release( &in ); oyImage_Release( &out ); /* Cairo uses a Blue Green Red Alpha channel layout */ #pragma omp parallel for for(j = 0; j < (int)size; ++j) { unsigned char t = image_data[j*4+2]; image_data[j*4+2] = image_data[j*4+0]; /*image_data[j*4+1] = 0;*/ image_data[j*4+0] = t; image_data[j*4+3] = 255; } cairo_surface_mark_dirty( image_surf ); /* place our images on a sheet */ if(argc-o > 1) { /* place in contact sheed style */ scale = (pixel_w - pixel_w/10.0)/4.0/(double)MAX(w,h); cairo_save( cr ); x = i%4 * (pixel_w - pixel_w/20.0)/4.0 + pixel_w/30.0; y = i/4 * (pixel_w - pixel_w/20.0)/4.0 + ((pixel_w - pixel_w/20.0)/4.0 - MIN(w,h)*scale)/2.0 + pixel_w/30.0; } else { /* single image */ scale = (pixel_w - pixel_w/10.0)/(double)MAX(w,h); x = pixel_w/20.0; y = ((pixel_w - pixel_w/20.0) - MIN(w,h)*scale)/2.0 + pixel_w/20.0; } /* draw a frame around the image */ frame = pixel_w/20.0 * scale; cairo_set_source_rgba( cr, .0, .0, .0, 1.0); cairo_set_line_width (cr, 1.); cairo_rectangle( cr, x - frame, y - frame, w*scale + 2*frame, h*scale + 2*frame); cairo_stroke(cr); /* draw the image */ cairo_translate( cr, x, y ); cairo_scale( cr, scale, scale ); cairo_set_source_surface( cr, image_surf, 0,0 ); cairo_paint( cr ); cairo_restore( cr ); /* small clean */ cairo_surface_destroy( image_surf ); } if(to_moni) cairo_surface_write_to_png( surface, "test.png" ); cairo_surface_finish( surface ); /* clean */ cairo_surface_destroy( surface ); oyProfile_Release( &monitor ); oyProfile_Release( &print ); return result; }
par_csr_matop_device.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "_hypre_utilities.h" #include "_hypre_parcsr_mv.h" #include "_hypre_utilities.hpp" #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) HYPRE_Int hypre_ParcsrGetExternalRowsDeviceInit( hypre_ParCSRMatrix *A, HYPRE_Int indices_len, HYPRE_BigInt *indices, hypre_ParCSRCommPkg *comm_pkg, HYPRE_Int want_data, void **request_ptr) { HYPRE_Int i, j; HYPRE_Int num_sends, num_rows_send, num_nnz_send, num_recvs, num_rows_recv, num_nnz_recv; HYPRE_Int *d_send_i, *send_i, *d_send_map, *d_recv_i, *recv_i; HYPRE_BigInt *d_send_j, *d_recv_j; HYPRE_Int *send_jstarts, *recv_jstarts; HYPRE_Complex *d_send_a = NULL, *d_recv_a = NULL; hypre_ParCSRCommPkg *comm_pkg_j; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; /* HYPRE_Int global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); */ /* diag part of A */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); /* HYPRE_Int local_num_rows = hypre_CSRMatrixNumRows(A_diag); */ /* off-diag part of A */ hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /* HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); */ /* HYPRE_Int first_row = hypre_ParCSRMatrixFirstRowIndex(A); */ HYPRE_Int first_col = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *d_col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A); MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_Int num_procs; HYPRE_Int my_id; void **vrequest; hypre_CSRMatrix *A_ext; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); /* number of sends (#procs) */ num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); /* number of rows to send */ num_rows_send = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); /* number of recvs (#procs) */ num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); /* number of rows to recv */ num_rows_recv = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs); /* must be true if indices contains proper offd indices */ hypre_assert(indices_len == num_rows_recv); /* send_i/recv_i: * the arrays to send and recv: we first send and recv the row lengths */ d_send_i = hypre_TAlloc(HYPRE_Int, num_rows_send + 1, HYPRE_MEMORY_DEVICE); d_send_map = hypre_TAlloc(HYPRE_Int, num_rows_send, HYPRE_MEMORY_DEVICE); send_i = hypre_TAlloc(HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST); recv_i = hypre_TAlloc(HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_HOST); d_recv_i = hypre_TAlloc(HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_DEVICE); /* fill the send array with row lengths */ hypre_TMemcpy(d_send_map, hypre_ParCSRCommPkgSendMapElmts(comm_pkg), HYPRE_Int, num_rows_send, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_Memset(d_send_i, 0, sizeof(HYPRE_Int), HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(num_rows_send, d_send_map, A_diag_i, A_offd_i, d_send_i + 1); /* send array send_i out: deviceTohost first and MPI (async) * note the shift in recv_i by one */ hypre_TMemcpy(send_i, d_send_i + 1, HYPRE_Int, num_rows_send, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, send_i, recv_i + 1); hypreDevice_IntegerInclusiveScan(num_rows_send + 1, d_send_i); /* total number of nnz to send */ hypre_TMemcpy(&num_nnz_send, d_send_i + num_rows_send, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); /* prepare data to send out. overlap with the above commmunication */ d_send_j = hypre_TAlloc(HYPRE_BigInt, num_nnz_send, HYPRE_MEMORY_DEVICE); if (want_data) { d_send_a = hypre_TAlloc(HYPRE_Complex, num_nnz_send, HYPRE_MEMORY_DEVICE); } if (d_col_map_offd_A == NULL) { d_col_map_offd_A = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(d_col_map_offd_A, col_map_offd_A, HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDeviceColMapOffd(A) = d_col_map_offd_A; } /* job == 2, d_send_i is input that contains row ptrs (length num_rows_send) */ hypreDevice_CopyParCSRRows(num_rows_send, d_send_map, 2, num_procs > 1, first_col, d_col_map_offd_A, A_diag_i, A_diag_j, A_diag_a, A_offd_i, A_offd_j, A_offd_a, d_send_i, d_send_j, d_send_a); /* pointers to each proc in send_j */ send_jstarts = hypre_TAlloc(HYPRE_Int, num_sends + 1, HYPRE_MEMORY_HOST); send_jstarts[0] = 0; for (i = 1; i <= num_sends; i++) { send_jstarts[i] = send_jstarts[i - 1]; for ( j = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i - 1); j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); j++ ) { send_jstarts[i] += send_i[j]; } } hypre_assert(send_jstarts[num_sends] == num_nnz_send); /* finish the above communication: send_i/recv_i */ hypre_ParCSRCommHandleDestroy(comm_handle); /* adjust recv_i to ptrs */ recv_i[0] = 0; for (i = 1; i <= num_rows_recv; i++) { recv_i[i] += recv_i[i - 1]; } num_nnz_recv = recv_i[num_rows_recv]; /* allocate device memory for j and a */ d_recv_j = hypre_TAlloc(HYPRE_BigInt, num_nnz_recv, HYPRE_MEMORY_DEVICE); if (want_data) { d_recv_a = hypre_TAlloc(HYPRE_Complex, num_nnz_recv, HYPRE_MEMORY_DEVICE); } recv_jstarts = hypre_TAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); recv_jstarts[0] = 0; for (i = 1; i <= num_recvs; i++) { j = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i); recv_jstarts[i] = recv_i[j]; } /* ready to send and recv: create a communication package for data */ comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm (comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends (comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs (comm_pkg_j) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = send_jstarts; hypre_ParCSRCommPkgNumRecvs (comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgRecvProcs (comm_pkg_j) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = recv_jstarts; /* init communication */ /* ja */ comm_handle_j = hypre_ParCSRCommHandleCreate_v2(21, comm_pkg_j, HYPRE_MEMORY_DEVICE, d_send_j, HYPRE_MEMORY_DEVICE, d_recv_j); if (want_data) { /* a */ comm_handle_a = hypre_ParCSRCommHandleCreate_v2(1, comm_pkg_j, HYPRE_MEMORY_DEVICE, d_send_a, HYPRE_MEMORY_DEVICE, d_recv_a); } else { comm_handle_a = NULL; } hypre_TMemcpy(d_recv_i, recv_i, HYPRE_Int, num_rows_recv + 1, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); /* create A_ext: on device */ A_ext = hypre_CSRMatrixCreate(num_rows_recv, hypre_ParCSRMatrixGlobalNumCols(A), num_nnz_recv); hypre_CSRMatrixI (A_ext) = d_recv_i; hypre_CSRMatrixBigJ(A_ext) = d_recv_j; hypre_CSRMatrixData(A_ext) = d_recv_a; hypre_CSRMatrixMemoryLocation(A_ext) = HYPRE_MEMORY_DEVICE; /* output */ vrequest = hypre_TAlloc(void *, 3, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) A_ext; *request_ptr = (void *) vrequest; /* free */ hypre_TFree(send_i, HYPRE_MEMORY_HOST); hypre_TFree(recv_i, HYPRE_MEMORY_HOST); hypre_TFree(d_send_i, HYPRE_MEMORY_DEVICE); hypre_TFree(d_send_map, HYPRE_MEMORY_DEVICE); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); return hypre_error_flag; } hypre_CSRMatrix* hypre_ParcsrGetExternalRowsDeviceWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *A_ext = (hypre_CSRMatrix *) request[2]; HYPRE_BigInt *send_j = comm_handle_j ? (HYPRE_BigInt *) hypre_ParCSRCommHandleSendData(comm_handle_j) : NULL; HYPRE_Complex *send_a = comm_handle_a ? (HYPRE_Complex *) hypre_ParCSRCommHandleSendData(comm_handle_a) : NULL; hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_TFree(send_j, HYPRE_MEMORY_DEVICE); hypre_TFree(send_a, HYPRE_MEMORY_DEVICE); hypre_TFree(request, HYPRE_MEMORY_HOST); return A_ext; } hypre_CSRMatrix* hypre_MergeDiagAndOffdDevice(hypre_ParCSRMatrix *A) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int local_num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt glbal_num_cols = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_BigInt first_col = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_BigInt *d_col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A); hypre_CSRMatrix *B; HYPRE_Int B_nrows = local_num_rows; HYPRE_BigInt B_ncols = glbal_num_cols; HYPRE_Int *B_i = hypre_TAlloc(HYPRE_Int, B_nrows + 1, HYPRE_MEMORY_DEVICE); HYPRE_BigInt *B_j; HYPRE_Complex *B_a; HYPRE_Int B_nnz; HYPRE_Int num_procs; hypre_MPI_Comm_size(comm, &num_procs); hypre_Memset(B_i, 0, sizeof(HYPRE_Int), HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(B_nrows, NULL, A_diag_i, A_offd_i, B_i + 1); hypreDevice_IntegerInclusiveScan(B_nrows + 1, B_i); /* total number of nnz */ hypre_TMemcpy(&B_nnz, B_i + B_nrows, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); B_j = hypre_TAlloc(HYPRE_BigInt, B_nnz, HYPRE_MEMORY_DEVICE); B_a = hypre_TAlloc(HYPRE_Complex, B_nnz, HYPRE_MEMORY_DEVICE); if (d_col_map_offd_A == NULL) { d_col_map_offd_A = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(d_col_map_offd_A, col_map_offd_A, HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDeviceColMapOffd(A) = d_col_map_offd_A; } hypreDevice_CopyParCSRRows(B_nrows, NULL, 2, num_procs > 1, first_col, d_col_map_offd_A, A_diag_i, A_diag_j, A_diag_a, A_offd_i, A_offd_j, A_offd_a, B_i, B_j, B_a); /* output */ B = hypre_CSRMatrixCreate(B_nrows, B_ncols, B_nnz); hypre_CSRMatrixI (B) = B_i; hypre_CSRMatrixBigJ(B) = B_j; hypre_CSRMatrixData(B) = B_a; hypre_CSRMatrixMemoryLocation(B) = HYPRE_MEMORY_DEVICE; hypre_SyncComputeStream(hypre_handle()); return B; } HYPRE_Int hypre_ExchangeExternalRowsDeviceInit( hypre_CSRMatrix *B_ext, hypre_ParCSRCommPkg *comm_pkg_A, HYPRE_Int want_data, void **request_ptr) { MPI_Comm comm = hypre_ParCSRCommPkgComm(comm_pkg_A); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A); HYPRE_Int *recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A); HYPRE_Int *recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A); HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg_A); HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg_A); HYPRE_Int *send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); HYPRE_Int num_elmts_send = send_map_starts[num_sends]; HYPRE_Int num_elmts_recv = recv_vec_starts[num_recvs]; HYPRE_Int *B_ext_i_d = hypre_CSRMatrixI(B_ext); HYPRE_BigInt *B_ext_j_d = hypre_CSRMatrixBigJ(B_ext); HYPRE_Complex *B_ext_a_d = hypre_CSRMatrixData(B_ext); HYPRE_Int B_ext_ncols = hypre_CSRMatrixNumCols(B_ext); HYPRE_Int B_ext_nrows = hypre_CSRMatrixNumRows(B_ext); HYPRE_Int B_ext_nnz = hypre_CSRMatrixNumNonzeros(B_ext); HYPRE_Int *B_ext_rownnz_d = hypre_TAlloc(HYPRE_Int, B_ext_nrows + 1, HYPRE_MEMORY_DEVICE); HYPRE_Int *B_ext_rownnz_h = hypre_TAlloc(HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST); HYPRE_Int *B_ext_i_h = hypre_TAlloc(HYPRE_Int, B_ext_nrows + 1, HYPRE_MEMORY_HOST); hypre_assert(num_elmts_recv == B_ext_nrows); /* output matrix */ hypre_CSRMatrix *B_int_d; HYPRE_Int B_int_nrows = num_elmts_send; HYPRE_Int B_int_ncols = B_ext_ncols; HYPRE_Int *B_int_i_h = hypre_TAlloc(HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_HOST); HYPRE_Int *B_int_i_d = hypre_TAlloc(HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_DEVICE); HYPRE_BigInt *B_int_j_d = NULL; HYPRE_Complex *B_int_a_d = NULL; HYPRE_Int B_int_nnz; hypre_ParCSRCommHandle *comm_handle, *comm_handle_j, *comm_handle_a; hypre_ParCSRCommPkg *comm_pkg_j; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int i; HYPRE_Int num_procs, my_id; void **vrequest; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); jdata_send_map_starts = hypre_TAlloc(HYPRE_Int, num_sends + 1, HYPRE_MEMORY_HOST); /*-------------------------------------------------------------------------- * B_ext_rownnz contains the number of elements of row j * (to be determined through send_map_elmnts on the receiving end) *--------------------------------------------------------------------------*/ HYPRE_THRUST_CALL(adjacent_difference, B_ext_i_d, B_ext_i_d + B_ext_nrows + 1, B_ext_rownnz_d); hypre_TMemcpy(B_ext_rownnz_h, B_ext_rownnz_d + 1, HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); /*-------------------------------------------------------------------------- * initialize communication: send/recv the row nnz * (note the use of comm_pkg_A, mode 12, as in transpose matvec *--------------------------------------------------------------------------*/ comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg_A, B_ext_rownnz_h, B_int_i_h + 1); jdata_recv_vec_starts = hypre_TAlloc(HYPRE_Int, num_recvs + 1, HYPRE_MEMORY_HOST); jdata_recv_vec_starts[0] = 0; B_ext_i_h[0] = 0; hypre_TMemcpy(B_ext_i_h + 1, B_ext_rownnz_h, HYPRE_Int, B_ext_nrows, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); for (i = 1; i <= B_ext_nrows; i++) { B_ext_i_h[i] += B_ext_i_h[i - 1]; } hypre_assert(B_ext_i_h[B_ext_nrows] == B_ext_nnz); for (i = 1; i <= num_recvs; i++) { jdata_recv_vec_starts[i] = B_ext_i_h[recv_vec_starts[i]]; } comm_pkg_j = hypre_CTAlloc(hypre_ParCSRCommPkg, 1, HYPRE_MEMORY_HOST); hypre_ParCSRCommPkgComm(comm_pkg_j) = comm; hypre_ParCSRCommPkgNumSends(comm_pkg_j) = num_recvs; hypre_ParCSRCommPkgNumRecvs(comm_pkg_j) = num_sends; hypre_ParCSRCommPkgSendProcs(comm_pkg_j) = recv_procs; hypre_ParCSRCommPkgRecvProcs(comm_pkg_j) = send_procs; hypre_ParCSRCommHandleDestroy(comm_handle); /*-------------------------------------------------------------------------- * compute B_int: row nnz to row ptrs *--------------------------------------------------------------------------*/ B_int_i_h[0] = 0; for (i = 1; i <= B_int_nrows; i++) { B_int_i_h[i] += B_int_i_h[i - 1]; } B_int_nnz = B_int_i_h[B_int_nrows]; B_int_j_d = hypre_TAlloc(HYPRE_BigInt, B_int_nnz, HYPRE_MEMORY_DEVICE); if (want_data) { B_int_a_d = hypre_TAlloc(HYPRE_Complex, B_int_nnz, HYPRE_MEMORY_DEVICE); } for (i = 0; i <= num_sends; i++) { jdata_send_map_starts[i] = B_int_i_h[send_map_starts[i]]; } /* note the order of send/recv is reversed */ hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j) = jdata_send_map_starts; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j) = jdata_recv_vec_starts; /* send/recv CSR rows */ if (want_data) { comm_handle_a = hypre_ParCSRCommHandleCreate_v2( 1, comm_pkg_j, HYPRE_MEMORY_DEVICE, B_ext_a_d, HYPRE_MEMORY_DEVICE, B_int_a_d ); } else { comm_handle_a = NULL; } comm_handle_j = hypre_ParCSRCommHandleCreate_v2(21, comm_pkg_j, HYPRE_MEMORY_DEVICE, B_ext_j_d, HYPRE_MEMORY_DEVICE, B_int_j_d ); hypre_TMemcpy(B_int_i_d, B_int_i_h, HYPRE_Int, B_int_nrows + 1, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); /* create CSR: on device */ B_int_d = hypre_CSRMatrixCreate(B_int_nrows, B_int_ncols, B_int_nnz); hypre_CSRMatrixI(B_int_d) = B_int_i_d; hypre_CSRMatrixBigJ(B_int_d) = B_int_j_d; hypre_CSRMatrixData(B_int_d) = B_int_a_d; hypre_CSRMatrixMemoryLocation(B_int_d) = HYPRE_MEMORY_DEVICE; /* output */ vrequest = hypre_TAlloc(void *, 3, HYPRE_MEMORY_HOST); vrequest[0] = (void *) comm_handle_j; vrequest[1] = (void *) comm_handle_a; vrequest[2] = (void *) B_int_d; *request_ptr = (void *) vrequest; /* free */ hypre_TFree(B_ext_rownnz_d, HYPRE_MEMORY_DEVICE); hypre_TFree(B_ext_rownnz_h, HYPRE_MEMORY_HOST); hypre_TFree(B_ext_i_h, HYPRE_MEMORY_HOST); hypre_TFree(B_int_i_h, HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_j), HYPRE_MEMORY_HOST); hypre_TFree(comm_pkg_j, HYPRE_MEMORY_HOST); return hypre_error_flag; } hypre_CSRMatrix* hypre_ExchangeExternalRowsDeviceWait(void *vrequest) { void **request = (void **) vrequest; hypre_ParCSRCommHandle *comm_handle_j = (hypre_ParCSRCommHandle *) request[0]; hypre_ParCSRCommHandle *comm_handle_a = (hypre_ParCSRCommHandle *) request[1]; hypre_CSRMatrix *B_int_d = (hypre_CSRMatrix *) request[2]; /* communication done */ hypre_ParCSRCommHandleDestroy(comm_handle_j); hypre_ParCSRCommHandleDestroy(comm_handle_a); hypre_TFree(request, HYPRE_MEMORY_HOST); return B_int_d; } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ HYPRE_Int hypre_ParCSRMatrixExtractBExtDeviceInit( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int want_data, void **request_ptr) { hypre_assert( hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B)) == hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixOffd(B)) ); /* hypre_assert( hypre_GetActualMemLocation( hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(B))) == HYPRE_MEMORY_DEVICE ); */ if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } hypre_ParcsrGetExternalRowsDeviceInit(B, hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A)), hypre_ParCSRMatrixColMapOffd(A), hypre_ParCSRMatrixCommPkg(A), want_data, request_ptr); return hypre_error_flag; } hypre_CSRMatrix* hypre_ParCSRMatrixExtractBExtDeviceWait(void *request) { return hypre_ParcsrGetExternalRowsDeviceWait(request); } hypre_CSRMatrix* hypre_ParCSRMatrixExtractBExtDevice( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int want_data ) { void *request; hypre_ParCSRMatrixExtractBExtDeviceInit(B, A, want_data, &request); return hypre_ParCSRMatrixExtractBExtDeviceWait(request); } /* return B = [Adiag, Aoffd] */ #if 1 __global__ void hypreCUDAKernel_ConcatDiagAndOffd(HYPRE_Int nrows, HYPRE_Int diag_ncol, HYPRE_Int *d_diag_i, HYPRE_Int *d_diag_j, HYPRE_Complex *d_diag_a, HYPRE_Int *d_offd_i, HYPRE_Int *d_offd_j, HYPRE_Complex *d_offd_a, HYPRE_Int *cols_offd_map, HYPRE_Int *d_ib, HYPRE_Int *d_jb, HYPRE_Complex *d_ab) { const HYPRE_Int row = hypre_cuda_get_grid_warp_id<1, 1>(); if (row >= nrows) { return; } /* lane id inside the warp */ const HYPRE_Int lane_id = hypre_cuda_get_lane_id<1>(); HYPRE_Int i, j, k, p, istart, iend, bstart; /* diag part */ if (lane_id < 2) { j = read_only_load(d_diag_i + row + lane_id); } if (lane_id == 0) { k = read_only_load(d_ib + row); } istart = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 0); iend = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 1); bstart = __shfl_sync(HYPRE_WARP_FULL_MASK, k, 0); p = bstart - istart; for (i = istart + lane_id; i < iend; i += HYPRE_WARP_SIZE) { d_jb[p + i] = read_only_load(d_diag_j + i); d_ab[p + i] = read_only_load(d_diag_a + i); } /* offd part */ if (lane_id < 2) { j = read_only_load(d_offd_i + row + lane_id); } bstart += iend - istart; istart = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 0); iend = __shfl_sync(HYPRE_WARP_FULL_MASK, j, 1); p = bstart - istart; for (i = istart + lane_id; i < iend; i += HYPRE_WARP_SIZE) { const HYPRE_Int t = read_only_load(d_offd_j + i); d_jb[p + i] = (cols_offd_map ? read_only_load(&cols_offd_map[t]) : t) + diag_ncol; d_ab[p + i] = read_only_load(d_offd_a + i); } } hypre_CSRMatrix* hypre_ConcatDiagAndOffdDevice(hypre_ParCSRMatrix *A) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *B = hypre_CSRMatrixCreate( hypre_CSRMatrixNumRows(A_diag), hypre_CSRMatrixNumCols(A_diag) + hypre_CSRMatrixNumCols(A_offd), hypre_CSRMatrixNumNonzeros(A_diag) + hypre_CSRMatrixNumNonzeros(A_offd) ); hypre_CSRMatrixInitialize_v2(B, 0, HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(hypre_CSRMatrixNumRows(B), NULL, hypre_CSRMatrixI(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixI(B)); HYPRE_THRUST_CALL( exclusive_scan, hypre_CSRMatrixI(B), hypre_CSRMatrixI(B) + hypre_CSRMatrixNumRows(B) + 1, hypre_CSRMatrixI(B) ); const dim3 bDim = hypre_GetDefaultDeviceBlockDimension(); const dim3 gDim = hypre_GetDefaultDeviceGridDimension(hypre_CSRMatrixNumRows(A_diag), "warp", bDim); HYPRE_CUDA_LAUNCH( hypreCUDAKernel_ConcatDiagAndOffd, gDim, bDim, hypre_CSRMatrixNumRows(A_diag), hypre_CSRMatrixNumCols(A_diag), hypre_CSRMatrixI(A_diag), hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixJ(A_offd), hypre_CSRMatrixData(A_offd), NULL, hypre_CSRMatrixI(B), hypre_CSRMatrixJ(B), hypre_CSRMatrixData(B) ); return B; } #else hypre_CSRMatrix* hypre_ConcatDiagAndOffdDevice(hypre_ParCSRMatrix *A) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int A_diag_nnz = hypre_CSRMatrixNumNonzeros(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int A_offd_nnz = hypre_CSRMatrixNumNonzeros(A_offd); hypre_CSRMatrix *B; HYPRE_Int B_nrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int B_ncols = hypre_CSRMatrixNumCols(A_diag) + hypre_CSRMatrixNumCols(A_offd); HYPRE_Int B_nnz = A_diag_nnz + A_offd_nnz; HYPRE_Int *B_ii = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE); HYPRE_Int *B_j = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE); HYPRE_Complex *B_a = hypre_TAlloc(HYPRE_Complex, B_nnz, HYPRE_MEMORY_DEVICE); // Adiag HYPRE_Int *A_diag_ii = hypreDevice_CsrRowPtrsToIndices(B_nrows, A_diag_nnz, A_diag_i); HYPRE_THRUST_CALL( copy_n, thrust::make_zip_iterator(thrust::make_tuple(A_diag_ii, A_diag_j, A_diag_a)), A_diag_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_j, B_a)) ); hypre_TFree(A_diag_ii, HYPRE_MEMORY_DEVICE); // Aoffd HYPRE_Int *A_offd_ii = hypreDevice_CsrRowPtrsToIndices(B_nrows, A_offd_nnz, A_offd_i); HYPRE_THRUST_CALL( copy_n, thrust::make_zip_iterator(thrust::make_tuple(A_offd_ii, A_offd_a)), A_offd_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_a)) + A_diag_nnz ); hypre_TFree(A_offd_ii, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, A_offd_j, A_offd_j + A_offd_nnz, thrust::make_constant_iterator(hypre_CSRMatrixNumCols(A_diag)), B_j + A_diag_nnz, thrust::plus<HYPRE_Int>() ); // B HYPRE_THRUST_CALL( stable_sort_by_key, B_ii, B_ii + B_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_j, B_a)) ); HYPRE_Int *B_i = hypreDevice_CsrRowIndicesToPtrs(B_nrows, B_nnz, B_ii); hypre_TFree(B_ii, HYPRE_MEMORY_DEVICE); B = hypre_CSRMatrixCreate(B_nrows, B_ncols, B_nnz); hypre_CSRMatrixI(B) = B_i; hypre_CSRMatrixJ(B) = B_j; hypre_CSRMatrixData(B) = B_a; hypre_CSRMatrixMemoryLocation(B) = HYPRE_MEMORY_DEVICE; return B; } #endif /* return B = [Adiag, Aoffd; E] */ #if 1 HYPRE_Int hypre_ConcatDiagOffdAndExtDevice(hypre_ParCSRMatrix *A, hypre_CSRMatrix *E, hypre_CSRMatrix **B_ptr, HYPRE_Int *num_cols_offd_ptr, HYPRE_BigInt **cols_map_offd_ptr) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *E_diag, *E_offd, *B; HYPRE_Int *cols_offd_map, num_cols_offd; HYPRE_BigInt *cols_map_offd; hypre_CSRMatrixSplitDevice(E, hypre_ParCSRMatrixFirstColDiag(A), hypre_ParCSRMatrixLastColDiag(A), hypre_CSRMatrixNumCols(A_offd), hypre_ParCSRMatrixDeviceColMapOffd(A), &cols_offd_map, &num_cols_offd, &cols_map_offd, &E_diag, &E_offd); B = hypre_CSRMatrixCreate(hypre_ParCSRMatrixNumRows(A) + hypre_CSRMatrixNumRows(E), hypre_ParCSRMatrixNumCols(A) + num_cols_offd, hypre_CSRMatrixNumNonzeros(A_diag) + hypre_CSRMatrixNumNonzeros(A_offd) + hypre_CSRMatrixNumNonzeros(E)); hypre_CSRMatrixInitialize_v2(B, 0, HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(hypre_ParCSRMatrixNumRows(A), NULL, hypre_CSRMatrixI(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixI(B)); HYPRE_THRUST_CALL( exclusive_scan, hypre_CSRMatrixI(B), hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1, hypre_CSRMatrixI(B) ); dim3 bDim = hypre_GetDefaultDeviceBlockDimension(); dim3 gDim = hypre_GetDefaultDeviceGridDimension(hypre_ParCSRMatrixNumRows(A), "warp", bDim); HYPRE_CUDA_LAUNCH( hypreCUDAKernel_ConcatDiagAndOffd, gDim, bDim, hypre_CSRMatrixNumRows(A_diag), hypre_CSRMatrixNumCols(A_diag), hypre_CSRMatrixI(A_diag), hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixJ(A_offd), hypre_CSRMatrixData(A_offd), cols_offd_map, hypre_CSRMatrixI(B), hypre_CSRMatrixJ(B), hypre_CSRMatrixData(B) ); hypre_TFree(cols_offd_map, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1, hypre_CSRMatrixI(E) + 1, HYPRE_Int, hypre_CSRMatrixNumRows(E), HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1, hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + hypre_CSRMatrixNumRows(E) + 1, thrust::make_constant_iterator(hypre_CSRMatrixNumNonzeros(A_diag) + hypre_CSRMatrixNumNonzeros( A_offd)), hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A) + 1, thrust::plus<HYPRE_Int>() ); gDim = hypre_GetDefaultDeviceGridDimension(hypre_CSRMatrixNumRows(E), "warp", bDim); hypre_assert(hypre_CSRMatrixNumCols(E_diag) == hypre_CSRMatrixNumCols(A_diag)); HYPRE_CUDA_LAUNCH( hypreCUDAKernel_ConcatDiagAndOffd, gDim, bDim, hypre_CSRMatrixNumRows(E_diag), hypre_CSRMatrixNumCols(E_diag), hypre_CSRMatrixI(E_diag), hypre_CSRMatrixJ(E_diag), hypre_CSRMatrixData(E_diag), hypre_CSRMatrixI(E_offd), hypre_CSRMatrixJ(E_offd), hypre_CSRMatrixData(E_offd), NULL, hypre_CSRMatrixI(B) + hypre_ParCSRMatrixNumRows(A), hypre_CSRMatrixJ(B), hypre_CSRMatrixData(B) ); hypre_CSRMatrixDestroy(E_diag); hypre_CSRMatrixDestroy(E_offd); *B_ptr = B; *num_cols_offd_ptr = num_cols_offd; *cols_map_offd_ptr = cols_map_offd; return hypre_error_flag; } #else HYPRE_Int hypre_ConcatDiagOffdAndExtDevice(hypre_ParCSRMatrix *A, hypre_CSRMatrix *E, hypre_CSRMatrix **B_ptr, HYPRE_Int *num_cols_offd_ptr, HYPRE_BigInt **cols_map_offd_ptr) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int A_nrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int A_ncols = hypre_CSRMatrixNumCols(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Complex *A_diag_a = hypre_CSRMatrixData(A_diag); HYPRE_Int A_diag_nnz = hypre_CSRMatrixNumNonzeros(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Complex *A_offd_a = hypre_CSRMatrixData(A_offd); HYPRE_Int A_offd_nnz = hypre_CSRMatrixNumNonzeros(A_offd); HYPRE_BigInt first_col_A = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_BigInt last_col_A = hypre_ParCSRMatrixLastColDiag(A); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A); HYPRE_Int *E_i = hypre_CSRMatrixI(E); HYPRE_BigInt *E_bigj = hypre_CSRMatrixBigJ(E); HYPRE_Complex *E_a = hypre_CSRMatrixData(E); HYPRE_Int E_nrows = hypre_CSRMatrixNumRows(E); HYPRE_Int E_nnz = hypre_CSRMatrixNumNonzeros(E); HYPRE_Int E_diag_nnz, E_offd_nnz; hypre_CSRMatrix *B; HYPRE_Int B_nnz = A_diag_nnz + A_offd_nnz + E_nnz; HYPRE_Int *B_ii = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE); HYPRE_Int *B_j = hypre_TAlloc(HYPRE_Int, B_nnz, HYPRE_MEMORY_DEVICE); HYPRE_Complex *B_a = hypre_TAlloc(HYPRE_Complex, B_nnz, HYPRE_MEMORY_DEVICE); // E hypre_CSRMatrixSplitDevice_core(0, E_nrows, E_nnz, NULL, E_bigj, NULL, NULL, first_col_A, last_col_A, num_cols_offd_A, NULL, NULL, NULL, NULL, &E_diag_nnz, NULL, NULL, NULL, NULL, &E_offd_nnz, NULL, NULL, NULL, NULL); HYPRE_Int *cols_offd_map, num_cols_offd; HYPRE_BigInt *cols_map_offd; HYPRE_Int *E_ii = hypreDevice_CsrRowPtrsToIndices(E_nrows, E_nnz, E_i); hypre_CSRMatrixSplitDevice_core(1, E_nrows, E_nnz, E_ii, E_bigj, E_a, NULL, first_col_A, last_col_A, num_cols_offd_A, col_map_offd_A, &cols_offd_map, &num_cols_offd, &cols_map_offd, &E_diag_nnz, B_ii + A_diag_nnz + A_offd_nnz, B_j + A_diag_nnz + A_offd_nnz, B_a + A_diag_nnz + A_offd_nnz, NULL, &E_offd_nnz, B_ii + A_diag_nnz + A_offd_nnz + E_diag_nnz, B_j + A_diag_nnz + A_offd_nnz + E_diag_nnz, B_a + A_diag_nnz + A_offd_nnz + E_diag_nnz, NULL); hypre_TFree(E_ii, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, B_ii + A_diag_nnz + A_offd_nnz, B_ii + B_nnz, thrust::make_constant_iterator(A_nrows), B_ii + A_diag_nnz + A_offd_nnz, thrust::plus<HYPRE_Int>() ); // Adiag HYPRE_Int *A_diag_ii = hypreDevice_CsrRowPtrsToIndices(A_nrows, A_diag_nnz, A_diag_i); HYPRE_THRUST_CALL( copy_n, thrust::make_zip_iterator(thrust::make_tuple(A_diag_ii, A_diag_j, A_diag_a)), A_diag_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_j, B_a)) ); hypre_TFree(A_diag_ii, HYPRE_MEMORY_DEVICE); // Aoffd HYPRE_Int *A_offd_ii = hypreDevice_CsrRowPtrsToIndices(A_nrows, A_offd_nnz, A_offd_i); HYPRE_THRUST_CALL( copy_n, thrust::make_zip_iterator(thrust::make_tuple(A_offd_ii, A_offd_a)), A_offd_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_ii, B_a)) + A_diag_nnz ); hypre_TFree(A_offd_ii, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( gather, A_offd_j, A_offd_j + A_offd_nnz, cols_offd_map, B_j + A_diag_nnz); hypre_TFree(cols_offd_map, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, B_j + A_diag_nnz, B_j + A_diag_nnz + A_offd_nnz, thrust::make_constant_iterator(A_ncols), B_j + A_diag_nnz, thrust::plus<HYPRE_Int>() ); HYPRE_THRUST_CALL( transform, B_j + A_diag_nnz + A_offd_nnz + E_diag_nnz, B_j + B_nnz, thrust::make_constant_iterator(A_ncols), B_j + A_diag_nnz + A_offd_nnz + E_diag_nnz, thrust::plus<HYPRE_Int>() ); // B HYPRE_THRUST_CALL( stable_sort_by_key, B_ii, B_ii + B_nnz, thrust::make_zip_iterator(thrust::make_tuple(B_j, B_a)) ); HYPRE_Int *B_i = hypreDevice_CsrRowIndicesToPtrs(A_nrows + E_nrows, B_nnz, B_ii); hypre_TFree(B_ii, HYPRE_MEMORY_DEVICE); B = hypre_CSRMatrixCreate(A_nrows + E_nrows, A_ncols + num_cols_offd, B_nnz); hypre_CSRMatrixI(B) = B_i; hypre_CSRMatrixJ(B) = B_j; hypre_CSRMatrixData(B) = B_a; hypre_CSRMatrixMemoryLocation(B) = HYPRE_MEMORY_DEVICE; *B_ptr = B; *num_cols_offd_ptr = num_cols_offd; *cols_map_offd_ptr = cols_map_offd; return hypre_error_flag; } #endif HYPRE_Int hypre_ParCSRMatrixGetRowDevice( hypre_ParCSRMatrix *mat, HYPRE_BigInt row, HYPRE_Int *size, HYPRE_BigInt **col_ind, HYPRE_Complex **values ) { HYPRE_Int nrows, local_row; HYPRE_BigInt row_start, row_end; hypre_CSRMatrix *Aa; hypre_CSRMatrix *Ba; if (!mat) { hypre_error_in_arg(1); return hypre_error_flag; } Aa = (hypre_CSRMatrix *) hypre_ParCSRMatrixDiag(mat); Ba = (hypre_CSRMatrix *) hypre_ParCSRMatrixOffd(mat); if (hypre_ParCSRMatrixGetrowactive(mat)) { return (-1); } hypre_ParCSRMatrixGetrowactive(mat) = 1; row_start = hypre_ParCSRMatrixFirstRowIndex(mat); row_end = hypre_ParCSRMatrixLastRowIndex(mat) + 1; nrows = row_end - row_start; if (row < row_start || row >= row_end) { return (-1); } local_row = row - row_start; /* if buffer is not allocated and some information is requested, allocate buffer with the max row_nnz */ if ( !hypre_ParCSRMatrixRowvalues(mat) && (col_ind || values) ) { HYPRE_Int max_row_nnz; HYPRE_Int *row_nnz = hypre_TAlloc(HYPRE_Int, nrows, HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(nrows, NULL, hypre_CSRMatrixI(Aa), hypre_CSRMatrixI(Ba), row_nnz); hypre_TMemcpy(size, row_nnz + local_row, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); max_row_nnz = HYPRE_THRUST_CALL(reduce, row_nnz, row_nnz + nrows, 0, thrust::maximum<HYPRE_Int>()); /* HYPRE_Int *max_row_nnz_d = HYPRE_THRUST_CALL(max_element, row_nnz, row_nnz + nrows); hypre_TMemcpy( &max_row_nnz, max_row_nnz_d, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE ); */ hypre_TFree(row_nnz, HYPRE_MEMORY_DEVICE); hypre_ParCSRMatrixRowvalues(mat) = (HYPRE_Complex *) hypre_TAlloc(HYPRE_Complex, max_row_nnz, hypre_ParCSRMatrixMemoryLocation(mat)); hypre_ParCSRMatrixRowindices(mat) = (HYPRE_BigInt *) hypre_TAlloc(HYPRE_BigInt, max_row_nnz, hypre_ParCSRMatrixMemoryLocation(mat)); } else { HYPRE_Int *size_d = hypre_TAlloc(HYPRE_Int, 1, HYPRE_MEMORY_DEVICE); hypreDevice_GetRowNnz(1, NULL, hypre_CSRMatrixI(Aa) + local_row, hypre_CSRMatrixI(Ba) + local_row, size_d); hypre_TMemcpy(size, size_d, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); hypre_TFree(size_d, HYPRE_MEMORY_DEVICE); } if (col_ind || values) { if (hypre_ParCSRMatrixDeviceColMapOffd(mat) == NULL) { hypre_ParCSRMatrixDeviceColMapOffd(mat) = hypre_TAlloc(HYPRE_BigInt, hypre_CSRMatrixNumCols(Ba), HYPRE_MEMORY_DEVICE); hypre_TMemcpy( hypre_ParCSRMatrixDeviceColMapOffd(mat), hypre_ParCSRMatrixColMapOffd(mat), HYPRE_BigInt, hypre_CSRMatrixNumCols(Ba), HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST ); } hypreDevice_CopyParCSRRows( 1, NULL, -1, Ba != NULL, hypre_ParCSRMatrixFirstColDiag(mat), hypre_ParCSRMatrixDeviceColMapOffd(mat), hypre_CSRMatrixI(Aa) + local_row, hypre_CSRMatrixJ(Aa), hypre_CSRMatrixData(Aa), hypre_CSRMatrixI(Ba) + local_row, hypre_CSRMatrixJ(Ba), hypre_CSRMatrixData(Ba), NULL, hypre_ParCSRMatrixRowindices(mat), hypre_ParCSRMatrixRowvalues(mat) ); } if (col_ind) { *col_ind = hypre_ParCSRMatrixRowindices(mat); } if (values) { *values = hypre_ParCSRMatrixRowvalues(mat); } hypre_SyncComputeStream(hypre_handle()); return hypre_error_flag; } /* Get element-wise tolerances based on row norms for ParCSRMatrix * NOTE: Keep the diagonal, i.e. elmt_tol = 0.0 for diagonals * Output vectors have size nnz: * elmt_tols_diag[j] = tol * (norm of row i) for j in [ A_diag_i[i] , A_diag_i[i+1] ) * elmt_tols_offd[j] = tol * (norm of row i) for j in [ A_offd_i[i] , A_offd_i[i+1] ) * type == -1, infinity norm, * 1, 1-norm * 2, 2-norm */ template<HYPRE_Int type> __global__ void hypre_ParCSRMatrixDropSmallEntriesDevice_getElmtTols( HYPRE_Int nrows, HYPRE_Real tol, HYPRE_Int *A_diag_i, HYPRE_Int *A_diag_j, HYPRE_Complex *A_diag_a, HYPRE_Int *A_offd_i, HYPRE_Complex *A_offd_a, HYPRE_Real *elmt_tols_diag, HYPRE_Real *elmt_tols_offd) { HYPRE_Int row_i = hypre_cuda_get_grid_warp_id<1, 1>(); if (row_i >= nrows) { return; } HYPRE_Int lane = hypre_cuda_get_lane_id<1>(); HYPRE_Int p_diag, p_offd, q_diag, q_offd; /* sum row norm over diag part */ if (lane < 2) { p_diag = read_only_load(A_diag_i + row_i + lane); } q_diag = __shfl_sync(HYPRE_WARP_FULL_MASK, p_diag, 1); p_diag = __shfl_sync(HYPRE_WARP_FULL_MASK, p_diag, 0); HYPRE_Real row_norm_i = 0.0; for (HYPRE_Int j = p_diag + lane; j < q_diag; j += HYPRE_WARP_SIZE) { HYPRE_Complex val = A_diag_a[j]; if (type == -1) { row_norm_i = hypre_max(row_norm_i, hypre_cabs(val)); } else if (type == 1) { row_norm_i += hypre_cabs(val); } else if (type == 2) { row_norm_i += val * val; } } /* sum row norm over offd part */ if (lane < 2) { p_offd = read_only_load(A_offd_i + row_i + lane); } q_offd = __shfl_sync(HYPRE_WARP_FULL_MASK, p_offd, 1); p_offd = __shfl_sync(HYPRE_WARP_FULL_MASK, p_offd, 0); for (HYPRE_Int j = p_offd + lane; j < q_offd; j += HYPRE_WARP_SIZE) { HYPRE_Complex val = A_offd_a[j]; if (type == -1) { row_norm_i = hypre_max(row_norm_i, hypre_cabs(val)); } else if (type == 1) { row_norm_i += hypre_cabs(val); } else if (type == 2) { row_norm_i += val * val; } } /* allreduce to get the row norm on all threads */ if (type == -1) { row_norm_i = warp_allreduce_max(row_norm_i); } else { row_norm_i = warp_allreduce_sum(row_norm_i); } if (type == 2) { row_norm_i = sqrt(row_norm_i); } /* set elmt_tols_diag */ for (HYPRE_Int j = p_diag + lane; j < q_diag; j += HYPRE_WARP_SIZE) { HYPRE_Int col = A_diag_j[j]; /* elmt_tol = 0.0 ensures diagonal will be kept */ if (col == row_i) { elmt_tols_diag[j] = 0.0; } else { elmt_tols_diag[j] = tol * row_norm_i; } } /* set elmt_tols_offd */ for (HYPRE_Int j = p_offd + lane; j < q_offd; j += HYPRE_WARP_SIZE) { elmt_tols_offd[j] = tol * row_norm_i; } } /* drop the entries that are not on the diagonal and smaller than: * type 0: tol * type 1: tol*(1-norm of row) * type 2: tol*(2-norm of row) * type -1: tol*(infinity norm of row) */ HYPRE_Int hypre_ParCSRMatrixDropSmallEntriesDevice( hypre_ParCSRMatrix *A, HYPRE_Complex tol, HYPRE_Int type) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_BigInt *h_col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixDeviceColMapOffd(A); HYPRE_Real *elmt_tols_diag = NULL; HYPRE_Real *elmt_tols_offd = NULL; if (col_map_offd_A == NULL) { col_map_offd_A = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(col_map_offd_A, h_col_map_offd_A, HYPRE_BigInt, num_cols_A_offd, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDeviceColMapOffd(A) = col_map_offd_A; } /* get elmement-wise tolerances if needed */ if (type != 0) { elmt_tols_diag = hypre_TAlloc(HYPRE_Real, hypre_CSRMatrixNumNonzeros(A_diag), HYPRE_MEMORY_DEVICE); elmt_tols_offd = hypre_TAlloc(HYPRE_Real, hypre_CSRMatrixNumNonzeros(A_offd), HYPRE_MEMORY_DEVICE); } dim3 bDim = hypre_GetDefaultDeviceBlockDimension(); dim3 gDim = hypre_GetDefaultDeviceGridDimension(hypre_CSRMatrixNumRows(A_diag), "warp", bDim); if (type == -1) { HYPRE_CUDA_LAUNCH( hypre_ParCSRMatrixDropSmallEntriesDevice_getElmtTols < -1 >, gDim, bDim, hypre_CSRMatrixNumRows(A_diag), tol, hypre_CSRMatrixI(A_diag), hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixData(A_offd), elmt_tols_diag, elmt_tols_offd); } if (type == 1) { HYPRE_CUDA_LAUNCH( hypre_ParCSRMatrixDropSmallEntriesDevice_getElmtTols<1>, gDim, bDim, hypre_CSRMatrixNumRows(A_diag), tol, hypre_CSRMatrixI(A_diag), hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixData(A_offd), elmt_tols_diag, elmt_tols_offd); } if (type == 2) { HYPRE_CUDA_LAUNCH( hypre_ParCSRMatrixDropSmallEntriesDevice_getElmtTols<2>, gDim, bDim, hypre_CSRMatrixNumRows(A_diag), tol, hypre_CSRMatrixI(A_diag), hypre_CSRMatrixJ(A_diag), hypre_CSRMatrixData(A_diag), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixData(A_offd), elmt_tols_diag, elmt_tols_offd); } /* drop entries from diag and offd CSR matrices */ hypre_CSRMatrixDropSmallEntriesDevice(A_diag, tol, elmt_tols_diag); hypre_CSRMatrixDropSmallEntriesDevice(A_offd, tol, elmt_tols_offd); hypre_ParCSRMatrixSetNumNonzeros(A); hypre_ParCSRMatrixDNumNonzeros(A) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(A); /* squeeze out zero columns of A_offd */ HYPRE_Int *tmp_j, *tmp_end, num_cols_A_offd_new; tmp_j = hypre_TAlloc(HYPRE_Int, hypre_CSRMatrixNumNonzeros(A_offd), HYPRE_MEMORY_DEVICE); hypre_TMemcpy(tmp_j, hypre_CSRMatrixJ(A_offd), HYPRE_Int, hypre_CSRMatrixNumNonzeros(A_offd), HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( sort, tmp_j, tmp_j + hypre_CSRMatrixNumNonzeros(A_offd) ); tmp_end = HYPRE_THRUST_CALL( unique, tmp_j, tmp_j + hypre_CSRMatrixNumNonzeros(A_offd) ); num_cols_A_offd_new = tmp_end - tmp_j; hypre_assert(num_cols_A_offd_new <= num_cols_A_offd); if (num_cols_A_offd_new < num_cols_A_offd) { hypre_CSRMatrixNumCols(A_offd) = num_cols_A_offd_new; HYPRE_Int *offd_mark = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_DEVICE); HYPRE_BigInt *col_map_offd_A_new = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd_new, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( scatter, thrust::counting_iterator<HYPRE_Int>(0), thrust::counting_iterator<HYPRE_Int>(num_cols_A_offd_new), tmp_j, offd_mark ); HYPRE_THRUST_CALL( gather, hypre_CSRMatrixJ(A_offd), hypre_CSRMatrixJ(A_offd) + hypre_CSRMatrixNumNonzeros(A_offd), offd_mark, hypre_CSRMatrixJ(A_offd) ); HYPRE_THRUST_CALL( gather, tmp_j, tmp_j + num_cols_A_offd_new, col_map_offd_A, col_map_offd_A_new ); hypre_TFree(offd_mark, HYPRE_MEMORY_DEVICE); hypre_TFree(col_map_offd_A, HYPRE_MEMORY_DEVICE); hypre_TFree(h_col_map_offd_A, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDeviceColMapOffd(A) = col_map_offd_A_new; hypre_ParCSRMatrixColMapOffd(A) = hypre_TAlloc(HYPRE_BigInt, num_cols_A_offd_new, HYPRE_MEMORY_HOST); hypre_TMemcpy(hypre_ParCSRMatrixColMapOffd(A), col_map_offd_A_new, HYPRE_BigInt, num_cols_A_offd_new, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); } if (type != 0) { hypre_TFree(elmt_tols_diag, HYPRE_MEMORY_DEVICE); hypre_TFree(elmt_tols_offd, HYPRE_MEMORY_DEVICE); } hypre_TFree(tmp_j, HYPRE_MEMORY_DEVICE); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixTransposeDevice *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixTransposeDevice( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix **AT_ptr, HYPRE_Int data ) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *A_diagT; hypre_CSRMatrix *AT_offd; HYPRE_Int num_procs; HYPRE_Int num_cols_offd_AT = 0; HYPRE_BigInt *col_map_offd_AT = NULL; hypre_ParCSRMatrix *AT; hypre_MPI_Comm_size(hypre_ParCSRMatrixComm(A), &num_procs); if (num_procs > 1) { void *request; hypre_CSRMatrix *A_offdT, *Aext; HYPRE_Int *Aext_ii, *Aext_j, Aext_nnz; HYPRE_Complex *Aext_data; HYPRE_BigInt *tmp_bigj; hypre_CSRMatrixTranspose(A_offd, &A_offdT, data); hypre_CSRMatrixBigJ(A_offdT) = hypre_TAlloc(HYPRE_BigInt, hypre_CSRMatrixNumNonzeros(A_offdT), HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( transform, hypre_CSRMatrixJ(A_offdT), hypre_CSRMatrixJ(A_offdT) + hypre_CSRMatrixNumNonzeros(A_offdT), thrust::make_constant_iterator(hypre_ParCSRMatrixFirstRowIndex(A)), hypre_CSRMatrixBigJ(A_offdT), thrust::plus<HYPRE_BigInt>() ); if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } hypre_ExchangeExternalRowsDeviceInit(A_offdT, hypre_ParCSRMatrixCommPkg(A), data, &request); hypre_CSRMatrixTranspose(A_diag, &A_diagT, data); Aext = hypre_ExchangeExternalRowsDeviceWait(request); hypre_CSRMatrixDestroy(A_offdT); // Aext contains offd of AT Aext_nnz = hypre_CSRMatrixNumNonzeros(Aext); Aext_ii = hypreDevice_CsrRowPtrsToIndices(hypre_CSRMatrixNumRows(Aext), Aext_nnz, hypre_CSRMatrixI(Aext)); hypre_ParCSRCommPkgCopySendMapElmtsToDevice(hypre_ParCSRMatrixCommPkg(A)); HYPRE_THRUST_CALL( gather, Aext_ii, Aext_ii + Aext_nnz, hypre_ParCSRCommPkgDeviceSendMapElmts(hypre_ParCSRMatrixCommPkg(A)), Aext_ii ); tmp_bigj = hypre_TAlloc(HYPRE_BigInt, Aext_nnz, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(tmp_bigj, hypre_CSRMatrixBigJ(Aext), HYPRE_BigInt, Aext_nnz, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( sort, tmp_bigj, tmp_bigj + Aext_nnz ); HYPRE_BigInt *new_end = HYPRE_THRUST_CALL( unique, tmp_bigj, tmp_bigj + Aext_nnz ); num_cols_offd_AT = new_end - tmp_bigj; col_map_offd_AT = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(col_map_offd_AT, tmp_bigj, HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); hypre_TFree(tmp_bigj, HYPRE_MEMORY_DEVICE); Aext_j = hypre_TAlloc(HYPRE_Int, Aext_nnz, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( lower_bound, col_map_offd_AT, col_map_offd_AT + num_cols_offd_AT, hypre_CSRMatrixBigJ(Aext), hypre_CSRMatrixBigJ(Aext) + Aext_nnz, Aext_j ); Aext_data = hypre_CSRMatrixData(Aext); hypre_CSRMatrixData(Aext) = NULL; hypre_CSRMatrixDestroy(Aext); if (data) { hypreDevice_StableSortByTupleKey(Aext_nnz, Aext_ii, Aext_j, Aext_data, 0); } else { HYPRE_THRUST_CALL( stable_sort, thrust::make_zip_iterator(thrust::make_tuple(Aext_ii, Aext_j)), thrust::make_zip_iterator(thrust::make_tuple(Aext_ii, Aext_j)) + Aext_nnz ); } AT_offd = hypre_CSRMatrixCreate(hypre_ParCSRMatrixNumCols(A), num_cols_offd_AT, Aext_nnz); hypre_CSRMatrixJ(AT_offd) = Aext_j; hypre_CSRMatrixData(AT_offd) = Aext_data; hypre_CSRMatrixInitialize_v2(AT_offd, 0, HYPRE_MEMORY_DEVICE); hypreDevice_CsrRowIndicesToPtrs_v2(hypre_CSRMatrixNumRows(AT_offd), Aext_nnz, Aext_ii, hypre_CSRMatrixI(AT_offd)); hypre_TFree(Aext_ii, HYPRE_MEMORY_DEVICE); } else { hypre_CSRMatrixTransposeDevice(A_diag, &A_diagT, data); AT_offd = hypre_CSRMatrixCreate(hypre_ParCSRMatrixNumCols(A), 0, 0); hypre_CSRMatrixInitialize_v2(AT_offd, 0, HYPRE_MEMORY_DEVICE); } AT = hypre_ParCSRMatrixCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumCols(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixColStarts(A), hypre_ParCSRMatrixRowStarts(A), num_cols_offd_AT, hypre_CSRMatrixNumNonzeros(A_diagT), hypre_CSRMatrixNumNonzeros(AT_offd)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(AT)); hypre_ParCSRMatrixDiag(AT) = A_diagT; hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(AT)); hypre_ParCSRMatrixOffd(AT) = AT_offd; if (num_cols_offd_AT) { hypre_ParCSRMatrixDeviceColMapOffd(AT) = col_map_offd_AT; hypre_ParCSRMatrixColMapOffd(AT) = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_HOST); hypre_TMemcpy(hypre_ParCSRMatrixColMapOffd(AT), col_map_offd_AT, HYPRE_BigInt, num_cols_offd_AT, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); } *AT_ptr = AT; return hypre_error_flag; } HYPRE_Int hypre_ParCSRMatrixAddDevice( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, HYPRE_Complex beta, hypre_ParCSRMatrix *B, hypre_ParCSRMatrix **C_ptr ) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); HYPRE_Int num_cols_offd_C = 0; HYPRE_BigInt *d_col_map_offd_C = NULL; HYPRE_Int num_procs; hypre_MPI_Comm_size(hypre_ParCSRMatrixComm(A), &num_procs); hypre_CSRMatrix *C_diag = hypre_CSRMatrixAddDevice(alpha, A_diag, beta, B_diag); hypre_CSRMatrix *C_offd; //if (num_cols_offd_A || num_cols_offd_B) if (num_procs > 1) { hypre_ParCSRMatrixCopyColMapOffdToDevice(A); hypre_ParCSRMatrixCopyColMapOffdToDevice(B); HYPRE_BigInt *tmp = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_A + num_cols_offd_B, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(tmp, hypre_ParCSRMatrixDeviceColMapOffd(A), HYPRE_BigInt, num_cols_offd_A, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(tmp + num_cols_offd_A, hypre_ParCSRMatrixDeviceColMapOffd(B), HYPRE_BigInt, num_cols_offd_B, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); HYPRE_THRUST_CALL( sort, tmp, tmp + num_cols_offd_A + num_cols_offd_B ); HYPRE_BigInt *new_end = HYPRE_THRUST_CALL( unique, tmp, tmp + num_cols_offd_A + num_cols_offd_B ); num_cols_offd_C = new_end - tmp; d_col_map_offd_C = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(d_col_map_offd_C, tmp, HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_DEVICE); /* reuse memory of tmp */ HYPRE_Int *offd_A2C = (HYPRE_Int *) tmp; HYPRE_Int *offd_B2C = offd_A2C + num_cols_offd_A; HYPRE_THRUST_CALL( lower_bound, d_col_map_offd_C, d_col_map_offd_C + num_cols_offd_C, hypre_ParCSRMatrixDeviceColMapOffd(A), hypre_ParCSRMatrixDeviceColMapOffd(A) + num_cols_offd_A, offd_A2C ); HYPRE_THRUST_CALL( lower_bound, d_col_map_offd_C, d_col_map_offd_C + num_cols_offd_C, hypre_ParCSRMatrixDeviceColMapOffd(B), hypre_ParCSRMatrixDeviceColMapOffd(B) + num_cols_offd_B, offd_B2C ); HYPRE_Int *C_offd_i, *C_offd_j, nnzC_offd; HYPRE_Complex *C_offd_a; hypreDevice_CSRSpAdd( hypre_CSRMatrixNumRows(A_offd), hypre_CSRMatrixNumRows(B_offd), num_cols_offd_C, hypre_CSRMatrixNumNonzeros(A_offd), hypre_CSRMatrixNumNonzeros(B_offd), hypre_CSRMatrixI(A_offd), hypre_CSRMatrixJ(A_offd), alpha, hypre_CSRMatrixData(A_offd), offd_A2C, hypre_CSRMatrixI(B_offd), hypre_CSRMatrixJ(B_offd), beta, hypre_CSRMatrixData(B_offd), offd_B2C, NULL, &nnzC_offd, &C_offd_i, &C_offd_j, &C_offd_a ); hypre_TFree(tmp, HYPRE_MEMORY_DEVICE); C_offd = hypre_CSRMatrixCreate(hypre_CSRMatrixNumRows(A_offd), num_cols_offd_C, nnzC_offd); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_CSRMatrixData(C_offd) = C_offd_a; hypre_CSRMatrixMemoryLocation(C_offd) = HYPRE_MEMORY_DEVICE; } else { C_offd = hypre_CSRMatrixCreate(hypre_CSRMatrixNumRows(A_offd), 0, 0); hypre_CSRMatrixInitialize_v2(C_offd, 0, HYPRE_MEMORY_DEVICE); } /* Create ParCSRMatrix C */ hypre_ParCSRMatrix *C = hypre_ParCSRMatrixCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixGlobalNumCols(A), hypre_ParCSRMatrixRowStarts(A), hypre_ParCSRMatrixColStarts(A), num_cols_offd_C, hypre_CSRMatrixNumNonzeros(C_diag), hypre_CSRMatrixNumNonzeros(C_offd)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(C)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(C)); hypre_ParCSRMatrixDiag(C) = C_diag; hypre_ParCSRMatrixOffd(C) = C_offd; if (num_cols_offd_C) { hypre_ParCSRMatrixDeviceColMapOffd(C) = d_col_map_offd_C; hypre_ParCSRMatrixColMapOffd(C) = hypre_TAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); hypre_TMemcpy(hypre_ParCSRMatrixColMapOffd(C), d_col_map_offd_C, HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); } hypre_ParCSRMatrixSetNumNonzeros(C); hypre_ParCSRMatrixDNumNonzeros(C) = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(C); /* create CommPkg of C */ hypre_MatvecCommPkgCreate(C); *C_ptr = C; return hypre_error_flag; } #endif // #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) /*-------------------------------------------------------------------------- * HYPRE_ParCSRDiagScale *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRDiagScale( HYPRE_ParCSRMatrix HA, HYPRE_ParVector Hy, HYPRE_ParVector Hx ) { hypre_ParCSRMatrix *A = (hypre_ParCSRMatrix *) HA; hypre_ParVector *y = (hypre_ParVector *) Hy; hypre_ParVector *x = (hypre_ParVector *) Hx; HYPRE_Real *x_data = hypre_VectorData(hypre_ParVectorLocalVector(x)); HYPRE_Real *y_data = hypre_VectorData(hypre_ParVectorLocalVector(y)); HYPRE_Real *A_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A)); HYPRE_Int *A_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A)); HYPRE_Int local_size = hypre_VectorSize(hypre_ParVectorLocalVector(x)); HYPRE_Int ierr = 0; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypreDevice_DiagScaleVector(local_size, A_i, A_data, y_data, 0.0, x_data); //hypre_SyncComputeStream(hypre_handle()); #else /* #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) */ HYPRE_Int i; #if defined(HYPRE_USING_DEVICE_OPENMP) #pragma omp target teams distribute parallel for private(i) is_device_ptr(x_data,y_data,A_data,A_i) #elif defined(HYPRE_USING_OPENMP) #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < local_size; i++) { x_data[i] = y_data[i] / A_data[A_i[i]]; } #endif /* #if defined(HYPRE_USING_CUDA) */ return ierr; }
5632.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "3mm.h" /* Array initialization. */ static void init_array(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nk; j++) A[i][j] = ((DATA_TYPE) i*j) / ni; for (i = 0; i < nk; i++) for (j = 0; j < nj; j++) B[i][j] = ((DATA_TYPE) i*(j+1)) / nj; for (i = 0; i < nj; i++) for (j = 0; j < nm; j++) C[i][j] = ((DATA_TYPE) i*(j+3)) / nl; for (i = 0; i < nm; i++) for (j = 0; j < nl; j++) D[i][j] = ((DATA_TYPE) i*(j+2)) / nk; } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nl, DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nl; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, G[i][j]); if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_3mm(int ni, int nj, int nk, int nl, int nm, DATA_TYPE POLYBENCH_2D(E,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk), DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj), DATA_TYPE POLYBENCH_2D(F,NJ,NL,nj,nl), DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm), DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl), DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl)) { int i, j, k; #pragma scop #pragma omp parallel private (i, j, k) num_threads(#P11) { /* E := A*B */ #pragma omp target teams distribute for (i = 0; i < _PB_NI; i++) { #pragma omp for (j = 0; j < _PB_NJ; j++) { E[i][j] = 0; for (k = 0; k < _PB_NK; ++k) E[i][j] += A[i][k] * B[k][j]; } } /* F := C*D */ #pragma omp target teams distribute for (i = 0; i < _PB_NJ; i++) { #pragma omp for (j = 0; j < _PB_NL; j++) { F[i][j] = 0; for (k = 0; k < _PB_NM; ++k) F[i][j] += C[i][k] * D[k][j]; } } /* G := E*F */ #pragma omp target teams distribute for (i = 0; i < _PB_NI; i++) { #pragma omp for (j = 0; j < _PB_NL; j++) { G[i][j] = 0; for (k = 0; k < _PB_NJ; ++k) G[i][j] += E[i][k] * F[k][j]; } } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; int nk = NK; int nl = NL; int nm = NM; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(E, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj); POLYBENCH_2D_ARRAY_DECL(F, DATA_TYPE, NJ, NL, nj, nl); POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NM, nj, nm); POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NM, NL, nm, nl); POLYBENCH_2D_ARRAY_DECL(G, DATA_TYPE, NI, NL, ni, nl); /* Initialize array(s). */ init_array (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_3mm (ni, nj, nk, nl, nm, POLYBENCH_ARRAY(E), POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B), POLYBENCH_ARRAY(F), POLYBENCH_ARRAY(C), POLYBENCH_ARRAY(D), POLYBENCH_ARRAY(G)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nl, POLYBENCH_ARRAY(G))); /* Be clean. */ POLYBENCH_FREE_ARRAY(E); POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); POLYBENCH_FREE_ARRAY(F); POLYBENCH_FREE_ARRAY(C); POLYBENCH_FREE_ARRAY(D); POLYBENCH_FREE_ARRAY(G); return 0; }
softmax-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file softmax-inl.h * \brief */ #ifndef MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #define MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #include <algorithm> #include <string> #include <utility> #include <vector> #include <type_traits> #include "../mxnet_op.h" #include "../operator_common.h" #include "../tensor/broadcast_reduce_op.h" using mshadow::red::limits::MinValue; namespace mxnet { namespace op { namespace mxnet_op { struct softmax_fwd { template <typename AType> MSHADOW_XINLINE static AType Map(float a, AType b) { return AType(expf(a) / b); } template <typename AType> MSHADOW_XINLINE static AType Map(double a, AType b) { return AType(exp(a) / b); } }; struct log_softmax_fwd { template <typename DType> MSHADOW_XINLINE static float Map(DType a, float b) { return a - logf(b); } template <typename DType> MSHADOW_XINLINE static double Map(DType a, double b) { return a - log(b); } }; template <typename OP, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void Softmax(Stream<cpu>* s, DType* in, OType* out, IType* length, Shape<ndim> shape, int axis, const DType temperature) { index_t M = shape[axis]; if (M == 0) return; index_t N = shape.Size() / M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; if (length == nullptr) { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); DType mmax = negate ? -in[base] : in[base]; DType val; for (index_t j = 1; j < M; ++j) { val = negate ? -in[base + j * sa] : in[base + j * sa]; if (mmax < val) mmax = val; } AType sum = AType(0); DType in_val; // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; sum += std::exp(in_val - mmax); } for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; out[base + j * sa] = OP::Map(in_val - mmax, sum); } } else { for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; sum += std::exp((in_val - mmax) / temperature); } for (index_t j = 0; j < M; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; out[base + j * sa] = OP::Map((in_val - mmax) / temperature, sum); } } } } else { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t len = static_cast<index_t>(length[i]); index_t base = unravel_dot(i, sshape, stride); DType mmax = negate ? -in[base] : in[base]; DType val; for (index_t j = 1; j < len; ++j) { val = negate ? -in[base + j * sa] : in[base + j * sa]; if (mmax < val) mmax = val; } for (index_t j = len; j < M; ++j) { out[base + j * sa] = OType(0.0f); } AType sum = AType(0); DType in_val; // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime if (temperature == 1.0) { for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; sum += std::exp(in_val - mmax); } for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; out[base + j * sa] = OP::Map(in_val - mmax, sum); } } else { for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; sum += std::exp((in_val - mmax) / temperature); } for (index_t j = 0; j < len; ++j) { in_val = negate ? -in[base + j * sa] : in[base + j * sa]; out[base + j * sa] = OP::Map((in_val - mmax) / temperature, sum); } } } } } struct masked_softmax_where { template <typename DType, int ndim> MSHADOW_XINLINE static void Map(index_t id, DType* out, const bool* cond, const DType* x, const double y, Shape<ndim> data_shape, Shape<ndim> mask_shape) { index_t mask_pos = 0; index_t stride = 1; for (index_t i = ndim - 1, j = id; i >= 0; --i) { auto tmp = j / data_shape[i]; if (mask_shape[i] != 1) { mask_pos += (j - tmp * mask_shape[i]) * stride; } stride *= mask_shape[i]; j = tmp; } KERNEL_ASSIGN(out[id], kWriteTo, (cond[mask_pos] ? x[id] : static_cast<DType>(y))); } }; template <typename OP, bool masked_neg_inf, bool negate, typename AType, typename DType, int ndim> inline void MaskedSoftmax(Stream<cpu>* s, DType* in, DType* out, bool* mask, Shape<ndim> data_shape, Shape<ndim> mask_shape, int axis, const double temperature, bool normalize, const OpContext& ctx) { Tensor<cpu, 1, DType> workspace = ctx.requested[0].get_space_typed<cpu, 1, DType>(Shape1(data_shape.Size()), s); DType* masked_input = TBlob(workspace).dptr<DType>(); double neg = MinValue<DType>(); Kernel<masked_softmax_where, cpu>::Launch( s, data_shape.Size(), masked_input, mask, in, neg, data_shape, mask_shape); int* max_lenghts = nullptr; double masked_value = 0.0; if (masked_neg_inf) masked_value = -INFINITY; Softmax<OP, negate, AType, DType>( s, masked_input, out, max_lenghts, data_shape, axis, temperature); Kernel<masked_softmax_where, cpu>::Launch( s, data_shape.Size(), out, mask, out, masked_value, data_shape, mask_shape); } struct softmax_bwd { template <typename DType, typename AType> MSHADOW_XINLINE static AType Map(DType ograd, DType out, AType sum) { return AType(out * (ograd - sum)); } }; struct log_softmax_bwd { template <typename AType> MSHADOW_XINLINE static AType Map(float ograd, float out, AType sum) { return AType(ograd - expf(out) * sum); } template <typename AType> MSHADOW_XINLINE static AType Map(double ograd, double out, AType sum) { return AType(ograd - exp(out) * sum); } }; template <typename OP1, typename OP2, int Req, bool negate, typename AType, typename DType, typename OType, typename IType, int ndim> inline void SoftmaxGrad(Stream<cpu>* s, OType* out, OType* ograd, DType* igrad, IType* length, Shape<ndim> shape, int axis, const DType temperature) { index_t M = shape[axis]; if (M == 0) return; index_t N = shape.Size() / M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; if (length != nullptr) { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); index_t len = static_cast<index_t>(length[i]); AType sum = AType(0); for (index_t j = 0; j < len; ++j) { sum += OP1::Map(ograd[base + j * sa], out[base + j * sa]); } // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime DType final_result; if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) : OP2::Map(ograd[base + j * sa], out[base + j * sa], sum); final_result = (j < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + j * sa], Req, final_result); } } else { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) / temperature : OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) / temperature; final_result = (j < len) ? final_result : DType(0.0f); KERNEL_ASSIGN(igrad[base + j * sa], Req, final_result); } } } } else { #pragma omp parallel for for (index_t i = 0; i < N; ++i) { index_t base = unravel_dot(i, sshape, stride); AType sum = AType(0); for (index_t j = 0; j < M; ++j) { sum += OP1::Map(ograd[base + j * sa], out[base + j * sa]); } // By default temperature is 1.0. // Adding a branch here to save the CPU 'divide-by-1' computation at runtime DType final_result; if (temperature == 1.0) { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) : OP2::Map(ograd[base + j * sa], out[base + j * sa], sum); KERNEL_ASSIGN(igrad[base + j * sa], Req, final_result); } } else { for (index_t j = 0; j < M; ++j) { final_result = negate ? -OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) / temperature : OP2::Map(ograd[base + j * sa], out[base + j * sa], sum) / temperature; KERNEL_ASSIGN(igrad[base + j * sa], Req, final_result); } } } } } template <typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType> inline void MaskedSoftmaxGrad(Stream<cpu>* s, DType* out, DType* ograd, DType* igrad, bool* mask, Shape<ndim> data_shape, Shape<ndim> mask_shape, int axis, const double temperature, const OpContext& ctx) { Tensor<cpu, 1, DType> workspace = ctx.requested[0].get_space_typed<cpu, 1, DType>(Shape1(data_shape.Size()), s); DType* masked_ograd = TBlob(workspace).dptr<DType>(); Kernel<masked_softmax_where, cpu>::Launch( s, data_shape.Size(), masked_ograd, mask, ograd, 0.0, data_shape, mask_shape); int* max_lenghts = nullptr; SoftmaxGrad<OP1, OP2, Req, negate, AType, DType, DType, int, ndim>( s, out, masked_ograd, igrad, max_lenghts, data_shape, axis, temperature); Kernel<masked_softmax_where, cpu>::Launch( s, data_shape.Size(), igrad, mask, igrad, 0.0, data_shape, mask_shape); } #ifdef __CUDACC__ const int softmax_threads_per_block = 512; template <int ndim> MSHADOW_XINLINE index_t get_mask_position(const index_t idx, const Shape<ndim>& data_shape, const Shape<ndim>& mask_shape, int axis, index_t* stride_axis) { index_t ret = 0; index_t stride = 1; *stride_axis = 1; #pragma unroll for (index_t i = ndim - 1, j = idx; i >= 0; --i) { auto tmp = j / data_shape[i]; if (i != axis && mask_shape[i] != 1) { ret += (j - tmp * mask_shape[i]) * stride; if (i > axis) *stride_axis *= mask_shape[i]; } stride *= mask_shape[i]; j = tmp; } return ret; } template <bool normalize, int x_bits, typename OP, bool masked_neg_inf, bool negate, typename AType, int ndim, typename DType> __global__ void masked_softmax_kernel(DType* in, DType* out, bool* in_mask, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride, Shape<ndim> mask_shape, const double temperature) { extern __shared__ double shared[]; AType* smem = reinterpret_cast<AType*>(shared); // x_size const unsigned x_size = 1 << x_bits; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t sa_mask = 0; index_t base_mask = get_mask_position(blockIdx.x, sshape, mask_shape, axis, &sa_mask); bool bcst_mask_axis = (mask_shape[axis] == 1); index_t x = threadIdx.x; DType smax = 0.0; if (normalize) { red::maximum::SetInitValue(smem[x]); for (index_t i = x; i < M; i += x_size) { bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; if (mask_value) smem[x] = ::max(smem[x], negate ? -in[base + i * sa] : in[base + i * sa]); } __syncthreads(); cuda::Reduce1D<red::maximum, x_bits>(smem); __syncthreads(); smax = smem[0]; __syncthreads(); } red::sum::SetInitValue(smem[x]); DType val; for (index_t i = x; i < M; i += x_size) { bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; if (mask_value) { val = (negate ? -in[base + i * sa] : in[base + i * sa]); smem[x] += static_cast<AType>(expf((val - smax) / static_cast<AType>(temperature))); } } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); AType ssum = smem[0]; __syncthreads(); double masked_value = 0.0; if (masked_neg_inf) masked_value = -INFINITY; for (index_t i = x; i < M; i += x_size) { val = (negate ? -in[base + i * sa] : in[base + i * sa]); bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; out[base + i * sa] = mask_value ? DType(OP::Map((val - smax) / static_cast<DType>(temperature), ssum)) : DType(masked_value); } } template <bool normalize, typename OP, bool masked_neg_inf, bool negate, typename AType, typename LType, typename LTypeMask, typename DType, int ndim> __global__ void masked_softmax_stride1_kernel(const DType* in, DType* out, bool* in_mask, const index_t M, int axis, Shape<ndim> sshape, Shape<ndim> mask_shape, const double temperature, const int rows_per_block, const index_t total_rows, const size_t size_input_shared, const size_t size_mask_shared) { const int entries_per_load = sizeof(LType) / sizeof(DType); const int entries_per_load_mask = sizeof(LTypeMask) / sizeof(bool); const int row_length = entries_per_load > 0 ? M / entries_per_load : 0; const int row_length_mask = entries_per_load > 0 ? M / entries_per_load_mask : 0; extern __shared__ double shared[]; LType* persistent_storage = reinterpret_cast<LType*>(shared); // rows_per_block * M (DType), aligned to double LTypeMask* mask_shared = reinterpret_cast<LTypeMask*>(&shared[size_input_shared]); // rows_per_block * M (bool), aligned to double AType* scratch = reinterpret_cast<AType*>(&shared[size_input_shared + size_mask_shared]); // softmax_threads_per_block const int warp_size = 32; const int threads_per_row = softmax_threads_per_block / rows_per_block; const int my_local_row = threadIdx.x / threads_per_row; const int my_row = blockIdx.x * rows_per_block + my_local_row; if (my_row >= total_rows) return; const int my_id = threadIdx.x % threads_per_row; size_t base = my_row * row_length; index_t pos_mask = 0; index_t stride = mask_shape[axis]; #pragma unroll for (index_t i = axis - 1, j = my_row; i >= 0; --i) { auto tmp = j / sshape[i]; if (mask_shape[i] != 1) { pos_mask += (j - tmp * mask_shape[i]) * stride; stride *= mask_shape[i]; } j = tmp; } const LType* in_aligned = reinterpret_cast<const LType*>(in); for (index_t i = my_id; i < row_length; i += threads_per_row) { persistent_storage[my_local_row * row_length + i] = in_aligned[base + i]; } const LTypeMask* in_mask_aligned = reinterpret_cast<const LTypeMask*>(&in_mask[pos_mask]); for (index_t i = my_id; i < row_length_mask; i += threads_per_row) { mask_shared[my_local_row * row_length_mask + i] = (mask_shape[axis] > 1) ? in_mask_aligned[i] : in_mask_aligned[0]; } DType* row = reinterpret_cast<DType*>(persistent_storage + my_local_row * row_length); bool* row_mask = reinterpret_cast<bool*>(mask_shared + my_local_row * row_length_mask); __syncthreads(); DType smax = 0.0; if (normalize) { DType my_max_value; red::maximum::SetInitValue(my_max_value); for (index_t i = my_id; i < M; i += threads_per_row) { if (row_mask[i]) my_max_value = ::max(my_max_value, negate ? -row[i] : row[i]); } scratch[threadIdx.x] = my_max_value; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] = ::max(scratch[threadIdx.x], scratch[threadIdx.x + size]); } __syncthreads(); } if (my_id < warp_size) { AType my_value = common::cuda::warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return ::max(x, y); }); scratch[threadIdx.x] = my_value; } __syncthreads(); smax = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); } AType my_sum; red::sum::SetInitValue(my_sum); for (index_t i = my_id; i < M; i += threads_per_row) { if (row_mask[i]) { const DType val = (negate ? -row[i] : row[i]); my_sum += static_cast<AType>(expf((val - smax) / static_cast<AType>(temperature))); } } scratch[threadIdx.x] = my_sum; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] += scratch[threadIdx.x + size]; } __syncthreads(); } if (my_id < warp_size) { AType my_value = common::cuda::warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return x + y; }); scratch[threadIdx.x] = my_value; } __syncthreads(); AType ssum = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); double masked_value = 0.0; if (masked_neg_inf) masked_value = -INFINITY; for (index_t i = my_id; i < M; i += threads_per_row) { const DType val = (negate ? -row[i] : row[i]); row[i] = row_mask[i] ? DType(OP::Map((val - smax) / static_cast<DType>(temperature), ssum)) : DType(masked_value); } __syncthreads(); LType* out_aligned = reinterpret_cast<LType*>(out); for (index_t i = my_id; i < row_length; i += threads_per_row) { out_aligned[base + i] = persistent_storage[my_local_row * row_length + i]; } } template <typename OP, bool masked_neg_inf, bool negate, typename AType, typename DType, typename OType, int ndim> inline void MaskedSoftmax(Stream<gpu>* s, DType* in, OType* out, bool* mask, Shape<ndim> data_shape, Shape<ndim> mask_shape, int axis, const double temperature, bool normalize, const OpContext& ctx) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = data_shape[axis]; if (M == 0 || data_shape.Size() == 0) return; index_t N = data_shape.Size() / M; Shape<ndim> stride = calc_stride(data_shape); Shape<ndim> sshape = data_shape; sshape[axis] = 1; const size_t DSize = sizeof(DType); // Using max of 20 kB of shared memory for InputData in the optimized case const size_t max_opt_M = 20 * 1024 / DSize; if (stride[axis] == 1 && static_cast<size_t>(M) <= max_opt_M && std::is_same<DType, OType>::value) { int ltype = mxnet::common::cuda::get_load_type(M * sizeof(DType)); int ltype_mask = mxnet::common::cuda::get_load_type(mask_shape[axis] * sizeof(bool)); MXNET_LOAD_TYPE_SWITCH(ltype, LType, { CHECK_LE(sizeof(DType), sizeof(LType)); MXNET_LOAD_TYPE_SWITCH(ltype_mask, LTypeMask, { CHECK_LE(sizeof(bool), sizeof(LTypeMask)); int rows_per_block = mxnet::common::cuda::get_rows_per_block( M * sizeof(DType) / sizeof(LType), softmax_threads_per_block); // calculate amount shared memory (slots aligned to double) int entries_per_load = entries_per_load = sizeof(LType) / sizeof(DType); int entries_per_load_mask = sizeof(LTypeMask) / sizeof(bool); size_t size_input_shared = entries_per_load > 0 ? rows_per_block * M / entries_per_load : 0; size_t size_mask_shared = entries_per_load_mask > 0 ? rows_per_block * M / entries_per_load_mask : 0; size_input_shared = ((size_input_shared * sizeof(LType) + sizeof(double) - 1) / sizeof(double)); size_mask_shared = ((size_mask_shared * sizeof(LTypeMask) + sizeof(double) - 1) / sizeof(double)); size_t amount_shared = size_input_shared * sizeof(double) + size_mask_shared * sizeof(double) + softmax_threads_per_block * sizeof(AType); int nblocks = (N + rows_per_block - 1) / rows_per_block; if (normalize) { masked_softmax_stride1_kernel<true, OP, masked_neg_inf, negate, AType, LType, LTypeMask> <<<nblocks, softmax_threads_per_block, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>(in, out, mask, M, axis, sshape, mask_shape, temperature, rows_per_block, N, size_input_shared, size_mask_shared); } else { masked_softmax_stride1_kernel<false, OP, masked_neg_inf, negate, AType, LType, LTypeMask> <<<nblocks, softmax_threads_per_block, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>(in, out, mask, M, axis, sshape, mask_shape, temperature, rows_per_block, N, size_input_shared, size_mask_shared); } }); }); MSHADOW_CUDA_POST_KERNEL_CHECK(masked_softmax_stride1_kernel); } else { size_t amount_shared = x_size * sizeof(AType); if (normalize) { masked_softmax_kernel<true, x_bits, OP, masked_neg_inf, negate, AType, ndim> <<<N, x_size, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>( in, out, mask, M, axis, sshape, stride, mask_shape, temperature); } else { masked_softmax_kernel<false, x_bits, OP, masked_neg_inf, negate, AType, ndim> <<<N, x_size, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>( in, out, mask, M, axis, sshape, stride, mask_shape, temperature); } MSHADOW_CUDA_POST_KERNEL_CHECK(masked_softmax_kernel); } } template <typename OP1, typename OP2, int Req, bool negate, typename AType, typename LType, typename LTypeMask, typename DType, typename OType, int ndim> __global__ void masked_softmax_stride1_grad_kernel(const OType* out, const OType* ograd, DType* igrad, const bool* in_mask, const index_t M, int axis, Shape<ndim> sshape, Shape<ndim> mask_shape, const double temperature, const int rows_per_block, const index_t total_rows, const size_t size_input_shared, const size_t size_mask_shared) { const int entries_per_load = sizeof(LType) / sizeof(DType); const int entries_per_load_mask = sizeof(LTypeMask) / sizeof(bool); const int row_length = entries_per_load > 0 ? M / entries_per_load : 0; const int row_length_mask = entries_per_load > 0 ? M / entries_per_load_mask : 0; extern __shared__ double shared[]; LType* persistent_storage = reinterpret_cast<LType*>(shared); // 2 * rows_per_block * M (DType), aligned to double LTypeMask* mask_shared = reinterpret_cast<LTypeMask*>(&shared[size_input_shared]); // rows_per_block * M (bool), aligned to double AType* scratch = reinterpret_cast<AType*>(&shared[size_input_shared + size_mask_shared]); // softmax_threads_per_block const int warp_size = 32; const int threads_per_row = softmax_threads_per_block / rows_per_block; const int my_local_row = threadIdx.x / threads_per_row; const int my_row = blockIdx.x * rows_per_block + my_local_row; if (my_row >= total_rows) return; const int my_id = threadIdx.x % threads_per_row; size_t base = my_row * row_length; index_t pos_mask = 0; index_t stride = mask_shape[axis]; #pragma unroll for (index_t i = axis - 1, j = my_row; i >= 0; --i) { auto tmp = j / sshape[i]; if (mask_shape[i] != 1) { pos_mask += (j - tmp * mask_shape[i]) * stride; stride *= mask_shape[i]; } j = tmp; } const LType* out_aligned = reinterpret_cast<const LType*>(out); const LType* ograd_aligned = reinterpret_cast<const LType*>(ograd); for (index_t i = my_id; i < row_length; i += threads_per_row) { persistent_storage[my_local_row * row_length * 2 + i] = out_aligned[base + i]; persistent_storage[my_local_row * row_length * 2 + row_length + i] = ograd_aligned[base + i]; } const LTypeMask* in_mask_aligned = reinterpret_cast<const LTypeMask*>(&in_mask[pos_mask]); for (index_t i = my_id; i < row_length_mask; i += threads_per_row) { mask_shared[my_local_row * row_length_mask + i] = (mask_shape[axis] > 1) ? in_mask_aligned[i] : in_mask_aligned[0]; } DType* row = reinterpret_cast<DType*>(persistent_storage + my_local_row * row_length * 2); bool* row_mask = reinterpret_cast<bool*>(mask_shared + my_local_row * row_length_mask); __syncthreads(); AType my_sum_value; red::sum::SetInitValue(my_sum_value); for (index_t i = my_id; i < M; i += threads_per_row) { if (row_mask[i]) my_sum_value += OP1::Map(row[i + M], row[i]); } scratch[threadIdx.x] = my_sum_value; __syncthreads(); for (int size = threads_per_row / 2; size >= warp_size; size /= 2) { if (my_id < size) { scratch[threadIdx.x] = scratch[threadIdx.x] + scratch[threadIdx.x + size]; } __syncthreads(); } if (my_id < warp_size) { AType my_value = common::cuda::warp_reduce(scratch[threadIdx.x], [](AType x, AType y) { return x + y; }); scratch[threadIdx.x] = my_value; } __syncthreads(); AType ssum = scratch[threadIdx.x - threadIdx.x % threads_per_row]; __syncthreads(); for (index_t i = my_id; i < M; i += threads_per_row) { const DType val = negate ? -OP2::Map(row[i + M], row[i], ssum) : OP2::Map(row[i + M], row[i], ssum); row[i] = row_mask[i] ? DType(val / static_cast<DType>(temperature)) : DType(0.0f); if (Req == kAddTo) { row[i] += igrad[my_row * M + i]; } } __syncthreads(); LType* igrad_aligned = reinterpret_cast<LType*>(igrad); for (index_t i = my_id; i < row_length; i += threads_per_row) { igrad_aligned[base + i] = persistent_storage[my_local_row * row_length * 2 + i]; } } template <int x_bits, typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType, typename OType> __global__ void masked_softmax_grad_kernel(OType* out, OType* ograd, DType* igrad, const bool* in_mask, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride, Shape<ndim> mask_shape, const double temperature) { const unsigned x_size = 1 << x_bits; __shared__ AType smem[x_size]; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t sa_mask = 0; index_t base_mask = get_mask_position(blockIdx.x, sshape, mask_shape, axis, &sa_mask); bool bcst_mask_axis = (mask_shape[axis] == 1); index_t x = threadIdx.x; red::sum::SetInitValue(smem[x]); for (index_t i = x; i < M; i += x_size) { bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; if (mask_value) smem[x] += OP1::Map(ograd[base + i * sa], out[base + i * sa]); } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); AType ssum = smem[0]; __syncthreads(); DType final_result; for (index_t i = x; i < M; i += x_size) { bool mask_value = bcst_mask_axis ? in_mask[base_mask] : in_mask[base_mask + i * sa_mask]; final_result = negate ? -OP2::Map(ograd[base + i * sa], out[base + i * sa], ssum) : OP2::Map(ograd[base + i * sa], out[base + i * sa], ssum); final_result = mask_value ? final_result / static_cast<DType>(temperature) : DType(0.0f); KERNEL_ASSIGN(igrad[base + i * sa], Req, final_result); } } template <typename OP1, typename OP2, int Req, bool negate, typename AType, int ndim, typename DType, typename OType> inline void MaskedSoftmaxGrad(Stream<gpu>* s, OType* out, OType* ograd, DType* igrad, bool* mask, Shape<ndim> data_shape, Shape<ndim> mask_shape, int axis, const double temperature, const OpContext& ctx) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = data_shape[axis]; if (M == 0 || data_shape.Size() == 0) return; index_t N = data_shape.Size() / M; Shape<ndim> stride = calc_stride(data_shape); Shape<ndim> sshape = data_shape; sshape[axis] = 1; const size_t DSize = sizeof(DType); // Using max of 20 kB of shared memory for InputData in the optimized case const size_t max_opt_M = 20 * 1024 / DSize; if (stride[axis] == 1 && static_cast<size_t>(M) <= max_opt_M && std::is_same<DType, OType>::value) { int ltype = mxnet::common::cuda::get_load_type(M * sizeof(DType)); int ltype_mask = mxnet::common::cuda::get_load_type(mask_shape[axis] * sizeof(bool)); MXNET_LOAD_TYPE_SWITCH(ltype, LType, { CHECK_LE(sizeof(DType), sizeof(LType)); MXNET_LOAD_TYPE_SWITCH(ltype_mask, LTypeMask, { CHECK_LE(sizeof(bool), sizeof(LTypeMask)); int rows_per_block = mxnet::common::cuda::get_rows_per_block( M * sizeof(DType) / sizeof(LType), softmax_threads_per_block); // calculate amount shared memory (slots aligned to double) int entries_per_load = entries_per_load = sizeof(LType) / sizeof(DType); int entries_per_load_mask = sizeof(LTypeMask) / sizeof(bool); size_t size_input_shared = entries_per_load > 0 ? rows_per_block * M / entries_per_load : 0; size_t size_mask_shared = entries_per_load_mask > 0 ? rows_per_block * M / entries_per_load_mask : 0; size_input_shared = ((2 * size_input_shared * sizeof(LType) + sizeof(double) - 1) / sizeof(double)); size_mask_shared = ((size_mask_shared * sizeof(LTypeMask) + sizeof(double) - 1) / sizeof(double)); size_t amount_shared = size_input_shared * sizeof(double) + size_mask_shared * sizeof(double) + softmax_threads_per_block * sizeof(AType); int nblocks = (N + rows_per_block - 1) / rows_per_block; masked_softmax_stride1_grad_kernel<OP1, OP2, Req, negate, AType, LType, LTypeMask> <<<nblocks, softmax_threads_per_block, amount_shared, mshadow::Stream<gpu>::GetStream(s)>>>(out, ograd, igrad, mask, M, axis, sshape, mask_shape, temperature, rows_per_block, N, size_input_shared, size_mask_shared); }); }); MSHADOW_CUDA_POST_KERNEL_CHECK(masked_softmax_stride1_grad_kernel); } else { masked_softmax_grad_kernel<x_bits, OP1, OP2, Req, negate, AType, ndim> <<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>( out, ograd, igrad, mask, M, axis, sshape, stride, mask_shape, temperature); MSHADOW_CUDA_POST_KERNEL_CHECK(masked_softmax_grad_kernel); } } #endif } // namespace mxnet_op struct SoftmaxParam : public dmlc::Parameter<SoftmaxParam> { int axis; dmlc::optional<double> temperature; dmlc::optional<int> dtype; dmlc::optional<bool> use_length; DMLC_DECLARE_PARAMETER(SoftmaxParam) { DMLC_DECLARE_FIELD(axis).set_default(-1).describe("The axis along which to compute softmax."); DMLC_DECLARE_FIELD(temperature) .set_default(dmlc::optional<double>()) .describe("Temperature parameter in softmax"); DMLC_DECLARE_FIELD(dtype) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(dmlc::optional<int>()) .describe( "DType of the output in case this can't be inferred. " "Defaults to the same as input's dtype if not defined (dtype=None)."); DMLC_DECLARE_FIELD(use_length) .set_default(dmlc::optional<bool>(false)) .describe("Whether to use the length input as a mask over the data input."); } bool operator==(const SoftmaxParam& other) const { return this->axis == other.axis && this->temperature == other.temperature && this->dtype == other.dtype && this->use_length == other.use_length; } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream axis_s, temperature_s, dtype_s, use_length_s; axis_s << axis; temperature_s << temperature; dtype_s << dtype; use_length_s << use_length; (*dict)["axis"] = axis_s.str(); (*dict)["temperature"] = temperature_s.str(); if (dtype.has_value()) { (*dict)["dtype"] = MXNetTypeWithBool2String(dtype.value()); } else { (*dict)["dtype"] = dtype_s.str(); } (*dict)["use_length"] = use_length_s.str(); } }; struct MaskedSoftmaxParam : public dmlc::Parameter<MaskedSoftmaxParam> { int axis; dmlc::optional<double> temperature; dmlc::optional<bool> normalize; DMLC_DECLARE_PARAMETER(MaskedSoftmaxParam) { DMLC_DECLARE_FIELD(axis).set_default(-1).describe("The axis along which to compute softmax."); DMLC_DECLARE_FIELD(temperature) .set_default(dmlc::optional<double>()) .describe("Temperature parameter in softmax"); DMLC_DECLARE_FIELD(normalize) .set_default(dmlc::optional<bool>(true)) .describe("Whether to normalize input data x: x = x - max(x)"); } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream axis_s, temperature_s, normalize_s; axis_s << axis; temperature_s << temperature; normalize_s << normalize; (*dict)["axis"] = axis_s.str(); (*dict)["temperature"] = temperature_s.str(); (*dict)["normalize"] = normalize_s.str(); } bool operator==(const MaskedSoftmaxParam& other) const { return this->axis == other.axis && this->temperature == other.temperature && this->normalize == other.normalize; } }; static inline bool softmax_has_dtype_override(const nnvm::NodeAttrs& attrs) { const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); return param.dtype.has_value() && param.dtype.value() != -1; } static inline bool softmax_use_length(const nnvm::NodeAttrs& attrs) { const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); return param.use_length.value(); } static inline bool SoftmaxOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), 1); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), softmax_use_length(attrs) ? 2U : 1U); if (softmax_has_dtype_override(attrs)) { TYPE_ASSIGN_CHECK(*out_attrs, 0, param.dtype.value()); type_assign(&(*in_attrs)[0], (*out_attrs)[0]); return true; } else { std::vector<int> tmp = {in_attrs->at(0)}; return ElemwiseType<1, 1>(attrs, &tmp, out_attrs); } } static inline bool SoftmaxOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { CHECK_EQ(out_attrs->size(), 1U); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), param.use_length.value() ? 2U : 1U); if (param.use_length.value()) { mxnet::TShape& dshape = in_attrs->at(0); mxnet::TShape tmp_shape((dshape.ndim() == 1) ? 1U : dshape.ndim() - 1, 1); int j = 0; int axis = param.axis != -1 ? param.axis : dshape.ndim() - 1; for (int i = 0; i < dshape.ndim(); ++i) { if (i != axis) { tmp_shape[j++] = dshape[i]; } } SHAPE_ASSIGN_CHECK(*in_attrs, 1, tmp_shape); } mxnet::ShapeVector tmp = {in_attrs->at(0)}; return ElemwiseShape<1, 1>(attrs, &tmp, out_attrs); } static inline bool SoftmaxGradOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { mxnet::ShapeVector ins = {in_attrs->at(0), in_attrs->at(1), in_attrs->at(3)}; mxnet::ShapeVector dgrad = {out_attrs->at(0)}; bool res = ElemwiseShape<3, 1>(attrs, &ins, &dgrad); SHAPE_ASSIGN_CHECK(*in_attrs, 0, ins[0]); SHAPE_ASSIGN_CHECK(*in_attrs, 1, ins[1]); SHAPE_ASSIGN_CHECK(*in_attrs, 3, ins[2]); SHAPE_ASSIGN_CHECK(*out_attrs, 0, dgrad[0]); mxnet::ShapeVector length = {in_attrs->at(2)}; mxnet::ShapeVector lgrad = {out_attrs->at(1)}; res = (res && ElemwiseShape<1, 1>(attrs, &length, &lgrad)); SHAPE_ASSIGN_CHECK(*in_attrs, 2, length[0]); SHAPE_ASSIGN_CHECK(*out_attrs, 1, lgrad[0]); return res; } else { return ElemwiseShape<3, 1>(attrs, in_attrs, out_attrs); } } else { return ElemwiseShape<2, 1>(attrs, in_attrs, out_attrs); } } static inline bool SoftmaxGradOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), softmax_use_length(attrs) ? 2U : 1U); if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { CHECK_EQ(in_attrs->size(), softmax_use_length(attrs) ? 4U : 3U); int in_dtype = (*in_attrs)[1]; int out_dtype = (*in_attrs)[softmax_use_length(attrs) ? 3 : 2]; TYPE_ASSIGN_CHECK(*in_attrs, 0, out_dtype); TYPE_ASSIGN_CHECK(*out_attrs, 0, in_dtype); if (softmax_use_length(attrs)) { TYPE_ASSIGN_CHECK(*out_attrs, 1, in_attrs->at(2)); } return (*out_attrs)[0] != -1 && (*in_attrs)[0] != -1 && (!softmax_use_length(attrs) || ((*out_attrs)[1] != -1 && (*in_attrs)[1] != -1)); } else { CHECK_EQ(in_attrs->size(), 2U); int out_dtype = (*in_attrs)[1]; TYPE_ASSIGN_CHECK(*out_attrs, 0, out_dtype); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_dtype); return (*out_attrs)[0] != -1 && (*in_attrs)[0] != -1; } } static inline std::vector<std::pair<int, int>> SoftmaxGradOpInplaceOption( const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { return std::vector<std::pair<int, int>>{{0, 0}, {1, 0}, {2, 1}, {3, 0}}; } else { return std::vector<std::pair<int, int>>{{0, 0}, {1, 0}, {2, 0}}; } } else { return std::vector<std::pair<int, int>>{{0, 0}, {1, 0}}; } } static inline uint32_t SoftmaxGradOpNumInputs(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { return softmax_use_length(attrs) ? 4 : 3; } return 2; } static inline std::vector<std::string> SoftmaxGradOpInputNames(const nnvm::NodeAttrs& attrs) { if (softmax_has_dtype_override(attrs) || softmax_use_length(attrs)) { if (softmax_use_length(attrs)) { return std::vector<std::string>{"ograd", "data", "length", "output"}; } else { return std::vector<std::string>{"ograd", "data", "output"}; } } else { return std::vector<std::string>{"ograd", "output"}; } } struct SoftmaxFGradient { const char* op_name; std::vector<nnvm::NodeEntry> operator()(const nnvm::ObjectPtr& n, const std::vector<nnvm::NodeEntry>& ograds) const { if (softmax_has_dtype_override(n->attrs) || softmax_use_length(n->attrs)) { return ElemwiseGradUseInOut{op_name}(n, ograds); // NOLINT } else { return ElemwiseGradUseOut{op_name}(n, ograds); // NOLINT } } }; static inline bool MaskedSoftmaxOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), 1); CHECK_EQ(in_attrs->size(), 2U); std::vector<int> tmp = {in_attrs->at(0)}; return ElemwiseType<1, 1>(attrs, &tmp, out_attrs); } static inline bool MaskedSoftmaxOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_shape, mxnet::ShapeVector* out_shape) { CHECK_EQ(out_shape->size(), 1U); CHECK_EQ(in_shape->size(), 2U); mxnet::TShape& data_shape = (*in_shape)[0]; mxnet::TShape& mask_shape = (*in_shape)[1]; if (!mxnet::ndim_is_known(data_shape) || !mxnet::ndim_is_known(mask_shape)) { return false; } CHECK(data_shape.ndim() == mask_shape.ndim()) << "Number of dimensions in data and mask does not match"; CHECK(data_shape.ndim() > 0) << "Empty tuple is not allowed"; for (int i = 0; i < data_shape.ndim(); ++i) { CHECK(data_shape[i] == mask_shape[i] || mask_shape[i] == 1) << "Mask cannot be broadcasted from " << mask_shape << " to " << data_shape; } SHAPE_ASSIGN_CHECK(*out_shape, 0, in_shape->at(0)); SHAPE_ASSIGN_CHECK(*in_shape, 0, out_shape->at(0)); return true; } static inline bool MaskedSoftmaxGradOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_shape, mxnet::ShapeVector* out_shape) { CHECK_EQ(out_shape->size(), 1U); CHECK_EQ(in_shape->size(), 3U); mxnet::TShape& ograd_shape = (*in_shape)[0]; mxnet::TShape& mask_shape = (*in_shape)[1]; if (!mxnet::ndim_is_known(ograd_shape) || !mxnet::ndim_is_known(mask_shape)) { return false; } CHECK(ograd_shape.ndim() == mask_shape.ndim()) << "Number of dimensions in data and mask does not match"; CHECK(ograd_shape.ndim() > 0) << "Empty tuple is not allowed"; for (int i = 0; i < ograd_shape.ndim(); ++i) { CHECK(ograd_shape[i] == mask_shape[i] || mask_shape[i] == 1) << "Mask cannot be broadcasted from " << mask_shape << " to " << ograd_shape; } SHAPE_ASSIGN_CHECK(*out_shape, 0, in_shape->at(0)); SHAPE_ASSIGN_CHECK(*out_shape, 0, in_shape->at(2)); SHAPE_ASSIGN_CHECK(*in_shape, 0, out_shape->at(0)); SHAPE_ASSIGN_CHECK(*in_shape, 2, out_shape->at(0)); return true; } static inline bool MaskedSoftmaxGradOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(out_attrs->size(), 1U); CHECK_EQ(in_attrs->size(), 3U); int data_dtype = (*in_attrs)[0]; TYPE_ASSIGN_CHECK(*in_attrs, 2, data_dtype); TYPE_ASSIGN_CHECK(*out_attrs, 0, data_dtype); data_dtype = (*out_attrs)[0]; TYPE_ASSIGN_CHECK(*in_attrs, 0, data_dtype); return true; } static inline std::vector<std::pair<int, int>> MaskedSoftmaxGradOpInplaceOption( const nnvm::NodeAttrs& attrs) { return std::vector<std::pair<int, int>>{{0, 0}, {1, 0}, {2, 1}, {3, 0}}; } template <typename xpu, typename OP, bool negate = false> void SoftmaxCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp || inputs[0].Size() == 0U) return; CHECK_NE(req[0], kAddTo); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; mxnet::TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); if (!safe_acc && inputs[0].type_flag_ == mshadow::kFloat16) { common::LogOnce( "MXNET_SAFE_ACCUMULATION=1 is recommended for softmax with float16 inputs. " "See https://mxnet.apache.org/api/faq/env_var " "for more details."); } MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, DType, AType, { MSHADOW_REAL_TYPE_SWITCH( outputs[0].type_flag_, OType, { int type = kInt32; if (param.use_length.value()) { CHECK(inputs.size() > 1) << "Mask needs to be provided when using softmax with use_length=True."; type = inputs[1].type_flag_; } MXNET_INT32_INT64_TYPE_SWITCH(type, IType, { IType* mask_ptr = nullptr; if (param.use_length.value()) { mask_ptr = inputs[1].dptr<IType>(); } if (safe_acc) { if (shape.ndim() == 2) { Softmax<OP, negate, AType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { Softmax<OP, negate, AType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } else { if (shape.ndim() == 2) { Softmax<OP, negate, DType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { Softmax<OP, negate, DType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<OType>(), mask_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } }); }); }); } template <typename xpu, typename OP, bool masked_neg_inf, bool negate = false> void MaskedSoftmaxCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp || inputs[0].Size() == 0U) return; CHECK_NE(req[0], kAddTo); const MaskedSoftmaxParam& param = nnvm::get<MaskedSoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); if (!safe_acc && inputs[0].type_flag_ == mshadow::kFloat16) { common::LogOnce( "MXNET_SAFE_ACCUMULATION=1 is recommended for masked_softmax with " "float16 inputs. " "See https://mxnet.apache.org/api/faq/env_var " "for more details."); } MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, DType, AType, { MXNET_NDIM_SWITCH(inputs[0].ndim(), ndim, { bool* mask_ptr = inputs[1].dptr<bool>(); if (safe_acc) { MaskedSoftmax<OP, masked_neg_inf, negate, AType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), mask_ptr, inputs[0].shape_.get<ndim>(), inputs[1].shape_.get<ndim>(), axis, temperature, param.normalize.value(), ctx); } else { MaskedSoftmax<OP, masked_neg_inf, negate, DType>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), mask_ptr, inputs[0].shape_.get<ndim>(), inputs[1].shape_.get<ndim>(), axis, temperature, param.normalize.value(), ctx); } }); }); } #if MXNET_USE_CUDA struct SoftmaxRTCCompute { std::string OP; bool negate = false; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; struct SoftmaxRTCGradCompute { std::string OP1; std::string OP2; bool negate = false; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; #endif template <typename xpu, typename OP1, typename OP2, bool negate = false> void SoftmaxGradCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (softmax_use_length(attrs)) { MXNET_INT32_INT64_TYPE_SWITCH(inputs[2].type_flag_, IType, { if (req[1] != kNullOp) { mxnet_op::Kernel<mxnet_op::set_zero, xpu>::Launch( ctx.get_stream<xpu>(), outputs[1].Size(), outputs[1].dptr<IType>()); } }); } if (req[0] == kNullOp) return; const int itype = softmax_use_length(attrs) ? inputs[2].type_flag_ : kInt32; const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; mxnet::TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); int out_idx = softmax_has_dtype_override(attrs) ? 2 : 1; out_idx = softmax_use_length(attrs) ? 3 : out_idx; bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, OType, AType, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MXNET_INT32_INT64_TYPE_SWITCH(itype, IType, { IType* length_ptr = nullptr; if (softmax_use_length(attrs)) { length_ptr = inputs[2].dptr<IType>(); } if (safe_acc) { if (shape.ndim() == 2) { SoftmaxGrad<OP1, OP2, Req, negate, AType>(ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { SoftmaxGrad<OP1, OP2, Req, negate, AType>(ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } else { if (shape.ndim() == 2) { SoftmaxGrad<OP1, OP2, Req, negate, DType>(ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<2>(), axis, static_cast<DType>(temperature)); } else { SoftmaxGrad<OP1, OP2, Req, negate, DType>(ctx.get_stream<xpu>(), inputs[out_idx].dptr<OType>(), inputs[0].dptr<OType>(), outputs[0].dptr<DType>(), length_ptr, shape.get<3>(), axis, static_cast<DType>(temperature)); } } }); }); }); }); } template <typename xpu, typename OP1, typename OP2, bool negate = false> void MaskedSoftmaxGradCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; const MaskedSoftmaxParam& param = nnvm::get<MaskedSoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); const double temperature = param.temperature.has_value() ? param.temperature.value() : 1.0; bool safe_acc = dmlc::GetEnv("MXNET_SAFE_ACCUMULATION", true); MXNET_REAL_ACC_TYPE_SWITCH(inputs[0].type_flag_, DType, AType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MXNET_NDIM_SWITCH(inputs[0].ndim(), ndim, { DType* ograd_ptr = inputs[0].dptr<DType>(); DType* out_ptr = inputs[2].dptr<DType>(); bool* mask_ptr = inputs[1].dptr<bool>(); DType* grad_data = outputs[0].dptr<DType>(); if (safe_acc) { MaskedSoftmaxGrad<OP1, OP2, Req, negate, AType>(ctx.get_stream<xpu>(), out_ptr, ograd_ptr, grad_data, mask_ptr, inputs[0].shape_.get<ndim>(), inputs[1].shape_.get<ndim>(), axis, static_cast<DType>(temperature), ctx); } else { MaskedSoftmaxGrad<OP1, OP2, Req, negate, DType>(ctx.get_stream<xpu>(), out_ptr, ograd_ptr, grad_data, mask_ptr, inputs[0].shape_.get<ndim>(), inputs[1].shape_.get<ndim>(), axis, static_cast<DType>(temperature), ctx); } }); }); }); } } // namespace op } // namespace mxnet namespace std { template <> struct hash<mxnet::op::SoftmaxParam> { size_t operator()(const mxnet::op::SoftmaxParam& val) { size_t ret = 0; ret = dmlc::HashCombine(ret, val.axis); ret = dmlc::HashCombine(ret, val.temperature); ret = dmlc::HashCombine(ret, val.dtype); ret = dmlc::HashCombine(ret, val.use_length); return ret; } }; template <> struct hash<mxnet::op::MaskedSoftmaxParam> { size_t operator()(const mxnet::op::MaskedSoftmaxParam& val) { size_t ret = 0; ret = dmlc::HashCombine(ret, val.axis); ret = dmlc::HashCombine(ret, val.temperature); ret = dmlc::HashCombine(ret, val.normalize); return ret; } }; } // namespace std #endif // MXNET_OPERATOR_NN_SOFTMAX_INL_H_
buggy_version.c
#include<stdio.h> #include <stdlib.h> int main(){ int T[10]; srand (1); // initializing array T for (int i = 0; i < 10; i ++) { T[i] = i; } // running the loop 10 times using openmp // increase all element in array T by 1 each iteraion #pragma omp parallel for shared (T) for ( int i = 0; i < 100; i ++) { int sum = rand(); for (int j =0; j < 10; j++) { T[j] +=sum; } } for (int i = 0; i < 10; i++) { printf("T[i] = %d\n",T[i] ); } }
Example2.c
//#include <stdio.h> //#include <omp.h> //#include <conio.h> // //int main(int argc, char *argv[]) //{ // int tid, tsize; //#pragma omp parallel num_threads(5) // { // tsize = omp_get_num_threads(); // printf("Number of Threads = %d \n", tsize); //#pragma omp sections // { //#pragma omp section // { // tid = omp_get_thread_num(); // printf("1st Thread %d is done. \n", tid); // } //#pragma omp section // { // tid = omp_get_thread_num(); // printf("2nd Thread %d is done. \n", tid); // } //#pragma omp section // { // tid = omp_get_thread_num(); // printf("3rd Thread %d is done. \n", tid); // } //#pragma omp section // { // tid = omp_get_thread_num(); // printf("4th Thread %d is done. \n", tid); // } //#pragma omp section // { // tid = omp_get_thread_num(); // printf("5th Thread %d is done. \n", tid); // } // } /*--The end of the sections block--*/ // } // _getch(); // for keep console from <conio.h> library // return 0; //}
VolumetricConvolutionMM.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "THNN/generic/VolumetricConvolutionMM.c" #else #include <ATen/div_rtn.h> #include <ATen/Parallel.h> #define CONV3D_OMP_THRESHOLD 20 static void inline THNN_(VolumetricConvolutionMM_shapeCheck)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *weight, THTensor *bias, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int weight_nullable) { THNN_ARGCHECK(!input->is_empty() && (input->dim() == 4 || input->dim() == 5), 2, input, "non-empty 4D or 5D (batch mode) tensor expected for input, but got: %s"); THArgCheck(kT > 0 && kW > 0 && kH > 0, 8, "kernel size should be greater than zero, but got kT: %d kH: %d kW: %d", kT, kH, kW); THArgCheck(dT > 0 && dW > 0 && dH > 0, 11, "stride should be greater than zero, but got dT: %d dH: %d dW: %d", dT, dH, dW); if (weight != NULL) { THNN_ARGCHECK(!weight->is_empty() && (weight->dim() == 2 || weight->dim() == 5), 5, weight, "non-empty 2D or 5D weight tensor expected, but got: %s"); if (bias != NULL) { THNN_CHECK_DIM_SIZE(bias, 1, 0, weight->size(0)); } } else if (!weight_nullable) { THError("weight tensor is expected to be non-nullable"); } int ndim = input->dim(); int dimf = 0; int dimt = 1; int dimh = 2; int dimw = 3; if (ndim == 5) { dimf++; dimt++; dimh++; dimw++; } int64_t inputDepth; int64_t inputHeight; int64_t inputWidth; int64_t exactInputDepth; int64_t exactInputHeight; int64_t exactInputWidth; int64_t outputDepth; int64_t outputHeight; int64_t outputWidth; inputDepth = input->size(dimt); inputHeight = input->size(dimh); inputWidth = input->size(dimw); exactInputDepth = inputDepth + 2*pT; exactInputHeight = inputHeight + 2*pH; exactInputWidth = inputWidth + 2*pW; if (exactInputDepth < kT || exactInputHeight < kH || exactInputWidth < kW) { THError("Calculated padded input size per channel: (%ld x %ld x %ld). " "Kernel size: (%d x %d x %d). Kernel size can't be greater than actual input size", exactInputDepth, exactInputHeight, exactInputWidth, kT, kH, kW); } outputDepth = div_rtn<int64_t>(exactInputDepth - kT, dT) + 1; outputHeight = div_rtn<int64_t>(exactInputHeight - kH, dH) + 1; outputWidth = div_rtn<int64_t>(exactInputWidth - kW, dW) + 1; if (outputDepth < 1 || outputWidth < 1 || outputHeight < 1) { THError("Given input size per channel: (%ld x %ld x %ld). " "Calculated output size per channel: (%ld x %ld x %ld). Output size is too small", inputDepth, inputHeight, inputWidth, outputDepth, outputHeight, outputWidth); } if (weight != NULL) { int64_t nInputPlane = weight->size(1); if (weight->dim() == 2) { nInputPlane /= (kT * kH * kW); } THNN_CHECK_DIM_SIZE(input, ndim, dimf, nInputPlane); } if (gradOutput != NULL) { if (weight != NULL) { int64_t nOutputPlane = weight->size(0); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimf, nOutputPlane); } else if (bias != NULL) { int64_t nOutputPlane = THTensor_sizeLegacyNoScalars(bias, 0); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimf, nOutputPlane); } THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimt, outputDepth); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimh, outputHeight); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimw, outputWidth); } } static THTensor* THNN_(newViewWeight)(THTensor *weight) { weight = THTensor_(newContiguous)(weight); if (weight->dim() == 5) { int64_t s1 = weight->size(0); int64_t s2 = weight->size(1) * weight->size(2) * weight->size(3) * weight->size(4); THTensor *old_weight = weight; weight = THTensor_(newWithStorage2d)(THTensor_getStoragePtr(weight), weight->storage_offset(), s1, -1, s2, -1); c10::raw::intrusive_ptr::decref(old_weight); } return weight; } // Kernel for fast unfold+copy // Borrowed from Theano // Authors: Arjun Jain, Frédéric Bastien, Jan Schlüter, Nicolas Ballas static void THNN_(unfolded_acc_vol)( THTensor *finput, THTensor *input, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int64_t nInputPlane, int64_t inputDepth, int64_t inputWidth, int64_t inputHeight, int64_t outputDepth, int64_t outputWidth, int64_t outputHeight) { scalar_t *input_data = input->data<scalar_t>(); scalar_t *finput_data = finput->data<scalar_t>(); int64_t n = nInputPlane * inputHeight * inputWidth * inputDepth; at::parallel_for(0, n, 0, [&](int64_t start, int64_t end) { int64_t line_index_offset = start; int64_t line_seg_len = (end - start); int64_t w = line_index_offset % inputWidth + pW; int64_t h_index = line_index_offset / inputWidth; int64_t h = h_index % inputHeight + pH; int64_t d_index = h_index / inputHeight; int64_t d = d_index % inputDepth + pT; int64_t c = d_index / inputDepth; int64_t outputHW = outputHeight * outputWidth; int64_t outputDHW = outputDepth * outputHW; int64_t kHkW = kH*kW; int64_t kTkHkW = kT*kHkW; int64_t coeff_d_col = outputHW - dT * kHkW * outputDHW; int64_t coeff_h_col = outputWidth - dH * kW * outputDHW; int64_t coeff_w_col = (1 - dW * outputDHW); int64_t count = 0; while (count < line_seg_len) { // compute the start and end of the output int64_t w_col_start = (w < kW) ? 0 : (w - kW) / dW + 1; int64_t w_col_tmp = w / dW + 1; int64_t w_col_end = w_col_tmp < outputWidth? w_col_tmp : outputWidth; int64_t h_col_start = (h < kH) ? 0 : (h - kH) / dH + 1; int64_t h_col_tmp = h / dH + 1; int64_t h_col_end = h_col_tmp < outputHeight? h_col_tmp : outputHeight; int64_t d_col_start = (d < kT) ? 0 : (d - kT) / dT + 1; int64_t d_col_tmp = d / dT + 1; int64_t d_col_end = d_col_tmp < outputDepth? d_col_tmp : outputDepth; scalar_t val = 0; int64_t offset = (c * kTkHkW + d * kHkW + h * kW + w) * outputDHW; int64_t offset_w_col_start = w_col_start * coeff_w_col; int64_t offset_d_col_start = d_col_start * coeff_d_col; int64_t offset_h_col_start = h_col_start * coeff_h_col; int64_t offset_w_col = offset_w_col_start + offset; int64_t offset_d_col; int64_t offset_h_col; int64_t w_col, d_col, h_col; for (w_col = w_col_start; w_col < w_col_end; ++w_col) { offset_d_col = offset_d_col_start + offset_w_col; for (d_col = d_col_start; d_col < d_col_end; ++d_col) { offset_h_col = offset_h_col_start + offset_d_col; for (h_col = h_col_start; h_col < h_col_end; ++h_col) { val += finput_data[offset_h_col]; offset_h_col += coeff_h_col; } offset_d_col += coeff_d_col; } offset_w_col += coeff_w_col; } input_data[line_index_offset+count] = val; count++; if (count < line_seg_len) { if (w - pW + 1 == inputWidth) { w = pW; if (h - pH + 1 == inputHeight) { h = pH; if (d - pT + 1 == inputDepth) { d = pT; c++; } else d++; } else h++; } else w++; } } }); } /* Modified from the version of CUDA implementation, but the loop iterations is larger than that one. The larger loop could lower the proportion of openmp overhead. And the inner part in loop is simpler. The naive code is below: scalar_t *input_data = input->data<scalar_t>(); scalar_t *finput_data = finput->data<scalar_t>(); int64_t n = nInputPlane*kT*kH*kW*outputDepth*outputWidth*outputHeight; #pragma omp parallel for firstprivate(finput_data, input_data, outputWidth, outputHeight, outputDepth, kW, kH, kT, dW, dH, dT, pW, pH, pT, inputHeight, inputWidth, inputDepth) for (int64_t idx = 0; idx < n ; ++idx) { int64_t w_out = line_index_offset % outputWidth; int64_t remained = line_index_offset / outputWidth; int64_t h_out = remained % outputHeight; remained /= outputHeight; int64_t d_out = remained % outputDepth; remained /= outputDepth; int k = remained % kW; remained /= kW; int j = remained % kH; remained /= kH; int i = remained % kT; int64_t nip = remained / kT; int64_t d = d_out * dT - pT + i; int64_t h = h_out * dH - pH + j; int64_t w = w_out * dW - pW + k; finput_data[idx] = (h >= 0 && w >= 0 && d >= 0 && h < inputHeight && w < inputWidth && d < inputDepth) ? input_data[nip*inputDepth*inputWidth*inputHeight+ d*inputHeight*inputWidth + h*inputWidth + w] : 0; } However, there are 6 quotient and 6 module operations which are very time-consuming. So we choose relatively more complex but more efficient pattern. */ static void THNN_(unfolded_copy_vol)( THTensor *finput, THTensor *input, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int64_t nInputPlane, int64_t inputDepth, int64_t inputWidth, int64_t inputHeight, int64_t outputDepth, int64_t outputWidth, int64_t outputHeight) { scalar_t *input_data = input->data<scalar_t>(); scalar_t *finput_data = finput->data<scalar_t>(); int64_t n = nInputPlane*kT*kH*kW*outputDepth*outputWidth*outputHeight; at::parallel_for(0, n, 0, [&](int64_t start, int64_t end) { int64_t line_index_offset = start; int64_t line_seg_len = (end - start); int64_t w_out = line_index_offset % outputWidth; int64_t remained = line_index_offset / outputWidth; int64_t h_out = remained % outputHeight; remained /= outputHeight; int64_t d_out = remained % outputDepth; remained /= outputDepth; int k = remained % kW; remained /= kW; int j = remained % kH; remained /= kH; int i = remained % kT; int64_t nip = remained / kT; int64_t count = 0; scalar_t* dst = finput_data + line_index_offset; int64_t inputHW = inputHeight*inputWidth; int64_t inputDHW = inputHW*inputDepth; while (count < line_seg_len) { int64_t w = w_out * dW - pW + k; int64_t h = h_out * dH - pH + j; int64_t d = d_out * dT - pT + i; *dst = (h >= 0 && w >= 0 && d >= 0 && h < inputHeight && w < inputWidth && d < inputDepth) ? input_data[nip*inputDHW+ d*inputHW + h*inputWidth + w] : 0; count++; if (count < line_seg_len) { dst++; w_out++; if (w_out == outputWidth) { w_out = 0; h_out++; if (h_out == outputHeight) { h_out = 0; d_out++; if (d_out == outputDepth) { d_out = 0; k++; if(k == kW) { k = 0; j++; if(j == kH) { j = 0; i++; if(i == kT) { i = 0; nip++; } } } } } } } } }); } static void THNN_(VolumetricConvolutionMM_updateOutput_frame)( THTensor *input, THTensor *output, THTensor *weight, THTensor *bias, THTensor *finput, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int64_t nInputPlane, int64_t inputDepth, int64_t inputWidth, int64_t inputHeight, int64_t nOutputPlane, int64_t outputDepth, int64_t outputWidth, int64_t outputHeight) { int64_t i; THTensor *output2d; THNN_(unfolded_copy_vol)( finput, input, kT, kW, kH, dT, dW, dH, pT, pW, pH, nInputPlane, inputDepth, inputWidth, inputHeight, outputDepth, outputWidth, outputHeight ); output2d = THTensor_(newWithStorage2d)( THTensor_getStoragePtr(output), output->storage_offset(), nOutputPlane, -1, outputDepth*outputHeight*outputWidth, -1 ); if (bias) { for (i = 0; i < nOutputPlane; i++) { THVector_(fill)( THStorage_(data)(THTensor_getStoragePtr(output))+output->storage_offset()+output->stride(0)*i, THTensor_(get1d)(bias, i), outputDepth*outputHeight*outputWidth ); } } else { THTensor_(zero)(output); } THTensor_(addmm)(output2d, 1, output2d, 1, weight, finput); c10::raw::intrusive_ptr::decref(output2d); } void THNN_(VolumetricConvolutionMM_updateOutput)( THNNState *state, THTensor *input, THTensor *output, THTensor *weight, THTensor *bias, THTensor *finput, THTensor *fgradInput, // unused int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH) { int dimf = 0; int dimt = 1; int dimh = 2; int dimw = 3; int64_t nInputPlane; int64_t inputDepth; int64_t inputHeight; int64_t inputWidth; int64_t nOutputPlane; int64_t outputDepth; int64_t outputHeight; int64_t outputWidth; THNN_(VolumetricConvolutionMM_shapeCheck)( state, input, NULL, weight, bias, kT, kW, kH, dT, dW, dH, pT, pW, pH, 0); input = THTensor_(newContiguous)(input); if (input->dim() == 5) { dimf++; dimt++; dimh++; dimw++; } nInputPlane = input->size(dimf); inputDepth = input->size(dimt); inputHeight = input->size(dimh); inputWidth = input->size(dimw); nOutputPlane = weight->size(0); outputDepth = (inputDepth + 2*pT - kT) / dT + 1; outputHeight = (inputHeight + 2*pH - kH) / dH + 1; outputWidth = (inputWidth + 2*pW - kW) / dW + 1; weight = THNN_(newViewWeight)(weight); if (input->dim() == 4) { THTensor_(resize2d)(finput, kT*kW*kH*nInputPlane, outputDepth*outputHeight*outputWidth); THTensor_(resize4d)(output, nOutputPlane, outputDepth, outputHeight, outputWidth); THNN_(VolumetricConvolutionMM_updateOutput_frame)( input, output, weight, bias, finput, kT, kW, kH, dT, dW, dH, pT, pW, pH, nInputPlane, inputDepth, inputWidth, inputHeight, nOutputPlane, outputDepth, outputWidth, outputHeight ); } else { int64_t T = input->size(0); THTensor_(resize3d)(finput, T, kT*kW*kH*nInputPlane, outputDepth*outputHeight*outputWidth); THTensor_(resize5d)(output, T, nOutputPlane, outputDepth, outputHeight, outputWidth); at::parallel_for(0, T, CONV3D_OMP_THRESHOLD, [&](int64_t start, int64_t end) { for (auto t = start; t < end; t++) { THTensor *input_t = THTensor_(newSelect)(input, 0, t); THTensor *output_t = THTensor_(newSelect)(output, 0, t); THTensor *finput_t = THTensor_(newSelect)(finput, 0, t); THNN_(VolumetricConvolutionMM_updateOutput_frame)( input_t, output_t, weight, bias, finput_t, kT, kW, kH, dT, dW, dH, pT, pW, pH, nInputPlane, inputDepth, inputWidth, inputHeight, nOutputPlane, outputDepth, outputWidth, outputHeight ); c10::raw::intrusive_ptr::decref(input_t); c10::raw::intrusive_ptr::decref(output_t); c10::raw::intrusive_ptr::decref(finput_t); } }); } c10::raw::intrusive_ptr::decref(input); c10::raw::intrusive_ptr::decref(weight); } #if !defined(TH_REAL_IS_LONG) static void THNN_(VolumetricConvolutionMM_updateGradInput_frame)( THTensor *gradInput, THTensor *gradOutput, THTensor *weight, THTensor *fgradInput, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH) { THTensor *gradOutput2d = THTensor_(newWithStorage2d)( THTensor_getStoragePtr(gradOutput), gradOutput->storage_offset(), gradOutput->size(0), -1, gradOutput->size(1)*gradOutput->size(2)*gradOutput->size(3), -1 ); THTensor_(addmm)(fgradInput, 0, fgradInput, 1, weight, gradOutput2d); c10::raw::intrusive_ptr::decref(gradOutput2d); THTensor_(zero)(gradInput); THNN_(unfolded_acc_vol)( fgradInput, gradInput, kT, kW, kH, dT, dW, dH, pT, pW, pH, gradInput->size(0), gradInput->size(1), gradInput->size(3), gradInput->size(2), gradOutput->size(1), gradOutput->size(3), gradOutput->size(2) ); } void THNN_(VolumetricConvolutionMM_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *weight, THTensor *finput, THTensor *fgradInput, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH) { THNN_(VolumetricConvolutionMM_shapeCheck)( state, input, gradOutput, weight, NULL, kT, kW, kH, dT, dW, dH, pT, pW, pH, 0); input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); weight = THNN_(newViewWeight)(weight); THTensor_(resizeAs)(gradInput, input); THTensor_(resizeAs)(fgradInput, finput); // depending on the BLAS library, fgradInput (result tensor) might // be left uninitialized on zero alpha, which might lead to weird behavior // hence, to be safe, zero it THTensor_(zero)(fgradInput); THTensor *tweight = THTensor_(new)(); THTensor_(transpose)(tweight, weight, 0, 1); if (input->dim() == 4) { THNN_(VolumetricConvolutionMM_updateGradInput_frame)( gradInput, gradOutput, tweight, fgradInput, kT, kW, kH, dT, dW, dH, pT, pW, pH ); } else { int64_t T = input->size(0); at::parallel_for(0, T, CONV3D_OMP_THRESHOLD, [&](int64_t start, int64_t end) { for (auto t = start; t < end; t++) { THTensor *gradInput_t = THTensor_(newSelect)(gradInput, 0, t); THTensor *gradOutput_t = THTensor_(newSelect)(gradOutput, 0, t); THTensor *fgradInput_t = THTensor_(newSelect)(fgradInput, 0, t); THNN_(VolumetricConvolutionMM_updateGradInput_frame)( gradInput_t, gradOutput_t, tweight, fgradInput_t, kT, kW, kH, dT, dW, dH, pT, pW, pH ); c10::raw::intrusive_ptr::decref(gradInput_t); c10::raw::intrusive_ptr::decref(gradOutput_t); c10::raw::intrusive_ptr::decref(fgradInput_t); } }); } c10::raw::intrusive_ptr::decref(tweight); c10::raw::intrusive_ptr::decref(input); c10::raw::intrusive_ptr::decref(gradOutput); c10::raw::intrusive_ptr::decref(weight); } static void THNN_(VolumetricConvolutionMM_accGradParameters_frame)( THTensor *gradOutput, THTensor *gradWeight, THTensor *gradBias, THTensor *finput, // can be NULL if gradWeight = NULL scalar_t scale) { int64_t i; THTensor *gradOutput2d = THTensor_(newWithStorage2d)( THTensor_getStoragePtr(gradOutput), gradOutput->storage_offset(), gradOutput->size(0), -1, gradOutput->size(1)*gradOutput->size(2)*gradOutput->size(3), -1 ); if (gradWeight){ THTensor *tfinput = THTensor_(new)(); THTensor_(transpose)(tfinput, finput, 0, 1); THTensor_(addmm)(gradWeight, 1, gradWeight, scale, gradOutput2d, tfinput); c10::raw::intrusive_ptr::decref(tfinput); } if (gradBias) { for (i = 0; i < THTensor_sizeLegacyNoScalars(gradBias, 0); i++) { int64_t k; scalar_t sum = 0; scalar_t *data = THStorage_(data)(THTensor_getStoragePtr(gradOutput2d)) + gradOutput2d->storage_offset() + i*gradOutput2d->stride(0); for (k = 0; k < gradOutput2d->size(1); k++) sum += data[k]; (THStorage_(data)(THTensor_getStoragePtr(gradBias)) + gradBias->storage_offset())[i] += scale * sum; } } c10::raw::intrusive_ptr::decref(gradOutput2d); } void THNN_(VolumetricConvolutionMM_accGradParameters)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradWeight, THTensor *gradBias, THTensor *finput, THTensor *fgradInput, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, accreal scale_) { scalar_t scale = TH_CONVERT_ACCREAL_TO_REAL(scale_); THNN_(VolumetricConvolutionMM_shapeCheck)( state, input, gradOutput, gradWeight, gradBias, kT, kW, kH, dT, dW, dH, pT, pW, pH, 1); input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); if (gradWeight) { gradWeight = THNN_(newViewWeight)(gradWeight); } if (input->dim() == 4) // non-batch mode { THNN_(VolumetricConvolutionMM_accGradParameters_frame)(gradOutput, gradWeight, gradBias, finput, scale); } else // batch mode { int64_t T = input->size(0); at::parallel_for(0, T, CONV3D_OMP_THRESHOLD, [&](int64_t start, int64_t end) { for (auto t = start; t < end; t++) { THTensor *gradOutput_t = THTensor_(newSelect)(gradOutput, 0, t); THTensor *finput_t = NULL; if (gradWeight) { finput_t = THTensor_(newSelect)(finput, 0, t); } THNN_(VolumetricConvolutionMM_accGradParameters_frame)(gradOutput_t, gradWeight, gradBias, finput_t, scale); c10::raw::intrusive_ptr::decref(gradOutput_t); if (gradWeight) { c10::raw::intrusive_ptr::decref(finput_t); } } }); } c10::raw::intrusive_ptr::decref(input); c10::raw::intrusive_ptr::decref(gradOutput); if (gradWeight) { c10::raw::intrusive_ptr::decref(gradWeight); } } #endif #endif