int main (int argc, char *argv[]) { lrs_dic *P1,*P2; /* structure for holding current dictionary and indices */ lrs_dat *Q1,*Q2; /* structure for holding static problem data */ lrs_mp_vector output1; /* holds one line of output; ray,vertex,facet,linearity */ lrs_mp_vector output2; /* holds one line of output; ray,vertex,facet,linearity */ lrs_mp_matrix Lin; /* holds input linearities if any are found */ lrs_dic *P2orig; /* we will save player 2's dictionary in getabasis */ long col; /* output column index for dictionary */ long startcol = 0; long prune = FALSE; /* if TRUE, getnextbasis will prune tree and backtrack */ long numequilib=0; /* number of nash equilibria found */ long oldnum=0; /* global variables lrs_ifp and lrs_ofp are file pointers for input and output */ /* they default to stdin and stdout, but may be overidden by command line parms. */ if(argc <= 2 ) { printf("Usage: index input1 input2 [outputfile] \n"); return 1; } /*************************************************** Step 0: Do some global initialization that should only be done once, no matter how many lrs_dat records are allocated. db ***************************************************/ if ( !lrs_init ("\n*index:")) return 1; printf(AUTHOR); /*********************************************************************************/ /* Step 1: Allocate lrs_dat, lrs_dic and set up the problem */ /*********************************************************************************/ Q1 = lrs_alloc_dat ("LRS globals"); /* allocate and init structure for static problem data */ if (Q1 == NULL) return 1; Q1->nash=TRUE; if (!lrs_read_dat (Q1, argc, argv)) /* read first part of problem data to get dimensions */ return 1; /* and problem type: H- or V- input representation */ P1 = lrs_alloc_dic (Q1); /* allocate and initialize lrs_dic */ if (P1 == NULL) return 1; if (!lrs_read_dic (P1, Q1)) /* read remainder of input to setup P1 and Q1 */ return 1; output1 = lrs_alloc_mp_vector (Q1->n + Q1->m); /* output holds one line of output from dictionary */ fclose(lrs_ifp); /* allocate and init structure for player 2's problem data */ printf ("\n*Second input taken from file %s\n", argv[2]); Q2 = lrs_alloc_dat ("LRS globals"); if (Q2 == NULL) return 1; Q2->nash=TRUE; if (!lrs_read_dat (Q2, 2, argv)) /* read first part of problem data to get dimensions */ return 1; /* and problem type: H- or V- input representation */ if (Q2->nlinearity > 0) free(Q2->linearity); /* we will start again */ Q2->linearity = CALLOC ((Q2->m + 2), sizeof (long)); P2 = lrs_alloc_dic (Q2); /* allocate and initialize lrs_dic */ if (P2 == NULL) return 1; if (!lrs_read_dic (P2, Q2)) /* read remainder of input to setup P2 and Q2 */ return 1; output2 = lrs_alloc_mp_vector (Q1->n + Q1->m); /* output holds one line of output from dictionary */ P2orig = lrs_getdic(Q2); /* allocate and initialize lrs_dic */ if (P2orig == NULL) return 1; copy_dict(Q2,P2orig,P2); fprintf (lrs_ofp, "\n***** %ld %ld rational", Q1->n, Q2->n); /*********************************************************************************/ /* Step 2: Find a starting cobasis from default of specified order */ /* P1 is created to hold active dictionary data and may be cached */ /* Lin is created if necessary to hold linearity space */ /* Print linearity space if any, and retrieve output from first dict. */ /*********************************************************************************/ if (!lrs_getfirstbasis (&P1, Q1, &Lin, TRUE)) return 1; if (Q1->dualdeg) { printf("\n*Warning! Dual degenerate, ouput may be incomplete"); printf("\n*Recommendation: Add dualperturb option before maximize in first input file\n"); } if (Q1->unbounded) { printf("\n*Warning! Unbounded starting dictionary for p1, output may be incomplete"); printf("\n*Recommendation: Change/remove maximize option, or include bounds \n"); } /* Pivot to a starting dictionary */ /* There may have been column redundancy */ /* If so the linearity space is obtained and redundant */ /* columns are removed. User can access linearity space */ /* from lrs_mp_matrix Lin dimensions nredundcol x d+1 */ if (Q1->homogeneous && Q1->hull) startcol++; /* col zero not treated as redundant */ for (col = startcol; col < Q1->nredundcol; col++) /* print linearity space */ lrs_printoutput (Q1, Lin[col]); /* Array Lin[][] holds the coeffs. */ /*********************************************************************************/ /* Step 3: Terminate if lponly option set, otherwise initiate a reverse */ /* search from the starting dictionary. Get output for each new dict. */ /*********************************************************************************/ /* We initiate reverse search from this dictionary */ /* getting new dictionaries until the search is complete */ /* User can access each output line from output which is */ /* vertex/ray/facet from the lrs_mp_vector output */ /* prune is TRUE if tree should be pruned at current node */ do { prune=lrs_checkbound(P1,Q1); if (!prune && lrs_getsolution (P1, Q1, output1, col)) { oldnum=numequilib; nash2_main(argc,argv,P1,Q1,P2orig,Q2,&numequilib,output2); if (numequilib > oldnum || Q1->verbose) { if(Q1->verbose) prat(" \np2's obj value: ",P1->objnum,P1->objden); lrs_nashoutput (Q1, output1, 1L); /* grab the lexico-min basis and run reverse search to enumerate the bases */ long temp[P1->d]; enumeratelexicopositivebasis(P1, Q1, output1, temp, 1); /*iteratereversesearch(P1, Q1, output1);*/ fprintf (lrs_ofp, "\n"); } } } while (lrs_getnextbasis (&P1, Q1, prune)); fprintf(lrs_ofp,"\n*Number of equilibria found: %ld",numequilib); fprintf (lrs_ofp,"\n*Player 1: vertices=%ld bases=%ld pivots=%ld", Q1->count[1], Q1->count[2],Q1->count[3]); fprintf (lrs_ofp,"\n*Player 2: vertices=%ld bases=%ld pivots=%ld", Q2->count[1], Q2->count[2],Q2->count[3]); lrs_clear_mp_vector(output1, Q1->m + Q1->n); lrs_clear_mp_vector(output2, Q1->m + Q1->n); lrs_free_dic (P1,Q1); /* deallocate lrs_dic */ lrs_free_dat (Q1); /* deallocate lrs_dat */ /* 2006.10.10 not sure what is going on with three lines below - sometimes crashes */ /* Q2->Qhead = P2; */ /* reset this or you crash free_dic */ /* lrs_free_dic (P2,Q2); */ /* deallocate lrs_dic */ /* lrs_free_dat (Q2); */ /* deallocate lrs_dat */ lrs_close ("nash:"); return 0; }
PUBLIC Status XvMCCreateSubpicture(Display *dpy, XvMCContext *context, XvMCSubpicture *subpicture, unsigned short width, unsigned short height, int xvimage_id) { XvMCContextPrivate *context_priv; XvMCSubpicturePrivate *subpicture_priv; struct pipe_context *pipe; struct pipe_resource tex_templ, *tex; struct pipe_sampler_view sampler_templ; Status ret; XVMC_MSG(XVMC_TRACE, "[XvMC] Creating subpicture %p.\n", subpicture); assert(dpy); if (!context) return XvMCBadContext; context_priv = context->privData; pipe = context_priv->pipe; if (!subpicture) return XvMCBadSubpicture; if (width > context_priv->subpicture_max_width || height > context_priv->subpicture_max_height) return BadValue; ret = Validate(dpy, context->port, context->surface_type_id, xvimage_id); if (ret != Success) return ret; subpicture_priv = CALLOC(1, sizeof(XvMCSubpicturePrivate)); if (!subpicture_priv) return BadAlloc; memset(&tex_templ, 0, sizeof(tex_templ)); tex_templ.target = PIPE_TEXTURE_2D; tex_templ.format = XvIDToPipe(xvimage_id); tex_templ.last_level = 0; if (pipe->screen->get_video_param(pipe->screen, PIPE_VIDEO_PROFILE_UNKNOWN, PIPE_VIDEO_CAP_NPOT_TEXTURES)) { tex_templ.width0 = width; tex_templ.height0 = height; } else { tex_templ.width0 = util_next_power_of_two(width); tex_templ.height0 = util_next_power_of_two(height); } tex_templ.depth0 = 1; tex_templ.array_size = 1; tex_templ.usage = PIPE_USAGE_DYNAMIC; tex_templ.bind = PIPE_BIND_SAMPLER_VIEW; tex_templ.flags = 0; tex = pipe->screen->resource_create(pipe->screen, &tex_templ); memset(&sampler_templ, 0, sizeof(sampler_templ)); u_sampler_view_default_template(&sampler_templ, tex, tex->format); subpicture_priv->sampler = pipe->create_sampler_view(pipe, tex, &sampler_templ); pipe_resource_reference(&tex, NULL); if (!subpicture_priv->sampler) { FREE(subpicture_priv); return BadAlloc; } subpicture_priv->context = context; subpicture->subpicture_id = XAllocID(dpy); subpicture->context_id = context->context_id; subpicture->xvimage_id = xvimage_id; subpicture->width = width; subpicture->height = height; subpicture->num_palette_entries = NumPaletteEntries4XvID(xvimage_id); subpicture->entry_bytes = PipeToComponentOrder(tex_templ.format, subpicture->component_order); subpicture->privData = subpicture_priv; if (subpicture->num_palette_entries > 0) { tex_templ.target = PIPE_TEXTURE_1D; tex_templ.format = PIPE_FORMAT_R8G8B8X8_UNORM; tex_templ.width0 = subpicture->num_palette_entries; tex_templ.height0 = 1; tex_templ.usage = PIPE_USAGE_STATIC; tex = pipe->screen->resource_create(pipe->screen, &tex_templ); memset(&sampler_templ, 0, sizeof(sampler_templ)); u_sampler_view_default_template(&sampler_templ, tex, tex->format); sampler_templ.swizzle_a = PIPE_SWIZZLE_ONE; subpicture_priv->palette = pipe->create_sampler_view(pipe, tex, &sampler_templ); pipe_resource_reference(&tex, NULL); if (!subpicture_priv->sampler) { FREE(subpicture_priv); return BadAlloc; } } SyncHandle(); XVMC_MSG(XVMC_TRACE, "[XvMC] Subpicture %p created.\n", subpicture); return Success; }
tm_topology_t* hwloc_to_tm(char *filename,double **pcost) { hwloc_topology_t topology; tm_topology_t *res = NULL; hwloc_obj_t *objs = NULL; unsigned topodepth,depth; int nb_nodes,i; double *cost; int err; /* Build the topology */ hwloc_topology_init(&topology); err = hwloc_topology_set_xml(topology,filename); if(err == -1){ if(get_verbose_level() >= CRITICAL) fprintf(stderr,"Error: %s is a bad xml topology file!\n",filename); exit(-1); } hwloc_topology_ignore_all_keep_structure(topology); hwloc_topology_load(topology); /* Test if symetric */ if(!symetric(topology)){ if(get_verbose_level() >= CRITICAL) fprintf(stderr,"%s not symetric!\n",filename); exit(-1); } /* work on depth */ topodepth = hwloc_topology_get_depth(topology); res = (tm_topology_t*)MALLOC(sizeof(tm_topology_t)); res->nb_levels = topodepth; res->node_id = (int**)MALLOC(sizeof(int*)*res->nb_levels); res->nb_nodes = (int*)MALLOC(sizeof(int)*res->nb_levels); res->arity = (int*)MALLOC(sizeof(int)*res->nb_levels); if(get_verbose_level() >= INFO) printf("topodepth = %d\n",topodepth); /* Build TreeMatch topology */ for( depth = 0 ; depth < topodepth ; depth++ ){ nb_nodes = hwloc_get_nbobjs_by_depth(topology, depth); res->nb_nodes[depth] = nb_nodes; res->node_id[depth] = (int*)MALLOC(sizeof(int)*nb_nodes); objs = (hwloc_obj_t*)MALLOC(sizeof(hwloc_obj_t)*nb_nodes); objs[0] = hwloc_get_next_obj_by_depth(topology,depth,NULL); hwloc_get_closest_objs(topology,objs[0],objs+1,nb_nodes-1); res->arity[depth] = objs[0]->arity; if(get_verbose_level() >= INFO) printf("%d(%d):",res->arity[depth],nb_nodes); /* Build process id tab */ for (i = 0; i < nb_nodes; i++){ res->node_id[depth][i] = objs[i]->os_index; /* if(depth==topodepth-1) */ } FREE(objs); } cost = (double*)CALLOC(res->nb_levels,sizeof(double)); for(i=0; i<res->nb_levels; i++){ cost[i] = speed(i); } *pcost = cost; /* Destroy topology object. */ hwloc_topology_destroy(topology); if(get_verbose_level() >= INFO) printf("\n"); return res; }
int main(void) { int fd; InputStream_T in = NULL; Bootstrap(); // Need to initialize library printf("============> Start InputStream Tests\n\n"); printf("=> Test0: create/destroy the file input stream\n"); { in = InputStream_new(File_open(DATA, "r")); assert(!InputStream_isClosed(in)); File_close(InputStream_getDescriptor(in)); InputStream_free(&in); assert(in == NULL); } printf("=> Test0: OK\n\n"); printf("=> Test1: get/set timeout\n"); { assert((fd = File_open(DATA, "r")) >= 0); in = InputStream_new(fd); printf("\tCurrent timeout: %ldms\n", InputStream_getTimeout(in)); InputStream_setTimeout(in, TIMEOUT); assert(InputStream_getTimeout(in) == TIMEOUT); printf("\tTimeout set to: %dms\n", TIMEOUT); File_close(fd); InputStream_free(&in); } printf("=> Test1: OK\n\n"); printf("=> Test2: read file by characters\n"); { int byte; int byteno = 0; char content[][1] = {"l", "i", "n", "e", "1", "\n", "l", "i", "n", "e", "2", "\n", "l", "i", "n", "e", "3", "\n"}; assert((fd = File_open(DATA, "r")) >= 0); in = InputStream_new(fd); while ((byte = InputStream_read(in)) > 0) { assert(byte == *content[byteno++]); } File_close(fd); InputStream_free(&in); } printf("=> Test2: OK\n\n"); printf("=> Test3: read file by lines\n"); { int lineno = 0; char line[STRLEN]; char content[][STRLEN] = {"line1\n", "line2\n", "line3\n"}; assert((fd = File_open(DATA, "r")) >= 0); in = InputStream_new(fd); while (InputStream_readLine(in, line, sizeof(line))) { assert(Str_isEqual(content[lineno++], line)); } File_close(fd); InputStream_free(&in); } printf("=> Test3: OK\n\n"); printf("=> Test4: read file by bytes\n"); { char array[STRLEN]; char content[] = "line1\nline2\nline3\n"; memset(array, 0, STRLEN); assert((fd = File_open(DATA, "r")) >= 0); in = InputStream_new(fd); while (InputStream_readBytes(in, array, sizeof(array)-1)) { assert(Str_isEqual(content, array)); } File_close(fd); InputStream_free(&in); } printf("=> Test4: OK\n\n"); printf("=> Test5: read a large file\n"); { if ((fd = File_open("/usr/share/dict/words", "r")) >= 0) { int n = 0; char array[2][STRLEN + 1]; in = InputStream_new(fd); for (int i = 0; ((n = InputStream_readBytes(in, array[i], STRLEN)) > 0); i = i ? 0 : 1) assert(strncmp(array[0], array[1], STRLEN/2) != 0); // ensure that InputStream buffer is filled anew File_rewind(fd); // Test read data larger than InputStream's internal buffer int filesize = (int)File_size("/usr/share/dict/words"); char *bigarray = CALLOC(1, filesize + 1); n = InputStream_readBytes(in, bigarray, filesize); assert(n == filesize); File_close(fd); InputStream_free(&in); FREE(bigarray); } else ERROR("\t/usr/share/dict/words not available -- skipping test\n"); } printf("=> Test5: OK\n\n"); printf("=> Test6: wrong descriptor - expecting read fail\n"); { in = InputStream_new(999); TRY assert(InputStream_read(in) != -1); assert(false); // Should not come here CATCH(AssertException) // Passed END_TRY; InputStream_free(&in); } printf("=> Test6: OK\n\n"); printf("============> InputStream Tests: OK\n\n"); return 0; }
extern int bwx_shell( struct bwb_line *l ) { static char *s_buffer; static int init = FALSE; static int position; /* get memory for temporary buffer if necessary */ if ( init == FALSE ) { init = TRUE; /* Revised to CALLOC pass-thru call by JBV */ if ( ( s_buffer = CALLOC( MAXSTRINGSIZE + 1, sizeof( char ),"bwx_shell" )) == NULL ) { bwb_error( err_getmem ); return FALSE; } } /* get the first element and check for a line number */ #if INTENSIVE_DEBUG sprintf( bwb_ebuf, "in bwx_shell(): line buffer is <%s>.", l->buffer ); bwb_debug( bwb_ebuf ); #endif position = 0; adv_element( l->buffer, &position, s_buffer ); if ( is_numconst( s_buffer ) != TRUE ) /* not a line number */ { #if INTENSIVE_DEBUG sprintf( bwb_ebuf, "in bwx_shell(): no line number, command <%s>.", l->buffer ); bwb_debug( bwb_ebuf ); #endif nl(); endwin(); /* Added by JBV 10/11/97 */ if ( system( l->buffer ) == 0 ) { refresh(); /* Added by JBV 10/11/97 */ nonl(); ncu_setpos(); return TRUE; } else { refresh(); /* Added by JBV 10/11/97 */ nonl(); ncu_setpos(); return FALSE; } } else /* advance past line number */ { adv_ws( l->buffer, &position ); /* advance past whitespace */ #if INTENSIVE_DEBUG sprintf( bwb_ebuf, "in bwx_shell(): line number, command <%s>.", l->buffer ); bwb_debug( bwb_ebuf ); #endif nl(); endwin(); /* Added by JBV 10/11/97 */ if ( system( &( l->buffer[ position ] ) ) == 0 ) { refresh(); /* Added by JBV 10/11/97 */ nonl(); ncu_setpos(); return TRUE; } else { refresh(); /* Added by JBV 10/11/97 */ nonl(); ncu_setpos(); return FALSE; } } }
void *mxCalloc(size_t n, size_t size) { //TODO return CALLOC(n, size); }
// this is the callback function called by the network thread // to receive packet data placed into a PacketData struct // // process the raw data stream and parse into signals, // push these signals to the signal buffer // returns true if parsing successful void processReceivedPacketData(const PacketData * pRaw) { GroupInfo g; GroupInfo* pgOnTrie; const uint8_t* pBufStart = pRaw->data; const uint8_t* pBuf = pRaw->data; bool isControlGroup, firstTimeGroupSeen, success, waitingNextTrial; int iSignal, nSignals; // logInfo("processing raw data!"); while(pBuf - pBufStart < pRaw->length) { if(*pBuf == 0) { // consider this the null terminator // odd-length packets are expanded to be even length in Simulink // so this can occasionally happen if (pRaw->length - (pBuf-pBufStart) > 1) logError("Packet parsing stopping due to NULL byte but %ld bytes remaining\n", pRaw->length - (pBuf-pBufStart)); break; } // parse the group header and build out the GroupInfo g pBuf = parseGroupInfoHeader(pBuf, &g); if(pBuf == NULL) { logError("Could not parse group header\n"); return; } nSignals = g.nSignals; if(nSignals == 0 || nSignals > MAX_GROUP_SIGNALS) { logError("Group %s has too many signals (%d)\n", g.name, nSignals); return; } // can do different processing here depending on the version of the packet // handle control groups differently if(g.type == GROUP_TYPE_CONTROL) isControlGroup = true; else isControlGroup = false; // allocate space to parse and hold onto all the signals at once // we do this in one pass in case parsing fails, since then we'll need to bail SignalSample* samples = (SignalSample*)CALLOC(sizeof(SignalSample), nSignals); // parse all the signals into SignalSamples bool parseError = false; for(iSignal = 0; iSignal < nSignals; iSignal++) { pBuf = parseSignalFromBuffer(pBuf, samples + iSignal); //if (strcmp(g.name, "taskEvent") == 0) // logError("Seeing event %s\n", samples[0].data); samples[iSignal].timestamp = g.lastTimestamp; if(pBuf == NULL) { parseError = true; logError("Error parsing signal %d / %d from buffer for group %s\n", iSignal+1, nSignals, g.name); for(; iSignal >= 0; iSignal--) freeSignalSampleData(samples + iSignal); FREE(samples); return; } } if(parseError) { for(iSignal = 0; iSignal < nSignals; iSignal++) freeSignalSampleData(samples + iSignal); FREE(samples); return; } if(isControlGroup) { success = processControlSignalSamples(nSignals, (const SignalSample*)samples); if(!success) { logError("Issue handling control signals\n"); for(iSignal = 0; iSignal < nSignals; iSignal++) freeSignalSampleData(samples + iSignal); FREE(samples); return; } } else { // non control group // check whether we'll store this or not waitingNextTrial = controlGetWaitingForNextTrial(); if(!waitingNextTrial) { firstTimeGroupSeen = false; // find existing group info onto the group trie // and hold onto that pointer pgOnTrie = findGroupInfoInTrie(&g); if(pgOnTrie == NULL) { firstTimeGroupSeen = true; // build a new group info on the group trie // this will also allocate the signals pointer list to be length nSignals pgOnTrie = addGroupInfoToTrie(&g); } // check the hash matches, bail if not if(pgOnTrie->configHash != g.configHash || pgOnTrie->nSignals != nSignals) { logError("Group %s received with different configuration\n", pgOnTrie->name); // free memory and bail for(iSignal = 0; iSignal < nSignals; iSignal++) freeSignalSampleData(samples + iSignal); FREE(samples); controlAdvanceToNewStatus(); return; } // associate each sample with this group for(iSignal = 0; iSignal < nSignals; iSignal++) samples[iSignal].pGroupInfo = pgOnTrie; // if it's the first time we've seen this group, build a SignalDataBuffer for each signal if(firstTimeGroupSeen) { for(iSignal = 0; iSignal < nSignals; iSignal++) { pgOnTrie->signals[iSignal] = buildSignalDataBufferFromSample(samples + iSignal); if(pgOnTrie->signals == NULL) { logError("Error building signal data buffer\n"); for(iSignal = 0; iSignal < nSignals; iSignal++) freeSignalSampleData(samples + iSignal); FREE(samples); return; } } } // add the timestamp to the group info, this is also where adjust the timestamps // for this sample based on signals with SIGNAL_TYPE_TIMESTAMP AND SIGNAL_TYPE_TIMESTAMPOFFSET // update the pgOnTrie's last timestamp with the last corrected timestamp as well pgOnTrie->lastTimestamp = pushTimestampToGroupInfo(pgOnTrie, g.lastTimestamp, (const SignalSample*)samples, nSignals); // and push each signal sample to each signal data buffer for(iSignal = 0; iSignal < nSignals; iSignal++) { success = pushSignalSampleToSignalDataBuffer(pgOnTrie->signals[iSignal], samples + iSignal); if(!success) { logError("Issue pushing signal data sample\n"); for(iSignal = 0; iSignal < nSignals; iSignal++) freeSignalSampleData(samples + iSignal); FREE(samples); return; } } } } // free data used by the SignalSamples for(iSignal = 0; iSignal < nSignals; iSignal++) freeSignalSampleData(samples + iSignal); FREE(samples); samples = NULL; // done parsing group, loop to next part of buffer } }
static sco_data *getScoData(scicos_block * block) { sco_data *sco = (sco_data *) * (block->work); int i, j; int nclk = block->nipar - 6; if (sco == NULL) { /* * Data allocation */ sco = (sco_data *) MALLOC(sizeof(sco_data)); if (sco == NULL) { goto error_handler_sco; } sco->internal.numberOfPoints = (int *)CALLOC(nclk, sizeof(int)); if (sco->internal.numberOfPoints == NULL) { goto error_handler_numberOfPoints; } sco->internal.maxNumberOfPoints = (int *)MALLOC(nclk * sizeof(int)); if (sco->internal.numberOfPoints == NULL) { goto error_handler_maxNumberOfPoints; } for (i = 0; i < nclk; i++) { sco->internal.maxNumberOfPoints[i] = DEFAULT_MAX_NUMBER_OF_POINTS; } sco->internal.data = (double **)CALLOC(2 * nclk, sizeof(double *)); if (sco->internal.data == NULL) { goto error_handler_data; } for (i = 0; i < nclk; i++) { /* * Alloc base pointer */ sco->internal.data[2 * i + 0] = (double *)CALLOC(3 * DEFAULT_MAX_NUMBER_OF_POINTS, sizeof(double)); if (sco->internal.data[2 * i + 0] == NULL) { goto error_handler_data_i; } /* * Alloc direction pointer */ sco->internal.data[2 * i + 1] = (double *)CALLOC(3 * DEFAULT_MAX_NUMBER_OF_POINTS, sizeof(double)); if (sco->internal.data[2 * i + 1] == NULL) { FREE(sco->internal.data[2 * i + 0]); goto error_handler_data_i; } } sco->scope.periodCounter = 0; sco->scope.cachedFigureUID = 0; sco->scope.cachedAxeUID = 0; sco->scope.cachedSegsUIDs = (int*)CALLOC(nclk, sizeof(int)); if (sco->scope.cachedSegsUIDs == NULL) { goto error_handler_data_i; } *(block->work) = sco; } return sco; /* * Error management (out of normal flow) */ error_handler_data_i: for (j = 0; j < i; j++) { FREE(sco->internal.data[2 * j + 0]); FREE(sco->internal.data[2 * j + 1]); } FREE(sco->internal.data); error_handler_data: FREE(sco->internal.maxNumberOfPoints); error_handler_maxNumberOfPoints: FREE(sco->internal.numberOfPoints); error_handler_numberOfPoints: FREE(sco); error_handler_sco: // allocation error set_block_error(-5); return NULL; }
/** The init function of the MLAA filter. */ static bool pp_jimenezmlaa_init_run(struct pp_queue_t *ppq, unsigned int n, unsigned int val, bool iscolor) { struct pipe_box box; struct pipe_resource res; char *tmp_text = NULL; tmp_text = CALLOC(sizeof(blend2fs_1) + sizeof(blend2fs_2) + IMM_SPACE, sizeof(char)); if (!tmp_text) { pp_debug("Failed to allocate shader space\n"); return FALSE; } ppq->constbuf = pipe_buffer_create(ppq->p->screen, PIPE_BIND_CONSTANT_BUFFER, PIPE_USAGE_DEFAULT, sizeof(constants)); if (ppq->constbuf == NULL) { pp_debug("Failed to allocate constant buffer\n"); goto fail; } pp_debug("mlaa: using %u max search steps\n", val); util_sprintf(tmp_text, "%s" "IMM FLT32 { %.8f, 0.0000, 0.0000, 0.0000}\n" "%s\n", blend2fs_1, (float) val, blend2fs_2); memset(&res, 0, sizeof(res)); res.target = PIPE_TEXTURE_2D; res.format = PIPE_FORMAT_R8G8_UNORM; res.width0 = res.height0 = 165; res.bind = PIPE_BIND_SAMPLER_VIEW; res.usage = PIPE_USAGE_DEFAULT; res.depth0 = res.array_size = res.nr_samples = 1; if (!ppq->p->screen->is_format_supported(ppq->p->screen, res.format, res.target, 1, res.bind)) pp_debug("Areamap format not supported\n"); ppq->areamaptex = ppq->p->screen->resource_create(ppq->p->screen, &res); if (ppq->areamaptex == NULL) { pp_debug("Failed to allocate area map texture\n"); goto fail; } u_box_2d(0, 0, 165, 165, &box); ppq->p->pipe->texture_subdata(ppq->p->pipe, ppq->areamaptex, 0, PIPE_TRANSFER_WRITE, &box, areamap, 165 * 2, sizeof(areamap)); ppq->shaders[n][1] = pp_tgsi_to_state(ppq->p->pipe, offsetvs, true, "offsetvs"); if (iscolor) ppq->shaders[n][2] = pp_tgsi_to_state(ppq->p->pipe, color1fs, false, "color1fs"); else ppq->shaders[n][2] = pp_tgsi_to_state(ppq->p->pipe, depth1fs, false, "depth1fs"); ppq->shaders[n][3] = pp_tgsi_to_state(ppq->p->pipe, tmp_text, false, "blend2fs"); ppq->shaders[n][4] = pp_tgsi_to_state(ppq->p->pipe, neigh3fs, false, "neigh3fs"); FREE(tmp_text); return TRUE; fail: FREE(tmp_text); /* * Call the common free function for destruction of partially initialized * resources. */ pp_jimenezmlaa_free(ppq, n); return FALSE; }
static struct _stack * _new_stack() { return (struct _stack *)CALLOC(1, sizeof(struct _stack)); }
/* * Decode OCTET STRING type. */ asn_dec_rval_t OCTET_STRING_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **sptr, const void *buf_ptr, size_t size, int tag_mode) { asn_OCTET_STRING_specifics_t *specs = td->specifics ? (asn_OCTET_STRING_specifics_t *)td->specifics : &asn_DEF_OCTET_STRING_specs; BIT_STRING_t *st = (BIT_STRING_t *)*sptr; asn_dec_rval_t rval; asn_struct_ctx_t *ctx; ssize_t consumed_myself = 0; struct _stack *stck; /* Expectations stack structure */ struct _stack_el *sel = 0; /* Stack element */ int tlv_constr; enum asn_OS_Subvariant type_variant = specs->subvariant; ASN_DEBUG("Decoding %s as %s (frame %ld)", td->name, (type_variant == ASN_OSUBV_STR) ? "OCTET STRING" : "OS-SpecialCase", (long)size); /* * Create the string if does not exist. */ if(st == NULL) { st = (BIT_STRING_t *)(*sptr = CALLOC(1, specs->struct_size)); if(st == NULL) RETURN(RC_FAIL); } /* Restore parsing context */ ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset); switch(ctx->phase) { case 0: /* * Check tags. */ rval = ber_check_tags(opt_codec_ctx, td, ctx, buf_ptr, size, tag_mode, -1, &ctx->left, &tlv_constr); if(rval.code != RC_OK) return rval; if(tlv_constr) { /* * Complex operation, requires stack of expectations. */ ctx->ptr = _new_stack(); if(ctx->ptr) { stck = (struct _stack *)ctx->ptr; } else { RETURN(RC_FAIL); } } else { /* * Jump into stackless primitive decoding. */ _CH_PHASE(ctx, 3); if(type_variant == ASN_OSUBV_ANY && tag_mode != 1) APPEND(buf_ptr, rval.consumed); ADVANCE(rval.consumed); goto phase3; } NEXT_PHASE(ctx); /* Fall through */ case 1: phase1: /* * Fill the stack with expectations. */ stck = (struct _stack *)ctx->ptr; sel = stck->cur_ptr; do { ber_tlv_tag_t tlv_tag; ber_tlv_len_t tlv_len; ber_tlv_tag_t expected_tag; ssize_t tl, ll, tlvl; /* This one works even if (sel->left == -1) */ size_t Left = ((!sel||(size_t)sel->left >= size) ?size:(size_t)sel->left); ASN_DEBUG("%p, s->l=%ld, s->wn=%ld, s->g=%ld\n", sel, (long)(sel?sel->left:0), (long)(sel?sel->want_nulls:0), (long)(sel?sel->got:0) ); if(sel && sel->left <= 0 && sel->want_nulls == 0) { if(sel->prev) { struct _stack_el *prev = sel->prev; if(prev->left != -1) { if(prev->left < sel->got) RETURN(RC_FAIL); prev->left -= sel->got; } prev->got += sel->got; sel = stck->cur_ptr = prev; if(!sel) break; tlv_constr = 1; continue; } else { sel = stck->cur_ptr = 0; break; /* Nothing to wait */ } } tl = ber_fetch_tag(buf_ptr, Left, &tlv_tag); ASN_DEBUG("fetch tag(size=%ld,L=%ld), %sstack, left=%ld, wn=%ld, tl=%ld", (long)size, (long)Left, sel?"":"!", (long)(sel?sel->left:0), (long)(sel?sel->want_nulls:0), (long)tl); switch(tl) { case -1: RETURN(RC_FAIL); case 0: RETURN(RC_WMORE); } tlv_constr = BER_TLV_CONSTRUCTED(buf_ptr); ll = ber_fetch_length(tlv_constr, (const char *)buf_ptr + tl,Left - tl,&tlv_len); ASN_DEBUG("Got tag=%s, tc=%d, left=%ld, tl=%ld, len=%ld, ll=%ld", ber_tlv_tag_string(tlv_tag), tlv_constr, (long)Left, (long)tl, (long)tlv_len, (long)ll); switch(ll) { case -1: RETURN(RC_FAIL); case 0: RETURN(RC_WMORE); } if(sel && sel->want_nulls && ((const uint8_t *)buf_ptr)[0] == 0 && ((const uint8_t *)buf_ptr)[1] == 0) { ASN_DEBUG("Eat EOC; wn=%d--", sel->want_nulls); if(type_variant == ASN_OSUBV_ANY && (tag_mode != 1 || sel->cont_level)) APPEND("\0\0", 2); ADVANCE(2); sel->got += 2; if(sel->left != -1) { sel->left -= 2; /* assert(sel->left >= 2) */ } sel->want_nulls--; if(sel->want_nulls == 0) { /* Move to the next expectation */ sel->left = 0; tlv_constr = 1; } continue; } /* * Set up expected tags, * depending on ASN.1 type being decoded. */ switch(type_variant) { case ASN_OSUBV_BIT: /* X.690: 8.6.4.1, NOTE 2 */ /* Fall through */ case ASN_OSUBV_STR: default: if(sel) { int level = sel->cont_level; if(level < td->all_tags_count) { expected_tag = td->all_tags[level]; break; } else if(td->all_tags_count) { expected_tag = td->all_tags [td->all_tags_count - 1]; break; } /* else, Fall through */ } /* Fall through */ case ASN_OSUBV_ANY: expected_tag = tlv_tag; break; } if(tlv_tag != expected_tag) { char buf[2][32]; ber_tlv_tag_snprint(tlv_tag, buf[0], sizeof(buf[0])); ber_tlv_tag_snprint(td->tags[td->tags_count-1], buf[1], sizeof(buf[1])); ASN_DEBUG("Tag does not match expectation: %s != %s", buf[0], buf[1]); RETURN(RC_FAIL); } tlvl = tl + ll; /* Combined length of T and L encoding */ if((tlv_len + tlvl) < 0) { /* tlv_len value is too big */ ASN_DEBUG("TLV encoding + length (%ld) is too big", (long)tlv_len); RETURN(RC_FAIL); } /* * Append a new expectation. */ sel = OS__add_stack_el(stck); if(!sel) RETURN(RC_FAIL); sel->tag = tlv_tag; sel->want_nulls = (tlv_len==-1); if(sel->prev && sel->prev->left != -1) { /* Check that the parent frame is big enough */ if(sel->prev->left < tlvl + (tlv_len==-1?0:tlv_len)) RETURN(RC_FAIL); if(tlv_len == -1) sel->left = sel->prev->left - tlvl; else sel->left = tlv_len; } else { sel->left = tlv_len; } if(type_variant == ASN_OSUBV_ANY && (tag_mode != 1 || sel->cont_level)) APPEND(buf_ptr, tlvl); sel->got += tlvl; ADVANCE(tlvl); ASN_DEBUG("+EXPECT2 got=%ld left=%ld, wn=%d, clvl=%d", (long)sel->got, (long)sel->left, sel->want_nulls, sel->cont_level); } while(tlv_constr); if(sel == NULL) { /* Finished operation, "phase out" */ ASN_DEBUG("Phase out"); _CH_PHASE(ctx, +3); break; } NEXT_PHASE(ctx); /* Fall through */ case 2: stck = (struct _stack *)ctx->ptr; sel = stck->cur_ptr; ASN_DEBUG("Phase 2: Need %ld bytes, size=%ld, alrg=%ld, wn=%d", (long)sel->left, (long)size, (long)sel->got, sel->want_nulls); { ber_tlv_len_t len; assert(sel->left >= 0); len = ((ber_tlv_len_t)size < sel->left) ? (ber_tlv_len_t)size : sel->left; if(len > 0) { if(type_variant == ASN_OSUBV_BIT && sel->bits_chopped == 0) { /* Put the unused-bits-octet away */ st->bits_unused = *(const uint8_t *)buf_ptr; APPEND(((const char *)buf_ptr+1), (len - 1)); sel->bits_chopped = 1; } else { APPEND(buf_ptr, len); } ADVANCE(len); sel->left -= len; sel->got += len; } if(sel->left) { ASN_DEBUG("OS left %ld, size = %ld, wn=%d\n", (long)sel->left, (long)size, sel->want_nulls); RETURN(RC_WMORE); } PREV_PHASE(ctx); goto phase1; } break; case 3: phase3: /* * Primitive form, no stack required. */ assert(ctx->left >= 0); if(size < (size_t)ctx->left) { if(!size) RETURN(RC_WMORE); if(type_variant == ASN_OSUBV_BIT && !ctx->context) { st->bits_unused = *(const uint8_t *)buf_ptr; ctx->left--; ADVANCE(1); } APPEND(buf_ptr, size); assert(ctx->context > 0); ctx->left -= size; ADVANCE(size); RETURN(RC_WMORE); } else { if(type_variant == ASN_OSUBV_BIT && !ctx->context && ctx->left) { st->bits_unused = *(const uint8_t *)buf_ptr; ctx->left--; ADVANCE(1); } APPEND(buf_ptr, ctx->left); ADVANCE(ctx->left); ctx->left = 0; NEXT_PHASE(ctx); } break; } /* * BIT STRING-specific processing. */ if(type_variant == ASN_OSUBV_BIT && st->size) { /* Finalize BIT STRING: zero out unused bits. */ st->buf[st->size-1] &= 0xff << st->bits_unused; } ASN_DEBUG("Took %ld bytes to encode %s: [%s]:%ld", (long)consumed_myself, td->name, (type_variant == ASN_OSUBV_STR) ? (char *)st->buf : "<data>", (long)st->size); RETURN(RC_OK); }
gammaScreenPtr gammaCreateScreen( __DRIscreenPrivate *sPriv ) { gammaScreenPtr gammaScreen; GLINTDRIPtr gDRIPriv = (GLINTDRIPtr)sPriv->pDevPriv; int i; #if 0 /* Check the DRI version */ { int major, minor, patch; if ( XF86DRIQueryVersion( sPriv->display, &major, &minor, &patch ) ) { if ( major != 3 || minor != 1 || patch < 0 ) { __driUtilMessage( "r128 DRI driver expected DRI version 3.1.x but got version %d.%d.%d", major, minor, patch ); return GL_FALSE; } } } /* Check that the DDX driver version is compatible */ if ( sPriv->ddxMajor != 4 || sPriv->ddxMinor != 0 || sPriv->ddxPatch < 0 ) { __driUtilMessage( "r128 DRI driver expected DDX driver version 4.0.x but got version %d.%d.%d", sPriv->ddxMajor, sPriv->ddxMinor, sPriv->ddxPatch ); return GL_FALSE; } /* Check that the DRM driver version is compatible */ if ( sPriv->drmMajor != 2 || sPriv->drmMinor != 1 || sPriv->drmPatch < 0 ) { __driUtilMessage( "r128 DRI driver expected DRM driver version 2.1.x but got version %d.%d.%d", sPriv->drmMajor, sPriv->drmMinor, sPriv->drmPatch ); return GL_FALSE; } #endif /* Allocate the private area */ gammaScreen = (gammaScreenPtr) CALLOC( sizeof(*gammaScreen) ); if ( !gammaScreen ) return NULL; gammaScreen->regionCount = 4; /* Magic number. Can we fix this? */ gammaScreen->regions = Xmalloc(gammaScreen->regionCount * sizeof(gammaRegion)); gammaScreen->regions[0].handle = gDRIPriv->registers0.handle; gammaScreen->regions[0].size = gDRIPriv->registers0.size; gammaScreen->regions[1].handle = gDRIPriv->registers1.handle; gammaScreen->regions[1].size = gDRIPriv->registers1.size; gammaScreen->regions[2].handle = gDRIPriv->registers2.handle; gammaScreen->regions[2].size = gDRIPriv->registers2.size; gammaScreen->regions[3].handle = gDRIPriv->registers3.handle; gammaScreen->regions[3].size = gDRIPriv->registers3.size; /* Next, map all the regions */ for (i = 0; i < gammaScreen->regionCount; i++) { if (drmMap(sPriv->fd, gammaScreen->regions[i].handle, gammaScreen->regions[i].size, &gammaScreen->regions[i].map)) { while (--i > 0) { (void)drmUnmap(gammaScreen->regions[i].map, gammaScreen->regions[i].size); } return GL_FALSE; } } /* Get the list of dma buffers */ gammaScreen->bufs = drmMapBufs(sPriv->fd); if (!gammaScreen->bufs) { while (gammaScreen->regionCount > 0) { (void)drmUnmap(gammaScreen->regions[gammaScreen->regionCount].map, gammaScreen->regions[gammaScreen->regionCount].size); gammaScreen->regionCount--; } return GL_FALSE; } gammaScreen->textureSize = gDRIPriv->textureSize; gammaScreen->logTextureGranularity = gDRIPriv->logTextureGranularity; gammaScreen->cpp = gDRIPriv->cpp; gammaScreen->frontOffset = gDRIPriv->frontOffset; gammaScreen->frontPitch = gDRIPriv->frontPitch; gammaScreen->backOffset = gDRIPriv->backOffset; gammaScreen->backPitch = gDRIPriv->backPitch; gammaScreen->backX = gDRIPriv->backX; gammaScreen->backY = gDRIPriv->backY; gammaScreen->depthOffset = gDRIPriv->depthOffset; gammaScreen->depthPitch = gDRIPriv->depthPitch; gammaScreen->driScreen = sPriv; return gammaScreen; }
/*! * pixaDisplayTiledAndScaled() * * Input: pixa * outdepth (output depth: 1, 8 or 32 bpp) * tilewidth (each pix is scaled to this width) * ncols (number of tiles in each row) * background (0 for white, 1 for black; this is the color * of the spacing between the images) * spacing (between images, and on outside) * border (width of additional black border on each image; * use 0 for no border) * Return: pix of tiled images, or null on error * * Notes: * (1) This can be used to tile a number of renderings of * an image that are at different scales and depths. * (2) Each image, after scaling and optionally adding the * black border, has width 'tilewidth'. Thus, the border does * not affect the spacing between the image tiles. The * maximum allowed border width is tilewidth / 5. */ PIX * pixaDisplayTiledAndScaled(PIXA *pixa, l_int32 outdepth, l_int32 tilewidth, l_int32 ncols, l_int32 background, l_int32 spacing, l_int32 border) { l_int32 x, y, w, h, wd, hd, d; l_int32 i, n, nrows, maxht, ninrow, irow, bordval; l_int32 *rowht; l_float32 scalefact; PIX *pix, *pixn, *pixt, *pixb, *pixd; PIXA *pixan; PROCNAME("pixaDisplayTiledAndScaled"); if (!pixa) return (PIX *)ERROR_PTR("pixa not defined", procName, NULL); if (outdepth != 1 && outdepth != 8 && outdepth != 32) return (PIX *)ERROR_PTR("outdepth not in {1, 8, 32}", procName, NULL); if (border < 0 || border > tilewidth / 5) border = 0; if ((n = pixaGetCount(pixa)) == 0) return (PIX *)ERROR_PTR("no components", procName, NULL); /* Normalize scale and depth for each pix; optionally add border */ pixan = pixaCreate(n); bordval = (outdepth == 1) ? 1 : 0; for (i = 0; i < n; i++) { if ((pix = pixaGetPix(pixa, i, L_CLONE)) == NULL) continue; pixGetDimensions(pix, &w, &h, &d); scalefact = (l_float32)(tilewidth - 2 * border) / (l_float32)w; if (d == 1 && outdepth > 1 && scalefact < 1.0) pixt = pixScaleToGray(pix, scalefact); else pixt = pixScale(pix, scalefact, scalefact); if (outdepth == 1) pixn = pixConvertTo1(pixt, 128); else if (outdepth == 8) pixn = pixConvertTo8(pixt, FALSE); else /* outdepth == 32 */ pixn = pixConvertTo32(pixt); pixDestroy(&pixt); if (border) pixb = pixAddBorder(pixn, border, bordval); else pixb = pixClone(pixn); pixaAddPix(pixan, pixb, L_INSERT); pixDestroy(&pix); pixDestroy(&pixn); } if ((n = pixaGetCount(pixan)) == 0) { /* should not have changed! */ pixaDestroy(&pixan); return (PIX *)ERROR_PTR("no components", procName, NULL); } /* Determine the size of each row and of pixd */ wd = tilewidth * ncols + spacing * (ncols + 1); nrows = (n + ncols - 1) / ncols; if ((rowht = (l_int32 *)CALLOC(nrows, sizeof(l_int32))) == NULL) return (PIX *)ERROR_PTR("rowht array not made", procName, NULL); maxht = 0; ninrow = 0; irow = 0; for (i = 0; i < n; i++) { pix = pixaGetPix(pixan, i, L_CLONE); ninrow++; pixGetDimensions(pix, &w, &h, NULL); maxht = L_MAX(h, maxht); if (ninrow == ncols) { rowht[irow] = maxht; maxht = ninrow = 0; /* reset */ irow++; } pixDestroy(&pix); } if (ninrow > 0) { /* last fencepost */ rowht[irow] = maxht; irow++; /* total number of rows */ } nrows = irow; hd = spacing * (nrows + 1); for (i = 0; i < nrows; i++) hd += rowht[i]; pixd = pixCreate(wd, hd, outdepth); if ((background == 1 && outdepth == 1) || (background == 0 && outdepth != 1)) pixSetAll(pixd); /* Now blit images to pixd */ x = y = spacing; irow = 0; for (i = 0; i < n; i++) { pix = pixaGetPix(pixan, i, L_CLONE); pixGetDimensions(pix, &w, &h, NULL); if (i && ((i % ncols) == 0)) { /* start new row */ x = spacing; y += spacing + rowht[irow]; irow++; } pixRasterop(pixd, x, y, w, h, PIX_SRC, pix, 0, 0); x += tilewidth + spacing; pixDestroy(&pix); } pixaDestroy(&pixan); FREE(rowht); return pixd; }
/* * The decoder of the SET type. */ asn_dec_rval_t SET_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **struct_ptr, const void *ptr, size_t size, int tag_mode) { /* * Bring closer parts of structure description. */ asn_SET_specifics_t *specs = (asn_SET_specifics_t *)td->specifics; asn_TYPE_member_t *elements = td->elements; /* * Parts of the structure being constructed. */ void *st = *struct_ptr; /* Target structure. */ asn_struct_ctx_t *ctx; /* Decoder context */ ber_tlv_tag_t tlv_tag; /* T from TLV */ asn_dec_rval_t rval; /* Return code from subparsers */ ssize_t consumed_myself = 0; /* Consumed bytes from ptr */ int edx; /* SET element's index */ ASN_DEBUG("Decoding %s as SET", td->name); if(_ASN_STACK_OVERFLOW_CHECK(opt_codec_ctx)) _ASN_DECODE_FAILED; /* * Create the target structure if it is not present already. */ if(st == 0) { st = *struct_ptr = CALLOC(1, specs->struct_size); if(st == 0) { RETURN(RC_FAIL); } } /* * Restore parsing context. */ ctx = (asn_struct_ctx_t *)((char *)st + specs->ctx_offset); /* * Start to parse where left previously */ switch(ctx->phase) { case 0: /* * PHASE 0. * Check that the set of tags associated with given structure * perfectly fits our expectations. */ rval = ber_check_tags(opt_codec_ctx, td, ctx, ptr, size, tag_mode, 1, &ctx->left, 0); if(rval.code != RC_OK) { ASN_DEBUG("%s tagging check failed: %d", td->name, rval.code); return rval; } if(ctx->left >= 0) ctx->left += rval.consumed; /* ?Substracted below! */ ADVANCE(rval.consumed); NEXT_PHASE(ctx); ASN_DEBUG("Structure advertised %ld bytes, " "buffer contains %ld", (long)ctx->left, (long)size); /* Fall through */ case 1: /* * PHASE 1. * From the place where we've left it previously, * try to decode the next member from the list of * this structure's elements. * Note that elements in BER may arrive out of * order, yet DER mandates that they shall arive in the * canonical order of their tags. So, there is a room * for optimization. */ for(;; ctx->step = 0) { asn_TYPE_tag2member_t *t2m; asn_TYPE_tag2member_t key; void *memb_ptr; /* Pointer to the member */ void **memb_ptr2; /* Pointer to that pointer */ ssize_t tag_len; /* Length of TLV's T */ if(ctx->step & 1) { edx = ctx->step >> 1; goto microphase2; } /* * MICROPHASE 1: Synchronize decoding. */ if(ctx->left == 0) /* * No more things to decode. * Exit out of here and check whether all mandatory * elements have been received (in the next phase). */ break; /* * Fetch the T from TLV. */ tag_len = ber_fetch_tag(ptr, LEFT, &tlv_tag); switch(tag_len) { case 0: if(!SIZE_VIOLATION) RETURN(RC_WMORE); /* Fall through */ case -1: RETURN(RC_FAIL); } if(ctx->left < 0 && ((const uint8_t *)ptr)[0] == 0) { if(LEFT < 2) { if(SIZE_VIOLATION) RETURN(RC_FAIL); else RETURN(RC_WMORE); } else if(((const uint8_t *)ptr)[1] == 0) { /* * Found the terminator of the * indefinite length structure. * Invoke the generic finalization function. */ goto phase3; } } key.el_tag = tlv_tag; t2m = (asn_TYPE_tag2member_t *)bsearch(&key, specs->tag2el, specs->tag2el_count, sizeof(specs->tag2el[0]), _t2e_cmp); if(t2m) { /* * Found the element corresponding to the tag. */ edx = t2m->el_no; ctx->step = (edx << 1) + 1; ASN_DEBUG("Got tag %s (%s), edx %d", ber_tlv_tag_string(tlv_tag), td->name, edx); } else if(specs->extensible == 0) { ASN_DEBUG("Unexpected tag %s " "in non-extensible SET %s", ber_tlv_tag_string(tlv_tag), td->name); RETURN(RC_FAIL); } else { /* Skip this tag */ ssize_t skip; ASN_DEBUG("Skipping unknown tag %s", ber_tlv_tag_string(tlv_tag)); skip = ber_skip_length(opt_codec_ctx, BER_TLV_CONSTRUCTED(ptr), (const char *)ptr + tag_len, LEFT - tag_len); switch(skip) { case 0: if(!SIZE_VIOLATION) RETURN(RC_WMORE); /* Fall through */ case -1: RETURN(RC_FAIL); } ADVANCE(skip + tag_len); continue; /* Try again with the next tag */ } /* * MICROPHASE 2: Invoke the member-specific decoder. */ microphase2: /* * Check for duplications: must not overwrite * already decoded elements. */ if(ASN_SET_ISPRESENT2((char *)st + specs->pres_offset, edx)) { ASN_DEBUG("SET %s: Duplicate element %s (%d)", td->name, elements[edx].name, edx); RETURN(RC_FAIL); } /* * Compute the position of the member inside a structure, * and also a type of containment (it may be contained * as pointer or using inline inclusion). */ if(elements[edx].flags & ATF_POINTER) { /* Member is a pointer to another structure */ memb_ptr2 = (void **)((char *)st + elements[edx].memb_offset); } else { /* * A pointer to a pointer * holding the start of the structure */ memb_ptr = (char *)st + elements[edx].memb_offset; memb_ptr2 = &memb_ptr; } /* * Invoke the member fetch routine according to member's type */ rval = elements[edx].type->ber_decoder(opt_codec_ctx, elements[edx].type, memb_ptr2, ptr, LEFT, elements[edx].tag_mode); switch(rval.code) { case RC_OK: ASN_SET_MKPRESENT((char *)st + specs->pres_offset, edx); break; case RC_WMORE: /* More data expected */ if(!SIZE_VIOLATION) { ADVANCE(rval.consumed); RETURN(RC_WMORE); } /* Fail through */ case RC_FAIL: /* Fatal error */ RETURN(RC_FAIL); } /* switch(rval) */ ADVANCE(rval.consumed); } /* for(all structure members) */ phase3: ctx->phase = 3; /* Fall through */ case 3: case 4: /* Only 00 is expected */ ASN_DEBUG("SET %s Leftover: %ld, size = %ld", td->name, (long)ctx->left, (long)size); /* * Skip everything until the end of the SET. */ while(ctx->left) { ssize_t tl, ll; tl = ber_fetch_tag(ptr, LEFT, &tlv_tag); switch(tl) { case 0: if(!SIZE_VIOLATION) RETURN(RC_WMORE); /* Fall through */ case -1: RETURN(RC_FAIL); } /* * If expected <0><0>... */ if(ctx->left < 0 && ((const uint8_t *)ptr)[0] == 0) { if(LEFT < 2) { if(SIZE_VIOLATION) RETURN(RC_FAIL); else RETURN(RC_WMORE); } else if(((const uint8_t *)ptr)[1] == 0) { /* * Correctly finished with <0><0>. */ ADVANCE(2); ctx->left++; ctx->phase = 4; continue; } } if(specs->extensible == 0 || ctx->phase == 4) { ASN_DEBUG("Unexpected continuation " "of a non-extensible type %s " "(ptr=%02x)", td->name, *(const uint8_t *)ptr); RETURN(RC_FAIL); } ll = ber_skip_length(opt_codec_ctx, BER_TLV_CONSTRUCTED(ptr), (const char *)ptr + tl, LEFT - tl); switch(ll) { case 0: if(!SIZE_VIOLATION) RETURN(RC_WMORE); /* Fall through */ case -1: RETURN(RC_FAIL); } ADVANCE(tl + ll); } ctx->phase = 5; case 5: /* Check that all mandatory elements are present. */ if(!_SET_is_populated(td, st)) RETURN(RC_FAIL); NEXT_PHASE(ctx); }
/* Internal constructor. */ static Json *Json_new (void) { return (Json*)CALLOC(Json, 1); }
/* * Decode an always-primitive type. */ asn_dec_rval_t ber_decode_primitive(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **sptr, const void *buf_ptr, size_t size, int tag_mode) { ASN__PRIMITIVE_TYPE_t *st = (ASN__PRIMITIVE_TYPE_t *)*sptr; asn_dec_rval_t rval; ber_tlv_len_t length = 0; // =0 to avoid [incorrect] warning. /* * If the structure is not there, allocate it. */ if(st == NULL) { st = (ASN__PRIMITIVE_TYPE_t *)CALLOC(1, sizeof(*st)); if(st == NULL) _ASN_DECODE_FAILED; *sptr = (void *)st; } ASN_DEBUG("Decoding %s as plain primitive (tm=%d)", td->name, tag_mode); /* * Check tags and extract value length. */ rval = ber_check_tags(opt_codec_ctx, td, 0, buf_ptr, size, tag_mode, 0, &length, 0); if(rval.code != RC_OK) return rval; ASN_DEBUG("%s length is %d bytes", td->name, (int)length); /* * Make sure we have this length. */ buf_ptr = ((const char *)buf_ptr) + rval.consumed; size -= rval.consumed; if(length > (ber_tlv_len_t)size) { rval.code = RC_WMORE; rval.consumed = 0; return rval; } st->size = (int)length; /* The following better be optimized away. */ if(sizeof(st->size) != sizeof(length) && (ber_tlv_len_t)st->size != length) { st->size = 0; _ASN_DECODE_FAILED; } st->buf = (uint8_t *)MALLOC(length + 1); if(!st->buf) { st->size = 0; _ASN_DECODE_FAILED; } memcpy(st->buf, buf_ptr, length); st->buf[length] = '\0'; /* Just in case */ rval.code = RC_OK; rval.consumed += length; ASN_DEBUG("Took %ld/%ld bytes to encode %s", (long)rval.consumed, (long)length, td->name); return rval; }
/** * Create a VdpVideoMixer. */ VdpStatus vlVdpVideoMixerCreate(VdpDevice device, uint32_t feature_count, VdpVideoMixerFeature const *features, uint32_t parameter_count, VdpVideoMixerParameter const *parameters, void const *const *parameter_values, VdpVideoMixer *mixer) { vlVdpVideoMixer *vmixer = NULL; VdpStatus ret; struct pipe_screen *screen; uint32_t max_2d_texture_level; unsigned max_size, i; vlVdpDevice *dev = vlGetDataHTAB(device); if (!dev) return VDP_STATUS_INVALID_HANDLE; screen = dev->vscreen->pscreen; vmixer = CALLOC(1, sizeof(vlVdpVideoMixer)); if (!vmixer) return VDP_STATUS_RESOURCES; DeviceReference(&vmixer->device, dev); pipe_mutex_lock(dev->mutex); vl_compositor_init_state(&vmixer->cstate, dev->context); vl_csc_get_matrix(VL_CSC_COLOR_STANDARD_BT_601, NULL, true, &vmixer->csc); if (!debug_get_bool_option("G3DVL_NO_CSC", FALSE)) vl_compositor_set_csc_matrix(&vmixer->cstate, (const vl_csc_matrix *)&vmixer->csc, 1.0f, 0.0f); *mixer = vlAddDataHTAB(vmixer); if (*mixer == 0) { ret = VDP_STATUS_ERROR; goto no_handle; } ret = VDP_STATUS_INVALID_VIDEO_MIXER_FEATURE; for (i = 0; i < feature_count; ++i) { switch (features[i]) { /* they are valid, but we doesn't support them */ case VDP_VIDEO_MIXER_FEATURE_DEINTERLACE_TEMPORAL_SPATIAL: case VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L1: case VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L2: case VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L3: case VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L4: case VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L5: case VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L6: case VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L7: case VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L8: case VDP_VIDEO_MIXER_FEATURE_HIGH_QUALITY_SCALING_L9: case VDP_VIDEO_MIXER_FEATURE_INVERSE_TELECINE: break; case VDP_VIDEO_MIXER_FEATURE_DEINTERLACE_TEMPORAL: vmixer->deint.supported = true; break; case VDP_VIDEO_MIXER_FEATURE_SHARPNESS: vmixer->sharpness.supported = true; break; case VDP_VIDEO_MIXER_FEATURE_NOISE_REDUCTION: vmixer->noise_reduction.supported = true; break; case VDP_VIDEO_MIXER_FEATURE_LUMA_KEY: vmixer->luma_key.supported = true; break; default: goto no_params; } } vmixer->chroma_format = PIPE_VIDEO_CHROMA_FORMAT_420; ret = VDP_STATUS_INVALID_VIDEO_MIXER_PARAMETER; for (i = 0; i < parameter_count; ++i) { switch (parameters[i]) { case VDP_VIDEO_MIXER_PARAMETER_VIDEO_SURFACE_WIDTH: vmixer->video_width = *(uint32_t*)parameter_values[i]; break; case VDP_VIDEO_MIXER_PARAMETER_VIDEO_SURFACE_HEIGHT: vmixer->video_height = *(uint32_t*)parameter_values[i]; break; case VDP_VIDEO_MIXER_PARAMETER_CHROMA_TYPE: vmixer->chroma_format = ChromaToPipe(*(VdpChromaType*)parameter_values[i]); break; case VDP_VIDEO_MIXER_PARAMETER_LAYERS: vmixer->max_layers = *(uint32_t*)parameter_values[i]; break; default: goto no_params; } } ret = VDP_STATUS_INVALID_VALUE; if (vmixer->max_layers > 4) { VDPAU_MSG(VDPAU_WARN, "[VDPAU] Max layers > 4 not supported\n", vmixer->max_layers); goto no_params; } max_2d_texture_level = screen->get_param(screen, PIPE_CAP_MAX_TEXTURE_2D_LEVELS); max_size = pow(2, max_2d_texture_level-1); if (vmixer->video_width < 48 || vmixer->video_width > max_size) { VDPAU_MSG(VDPAU_WARN, "[VDPAU] 48 < %u < %u not valid for width\n", vmixer->video_width, max_size); goto no_params; } if (vmixer->video_height < 48 || vmixer->video_height > max_size) { VDPAU_MSG(VDPAU_WARN, "[VDPAU] 48 < %u < %u not valid for height\n", vmixer->video_height, max_size); goto no_params; } vmixer->luma_key.luma_min = 1.0f; vmixer->luma_key.luma_max = 0.0f; pipe_mutex_unlock(dev->mutex); return VDP_STATUS_OK; no_params: vlRemoveDataHTAB(*mixer); no_handle: vl_compositor_cleanup_state(&vmixer->cstate); pipe_mutex_unlock(dev->mutex); DeviceReference(&vmixer->device, NULL); FREE(vmixer); return ret; }
asn_dec_rval_t xer_decode_primitive(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **sptr, size_t struct_size, const char *opt_mname, const void *buf_ptr, size_t size, xer_primitive_body_decoder_f *prim_body_decoder ) { const char *xml_tag = opt_mname ? opt_mname : td->xml_tag; asn_struct_ctx_t s_ctx; struct xdp_arg_s s_arg; asn_dec_rval_t rc; /* * Create the structure if does not exist. */ if(!*sptr) { *sptr = CALLOC(1, struct_size); if(!*sptr) _ASN_DECODE_FAILED; } memset(&s_ctx, 0, sizeof(s_ctx)); s_arg.type_descriptor = td; s_arg.struct_key = *sptr; s_arg.prim_body_decoder = prim_body_decoder; s_arg.decoded_something = 0; s_arg.want_more = 0; rc = xer_decode_general(opt_codec_ctx, &s_ctx, &s_arg, xml_tag, buf_ptr, size, xer_decode__unexpected_tag, xer_decode__primitive_body); switch(rc.code) { case RC_OK: if(!s_arg.decoded_something) { char ch; ASN_DEBUG("Primitive body is not recognized, " "supplying empty one"); /* * Decoding opportunity has come and gone. * Where's the result? * Try to feed with empty body, see if it eats it. */ if(prim_body_decoder(s_arg.type_descriptor, s_arg.struct_key, &ch, 0) != XPBD_BODY_CONSUMED) { /* * This decoder does not like empty stuff. */ _ASN_DECODE_FAILED; } } break; case RC_WMORE: /* * Redo the whole thing later. * We don't have a context to save intermediate parsing state. */ rc.consumed = 0; break; case RC_FAIL: rc.consumed = 0; if(s_arg.want_more) rc.code = RC_WMORE; else _ASN_DECODE_FAILED; break; } return rc; }
/*! * pixWrite() * * Input: filename * pix * format (defined in imageio.h) * Return: 0 if OK; 1 on error * * Notes: * (1) Open for write using binary mode (with the "b" flag) * to avoid having Windows automatically translate the NL * into CRLF, which corrupts image files. On non-windows * systems this flag should be ignored, per ISO C90. * Thanks to Dave Bryan for pointing this out. * (2) If the default image format IFF_DEFAULT is requested: * use the input format if known; otherwise, use a lossless format. * (3) There are two modes with respect to file naming. * (a) The default code writes to @filename. * (b) If WRITE_AS_NAMED is defined to 0, it's a bit fancier. * Then, if @filename does not have a file extension, one is * automatically appended, depending on the requested format. * The original intent for providing option (b) was to insure * that filenames on Windows have an extension that matches * the image compression. However, this is not the default. */ l_int32 pixWrite(const char *filename, PIX *pix, l_int32 format) { char *fname; FILE *fp; PROCNAME("pixWrite"); if (!pix) return ERROR_INT("pix not defined", procName, 1); if (!filename) return ERROR_INT("filename not defined", procName, 1); if (format == IFF_JP2) return ERROR_INT("jp2 not supported", procName, 1); fname = genPathname(filename, NULL); #if WRITE_AS_NAMED /* Default */ if ((fp = fopenWriteStream(fname, "wb+")) == NULL) { FREE(fname); return ERROR_INT("stream not opened", procName, 1); } #else /* Add an extension to the output name if none exists */ {l_int32 extlen; char *extension, *filebuf; splitPathAtExtension(fname, NULL, &extension); extlen = strlen(extension); FREE(extension); if (extlen == 0) { if (format == IFF_DEFAULT || format == IFF_UNKNOWN) format = pixChooseOutputFormat(pix); filebuf = (char *)CALLOC(strlen(fname) + 10, sizeof(char)); if (!filebuf) { return ERROR_INT("filebuf not made", procName, 1); FREE(fname); } strncpy(filebuf, fname, strlen(fname)); strcat(filebuf, "."); strcat(filebuf, ImageFileFormatExtensions[format]); } else { filebuf = (char *)fname; } fp = fopenWriteStream(filebuf, "wb+"); if (filebuf != fname) FREE(filebuf); if (fp == NULL) { FREE(fname); return ERROR_INT("stream not opened", procName, 1); } } #endif /* WRITE_AS_NAMED */ FREE(fname); if (pixWriteStream(fp, pix, format)) { fclose(fp); return ERROR_INT("pix not written to stream", procName, 1); } /* Close the stream except if GIF under windows, because * EGifCloseFile() closes the windows file stream! */ if (format != IFF_GIF) fclose(fp); #ifndef _WIN32 else /* gif file */ fclose(fp); #endif /* ! _WIN32 */ return 0; }
bool Parserange_query (char **divstring, unsigned int *coordstart, unsigned int *coordend, bool *revcomp, char *query, char *filename) { char *coords; unsigned int result, left, length; int div_strlen; IIT_T iit; *divstring = NULL; *revcomp = false; if ((coords = find_div(&div_strlen,query,':')) != NULL) { /* Query may have a div */ *divstring = (char *) CALLOC(div_strlen+1,sizeof(char)); strncpy(*divstring,query,div_strlen); debug(printf("Parsed query %s into divstring %s and coords %s\n", query,*divstring,coords)); if (IIT_read_divint(filename,*divstring,/*add_iit_p*/true) < 0) { fprintf(stderr,"Chromosome %s not found in IIT file\n",*divstring); debug(printf(" but divstring not found, so treat as label\n")); FREE(*divstring); /* free only when returning false */ return false; } else if (coords == NULL || *coords == '\0') { debug(printf(" entire div\n")); if ((iit = IIT_read(filename,/*name*/NULL,/*readonlyp*/true,/*divread*/READ_ONE,*divstring, /*add_iit_p*/true,/*labels_read_p*/false)) == NULL) { if (Access_file_exists_p(filename) == false) { fprintf(stderr,"Cannot read file %s\n",filename); } else { fprintf(stderr,"File %s appears to be an invalid IIT file\n",filename); } exit(9); } else { *coordstart= 0; *coordend = IIT_divlength(iit,*divstring); debug(printf(" divlength is %u\n",*coordend)); IIT_free(&iit); } return true; } else if (isnumberp(&result,coords)) { debug(printf(" and coords %s as a number\n",coords)); *coordstart = result; *coordend = result; return true; } else if (isrange(&left,&length,&(*revcomp),coords)) { debug(printf(" and coords %s as a range starting at %u with length %u and revcomp = %d\n", coords,left,length,*revcomp)); *coordstart = left + 1; /* Because isrange is 0-based */ *coordend = left + length; return true; } else { debug(printf(" but coords %s is neither a number nor a range. Interpret as a label.\n",coords)); FREE(*divstring); /* free only when returning false */ return false; } } else { /* No div. Query must be a number, range, or label */ debug(printf("Parsed query %s without a div ",query)); if (isnumberp(&result,query)) { debug(printf("number\n")); *coordstart = result; *coordend = result; return true; } else if (isrange(&left,&length,&(*revcomp),query)) { debug(printf("range\n")); *coordstart = left + 1; /* Because isrange is 0-based */ *coordend = left + length; return true; } else { debug(printf("label\n")); return false; } } }
void Genome_write (char *genomesubdir, char *fileroot, FILE *input, IIT_T contig_iit, IIT_T altstrain_iit, bool uncompressedp, bool rawp, bool writefilep, unsigned int genomelength, int index1part) { unsigned int nuint4; FILE *refgenome_fp; char *filename; UINT4 *genomecomp; fprintf(stderr,"Genome length is %u nt\n",genomelength); if (uncompressedp == true) { filename = (char *) CALLOC(strlen(genomesubdir)+strlen("/")+ strlen(fileroot)+strlen(".genome")+1,sizeof(char)); sprintf(filename,"%s/%s.genome",genomesubdir,fileroot); if ((refgenome_fp = FOPEN_WRITE_BINARY(filename)) == NULL) { fprintf(stderr,"Can't write to file %s\n",filename); exit(9); } if (rawp == true) { genome_writeraw_file(refgenome_fp,input,contig_iit,altstrain_iit,fileroot,index1part); } else { genome_write_file(refgenome_fp,input,contig_iit,altstrain_iit,fileroot,/*uncompressedp*/true,index1part); } fclose(refgenome_fp); FREE(filename); } else if (writefilep == true) { filename = (char *) CALLOC(strlen(genomesubdir)+strlen("/")+ strlen(fileroot)+strlen(".genomecomp")+1,sizeof(char)); sprintf(filename,"%s/%s.genomecomp",genomesubdir,fileroot); fprintf(stderr,"User requested build of genome in file\n"); if ((refgenome_fp = FOPEN_RW_BINARY(filename)) == NULL) { fprintf(stderr,"Can't open file %s for read/write\n",filename); exit(9); } genome_write_file(refgenome_fp,input,contig_iit,altstrain_iit,fileroot,/*uncompressedp*/false,index1part); fclose(refgenome_fp); FREE(filename); } else { filename = (char *) CALLOC(strlen(genomesubdir)+strlen("/")+ strlen(fileroot)+strlen(".genomecomp")+1,sizeof(char)); sprintf(filename,"%s/%s.genomecomp",genomesubdir,fileroot); nuint4 = ((genomelength + 31)/32U)*3; fprintf(stderr,"Trying to allocate %d*%u bytes of memory...",nuint4,(unsigned int) sizeof(UINT4)); genomecomp = (UINT4 *) CALLOC_NO_EXCEPTION(nuint4,sizeof(UINT4)); if (genomecomp == NULL) { fprintf(stderr,"failed. Building genome in file.\n"); if ((refgenome_fp = FOPEN_RW_BINARY(filename)) == NULL) { fprintf(stderr,"Can't open file %s for read/write\n",filename); exit(9); } genome_write_file(refgenome_fp,input,contig_iit,altstrain_iit,fileroot,/*uncompressedp*/false,index1part); fclose(refgenome_fp); } else { fprintf(stderr,"succeeded. Building genome in memory.\n"); /* Creates X's at end */ genomecomp[nuint4-3] = 0xFFFFFFFF; genomecomp[nuint4-2] = 0xFFFFFFFF; genomecomp[nuint4-1] = 0xFFFFFFFF; if ((refgenome_fp = FOPEN_WRITE_BINARY(filename)) == NULL) { fprintf(stderr,"Can't open file %s for write\n",filename); exit(9); } genome_write_memory(refgenome_fp,input,contig_iit,altstrain_iit,genomecomp,nuint4,fileroot); fclose(refgenome_fp); FREE(genomecomp); } FREE(filename); } return; }
bool Parserange_universal (char **div, bool *revcomp, Genomicpos_T *genomicstart, Genomicpos_T *genomiclength, Genomicpos_T *chrstart, Genomicpos_T *chrend, Genomicpos_T *chroffset, Genomicpos_T *chrlength, char *query, char *genomesubdir, char *fileroot) { char *coords, *filename; Genomicpos_T result, left, length; IIT_T chromosome_iit, contig_iit; Interval_T interval; int theindex; int rc; *revcomp = false; if (index(query,':')) { /* Segment must be a genome, chromosome, or contig */ debug(printf("Parsed query %s into ",query)); *div = strtok(query,":"); if ((*div)[0] == '+') { *revcomp = false; *div = &((*div)[1]); } else if ((*div)[0] == '_') { *revcomp = true; *div = &((*div)[1]); } coords = strtok(NULL,":"); debug(printf("segment %s and coords %s\n",*div,coords)); /* Try chromosome first */ filename = (char *) CALLOC(strlen(genomesubdir)+strlen("/")+strlen(fileroot)+ strlen(".chromosome.iit")+1,sizeof(char)); sprintf(filename,"%s/%s.chromosome.iit",genomesubdir,fileroot); chromosome_iit = IIT_read(filename,/*name*/NULL,/*readonlyp*/true,/*divread*/READ_ALL, /*divstring*/NULL,/*add_iit_p*/false,/*labels_read_p*/true); FREE(filename); debug(printf("Interpreting segment %s as a chromosome\n",*div)); if (coords == NULL) { debug(printf(" entire chromosome\n")); rc = translate_chromosomepos_universal(&(*genomicstart),&(*genomiclength),*div,left=0,length=0,chromosome_iit); } else if (isnumberp(&result,coords)) { debug(printf(" and coords %s as a number\n",coords)); rc = translate_chromosomepos_universal(&(*genomicstart),&(*genomiclength),*div,left=result-1,length=1,chromosome_iit); } else if (isrange(&left,&length,&(*revcomp),coords)) { debug(printf(" and coords %s as a range starting at %u with length %u and revcomp = %d\n", coords,left,length,*revcomp)); rc = translate_chromosomepos_universal(&(*genomicstart),&(*genomiclength),*div,left,length,chromosome_iit); } else { debug(printf(" but coords %s is neither a number nor a range\n",coords)); rc = -1; } /* Compute chromosomal coordinates */ *chrstart = left; *chrend = *chrstart + *genomiclength; *chrstart += 1U; /* Make 1-based */ /* Get chromosomal information */ if ((theindex = IIT_find_one(chromosome_iit,*div)) < 0) { fprintf(stderr,"Cannot find chromosome %s in chromosome IIT file\n",*div); /* exit(9); */ } else { interval = IIT_interval(chromosome_iit,theindex); *chroffset = Interval_low(interval); *chrlength = Interval_length(interval); } IIT_free(&chromosome_iit); #if 0 /* Contig IIT's are of type 1, which require some work to compute on current div-based scheme. Just abandoning for now. */ if (rc != 0) { /* Try contig */ filename = (char *) CALLOC(strlen(genomesubdir)+strlen("/")+strlen(fileroot)+ strlen(".contig.iit")+1,sizeof(char)); sprintf(filename,"%s/%s.contig.iit",genomesubdir,fileroot); contig_iit = IIT_read(filename,/*name*/NULL,/*readonlyp*/true,/*divread*/READ_ALL, /*divstring*/NULL,/*add_iit_p*/false,/*labels_read_p*/true); FREE(filename); debug(printf("Interpreting segment %s as a contig\n",*div)); if (coords == NULL) { debug(printf(" entire contig\n")); rc = translate_contig_universal(&(*genomicstart),&(*genomiclength),*div,left=0,length=0,chromosome_iit); } else if (isnumberp(&result,coords)) { debug(printf(" and coords %s as a number\n",coords)); rc = translate_contig(&(*genomicstart),&(*genomiclength),*div,left=result-1,length=1,contig_iit); } else if (isrange(&left,&length,&(*revcomp),coords)) { debug(printf(" and coords %s as a range starting at %u with length %u and revcomp = %d\n", coords,left,length,*revcomp)); rc = translate_contig(&(*genomicstart),&(*genomiclength),*div,left,length,contig_iit); } else { debug(printf(" but coords %s is neither a number nor a range\n",coords)); rc = -1; } IIT_free(&contig_iit); } #endif if (rc != 0) { fprintf(stderr,"Can't find coordinates %s:%s\n",*div,coords); return false; } else { return true; } } else { /* Query must be a genomic position, genomic range, or contig */ *chrstart = *chroffset = *chrlength = 0; debug(printf("Parsed query %s as atomic ",query)); if (isnumberp(&result,query)) { debug(printf("number\n")); *genomicstart = result-1; *genomiclength = 1; } else if (isrange(&left,&length,&(*revcomp),query)) { debug(printf("range\n")); *genomicstart = left; *genomiclength = length; } else { debug(printf("contig\n")); return false; #if 0 filename = (char *) CALLOC(strlen(genomesubdir)+strlen("/")+strlen(fileroot)+ strlen(".contig.iit")+1,sizeof(char)); sprintf(filename,"%s/%s.contig.iit",genomesubdir,fileroot); contig_iit = IIT_read(filename,/*name*/NULL,/*readonlyp*/true,/*divread*/READ_ALL, /*divstring*/NULL,/*add_iit_p*/false,/*labels_read_p*/true); FREE(filename); rc = translate_contig(&(*genomicstart),&(*genomiclength),query,left=0,length=0,contig_iit); IIT_free(&contig_iit); #endif } *div = convert_to_chrpos(&(*chrstart),genomesubdir,fileroot,*genomicstart); *chrend = *chrstart + *genomiclength; *chrstart += 1U; /* Make 1-based */ /* Try chromosome first */ filename = (char *) CALLOC(strlen(genomesubdir)+strlen("/")+strlen(fileroot)+ strlen(".chromosome.iit")+1,sizeof(char)); sprintf(filename,"%s/%s.chromosome.iit",genomesubdir,fileroot); chromosome_iit = IIT_read(filename,/*name*/NULL,/*readonlyp*/true,/*divread*/READ_ALL, /*divstring*/NULL,/*add_iit_p*/false,/*labels_read_p*/true); FREE(filename); if ((theindex = IIT_find_one(chromosome_iit,*div)) < 0) { fprintf(stderr,"Cannot find chromosome %s in chromosome IIT file\n",*div); IIT_free(&chromosome_iit); return false; } else { interval = IIT_interval(chromosome_iit,theindex); *chroffset = Interval_low(interval); *chrlength = Interval_length(interval); IIT_free(&chromosome_iit); return true; } } }
static HRESULT NineVolumeTexture9_ctor( struct NineVolumeTexture9 *This, struct NineUnknownParams *pParams, UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, HANDLE *pSharedHandle ) { struct pipe_resource *info = &This->base.base.info; struct pipe_screen *screen = pParams->device->screen; enum pipe_format pf; unsigned l; D3DVOLUME_DESC voldesc; HRESULT hr; DBG("This=%p pParams=%p Width=%u Height=%u Depth=%u Levels=%u " "Usage=%d Format=%d Pool=%d pSharedHandle=%p\n", This, pParams, Width, Height, Depth, Levels, Usage, Format, Pool, pSharedHandle); user_assert(Width && Height && Depth, D3DERR_INVALIDCALL); /* user_assert(!pSharedHandle || Pool == D3DPOOL_DEFAULT, D3DERR_INVALIDCALL); */ user_assert(!pSharedHandle, D3DERR_INVALIDCALL); /* TODO */ /* An IDirect3DVolume9 cannot be bound as a render target can it ? */ user_assert(!(Usage & (D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL)), D3DERR_INVALIDCALL); user_assert(!(Usage & D3DUSAGE_AUTOGENMIPMAP), D3DERR_INVALIDCALL); pf = d3d9_to_pipe_format_checked(screen, Format, PIPE_TEXTURE_3D, 0, PIPE_BIND_SAMPLER_VIEW, FALSE, Pool == D3DPOOL_SCRATCH); if (pf == PIPE_FORMAT_NONE) return D3DERR_INVALIDCALL; /* We support ATI1 and ATI2 hacks only for 2D and Cube textures */ if (Format == D3DFMT_ATI1 || Format == D3DFMT_ATI2) return D3DERR_INVALIDCALL; if (compressed_format(Format)) { const unsigned w = util_format_get_blockwidth(pf); const unsigned h = util_format_get_blockheight(pf); /* Compressed formats are not compressed on depth component */ user_assert(!(Width % w) && !(Height % h), D3DERR_INVALIDCALL); } info->screen = pParams->device->screen; info->target = PIPE_TEXTURE_3D; info->format = pf; info->width0 = Width; info->height0 = Height; info->depth0 = Depth; if (Levels) info->last_level = Levels - 1; else info->last_level = util_logbase2(MAX2(MAX2(Width, Height), Depth)); info->array_size = 1; info->nr_samples = 0; info->nr_storage_samples = 0; info->bind = PIPE_BIND_SAMPLER_VIEW; info->usage = PIPE_USAGE_DEFAULT; info->flags = 0; if (Usage & D3DUSAGE_DYNAMIC) { info->usage = PIPE_USAGE_DYNAMIC; } if (Usage & D3DUSAGE_SOFTWAREPROCESSING) DBG("Application asked for Software Vertex Processing, " "but this is unimplemented\n"); This->volumes = CALLOC(info->last_level + 1, sizeof(*This->volumes)); if (!This->volumes) return E_OUTOFMEMORY; This->base.pstype = 3; hr = NineBaseTexture9_ctor(&This->base, pParams, NULL, D3DRTYPE_VOLUMETEXTURE, Format, Pool, Usage); if (FAILED(hr)) return hr; voldesc.Format = Format; voldesc.Type = D3DRTYPE_VOLUME; voldesc.Usage = Usage; voldesc.Pool = Pool; for (l = 0; l <= info->last_level; ++l) { voldesc.Width = u_minify(Width, l); voldesc.Height = u_minify(Height, l); voldesc.Depth = u_minify(Depth, l); hr = NineVolume9_new(This->base.base.base.device, NineUnknown(This), This->base.base.resource, l, &voldesc, &This->volumes[l]); if (FAILED(hr)) return hr; } /* Textures start initially dirty */ NineVolumeTexture9_AddDirtyBox(This, NULL); return D3D_OK; }
/* Returns coordinates as zero-based */ static bool isrange (unsigned int *left, unsigned int *length, bool *revcomp, char *string) { bool result; char *copy, *startstring, *endstring; unsigned int start, end; copy = (char *) CALLOC(strlen(string)+1,sizeof(char)); strcpy(copy,string); if (index(copy,'.')) { startstring = strtok(copy,".."); endstring = strtok(NULL,".."); if (!isnumberp(&start,startstring) || !isnumberp(&end,endstring)) { result = false; } else if (start <= end) { *length = end - start + 1; *left = start - 1; *revcomp = false; debug(printf("(..) ")); result = true; } else { *length = start - end + 1; *left = end - 1; *revcomp = true; debug(printf("(..) ")); result = true; } } else if (index(copy,'+')) { startstring = strtok(copy,"+"); endstring = strtok(NULL,"+"); if (!isnumberp(&start,startstring)) { result = false; } else if (endstring[0] == '-' && isnumberp(&(*length),&(endstring[1]))) { *left = start - (*length); *revcomp = true; debug(printf("(-) ")); result = true; } else if (!isnumberp(&(*length),endstring)) { result = false; } else { *left = start - 1; *revcomp = false; debug(printf("(+) ")); result = true; } } else if (index(copy,'-')) { /* Old notation */ startstring = strtok(copy,"--"); endstring = strtok(NULL,"--"); if (!isnumberp(&start,startstring) || !isnumberp(&end,endstring)) { result = false; } else if (start <= end) { *length = end - start + 1; *left = start - 1; *revcomp = false; debug(printf("(--) ")); result = true; } else { *length = start - end + 1; *left = end - 1; *revcomp = true; debug(printf("(--) ")); result = true; } /* Don't allow this yet ... } else if (index(copy,'-')) { startstring = strtok(copy,"-"); endstring = strtok(NULL,"-"); if (!isnumberp(&start,startstring) || !isnumberp(&end,endstring)) { result = false; } else if (end > start - 1) { result = false; } else { *left = start - 1 - end; *length = end; *revcomp = true; result = true; } */ } else { result = false; } FREE(copy); return result; }
/**MAJ pour le 3D DJ.Abdemouche 2003**/ double *sciGetPoint(char * pthis, int *numrow, int *numcol) { int iType = -1; int *piType = &iType; double *tab = NULL; int i = 0; getGraphicObjectProperty(pthis, __GO_TYPE__, jni_int, (void **)&piType); /* * Object type determined by string comparisons * Required as we have no better way to do this for the moment */ switch (iType) { case __GO_FIGURE__ : { int* figurePosition = NULL; int* axesSize = NULL; *numrow = 2; *numcol = 2; if ((tab = CALLOC((*numrow) * (*numcol), sizeof(double))) == NULL) { *numrow = -1; *numcol = -1; return NULL; } getGraphicObjectProperty(pthis, __GO_POSITION__, jni_int_vector, (void **)&figurePosition); getGraphicObjectProperty(pthis, __GO_AXES_SIZE__, jni_int_vector, (void **)&axesSize); tab[0] = (double) figurePosition[0]; tab[1] = (double) figurePosition[1]; tab[2] = (double) axesSize[0]; tab[3] = (double) axesSize[1]; return tab; } case __GO_POLYLINE__ : { char* parentAxes = NULL; double* dataX = NULL; double* dataY = NULL; double* dataZ = NULL; int iTmp = 0; int* piTmp = &iTmp; int iView = 0; int *piView = &iView; /* * Testing whether data properties exist for this object * is currently done only for this property. The type comparison already * ensures that this is the case, though doing so is awkward. */ getGraphicObjectProperty(pthis, __GO_DATA_MODEL_NUM_ELEMENTS__, jni_int, (void**)&piTmp); if (piTmp == NULL) { *numrow = -2; *numcol = -2; return NULL; } *numrow = iTmp; getGraphicObjectProperty(pthis, __GO_DATA_MODEL_Z_COORDINATES_SET__, jni_int, (void**)&piTmp); if (iTmp) { *numcol = 3; } else { *numcol = 2; } if ((*numrow) * (*numcol) == 0) { /* empty data, no warnings */ *numrow = 0; *numcol = 0; return NULL; } getGraphicObjectProperty(pthis, __GO_PARENT_AXES__, jni_string, (void **)&parentAxes); getGraphicObjectProperty(parentAxes, __GO_VIEW__, jni_int, (void**)&piView); getGraphicObjectProperty(pthis, __GO_DATA_MODEL_X__, jni_double_vector, (void **)&dataX); getGraphicObjectProperty(pthis, __GO_DATA_MODEL_Y__, jni_double_vector, (void **)&dataY); if (*numcol == 2 && iView) { *numcol = (*numcol) + 1; /* colonne de 0. a prendre en compte / afficher => numcol+1*/ if ((tab = CALLOC((*numrow) * (*numcol), sizeof(double))) == NULL) { *numrow = -1; *numcol = -1; return NULL; } for (i = 0 ; i < *numrow ; i++) { tab[i] = dataX[i]; tab[*numrow + i] = dataY[i]; tab[(2 * (*numrow)) + i] = 0.; } } else { if ((tab = CALLOC((*numrow) * (*numcol), sizeof(double))) == NULL) { *numrow = -1; *numcol = -1; return NULL; } if (*numcol == 3) { getGraphicObjectProperty(pthis, __GO_DATA_MODEL_Z__, jni_double_vector, (void **)&dataZ); } for (i = 0 ; i < *numrow ; i++) { tab[i] = dataX[i]; tab[*numrow + i] = dataY[i]; if (*numcol == 3) { tab[(2 * (*numrow)) + i] = dataZ[i]; } } } return tab; } case __GO_RECTANGLE__ : { char* parentAxes = NULL; double* upperLeftPoint = NULL; double width = 0.0; double *pdblWidth = &width; double height = 0.0; double *pdblHeight = &height; int iView = 0; int *piView = &iView; *numrow = 1; getGraphicObjectProperty(pthis, __GO_PARENT_AXES__, jni_string, (void **)&parentAxes); getGraphicObjectProperty(parentAxes, __GO_VIEW__, jni_int, (void**)&piView); *numcol = iView ? 5 : 4; if ((tab = CALLOC((*numrow) * (*numcol), sizeof(double))) == NULL) { *numrow = -1; *numcol = -1; return NULL; } getGraphicObjectProperty(pthis, __GO_UPPER_LEFT_POINT__, jni_double_vector, (void **)&upperLeftPoint); getGraphicObjectProperty(pthis, __GO_WIDTH__, jni_double, (void**)&pdblWidth); getGraphicObjectProperty(pthis, __GO_HEIGHT__, jni_double, (void **)&pdblHeight); tab[0] = upperLeftPoint[0]; tab[1] = upperLeftPoint[1]; if (iView) { tab[2] = upperLeftPoint[2]; tab[3] = width; tab[4] = height; } else { tab[2] = width; tab[3] = height; } return (double*)tab; } case __GO_ARC__ : { char* parentAxes = NULL; double* upperLeftPoint = NULL; double width = 0.0; double *pdblWidth = &width; double height = 0.; double *pdblHeight = &height; double startAngle = 0.; double *pdblStartAngle = &startAngle; double endAngle = 0.; double *pdblEndAngle = &endAngle; int view = 0; int *piView = &view; *numrow = 1; getGraphicObjectProperty(pthis, __GO_PARENT_AXES__, jni_string, (void **)&parentAxes); getGraphicObjectProperty(parentAxes, __GO_VIEW__, jni_int, (void**)&piView); *numcol = view ? 7 : 6; if ((tab = CALLOC((*numrow) * (*numcol), sizeof(double))) == NULL) { *numrow = -1; *numcol = -1; return NULL; } getGraphicObjectProperty(pthis, __GO_UPPER_LEFT_POINT__, jni_double_vector, (void **)&upperLeftPoint); getGraphicObjectProperty(pthis, __GO_WIDTH__, jni_double, (void **)&pdblWidth); getGraphicObjectProperty(pthis, __GO_HEIGHT__, jni_double, (void **)&pdblHeight); getGraphicObjectProperty(pthis, __GO_START_ANGLE__, jni_double, (void **)&pdblStartAngle); getGraphicObjectProperty(pthis, __GO_END_ANGLE__, jni_double, (void **)&pdblEndAngle); tab[0] = upperLeftPoint[0]; tab[1] = upperLeftPoint[1]; if (view) { tab[2] = upperLeftPoint[2]; tab[3] = width; tab[4] = height; tab[5] = RAD2DEG(startAngle); tab[6] = RAD2DEG(endAngle); } else { tab[2] = width; tab[3] = height; tab[4] = RAD2DEG(startAngle); tab[5] = RAD2DEG(endAngle); } return (double*)tab; } case __GO_COMPOUND__ : { return (double*)NULL; } case __GO_TEXT__ : { char* parentAxes = NULL; double* textPosition = NULL; int iView = 0; int* piView = &iView; *numrow = 1; getGraphicObjectProperty(pthis, __GO_PARENT_AXES__, jni_string, (void **)&parentAxes); getGraphicObjectProperty(parentAxes, __GO_VIEW__, jni_int, (void**)&piView); *numcol = iView ? 3 : 2; if ((tab = CALLOC((*numrow) * (*numcol), sizeof(double))) == NULL) { *numrow = -1; *numcol = -1; return NULL; } getGraphicObjectProperty(pthis, __GO_POSITION__, jni_double_vector, (void **)&textPosition); tab[0] = textPosition[0]; tab[1] = textPosition[1]; if (iView) { tab[2] = textPosition[2]; } return (double*)tab; } case __GO_SEGS__ : { int iView = 0; int* piView = &iView; int iNumArrows = 0; int* piNumArrows = &iNumArrows; char* parentAxes = NULL; double* arrowBases = NULL; double* arrowDirections = NULL; getGraphicObjectProperty(pthis, __GO_NUMBER_ARROWS__, jni_int, (void**)&piNumArrows); *numrow = iNumArrows; /* only two coordinates are displayed if the axe is in 2d and the z coordinates has never been modified */ getGraphicObjectProperty(pthis, __GO_PARENT_AXES__, jni_string, (void **)&parentAxes); getGraphicObjectProperty(parentAxes, __GO_VIEW__, jni_int, (void**)&piView); if (iView == 0) // 2-D { *numcol = 2; } else // 3-D { *numcol = 3; } if ((tab = CALLOC(2 * (*numrow) * (*numcol), sizeof(double))) == NULL) { *numrow = -1; *numcol = -1; return NULL; } getGraphicObjectProperty(pthis, __GO_BASE__, jni_double_vector, (void **)&arrowBases); getGraphicObjectProperty(pthis, __GO_DIRECTION__, jni_double_vector, (void **)&arrowDirections); for (i = 0; i < *numrow; i++) { tab[2 * i] = arrowBases[3 * i]; tab[2 * i + 1] = arrowDirections[3 * i]; tab[2 * (*numrow) + 2 * i] = arrowBases[3 * i + 1]; tab[2 * (*numrow) + 2 * i + 1] = arrowDirections[3 * i + 1]; if (*numcol == 3) { tab[4 * (*numrow) + 2 * i] = arrowBases[3 * i + 2]; tab[4 * (*numrow) + 2 * i + 1] = arrowDirections[3 * i + 2]; } } /* There are twice as many points as arrows (2 endpoints) */ *numrow = 2 * (*numrow); return (double*)tab; } case __GO_FAC3D__ : case __GO_PLOT3D__ : { *numrow = -1; *numcol = -1; return (double*) NULL; } case __GO_MATPLOT__ : { int nx = 0; int *piNx = &nx; int ny = 0; int *piNy = &ny; double* data; getGraphicObjectProperty(pthis, __GO_DATA_MODEL_NUM_X__, jni_int, (void**)&piNx); getGraphicObjectProperty(pthis, __GO_DATA_MODEL_NUM_Y__, jni_int, (void**)&piNy); /* The z data matrix has (ny-1) rows and (nx-1) cols */ nx = nx - 1; ny = ny - 1; *numrow = ny; *numcol = nx; if ((tab = CALLOC(nx * ny, sizeof(double))) == NULL) { *numrow = -1; *numcol = -1; return (double*)NULL; } getGraphicObjectProperty(pthis, __GO_DATA_MODEL_Z__, jni_double_vector, (void **)&data); for (i = 0; i < nx * ny; i++) { tab[i] = data[i]; } return (double*)tab; } case __GO_FEC__ : { double* coordinates = NULL; double* values = NULL; int iTmp = 0; int* piTmp = &iTmp; *numcol = 3; getGraphicObjectProperty(pthis, __GO_DATA_MODEL_NUM_VERTICES__, jni_int, (void**)&piTmp); *numrow = iTmp; if ((tab = CALLOC(*numrow * 3, sizeof(double))) == NULL) { *numrow = -1; *numcol = -1; return (double*)NULL; } getGraphicObjectProperty(pthis, __GO_DATA_MODEL_COORDINATES__, jni_double_vector, (void **)&coordinates); getGraphicObjectProperty(pthis, __GO_DATA_MODEL_VALUES__, jni_double_vector, (void **)&values); for (i = 0; i < *numrow; i++) { tab[i] = coordinates[3 * i]; tab[*numrow + i] = coordinates[3 * i + 1]; tab[*numrow * 2 + i] = values[i]; } return (double*)tab; } case __GO_LEGEND__ : case __GO_AXES__ : case __GO_LABEL__ : default : { *numrow = -2; *numcol = -2; return (double*)NULL; } } #if 0 case SCI_UIMENU: #endif return (double*)NULL; }
int main(int argc, char **argv) #endif #endif { int i; #if HAVE_GSL /* if HAVE_GSL and the environment variable GSL_IEEE_MODE exists, use it */ /* GSL_IEEE_MODE=double-precision,mask-underflow,mask-denormalized */ if (getenv("GSL_IEEE_MODE") != NULL) gsl_ieee_env_setup(); gsl_set_error_handler(snd_gsl_error); #endif #if ENABLE_NLS && HAVE_GETTEXT && defined(LOCALE_DIR) /* both flags needed to avoid idiotic confusion on the Sun */ #if HAVE_SETLOCALE setlocale (LC_ALL, ""); #endif bindtextdomain (PACKAGE, LOCALE_DIR); textdomain (PACKAGE); /* (bindtextdomain "snd" "/usr/local/share/locale") (textdomain "snd") (define _ gettext) (display (_ "no selection")) but that is limited to Snd's messages */ #endif ss = (snd_state *)CALLOC(1, sizeof(snd_state)); ss->fam_ok = false; ss->startup_errors = NULL; mus_sound_initialize(); /* has to precede version check (mus_audio_moniker needs to be setup in Alsa/Oss) */ #if HAVE_FORTH || HAVE_GAUCHE || HAVE_RUBY xen_initialize(); #endif for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--version") == 0) { fprintf(stdout, version_info()); snd_exit(0); } else { if (strcmp(argv[i], "--help") == 0) { fprintf(stdout, _("Snd is a sound editor; see http://ccrma.stanford.edu/software/snd/.\n")); fprintf(stdout, version_info()); snd_exit(0); } } } initialize_format_lists(); snd_set_global_defaults(false); #if MUS_DEBUGGING ss->Trap_Segfault = false; #else ss->Trap_Segfault = DEFAULT_TRAP_SEGFAULT; #endif ss->jump_ok = false; allocate_regions(max_regions(ss)); ss->init_window_x = DEFAULT_INIT_WINDOW_X; ss->init_window_y = DEFAULT_INIT_WINDOW_Y; ss->init_window_width = DEFAULT_INIT_WINDOW_WIDTH; ss->init_window_height = DEFAULT_INIT_WINDOW_HEIGHT; ss->click_time = 100; init_sound_file_extensions(); ss->max_sounds = 4; /* expands to accommodate any number of files */ ss->sound_sync_max = 0; ss->stopped_explicitly = false; /* C-g sets this flag so that we can interrupt various loops */ ss->checking_explicitly = false; ss->reloading_updated_file = 0; ss->selected_sound = NO_SELECTION; ss->sounds = (snd_info **)CALLOC(ss->max_sounds, sizeof(snd_info *)); ss->print_choice = PRINT_SND; ss->graph_hook_active = false; ss->lisp_graph_hook_active = false; ss->error_lock = false; ss->exiting = false; ss->deferred_regions = 0; ss->fam_connection = NULL; ss->snd_error_data = NULL; ss->snd_error_handler = NULL; ss->snd_warning_data = NULL; ss->snd_warning_handler = NULL; ss->xen_error_data = NULL; ss->xen_error_handler = NULL; #if USE_NO_GUI || HAVE_RUBY || HAVE_FORTH || HAVE_GAUCHE ss->catch_exists = 1; /* scm_shell for USE_NO_GUI case */ #else ss->catch_exists = 0; #endif #if HAVE_GL && MUS_WITH_GL2PS ss->gl_printing = false; #endif g_xen_initialize(); ss->search_proc = XEN_UNDEFINED; ss->search_expr = NULL; ss->search_tree = NULL; mus_error_set_handler(mus_error_to_snd); mus_print_set_handler(mus_print_to_snd); initialize_load_path(); /* merge SND_PATH entries into the load-path */ #ifdef SND_AS_PD_EXTERNAL return; #else #ifdef SND_AS_WIDGET return(ss); #else snd_doit(argc, argv); #if (!HAVE_GUILE) return(0); #endif #endif #endif }
/* Create the device specific rendering context. */ GLboolean r200CreateContext( gl_api api, const struct gl_config *glVisual, __DRIcontext *driContextPriv, unsigned major_version, unsigned minor_version, uint32_t flags, unsigned *error, void *sharedContextPrivate) { __DRIscreen *sPriv = driContextPriv->driScreenPriv; radeonScreenPtr screen = (radeonScreenPtr)(sPriv->driverPrivate); struct dd_function_table functions; r200ContextPtr rmesa; struct gl_context *ctx; int i; int tcl_mode; switch (api) { case API_OPENGL: if (major_version > 1 || minor_version > 3) { *error = __DRI_CTX_ERROR_BAD_VERSION; return GL_FALSE; } break; case API_OPENGLES: break; default: *error = __DRI_CTX_ERROR_BAD_API; return GL_FALSE; } /* Flag filtering is handled in dri2CreateContextAttribs. */ (void) flags; assert(glVisual); assert(driContextPriv); assert(screen); /* Allocate the R200 context */ rmesa = (r200ContextPtr) CALLOC( sizeof(*rmesa) ); if ( !rmesa ) { *error = __DRI_CTX_ERROR_NO_MEMORY; return GL_FALSE; } rmesa->radeon.radeonScreen = screen; r200_init_vtbl(&rmesa->radeon); /* init exp fog table data */ radeonInitStaticFogData(); /* Parse configuration files. * Do this here so that initialMaxAnisotropy is set before we create * the default textures. */ driParseConfigFiles (&rmesa->radeon.optionCache, &screen->optionCache, screen->driScreen->myNum, "r200"); rmesa->radeon.initialMaxAnisotropy = driQueryOptionf(&rmesa->radeon.optionCache, "def_max_anisotropy"); if ( sPriv->drm_version.major == 1 && driQueryOptionb( &rmesa->radeon.optionCache, "hyperz" ) ) { if ( sPriv->drm_version.minor < 13 ) fprintf( stderr, "DRM version 1.%d too old to support HyperZ, " "disabling.\n", sPriv->drm_version.minor ); else rmesa->using_hyperz = GL_TRUE; } if ( sPriv->drm_version.minor >= 15 ) rmesa->texmicrotile = GL_TRUE; /* Init default driver functions then plug in our R200-specific functions * (the texture functions are especially important) */ _mesa_init_driver_functions(&functions); r200InitDriverFuncs(&functions); r200InitIoctlFuncs(&functions); r200InitStateFuncs(&rmesa->radeon, &functions); r200InitTextureFuncs(&rmesa->radeon, &functions); r200InitShaderFuncs(&functions); radeonInitQueryObjFunctions(&functions); if (!radeonInitContext(&rmesa->radeon, &functions, glVisual, driContextPriv, sharedContextPrivate)) { FREE(rmesa); *error = __DRI_CTX_ERROR_NO_MEMORY; return GL_FALSE; } rmesa->radeon.swtcl.RenderIndex = ~0; rmesa->radeon.hw.all_dirty = 1; /* Set the maximum texture size small enough that we can guarentee that * all texture units can bind a maximal texture and have all of them in * texturable memory at once. Depending on the allow_large_textures driconf * setting allow larger textures. */ ctx = rmesa->radeon.glCtx; ctx->Const.MaxTextureUnits = driQueryOptioni (&rmesa->radeon.optionCache, "texture_units"); ctx->Const.MaxTextureImageUnits = ctx->Const.MaxTextureUnits; ctx->Const.MaxTextureCoordUnits = ctx->Const.MaxTextureUnits; ctx->Const.MaxCombinedTextureImageUnits = ctx->Const.MaxTextureUnits; ctx->Const.StripTextureBorder = GL_TRUE; i = driQueryOptioni( &rmesa->radeon.optionCache, "allow_large_textures"); /* FIXME: When no memory manager is available we should set this * to some reasonable value based on texture memory pool size */ ctx->Const.MaxTextureLevels = 12; ctx->Const.Max3DTextureLevels = 9; ctx->Const.MaxCubeTextureLevels = 12; ctx->Const.MaxTextureRectSize = 2048; ctx->Const.MaxRenderbufferSize = 2048; ctx->Const.MaxTextureMaxAnisotropy = 16.0; /* No wide AA points. */ ctx->Const.MinPointSize = 1.0; ctx->Const.MinPointSizeAA = 1.0; ctx->Const.MaxPointSizeAA = 1.0; ctx->Const.PointSizeGranularity = 0.0625; ctx->Const.MaxPointSize = 2047.0; /* mesa initialization problem - _mesa_init_point was already called */ ctx->Point.MaxSize = ctx->Const.MaxPointSize; ctx->Const.MinLineWidth = 1.0; ctx->Const.MinLineWidthAA = 1.0; ctx->Const.MaxLineWidth = 10.0; ctx->Const.MaxLineWidthAA = 10.0; ctx->Const.LineWidthGranularity = 0.0625; ctx->Const.VertexProgram.MaxNativeInstructions = R200_VSF_MAX_INST; ctx->Const.VertexProgram.MaxNativeAttribs = 12; ctx->Const.VertexProgram.MaxNativeTemps = R200_VSF_MAX_TEMPS; ctx->Const.VertexProgram.MaxNativeParameters = R200_VSF_MAX_PARAM; ctx->Const.VertexProgram.MaxNativeAddressRegs = 1; ctx->Const.MaxDrawBuffers = 1; ctx->Const.MaxColorAttachments = 1; _mesa_set_mvp_with_dp4( ctx, GL_TRUE ); /* Initialize the software rasterizer and helper modules. */ _swrast_CreateContext( ctx ); _vbo_CreateContext( ctx ); _tnl_CreateContext( ctx ); _swsetup_CreateContext( ctx ); _ae_create_context( ctx ); /* Install the customized pipeline: */ _tnl_destroy_pipeline( ctx ); _tnl_install_pipeline( ctx, r200_pipeline ); /* Try and keep materials and vertices separate: */ /* _tnl_isolate_materials( ctx, GL_TRUE ); */ /* Configure swrast and TNL to match hardware characteristics: */ _swrast_allow_pixel_fog( ctx, GL_FALSE ); _swrast_allow_vertex_fog( ctx, GL_TRUE ); _tnl_allow_pixel_fog( ctx, GL_FALSE ); _tnl_allow_vertex_fog( ctx, GL_TRUE ); for ( i = 0 ; i < R200_MAX_TEXTURE_UNITS ; i++ ) { _math_matrix_ctr( &rmesa->TexGenMatrix[i] ); _math_matrix_set_identity( &rmesa->TexGenMatrix[i] ); } _math_matrix_ctr( &rmesa->tmpmat ); _math_matrix_set_identity( &rmesa->tmpmat ); ctx->Extensions.ARB_half_float_pixel = true; ctx->Extensions.ARB_occlusion_query = true; ctx->Extensions.ARB_texture_border_clamp = true; ctx->Extensions.ARB_texture_env_combine = true; ctx->Extensions.ARB_texture_env_dot3 = true; ctx->Extensions.ARB_texture_env_crossbar = true; ctx->Extensions.EXT_blend_color = true; ctx->Extensions.EXT_blend_minmax = true; ctx->Extensions.EXT_fog_coord = true; ctx->Extensions.EXT_packed_depth_stencil = true; ctx->Extensions.EXT_secondary_color = true; ctx->Extensions.EXT_texture_env_dot3 = true; ctx->Extensions.EXT_texture_filter_anisotropic = true; ctx->Extensions.EXT_texture_mirror_clamp = true; ctx->Extensions.ATI_texture_env_combine3 = true; ctx->Extensions.ATI_texture_mirror_once = true; ctx->Extensions.MESA_pack_invert = true; ctx->Extensions.NV_blend_square = true; ctx->Extensions.NV_texture_rectangle = true; #if FEATURE_OES_EGL_image ctx->Extensions.OES_EGL_image = true; #endif ctx->Extensions.EXT_framebuffer_object = true; ctx->Extensions.ARB_occlusion_query = true; if (!(rmesa->radeon.radeonScreen->chip_flags & R200_CHIPSET_YCBCR_BROKEN)) { /* yuv textures don't work with some chips - R200 / rv280 okay so far others get the bit ordering right but don't actually do YUV-RGB conversion */ ctx->Extensions.MESA_ycbcr_texture = true; } if (rmesa->radeon.glCtx->Mesa_DXTn) { ctx->Extensions.EXT_texture_compression_s3tc = true; ctx->Extensions.S3_s3tc = true; } else if (driQueryOptionb (&rmesa->radeon.optionCache, "force_s3tc_enable")) { ctx->Extensions.EXT_texture_compression_s3tc = true; } ctx->Extensions.ARB_texture_cube_map = true; ctx->Extensions.EXT_blend_equation_separate = true; ctx->Extensions.EXT_blend_func_separate = true; ctx->Extensions.ARB_vertex_program = true; ctx->Extensions.EXT_gpu_program_parameters = true; ctx->Extensions.NV_vertex_program = driQueryOptionb(&rmesa->radeon.optionCache, "nv_vertex_program"); ctx->Extensions.ATI_fragment_shader = (ctx->Const.MaxTextureUnits == 6); ctx->Extensions.ARB_point_sprite = true; ctx->Extensions.EXT_point_parameters = true; #if 0 r200InitDriverFuncs( ctx ); r200InitIoctlFuncs( ctx ); r200InitStateFuncs( ctx ); r200InitTextureFuncs( ctx ); #endif /* plug in a few more device driver functions */ /* XXX these should really go right after _mesa_init_driver_functions() */ radeon_fbo_init(&rmesa->radeon); radeonInitSpanFuncs( ctx ); r200InitTnlFuncs( ctx ); r200InitState( rmesa ); r200InitSwtcl( ctx ); rmesa->prefer_gart_client_texturing = (getenv("R200_GART_CLIENT_TEXTURES") != 0); tcl_mode = driQueryOptioni(&rmesa->radeon.optionCache, "tcl_mode"); if (driQueryOptionb(&rmesa->radeon.optionCache, "no_rast")) { fprintf(stderr, "disabling 3D acceleration\n"); FALLBACK(rmesa, R200_FALLBACK_DISABLE, 1); } else if (tcl_mode == DRI_CONF_TCL_SW || getenv("R200_NO_TCL") || !(rmesa->radeon.radeonScreen->chip_flags & RADEON_CHIPSET_TCL)) { if (rmesa->radeon.radeonScreen->chip_flags & RADEON_CHIPSET_TCL) { rmesa->radeon.radeonScreen->chip_flags &= ~RADEON_CHIPSET_TCL; fprintf(stderr, "Disabling HW TCL support\n"); } TCL_FALLBACK(rmesa->radeon.glCtx, R200_TCL_FALLBACK_TCL_DISABLE, 1); } _mesa_compute_version(ctx); *error = __DRI_CTX_ERROR_SUCCESS; return GL_TRUE; }
/* Create the device specific context. */ GLboolean r128CreateContext( const __GLcontextModes *glVisual, __DRIcontextPrivate *driContextPriv, void *sharedContextPrivate ) { GLcontext *ctx, *shareCtx; __DRIscreenPrivate *sPriv = driContextPriv->driScreenPriv; struct dd_function_table functions; r128ContextPtr rmesa; r128ScreenPtr r128scrn; int i; /* Allocate the r128 context */ rmesa = (r128ContextPtr) CALLOC( sizeof(*rmesa) ); if ( !rmesa ) return GL_FALSE; /* Init default driver functions then plug in our Radeon-specific functions * (the texture functions are especially important) */ _mesa_init_driver_functions( &functions ); r128InitDriverFuncs( &functions ); r128InitIoctlFuncs( &functions ); r128InitTextureFuncs( &functions ); /* Allocate the Mesa context */ if (sharedContextPrivate) shareCtx = ((r128ContextPtr) sharedContextPrivate)->glCtx; else shareCtx = NULL; rmesa->glCtx = _mesa_create_context(glVisual, shareCtx, &functions, (void *) rmesa); if (!rmesa->glCtx) { FREE(rmesa); return GL_FALSE; } driContextPriv->driverPrivate = rmesa; ctx = rmesa->glCtx; rmesa->driContext = driContextPriv; rmesa->driScreen = sPriv; rmesa->driDrawable = NULL; rmesa->hHWContext = driContextPriv->hHWContext; rmesa->driHwLock = &sPriv->pSAREA->lock; rmesa->driFd = sPriv->fd; r128scrn = rmesa->r128Screen = (r128ScreenPtr)(sPriv->private); /* Parse configuration files */ driParseConfigFiles (&rmesa->optionCache, &r128scrn->optionCache, r128scrn->driScreen->myNum, "r128"); rmesa->sarea = (drm_r128_sarea_t *)((char *)sPriv->pSAREA + r128scrn->sarea_priv_offset); rmesa->CurrentTexObj[0] = NULL; rmesa->CurrentTexObj[1] = NULL; (void) memset( rmesa->texture_heaps, 0, sizeof( rmesa->texture_heaps ) ); make_empty_list( & rmesa->swapped ); rmesa->nr_heaps = r128scrn->numTexHeaps; for ( i = 0 ; i < rmesa->nr_heaps ; i++ ) { rmesa->texture_heaps[i] = driCreateTextureHeap( i, rmesa, r128scrn->texSize[i], 12, R128_NR_TEX_REGIONS, (drmTextureRegionPtr)rmesa->sarea->tex_list[i], &rmesa->sarea->tex_age[i], &rmesa->swapped, sizeof( r128TexObj ), (destroy_texture_object_t *) r128DestroyTexObj ); driSetTextureSwapCounterLocation( rmesa->texture_heaps[i], & rmesa->c_textureSwaps ); } rmesa->texture_depth = driQueryOptioni (&rmesa->optionCache, "texture_depth"); if (rmesa->texture_depth == DRI_CONF_TEXTURE_DEPTH_FB) rmesa->texture_depth = ( r128scrn->cpp == 4 ) ? DRI_CONF_TEXTURE_DEPTH_32 : DRI_CONF_TEXTURE_DEPTH_16; rmesa->RenderIndex = -1; /* Impossible value */ rmesa->vert_buf = NULL; rmesa->num_verts = 0; RENDERINPUTS_ONES( rmesa->tnl_state_bitset ); /* Set the maximum texture size small enough that we can guarentee that * all texture units can bind a maximal texture and have them both in * texturable memory at once. */ ctx->Const.MaxTextureUnits = 2; ctx->Const.MaxTextureImageUnits = 2; ctx->Const.MaxTextureCoordUnits = 2; driCalculateMaxTextureLevels( rmesa->texture_heaps, rmesa->nr_heaps, & ctx->Const, 4, 10, /* max 2D texture size is 1024x1024 */ 0, /* 3D textures unsupported. */ 0, /* cube textures unsupported. */ 0, /* texture rectangles unsupported. */ 11, GL_FALSE, 0 ); /* No wide points. */ ctx->Const.MinPointSize = 1.0; ctx->Const.MinPointSizeAA = 1.0; ctx->Const.MaxPointSize = 1.0; ctx->Const.MaxPointSizeAA = 1.0; /* No wide lines. */ ctx->Const.MinLineWidth = 1.0; ctx->Const.MinLineWidthAA = 1.0; ctx->Const.MaxLineWidth = 1.0; ctx->Const.MaxLineWidthAA = 1.0; ctx->Const.LineWidthGranularity = 1.0; #if ENABLE_PERF_BOXES rmesa->boxes = driQueryOptionb(&rmesa->optionCache, "performance_boxes"); #endif /* Initialize the software rasterizer and helper modules. */ _swrast_CreateContext( ctx ); _vbo_CreateContext( ctx ); _tnl_CreateContext( ctx ); _swsetup_CreateContext( ctx ); /* Install the customized pipeline: */ /* _tnl_destroy_pipeline( ctx ); */ /* _tnl_install_pipeline( ctx, r128_pipeline ); */ /* Configure swrast and T&L to match hardware characteristics: */ _swrast_allow_pixel_fog( ctx, GL_FALSE ); _swrast_allow_vertex_fog( ctx, GL_TRUE ); _tnl_allow_pixel_fog( ctx, GL_FALSE ); _tnl_allow_vertex_fog( ctx, GL_TRUE ); driInitExtensions( ctx, card_extensions, GL_TRUE ); if (sPriv->drmMinor >= 4) _mesa_enable_extension( ctx, "GL_MESA_ycbcr_texture" ); r128InitTriFuncs( ctx ); r128DDInitStateFuncs( ctx ); r128DDInitSpanFuncs( ctx ); r128DDInitState( rmesa ); rmesa->vblank_flags = (rmesa->r128Screen->irq != 0) ? driGetDefaultVBlankFlags(&rmesa->optionCache) : VBLANK_FLAG_NO_IRQ; driContextPriv->driverPrivate = (void *)rmesa; #if DO_DEBUG R128_DEBUG = driParseDebugString( getenv( "R128_DEBUG" ), debug_control ); #endif if (driQueryOptionb(&rmesa->optionCache, "no_rast")) { fprintf(stderr, "disabling 3D acceleration\n"); FALLBACK(rmesa, R128_FALLBACK_DISABLE, 1); } return GL_TRUE; }
/* transform a tgt scotch file into a topology file*/ tm_topology_t * tgt_to_tm(char *filename, double **pcost) { tm_topology_t *topology = NULL; FILE *pf = NULL; char line[1024]; char *s = NULL; double *cost = NULL; int i; pf = fopen(filename,"r"); if(!pf){ if(get_verbose_level() >= CRITICAL) fprintf(stderr,"Cannot open %s\n",filename); exit(-1); } if(get_verbose_level() >= INFO) printf("Reading TGT file: %s\n",filename); fgets(line,1024,pf); s = strstr(line,"tleaf"); if(!s){ if(get_verbose_level() >= CRITICAL) fprintf(stderr,"Syntax error! %s is not a tleaf file\n",filename); exit(-1); } s += 5; while(isspace(*s)) s++; topology = (tm_topology_t*)MALLOC(sizeof(tm_topology_t)); topology->nb_levels = atoi(strtok(s," "))+1; topology->arity = (int*)MALLOC(sizeof(int)*topology->nb_levels); cost = (double*)CALLOC(topology->nb_levels,sizeof(double)); for( i = 0 ; i < topology->nb_levels-1 ; i++ ){ topology->arity[i] = atoi(strtok(NULL," ")); cost[i] = atoi(strtok(NULL," ")); } topology->arity[topology->nb_levels-1] = 0; /* cost[topology->nb_levels-1]=0; */ /*aggregate costs*/ for( i = topology->nb_levels-2 ; i >= 0 ; i-- ) cost[i] += cost[i+1]; build_synthetic_proc_id(topology); *pcost = cost; /* FREE(cost); */ /* topology->arity[0]=nb_proc; topology->nb_levels=decompose((int)ceil((1.0*nb_obj)/nb_proc),1,topology->arity); printf("levels=%d\n",topology->nb_levels); */ if(get_verbose_level() >= INFO) printf("Topology built from %s!\n",filename); return topology; }
StorageData *init_storage(AppData *ad) { CALLED(); StorageData *sd = CALLOC(1, sizeof(StorageData)); eet_init(); ecore_file_init(); sd->ef = eet_open(STORAGE_FILEPATH, EET_FILE_MODE_READ_WRITE); /* if (sd->ef) { int read_size; indexType *read_data; read_data = eet_read(sd->ef, STORAGE_KEY_INDEX, &read_size); int storage_size = sizeof(indexType) * STORAGE_ITEM_CNT; int copy_size = storage_size < read_size ? storage_size : read_size; if (read_data) { indexType *temp = MALLOC(read_size); if (!temp) return sd; memcpy(temp, read_data, read_size); int i; int copy_cnt = copy_size/sizeof(indexType); for (i = 0; i < copy_cnt; i++) { int maxIndex = getMaxIndex(temp, copy_cnt); if (temp[maxIndex] == STORAGE_INDEX_ITEM_NONE) break; sd->itemTable[i] = storage_item_load(sd, maxIndex); if (sd->itemTable[i]) sd->indexTable[i] = temp[maxIndex]; temp[maxIndex] = STORAGE_INDEX_ITEM_NONE; DMSG("load storage item index %d\n", i); } for (i = copy_cnt - 1; i >= 0; i--) { if (sd->itemTable[i]) item_add_by_CNP_ITEM(ad, sd->itemTable[i]); } } else { DMSG("load storage index failed\n"); } } else DMSG("storage ef is NULLd\n"); */ dump_items(sd); ad->storage_item_add = storage_item_write; ad->storage_item_del = storage_item_delete; // ad->storage_item_load = storage_item_load; return sd; }