char* LytCtgData::readName(char* s, GHash<int>& names) { char* p=strchrs(s, " \t"); if (p!=NULL) { char* tmp; char* tmp2; GMALLOC(tmp, (p-s+30)*sizeof(char)); strncpy(tmp, s,p-s); tmp[p-s]='\0'; GMALLOC(tmp2, (p-s+30)*sizeof(char)); strcpy(tmp2, tmp); //make it unique (by simple versioning) int v=0; while (names.hasKey(tmp2)) { v++; sprintf(tmp2, "%s.%d", tmp, v); } name=Gstrdup(tmp2); GFREE(tmp); GFREE(tmp2); names.shkAdd(name, new int(1)); p++; } else { GMessage("LytCtgData::readName: Cannot find the token delimiter in:\n%s\n", s); } return p; }
static void gst_motioncells_update_motion_cells (GstMotioncells * filter) { int i = 0; int cellscnt = 0; int j = 0; int newcellscnt; motioncellidx *motioncellsidx; for (i = 0; i < filter->motioncells_count; i++) { if ((filter->gridx <= filter->motioncellsidx[i].columnidx) || (filter->gridy <= filter->motioncellsidx[i].lineidx)) { cellscnt++; } } newcellscnt = filter->motioncells_count - cellscnt; motioncellsidx = g_new0 (motioncellidx, newcellscnt); for (i = 0; i < filter->motioncells_count; i++) { if ((filter->motioncellsidx[i].lineidx < filter->gridy) && (filter->motioncellsidx[i].columnidx < filter->gridx)) { motioncellsidx[j].lineidx = filter->motioncellsidx[i].lineidx; motioncellsidx[j].columnidx = filter->motioncellsidx[i].columnidx; j++; } } GFREE (filter->motioncellsidx); filter->motioncells_count = newcellscnt; filter->motioncellsidx = g_new0 (motioncellidx, filter->motioncells_count); j = 0; for (i = 0; i < filter->motioncells_count; i++) { filter->motioncellsidx[i].lineidx = motioncellsidx[j].lineidx; filter->motioncellsidx[i].columnidx = motioncellsidx[j].columnidx; j++; } GFREE (motioncellsidx); }
GArgs::~GArgs() { int i; for (i=0; i<fmtcount; i++) GFREE(fmt[i].opt); GFREE(fmt); for (i=0; i<count; i++) { GFREE(args[i].opt); GFREE(args[i].value); } GFREE(args); }
int GArgs::validLongOpt(char* o, char* to) { char* pstr=Gstrdup(o,to); for (int i=0; i<fmtcount; i++) { if (fmt[i].longopt && strcmp(fmt[i].longopt, pstr)==0) { GFREE(pstr); return i; } } GFREE(pstr); return -1; }
int Gmkdir(const char *path, bool recursive, int perms) { if (path==NULL || path[0]==0) return -1; mode_t process_mask = umask(0); //is this really needed? if (!recursive) { int r=G_mkdir(path, perms); if (r!=0) GMessage("Warning: G_mkdir(%s) failed: %s\n", path, strerror(errno)); umask(process_mask); return r; } int plen=strlen(path); char* gpath=NULL; //make sure gpath ends with / if (path[plen-1]=='/') { gpath=Gstrdup(path); } else { GMALLOC(gpath, plen+2); strcpy(gpath,path); strcat(gpath, "/"); ++plen; } //char* ss=gpath+plen-1; char* psep = gpath+plen-1; //start at the last / GDynArray<char*> dirstack(4); // stack of directories that should be created while (psep>gpath && *(psep-1)=='/') --psep; //skip double slashes *psep='\0'; int fexists=0; while ((fexists=fileExists(gpath))==0) { dirstack.Push(psep); do { --psep; } while (psep>gpath && *psep!='/'); if (psep<=gpath) { psep=NULL; break; } while (psep>gpath && *(psep-1)=='/') --psep; *psep='\0'; } if (psep) *psep='/'; while (dirstack.Count()>0) { psep=dirstack.Pop(); int mkdir_err=0; if ((mkdir_err=G_mkdir(gpath, perms))!=0) { GMessage("Warning: mkdir(%s) failed: %s\n", gpath, strerror(errno)); GFREE(gpath); umask(process_mask); return -1; } *psep='/'; } GFREE(gpath); umask(process_mask); return 0; }
/* Clean up */ static void gst_motion_cells_finalize (GObject * obj) { GstMotioncells *filter = gst_motion_cells (obj); motion_cells_free (filter->id); //freeing previously allocated dynamic array if (filter->motionmaskcoord_count > 0) { GFREE (filter->motionmaskcoords); } if (filter->motionmaskcells_count > 0) { GFREE (filter->motionmaskcellsidx); } if (filter->motioncells_count > 0) { GFREE (filter->motioncellsidx); } if (filter->cvImage) { cvReleaseImage (&filter->cvImage); } GFREE (filter->motioncellscolor); GFREE (filter->prev_datafile); GFREE (filter->cur_datafile); GFREE (filter->basename_datafile); GFREE (filter->datafile_extension); g_mutex_free (filter->propset_mutex); G_OBJECT_CLASS (parent_class)->finalize (obj); }
char* replaceStr(char* &str, char* newvalue) { if (str!=NULL) GFREE(str); if (newvalue==NULL) { return NULL; } GMALLOC(str, strlen(newvalue)+1); strcpy(str,newvalue); return str; }
int GFastaIndex::storeIndex(const char* finame) { //write the hash to a file if (records.Count()==0) GError("Error at GFastaIndex:storeIndex(): no records found!\n"); FILE* fai=fopen(finame, "w"); if (fai==NULL) GError("Error creating fasta index file: %s\n",finame); int rcount=storeIndex(fai); GFREE(fai_name); fai_name=Gstrdup(finame); return rcount; }
bool AceParser::loadContig(int ctgidx, fnLytSeq* seqfn, bool re_pos) { bool forgetCtg = false; if (ctgidx>=contigs.Count()) GError("LayoutParser: invalid contig index '%d'\n", ctgidx); LytCtgData* ctgdata=contigs[ctgidx]; if (re_pos && currentContig!=NULL) { //free previously loaded contig data currentContig->seqs.Clear(); // unless it was a parse() call seqinfo.Clear(); } currentContig=ctgdata; int ctg_numSeqs=ctgdata->numseqs; if (re_pos) { seek(ctgdata->fpos); //position right where the contig definition starts char *r = linebuf->getLine(f,f_pos); if (r==NULL) return false; } if (seqfn!=NULL) { //process the contig sequence! char* ctgseq=readSeq(); forgetCtg=(*seqfn)(numContigs, ctgdata, NULL, ctgseq); GFREE(ctgseq); //obviously the caller should have made a copy } //now look for all the component sequences if (fskipTo("AF ")<0) { GMessage("AceParser: error finding sequence offsets (AF)" " for contig '%s' (%d)\n", ctgdata->name, ctgdata->len); return false; } int numseqs=0; while (startsWith(linebuf->chars(), "AF ",3)) { if (addSeq(linebuf->chars(), ctgdata)==NULL) { GMessage("AceParser: error parsing AF entry:\n%s\n",linebuf->chars()); return false; } numseqs++; //read next line: linebuf->getLine(f,f_pos); } if (numseqs!=ctg_numSeqs) { GMessage("Invalid number of AF entries found (%d) for contig '%s' " "(length %d, numseqs %d)\n", numseqs, ctgdata->name, ctgdata->len, ctg_numSeqs); return false; } //now read each sequence entry off_t seqpos=fskipTo("RD "); numseqs=0; //count again, now the RD entries if (seqpos<0) { GMessage("AceParser: error locating first RD entry for contig '%s'\n", ctgdata->name); return false; } //int numseqs=0; //reading the actual component sequence details while (startsWith(linebuf->chars(), "RD ",3)) { char* s=linebuf->chars()+3; char* p=strchrs(s, " \t"); LytSeqInfo* seq; if (p==NULL) { GMessage("AceParser: Error parsing RD header line:\n%s\n", linebuf->chars()); return false; } *p='\0'; if ((seq=seqinfo.Find(s))==NULL) { GMessage("AceParser: unknown RD encountered: '%s'\n", s); return false; } p++; //now p is in linebuf after the RD name seq->fpos=seqpos; int len; if (sscanf(p, "%d", &len)!=1) { GMessage("AceParser: cannot parse RD length for '%s'\n", s); return false; } seq->setLength(len); //read the sequence data here if a callback fn was given: char* sseq=NULL; if (seqfn!=NULL) sseq=readSeq(seq); //read full sequence here if (fskipTo("QA ")<0) { GMessage("AceParser: Error finding QA entry for read %s! (fpos=%llu)\n", seq->name, (unsigned long long)f_pos); return false; } //parse QA entry: int tmpa, tmpb; if (sscanf(linebuf->chars()+3, "%d %d %d %d", &tmpa, &tmpb, &seq->left,&seq->right)!=4 || seq->left<=0 || seq->right<=0) { GMessage("AceParser: Error parsing QA entry.\n"); return false; } /* if (fskipTo("DS")<0) { GMessage("AceParser: Error closing RD entry ('DS' not found).\n"); return false; } */ seqpos=getFilePos()+1; bool forgetSeq=false; if (seqfn!=NULL) { forgetSeq=(*seqfn)(numContigs, ctgdata, seq, sseq); GFREE(sseq); } if (forgetSeq) { //parsing the whole stream -- aceconv) ctg_numSeqs--; seqinfo.Remove(seq->name); ctgdata->seqs.RemovePtr(seq); } numseqs++; if (numseqs<ctgdata->numseqs) seqpos=fskipTo("RD ", "CO "); //more sequences left to read } if (numseqs!=ctgdata->numseqs) { GMessage("Error: Invalid number of RD entries found (%d) for contig '%s' " "(length %d, numseqs %d)\n", numseqs, ctgdata->name, ctgdata->len, ctg_numSeqs); return false; } if (forgetCtg) { ctgIDs.Remove(ctgdata->name); ctgdata->seqs.Clear(); seqinfo.Clear(); contigs.RemovePtr(ctgdata); } return true; }
GPrivate void urbd_free(RBDataP_t pData) { GFREE(pData); }
~SeqInfo() { GFREE(descr); }
~RefTran() { GFREE(new_name); }
int main(int argc, char * const argv[]) { GArgs args(argc, argv, "hFCq:r:o:"); int e; if ((e=args.isError())>0) GError("%s\nInvalid argument: %s\n", USAGE, argv[e]); if (args.getOpt('h')!=NULL){ GMessage("%s\n", USAGE); exit(1); } args.startNonOpt(); GStr fadb(args.nextNonOpt()); if (fadb.is_empty()) GError("%s Error: multi-fasta file expected!\n",USAGE); GStr fname(fadb); fname.append(".fai"); bool createLocal=(args.getOpt('F')!=NULL); const char* idxname=(createLocal)? NULL : fname.chars(); GFastaIndex faidx(fadb.chars(), idxname); //also tried to load the index if exists in the current directory GStr fnamecwd(fname); //name in current directory (without path) int ip=-1; if ((ip=fnamecwd.rindex(CHPATHSEP))>=0) { fnamecwd.cut(0,ip+1); } if (!createLocal) { //look for existing indexes to load //try the same directory as the fasta file first if (!faidx.hasIndex() and fileExists(fnamecwd.chars())>1) { //try current working directory next faidx.loadIndex(fnamecwd.chars()); } if (!faidx.hasIndex()) {//could not load any index data //try to create it in the same directory as the fasta file GMessage("No fasta index found. Rebuilding..\n"); faidx.buildIndex(); if (faidx.getCount()==0) GError("Error: no fasta records to be indexed!\n"); GMessage("Fasta index rebuilt.\n"); //check if we can create a file there FILE* fcreate=fopen(fname.chars(), "w"); if (fcreate==NULL) GMessage("Warning: cannot create fasta index %s! (permissions?)\n", fname.chars()); else { fclose(fcreate); if (faidx.storeIndex(fname.chars())<faidx.getCount()) GMessage("Warning: error writing the index file %s!\n",fname.chars()); } //creating index file in the same directory as fasta file }//trying to create the index file } if (createLocal || !faidx.hasIndex()) { //simply rebuild the index in the current directory and use it: //remove directories in path, if any if (faidx.getCount()==0) { faidx.buildIndex(); if (faidx.getCount()==0) GError("Error: no fasta records to be indexed!\n"); } if (faidx.storeIndex(fnamecwd.chars())<faidx.getCount()) GMessage("Warning: error writing the index file %s!\n",fnamecwd.chars()); } GStr qry(args.getOpt('q')); if (qry.is_empty()) exit(0); GFastaRec* farec=faidx.getRecord(qry.chars()); if (farec==NULL) { GMessage("Error: couldn't find fasta record for '%s'!\n",qry.chars()); exit(1); } GFaSeqGet faseq(fadb.chars(),farec->seqlen, farec->fpos, farec->line_len, farec->line_blen); //TODO: read these from -r option uint qstart=0; uint qend=0; //farec->seqlen bool revCompl=(args.getOpt('C')!=NULL); char* s=args.getOpt('r'); if (s!=NULL) { char *p=s; while (isdigit(*p)) p++; if (*p=='-') { sscanf(s,"%u-%u",&qstart, &qend); if (qstart==0 || qend==0) GError("Error parsing sequence range: %s\n",s); } else if (*p==':') { int qlen=0; sscanf(s,"%u:%d", &qstart, &qlen); if (qstart==0 || qlen==0) GError("Error parsing sequence range: %s\n",s); qend=qstart+qlen-1; } else if (*p=='.') { sscanf(s,"%u..%u",&qstart, &qend); if (qstart==0 || qend==0) GError("Error parsing sequence range: %s\n",s); } } if (qstart==0) qstart=1; if (qend==0) qend=farec->seqlen; // call faseq.loadall() here if multiple ranges are to be extracted all // over this genomic sequence char* subseq=faseq.copyRange(qstart, qend, revCompl, true); FILE* f_out=NULL; openfwrite(f_out, args, 'o'); if (f_out==NULL) f_out=stdout; writeFasta(f_out, qry.chars(), NULL, subseq, 70, qend-qstart+1); GFREE(subseq); }
int GFastaIndex::buildIndex() { //this parses the whole fasta file, so it could be slow if (fa_name==NULL) GError("Error: GFastaIndex::buildIndex() called with no fasta file!\n"); FILE* fa=fopen(fa_name,"rb"); if (fa==NULL) { GMessage("Warning: cannot open fasta index file: %s!\n",fa_name); return 0; } records.Clear(); GLineReader fl(fa); char* s=NULL; uint seqlen=0; int line_len=0,line_blen=0; bool newSeq=false; //set to true after defline off_t newSeqOffset=0; int prevOffset=0; char* seqname=NULL; int last_len=0; bool mustbeLastLine=false; //true if the line length decreases while ((s=fl.nextLine())!=NULL) { if (s[0]=='>') { if (seqname!=NULL) { if (seqlen==0) GError("Warning: empty FASTA record skipped (%s)!\n",seqname); else { //seqlen!=0 addRecord(seqname, seqlen,newSeqOffset, line_len, line_blen); } } char *p=s; while (*p > 32) p++; *p=0; GFREE(seqname); seqname=Gstrdup(&s[1]); newSeq=true; newSeqOffset=fl.getfpos(); last_len=0; line_len=0; line_blen=0; seqlen=0; mustbeLastLine=false; } //defline parsing else { //sequence line int llen=fl.length(); int lblen=fl.getFpos()-prevOffset; if (newSeq) { //first sequence line after defline line_len=llen; line_blen=lblen; } else {//next seq lines after first if (mustbeLastLine || llen>last_len) GError(ERR_FALINELEN); if (llen<last_len) mustbeLastLine=true; } seqlen+=llen; last_len=llen; newSeq=false; } //sequence line prevOffset=fl.getfpos(); }//for each line of the fasta file if (seqlen>0) addRecord(seqname, seqlen, newSeqOffset, line_len, line_blen); GFREE(seqname); fclose(fa); return records.Count(); }
bool process_transcript(GFastaDb& gfasta, GffObj& gffrec) { //returns true if the transcript passed the filter char* gname=gffrec.getGeneName(); if (gname==NULL) gname=gffrec.getGeneID(); GStr defline(gffrec.getID()); if (f_out && !fmtGTF) { const char* tname=NULL; if ((tname=gffrec.getAttr("transcript_name"))!=NULL) { gffrec.addAttr("Name", tname); gffrec.removeAttr("transcript_name"); } } if (ensembl_convert && startsWith(gffrec.getID(), "ENS")) { const char* biotype=gffrec.getAttr("gene_biotype"); if (biotype) { gffrec.addAttr("type", biotype); gffrec.removeAttr("gene_biotype"); } else { //old Ensembl files lacking gene_biotype gffrec.addAttr("type", gffrec.getTrackName()); } //bool is_gene=false; bool is_pseudo=false; if (strcmp(biotype, "protein_coding")==0 || gffrec.hasCDS()) gffrec.setFeatureName("mRNA"); else { if (strcmp(biotype, "processed_transcript")==0) gffrec.setFeatureName("proc_RNA"); else { //is_gene=endsWith(biotype, "gene"); is_pseudo=strifind(biotype, "pseudo"); if (is_pseudo) { gffrec.setFeatureName("pseudo_RNA"); } else if (endsWith(biotype, "RNA")) { gffrec.setFeatureName(biotype); } else gffrec.setFeatureName("misc_RNA"); } } } if (gname && strcmp(gname, gffrec.getID())!=0) { int* isonum=isoCounter.Find(gname); if (isonum==NULL) { isonum=new int(1); isoCounter.Add(gname,isonum); } else (*isonum)++; defline.appendfmt(" gene=%s", gname); } int seqlen=0; const char* tlabel=tracklabel; if (tlabel==NULL) tlabel=gffrec.getTrackName(); //defline.appendfmt(" track:%s",tlabel); char* cdsnt = NULL; char* cdsaa = NULL; int aalen=0; for (int i=1;i<gffrec.exons.Count();i++) { int ilen=gffrec.exons[i]->start-gffrec.exons[i-1]->end-1; if (ilen>4000000) GMessage("Warning: very large intron (%d) for transcript %s\n", ilen, gffrec.getID()); if (ilen>maxintron) { return false; } } GList<GSeg> seglst(false,true); GFaSeqGet* faseq=fastaSeqGet(gfasta, gffrec); if (spliceCheck && gffrec.exons.Count()>1) { //check introns for splice site consensi ( GT-AG, GC-AG or AT-AC ) if (faseq==NULL) GError("Error: no genomic sequence available!\n"); int glen=gffrec.end-gffrec.start+1; const char* gseq=faseq->subseq(gffrec.start, glen); bool revcompl=(gffrec.strand=='-'); bool ssValid=true; for (int e=1;e<gffrec.exons.Count();e++) { const char* intron=gseq+gffrec.exons[e-1]->end+1-gffrec.start; int intronlen=gffrec.exons[e]->start-gffrec.exons[e-1]->end-1; GSpliceSite acceptorSite(intron,intronlen,true, revcompl); GSpliceSite donorSite(intron,intronlen, false, revcompl); //GMessage("%c intron %d-%d : %s .. %s\n", // gffrec.strand, istart, iend, donorSite.nt, acceptorSite.nt); if (acceptorSite=="AG") { // GT-AG or GC-AG if (!donorSite.canonicalDonor()) { ssValid=false;break; } } else if (acceptorSite=="AC") { // if (donorSite!="AT") { ssValid=false; break; } } else { ssValid=false; break; } } //GFREE(gseq); if (!ssValid) { if (verbose) GMessage("Invalid splice sites found for '%s'\n",gffrec.getID()); return false; //don't print this one! } } bool trprint=true; int stopCodonAdjust=0; int mCDphase=0; bool hasStop=false; if (gffrec.CDphase=='1' || gffrec.CDphase=='2') mCDphase = gffrec.CDphase-'0'; if (f_y!=NULL || f_x!=NULL || validCDSonly) { if (faseq==NULL) GError("Error: no genomic sequence provided!\n"); //if (protmap && fullCDSonly) { //if (protmap && (fullCDSonly || (gffrec.qlen>0 && gffrec.qend==gffrec.qlen))) { if (validCDSonly) { //make sure the stop codon is always included //adjust_stopcodon(gffrec,3); stopCodonAdjust=adjust_stopcodon(gffrec,3); } int strandNum=0; int phaseNum=0; CDS_CHECK: cdsnt=gffrec.getSpliced(faseq, true, &seqlen, NULL, NULL, &seglst); if (cdsnt==NULL) trprint=false; else { //has CDS if (validCDSonly) { cdsaa=translateDNA(cdsnt, aalen, seqlen); char* p=strchr(cdsaa,'.'); hasStop=false; if (p!=NULL) { if (p-cdsaa>=aalen-2) { //stop found as the last codon *p='0';//remove it hasStop=true; if (aalen-2==p-cdsaa) { //previous to last codon is the stop codon //so correct the CDS stop accordingly adjust_stopcodon(gffrec,-3, &seglst); stopCodonAdjust=0; //clear artificial stop adjustment seqlen-=3; cdsnt[seqlen]=0; } aalen=p-cdsaa; } else {//stop found before the last codon trprint=false; } }//stop codon found if (trprint==false) { //failed CDS validity check //in-frame stop codon found if (altPhases && phaseNum<3) { phaseNum++; gffrec.CDphase = '0'+((mCDphase+phaseNum)%3); GFREE(cdsaa); goto CDS_CHECK; } if (gffrec.exons.Count()==1 && bothStrands) { strandNum++; phaseNum=0; if (strandNum<2) { GFREE(cdsaa); gffrec.strand = (gffrec.strand=='-') ? '+':'-'; goto CDS_CHECK; //repeat the CDS check for a different frame } } if (verbose) GMessage("In-frame STOP found for '%s'\n",gffrec.getID()); } //has in-frame STOP if (fullCDSonly) { if (!hasStop || cdsaa[0]!='M') trprint=false; } } // CDS check requested } //has CDS } //translation or codon check/output was requested if (!trprint) { GFREE(cdsnt); GFREE(cdsaa); return false; } if (stopCodonAdjust>0 && !hasStop) { //restore stop codon location adjust_stopcodon(gffrec, -stopCodonAdjust, &seglst); if (cdsnt!=NULL && seqlen>0) { seqlen-=stopCodonAdjust; cdsnt[seqlen]=0; } if (cdsaa!=NULL) aalen--; } if (f_y!=NULL) { //CDS translation fasta output requested //char* if (cdsaa==NULL) { //translate now if not done before cdsaa=translateDNA(cdsnt, aalen, seqlen); } if (fullattr && gffrec.attrs!=NULL) { //append all attributes found for each transcripts for (int i=0;i<gffrec.attrs->Count();i++) { defline.append(" "); defline.append(gffrec.getAttrName(i)); defline.append("="); defline.append(gffrec.getAttrValue(i)); } } printFasta(f_y, defline, cdsaa, aalen); } if (f_x!=NULL) { //CDS only if (writeExonSegs) { defline.append(" loc:"); defline.append(gffrec.getGSeqName()); defline.appendfmt("(%c)",gffrec.strand); //warning: not CDS coordinates are written here, but the exon ones defline+=(int)gffrec.start; defline+=(char)'-'; defline+=(int)gffrec.end; // -- here these are CDS substring coordinates on the spliced sequence: defline.append(" segs:"); for (int i=0;i<seglst.Count();i++) { if (i>0) defline.append(","); defline+=(int)seglst[i]->start; defline.append("-"); defline+=(int)seglst[i]->end; } } if (fullattr && gffrec.attrs!=NULL) { //append all attributes found for each transcript for (int i=0;i<gffrec.attrs->Count();i++) { defline.append(" "); defline.append(gffrec.getAttrName(i)); defline.append("="); defline.append(gffrec.getAttrValue(i)); } } printFasta(f_x, defline, cdsnt, seqlen); } GFREE(cdsnt); GFREE(cdsaa); if (f_w!=NULL) { //write spliced exons uint cds_start=0; uint cds_end=0; seglst.Clear(); char* exont=gffrec.getSpliced(faseq, false, &seqlen, &cds_start, &cds_end, &seglst); if (exont!=NULL) { if (gffrec.CDstart>0) { defline.appendfmt(" CDS=%d-%d", cds_start, cds_end); } if (writeExonSegs) { defline.append(" loc:"); defline.append(gffrec.getGSeqName()); defline+=(char)'|'; defline+=(int)gffrec.start; defline+=(char)'-'; defline+=(int)gffrec.end; defline+=(char)'|'; defline+=(char)gffrec.strand; defline.append(" exons:"); for (int i=0;i<gffrec.exons.Count();i++) { if (i>0) defline.append(","); defline+=(int)gffrec.exons[i]->start; defline.append("-"); defline+=(int)gffrec.exons[i]->end; } defline.append(" segs:"); for (int i=0;i<seglst.Count();i++) { if (i>0) defline.append(","); defline+=(int)seglst[i]->start; defline.append("-"); defline+=(int)seglst[i]->end; } } if (fullattr && gffrec.attrs!=NULL) { //append all attributes found for each transcripts for (int i=0;i<gffrec.attrs->Count();i++) { defline.append(" "); defline.append(gffrec.getAttrName(i)); defline.append("="); defline.append(gffrec.getAttrValue(i)); } } printFasta(f_w, defline, exont, seqlen); GFREE(exont); } } //writing f_w (spliced exons) return true; }
static void gst_motion_cells_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstMotioncells *filter = gst_motion_cells (object); //variables for overlay regions setup gchar **strs, **colorstr, **motioncellsstr, **motionmaskcellsstr; int i, ux, uy, lx, ly; int r, g, b; int cellscolorscnt = 0; int linidx, colidx, masklinidx, maskcolidx; int tmpux = -1; int tmpuy = -1; int tmplx = -1; int tmply = -1; GstStateChangeReturn ret; g_mutex_lock (filter->propset_mutex); switch (prop_id) { case PROP_GRID_X: ret = gst_element_get_state (GST_ELEMENT (filter), &filter->state, NULL, 250 * GST_NSECOND); filter->gridx = g_value_get_int (value); if (filter->prevgridx != filter->gridx && ret == GST_STATE_CHANGE_SUCCESS && filter->state == GST_STATE_PLAYING) { filter->changed_gridx = true; } filter->prevgridx = filter->gridx; break; case PROP_GRID_Y: ret = gst_element_get_state (GST_ELEMENT (filter), &filter->state, NULL, 250 * GST_NSECOND); filter->gridy = g_value_get_int (value); if (filter->prevgridy != filter->gridy && ret == GST_STATE_CHANGE_SUCCESS && filter->state == GST_STATE_PLAYING) { filter->changed_gridy = true; } filter->prevgridy = filter->gridy; break; case PROP_GAP: filter->gap = g_value_get_int (value); break; case PROP_POSTNOMOTION: filter->postnomotion = g_value_get_int (value); break; case PROP_MINIMUNMOTIONFRAMES: filter->minimum_motion_frames = g_value_get_int (value); break; case PROP_SENSITIVITY: filter->sensitivity = g_value_get_double (value); break; case PROP_THRESHOLD: filter->threshold = g_value_get_double (value); break; case PROP_DISPLAY: filter->display = g_value_get_boolean (value); break; case PROP_POSTALLMOTION: filter->postallmotion = g_value_get_boolean (value); break; case PROP_USEALPHA: filter->usealpha = g_value_get_boolean (value); break; case PROP_CALCULATEMOTION: filter->calculate_motion = g_value_get_boolean (value); break; case PROP_DATE: ret = gst_element_get_state (GST_ELEMENT (filter), &filter->state, NULL, 250 * GST_NSECOND); if (ret == GST_STATE_CHANGE_SUCCESS && filter->state == GST_STATE_PLAYING) { filter->changed_startime = true; } filter->starttime = g_value_get_long (value); break; case PROP_DATAFILE: GFREE (filter->cur_datafile); GFREE (filter->basename_datafile); filter->basename_datafile = g_value_dup_string (value); if (strlen (filter->basename_datafile) == 0) { filter->cur_datafile = g_strdup (NULL); break; } filter->cur_datafile = g_strdup_printf ("%s-0.%s", filter->basename_datafile, filter->datafile_extension); if (g_strcmp0 (filter->prev_datafile, filter->basename_datafile) != 0) { filter->changed_datafile = TRUE; filter->sent_init_error_msg = FALSE; filter->sent_save_error_msg = FALSE; filter->datafileidx = 0; motion_cells_free_resources (filter->id); } else { filter->changed_datafile = FALSE; } GFREE (filter->prev_datafile); filter->prev_datafile = g_strdup (filter->basename_datafile); break; case PROP_DATAFILE_EXT: GFREE (filter->datafile_extension); filter->datafile_extension = g_value_dup_string (value); break; case PROP_MOTIONMASKCOORD: strs = g_strsplit (g_value_get_string (value), ",", 255); GFREE (filter->motionmaskcoords); //setting number of regions for (filter->motionmaskcoord_count = 0; strs[filter->motionmaskcoord_count] != NULL; ++filter->motionmaskcoord_count); if (filter->motionmaskcoord_count > 0) { sscanf (strs[0], "%d:%d:%d:%d", &tmpux, &tmpuy, &tmplx, &tmply); if (tmpux > -1 && tmpuy > -1 && tmplx > -1 && tmply > -1) { filter->motionmaskcoords = g_new0 (motionmaskcoordrect, filter->motionmaskcoord_count); for (i = 0; i < filter->motionmaskcoord_count; ++i) { sscanf (strs[i], "%d:%d:%d:%d", &ux, &uy, &lx, &ly); ux = CLAMP (ux, 0, filter->width - 1); uy = CLAMP (uy, 0, filter->height - 1); lx = CLAMP (lx, 0, filter->width - 1); ly = CLAMP (ly, 0, filter->height - 1); filter->motionmaskcoords[i].upper_left_x = ux; filter->motionmaskcoords[i].upper_left_y = uy; filter->motionmaskcoords[i].lower_right_x = lx; filter->motionmaskcoords[i].lower_right_y = ly; } } else { filter->motionmaskcoord_count = 0; } } if (strs) g_strfreev (strs); tmpux = -1; tmpuy = -1; tmplx = -1; tmply = -1; break; case PROP_MOTIONMASKCELLSPOS: motionmaskcellsstr = g_strsplit (g_value_get_string (value), ",", 255); GFREE (filter->motionmaskcellsidx); //setting number of regions for (filter->motionmaskcells_count = 0; motionmaskcellsstr[filter->motionmaskcells_count] != NULL; ++filter->motionmaskcells_count); if (filter->motionmaskcells_count > 0) { sscanf (motionmaskcellsstr[0], "%d:%d", &tmpux, &tmpuy); if (tmpux > -1 && tmpuy > -1) { filter->motionmaskcellsidx = g_new0 (motioncellidx, filter->motionmaskcells_count); for (i = 0; i < filter->motionmaskcells_count; ++i) { sscanf (motionmaskcellsstr[i], "%d:%d", &masklinidx, &maskcolidx); filter->motionmaskcellsidx[i].lineidx = masklinidx; filter->motionmaskcellsidx[i].columnidx = maskcolidx; } } else { filter->motionmaskcells_count = 0; } } if (motionmaskcellsstr) g_strfreev (motionmaskcellsstr); tmpux = -1; tmpuy = -1; tmplx = -1; tmply = -1; break; case PROP_CELLSCOLOR: colorstr = g_strsplit (g_value_get_string (value), ",", 255); for (cellscolorscnt = 0; colorstr[cellscolorscnt] != NULL; ++cellscolorscnt); if (cellscolorscnt == 3) { sscanf (colorstr[0], "%d", &r); sscanf (colorstr[1], "%d", &g); sscanf (colorstr[2], "%d", &b); //check right RGB color format r = CLAMP (r, 1, 255); g = CLAMP (g, 1, 255); b = CLAMP (b, 1, 255); filter->motioncellscolor->R_channel_value = r; filter->motioncellscolor->G_channel_value = g; filter->motioncellscolor->B_channel_value = b; } if (colorstr) g_strfreev (colorstr); break; case PROP_MOTIONCELLSIDX: motioncellsstr = g_strsplit (g_value_get_string (value), ",", 255); //setting number of regions for (filter->motioncells_count = 0; motioncellsstr[filter->motioncells_count] != NULL; ++filter->motioncells_count); if (filter->motioncells_count > 0) { sscanf (motioncellsstr[0], "%d:%d", &tmpux, &tmpuy); if (tmpux > -1 && tmpuy > -1) { GFREE (filter->motioncellsidx); filter->motioncellsidx = g_new0 (motioncellidx, filter->motioncells_count); for (i = 0; i < filter->motioncells_count; ++i) { sscanf (motioncellsstr[i], "%d:%d", &linidx, &colidx); filter->motioncellsidx[i].lineidx = linidx; filter->motioncellsidx[i].columnidx = colidx; } } else { filter->motioncells_count = 0; } } if (motioncellsstr) g_strfreev (motioncellsstr); tmpux = -1; tmpuy = -1; tmplx = -1; tmply = -1; break; case PROP_MOTIONCELLTHICKNESS: filter->thickness = g_value_get_int (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } g_mutex_unlock (filter->propset_mutex); }
int main(int argc, char * const argv[]) { GArgs args(argc, argv, "debug;merge;cluster-only;help;force-exons;no-pseudo;MINCOV=MINPID=hvOUNHWCVJMKQNSXTDAPRZFGLEm:g:i:r:s:t:a:b:o:w:x:y:d:"); args.printError(USAGE, true); if (args.getOpt('h') || args.getOpt("help")) { GMessage("%s",USAGE); exit(1); } debugMode=(args.getOpt("debug")!=NULL); decodeChars=(args.getOpt('D')!=NULL); forceExons=(args.getOpt("force-exons")!=NULL); NoPseudo=(args.getOpt("no-pseudo")!=NULL); mRNAOnly=(args.getOpt('O')==NULL); //sortByLoc=(args.getOpt('S')!=NULL); addDescr=(args.getOpt('A')!=NULL); verbose=(args.getOpt('v')!=NULL); wCDSonly=(args.getOpt('C')!=NULL); validCDSonly=(args.getOpt('V')!=NULL); altPhases=(args.getOpt('H')!=NULL); fmtGTF=(args.getOpt('T')!=NULL); //switch output format to GTF bothStrands=(args.getOpt('B')!=NULL); fullCDSonly=(args.getOpt('J')!=NULL); spliceCheck=(args.getOpt('N')!=NULL); bool matchAllIntrons=(args.getOpt('K')==NULL); bool fuzzSpan=(args.getOpt('Q')!=NULL); if (args.getOpt('M') || args.getOpt("merge")) { doCluster=true; doCollapseRedundant=true; } else { if (!matchAllIntrons || fuzzSpan) { GMessage("%s",USAGE); GMessage("Error: -K or -Q options require -M/--merge option!\n"); exit(1); } } if (args.getOpt("cluster-only")) { doCluster=true; doCollapseRedundant=false; if (!matchAllIntrons || fuzzSpan) { GMessage("%s",USAGE); GMessage("Error: -K or -Q options have no effect with --cluster-only.\n"); exit(1); } } if (fullCDSonly) validCDSonly=true; if (verbose) { fprintf(stderr, "Command line was:\n"); args.printCmdLine(stderr); } fullattr=(args.getOpt('F')!=NULL); if (args.getOpt('G')==NULL) noExonAttr=!fullattr; else { noExonAttr=true; fullattr=true; } if (NoPseudo && !fullattr) { noExonAttr=true; fullattr=true; } ensembl_convert=(args.getOpt('L')!=NULL); if (ensembl_convert) { fullattr=true; noExonAttr=false; //sortByLoc=true; } mergeCloseExons=(args.getOpt('Z')!=NULL); multiExon=(args.getOpt('U')!=NULL); writeExonSegs=(args.getOpt('W')!=NULL); tracklabel=args.getOpt('t'); GFastaDb gfasta(args.getOpt('g')); //if (gfasta.fastaPath!=NULL) // sortByLoc=true; //enforce sorting by chromosome/contig GStr s=args.getOpt('i'); if (!s.is_empty()) maxintron=s.asInt(); FILE* f_repl=NULL; s=args.getOpt('d'); if (!s.is_empty()) { if (s=="-") f_repl=stdout; else { f_repl=fopen(s.chars(), "w"); if (f_repl==NULL) GError("Error creating file %s\n", s.chars()); } } rfltWithin=(args.getOpt('R')!=NULL); s=args.getOpt('r'); if (!s.is_empty()) { s.trim(); if (s[0]=='+' || s[0]=='-') { rfltStrand=s[0]; s.cut(0,1); } int isep=s.index(':'); if (isep>0) { //gseq name given if (rfltStrand==0 && (s[isep-1]=='+' || s[isep-1]=='-')) { isep--; rfltStrand=s[isep]; s.cut(isep,1); } if (isep>0) rfltGSeq=Gstrdup((s.substr(0,isep)).chars()); s.cut(0,isep+1); } GStr gsend; char slast=s[s.length()-1]; if (rfltStrand==0 && (slast=='+' || slast=='-')) { s.chomp(slast); rfltStrand=slast; } if (s.index("..")>=0) gsend=s.split(".."); else gsend=s.split('-'); if (!s.is_empty()) rfltStart=(uint)s.asInt(); if (!gsend.is_empty()) { rfltEnd=(uint)gsend.asInt(); if (rfltEnd==0) rfltEnd=MAX_UINT; } } //gseq/range filtering else { if (rfltWithin) GError("Error: option -R requires -r!\n"); //if (rfltWholeTranscript) // GError("Error: option -P requires -r!\n"); } s=args.getOpt('m'); if (!s.is_empty()) { FILE* ft=fopen(s,"r"); if (ft==NULL) GError("Error opening reference table: %s\n",s.chars()); loadRefTable(ft, reftbl); fclose(ft); } s=args.getOpt('s'); if (!s.is_empty()) { FILE* fsize=fopen(s,"r"); if (fsize==NULL) GError("Error opening info file: %s\n",s.chars()); loadSeqInfo(fsize, seqinfo); fclose(fsize); } openfw(f_out, args, 'o'); //if (f_out==NULL) f_out=stdout; if (gfasta.fastaPath==NULL && (validCDSonly || spliceCheck || args.getOpt('w')!=NULL || args.getOpt('x')!=NULL || args.getOpt('y')!=NULL)) GError("Error: -g option is required for options -w, -x, -y, -V, -N, -M !\n"); openfw(f_w, args, 'w'); openfw(f_x, args, 'x'); openfw(f_y, args, 'y'); if (f_y!=NULL || f_x!=NULL) wCDSonly=true; //useBadCDS=useBadCDS || (fgtfok==NULL && fgtfbad==NULL && f_y==NULL && f_x==NULL); int numfiles = args.startNonOpt(); //GList<GffObj> gfkept(false,true); //unsorted, free items on delete int out_counter=0; //number of records printed while (true) { GStr infile; if (numfiles) { infile=args.nextNonOpt(); if (infile.is_empty()) break; if (infile=="-") { f_in=stdin; infile="stdin"; } else if ((f_in=fopen(infile, "r"))==NULL) GError("Error: cannot open input file %s!\n",infile.chars()); } else infile="-"; GffLoader gffloader(infile.chars()); gffloader.transcriptsOnly=mRNAOnly; gffloader.fullAttributes=fullattr; gffloader.noExonAttrs=noExonAttr; gffloader.mergeCloseExons=mergeCloseExons; gffloader.showWarnings=(args.getOpt('E')!=NULL); gffloader.noPseudo=NoPseudo; gffloader.load(g_data, &validateGffRec, doCluster, doCollapseRedundant, matchAllIntrons, fuzzSpan, forceExons); if (doCluster) collectLocusData(g_data); if (numfiles==0) break; } GStr loctrack("gffcl"); if (tracklabel) loctrack=tracklabel; g_data.setSorted(&gseqCmpName); GffPrintMode exonPrinting; if (fmtGTF) { exonPrinting = pgtfAny; } else { exonPrinting = forceExons ? pgffBoth : pgffAny; } bool firstGff3Print=!fmtGTF; if (doCluster) { //grouped in loci for (int g=0;g<g_data.Count();g++) { GenomicSeqData* gdata=g_data[g]; int gfs_i=0; for (int l=0;l<gdata->loci.Count();l++) { GffLocus& loc=*(gdata->loci[l]); //check all non-replaced transcripts in this locus: int numvalid=0; int idxfirstvalid=-1; for (int i=0;i<loc.rnas.Count();i++) { GffObj& t=*(loc.rnas[i]); if (f_out) { while (gfs_i<gdata->gfs.Count() && gdata->gfs[gfs_i]->start<=t.start) { GffObj& gfst=*(gdata->gfs[gfs_i]); if ((gfst.udata&4)==0) { //never printed gfst.udata|=4; if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } if (gfst.exons.Count()==0 && gfst.children.Count()==0 && forceExons) gfst.addExon(gfst.start,gfst.end); gfst.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } ++gfs_i; } } GTData* tdata=(GTData*)(t.uptr); if (tdata->replaced_by!=NULL) { if (f_repl && (t.udata & 8)==0) { //t.udata|=8; fprintf(f_repl, "%s", t.getID()); GTData* rby=tdata; while (rby->replaced_by!=NULL) { fprintf(f_repl," => %s", rby->replaced_by->getID()); rby->rna->udata|=8; rby=(GTData*)(rby->replaced_by->uptr); } fprintf(f_repl, "\n"); } continue; } if (process_transcript(gfasta, t)) { t.udata|=4; //tag it as valid numvalid++; if (idxfirstvalid<0) idxfirstvalid=i; } } if (f_out && numvalid>0) { GStr locname("RLOC_"); locname.appendfmt("%08d",loc.locus_num); if (!fmtGTF) { if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } fprintf(f_out,"%s\t%s\tlocus\t%d\t%d\t.\t%c\t.\tID=%s;locus=%s", loc.rnas[0]->getGSeqName(), loctrack.chars(), loc.start, loc.end, loc.strand, locname.chars(), locname.chars()); //const char* loc_gname=loc.getGeneName(); if (loc.gene_names.Count()>0) { //print all gene names associated to this locus fprintf(f_out, ";genes=%s",loc.gene_names.First()->name.chars()); for (int i=1;i<loc.gene_names.Count();i++) { fprintf(f_out, ",%s",loc.gene_names[i]->name.chars()); } } if (loc.gene_ids.Count()>0) { //print all GeneIDs names associated to this locus fprintf(f_out, ";geneIDs=%s",loc.gene_ids.First()->name.chars()); for (int i=1;i<loc.gene_ids.Count();i++) { fprintf(f_out, ",%s",loc.gene_ids[i]->name.chars()); } } fprintf(f_out, ";transcripts=%s",loc.rnas[idxfirstvalid]->getID()); for (int i=idxfirstvalid+1;i<loc.rnas.Count();i++) { fprintf(f_out, ",%s",loc.rnas[i]->getID()); } fprintf(f_out, "\n"); } //now print all valid, non-replaced transcripts in this locus: for (int i=0;i<loc.rnas.Count();i++) { GffObj& t=*(loc.rnas[i]); GTData* tdata=(GTData*)(t.uptr); if (tdata->replaced_by!=NULL || ((t.udata & 4)==0)) continue; t.addAttr("locus", locname.chars()); out_counter++; if (fmtGTF) t.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); else { if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } //print the parent first, if any if (t.parent!=NULL && ((t.parent->udata & 4)==0)) { GTData* pdata=(GTData*)(t.parent->uptr); if (pdata && pdata->geneinfo!=NULL) pdata->geneinfo->finalize(); t.parent->addAttr("locus", locname.chars()); t.parent->printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); t.parent->udata|=4; } t.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } } } //have valid transcripts to print }//for each locus //print the rest of the isolated pseudo/gene/region features not printed yet if (f_out) { while (gfs_i<gdata->gfs.Count()) { GffObj& gfst=*(gdata->gfs[gfs_i]); if ((gfst.udata&4)==0) { //never printed gfst.udata|=4; if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } if (gfst.exons.Count()==0 && gfst.children.Count()==0 && forceExons) gfst.addExon(gfst.start,gfst.end); gfst.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } ++gfs_i; } } } //for each genomic sequence } else { //not grouped into loci, print the rnas with their parents, if any int numvalid=0; for (int g=0;g<g_data.Count();g++) { GenomicSeqData* gdata=g_data[g]; int gfs_i=0; for (int m=0;m<gdata->rnas.Count();m++) { GffObj& t=*(gdata->rnas[m]); if (f_out) { while (gfs_i<gdata->gfs.Count() && gdata->gfs[gfs_i]->start<=t.start) { GffObj& gfst=*(gdata->gfs[gfs_i]); if ((gfst.udata&4)==0) { //never printed gfst.udata|=4; if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } if (gfst.exons.Count()==0 && gfst.children.Count()==0 && forceExons) gfst.addExon(gfst.start,gfst.end); gfst.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } ++gfs_i; } } GTData* tdata=(GTData*)(t.uptr); if (tdata->replaced_by!=NULL) continue; if (process_transcript(gfasta, t)) { t.udata|=4; //tag it as valid numvalid++; if (f_out) { if (tdata->geneinfo) tdata->geneinfo->finalize(); out_counter++; if (fmtGTF) t.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); else { if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } //print the parent first, if any if (t.parent!=NULL && ((t.parent->udata & 4)==0)) { GTData* pdata=(GTData*)(t.parent->uptr); if (pdata && pdata->geneinfo!=NULL) pdata->geneinfo->finalize(); t.parent->printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); t.parent->udata|=4; } t.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } }//GFF/GTF output requested } //valid transcript } //for each rna //print the rest of the isolated pseudo/gene/region features not printed yet if (f_out) { while (gfs_i<gdata->gfs.Count()) { GffObj& gfst=*(gdata->gfs[gfs_i]); if ((gfst.udata&4)==0) { //never printed gfst.udata|=4; if (firstGff3Print) { printGff3Header(f_out, args);firstGff3Print=false; } if (gfst.exons.Count()==0 && gfst.children.Count()==0 && forceExons) gfst.addExon(gfst.start,gfst.end); gfst.printGxf(f_out, exonPrinting, tracklabel, NULL, decodeChars); } ++gfs_i; } } } //for each genomic seq } //not clustered if (f_repl && f_repl!=stdout) fclose(f_repl); seqinfo.Clear(); //if (faseq!=NULL) delete faseq; //if (gcdb!=NULL) delete gcdb; GFREE(rfltGSeq); FRCLOSE(f_in); FWCLOSE(f_out); FWCLOSE(f_w); FWCLOSE(f_x); FWCLOSE(f_y); }
/* chain function * this function does the actual processing */ static GstFlowReturn gst_motion_cells_chain (GstPad * pad, GstBuffer * buf) { GstMotioncells *filter; filter = gst_motion_cells (GST_OBJECT_PARENT (pad)); if (filter->calculate_motion) { double sensitivity; int framerate, gridx, gridy, motionmaskcells_count, motionmaskcoord_count, motioncells_count, i; int thickness, success, motioncellsidxcnt, numberOfCells, motioncellsnumber, cellsOfInterestNumber; int mincellsOfInterestNumber, motiondetect; char *datafile; bool display, changed_datafile, useAlpha; gint64 starttime; motionmaskcoordrect *motionmaskcoords; motioncellidx *motionmaskcellsidx; cellscolor motioncellscolor; motioncellidx *motioncellsidx; g_mutex_lock (filter->propset_mutex); buf = gst_buffer_make_writable (buf); filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf); if (filter->firstframe) { setPrevFrame (filter->cvImage, filter->id); filter->firstframe = FALSE; } sensitivity = filter->sensitivity; framerate = filter->framerate; gridx = filter->gridx; gridy = filter->gridy; display = filter->display; motionmaskcoord_count = filter->motionmaskcoord_count; motionmaskcoords = g_new0 (motionmaskcoordrect, filter->motionmaskcoord_count); for (i = 0; i < filter->motionmaskcoord_count; i++) { //we need divide 2 because we use gauss pyramid in C++ side motionmaskcoords[i].upper_left_x = filter->motionmaskcoords[i].upper_left_x / 2; motionmaskcoords[i].upper_left_y = filter->motionmaskcoords[i].upper_left_y / 2; motionmaskcoords[i].lower_right_x = filter->motionmaskcoords[i].lower_right_x / 2; motionmaskcoords[i].lower_right_y = filter->motionmaskcoords[i].lower_right_y / 2; } motioncellscolor.R_channel_value = filter->motioncellscolor->R_channel_value; motioncellscolor.G_channel_value = filter->motioncellscolor->G_channel_value; motioncellscolor.B_channel_value = filter->motioncellscolor->B_channel_value; if ((filter->changed_gridx || filter->changed_gridy || filter->changed_startime)) { if ((g_strcmp0 (filter->cur_datafile, NULL) != 0)) { GFREE (filter->cur_datafile); filter->datafileidx++; filter->cur_datafile = g_strdup_printf ("%s-%d.%s", filter->basename_datafile, filter->datafileidx, filter->datafile_extension); filter->changed_datafile = TRUE; motion_cells_free_resources (filter->id); } if (filter->motioncells_count > 0) gst_motioncells_update_motion_cells (filter); if (filter->motionmaskcells_count > 0) gst_motioncells_update_motion_masks (filter); filter->changed_gridx = FALSE; filter->changed_gridy = FALSE; filter->changed_startime = FALSE; } datafile = g_strdup (filter->cur_datafile); filter->cur_buff_timestamp = (GST_BUFFER_TIMESTAMP (buf) / GST_MSECOND); filter->starttime += (filter->cur_buff_timestamp - filter->prev_buff_timestamp); starttime = filter->starttime; if (filter->changed_datafile || filter->diff_timestamp < 0) filter->diff_timestamp = (gint64) (GST_BUFFER_TIMESTAMP (buf) / GST_MSECOND); changed_datafile = filter->changed_datafile; motionmaskcells_count = filter->motionmaskcells_count; motionmaskcellsidx = g_new0 (motioncellidx, filter->motionmaskcells_count); for (i = 0; i < filter->motionmaskcells_count; i++) { motionmaskcellsidx[i].lineidx = filter->motionmaskcellsidx[i].lineidx; motionmaskcellsidx[i].columnidx = filter->motionmaskcellsidx[i].columnidx; } motioncells_count = filter->motioncells_count; motioncellsidx = g_new0 (motioncellidx, filter->motioncells_count); for (i = 0; i < filter->motioncells_count; i++) { motioncellsidx[i].lineidx = filter->motioncellsidx[i].lineidx; motioncellsidx[i].columnidx = filter->motioncellsidx[i].columnidx; } useAlpha = filter->usealpha; thickness = filter->thickness; success = perform_detection_motion_cells (filter->cvImage, sensitivity, framerate, gridx, gridy, (gint64) (GST_BUFFER_TIMESTAMP (buf) / GST_MSECOND) - filter->diff_timestamp, display, useAlpha, motionmaskcoord_count, motionmaskcoords, motionmaskcells_count, motionmaskcellsidx, motioncellscolor, motioncells_count, motioncellsidx, starttime, datafile, changed_datafile, thickness, filter->id); if ((success == 1) && (filter->sent_init_error_msg == false)) { char *initfailedreason; int initerrorcode; GstStructure *s; GstMessage *m; initfailedreason = getInitDataFileFailed (filter->id); initerrorcode = getInitErrorCode (filter->id); s = gst_structure_new ("motion", "init_error_code", G_TYPE_INT, initerrorcode, "details", G_TYPE_STRING, initfailedreason, NULL); m = gst_message_new_element (GST_OBJECT (filter), s); gst_element_post_message (GST_ELEMENT (filter), m); filter->sent_init_error_msg = TRUE; } if ((success == -1) && (filter->sent_save_error_msg == false)) { char *savefailedreason; int saveerrorcode; GstStructure *s; GstMessage *m; savefailedreason = getSaveDataFileFailed (filter->id); saveerrorcode = getSaveErrorCode (filter->id); s = gst_structure_new ("motion", "save_error_code", G_TYPE_INT, saveerrorcode, "details", G_TYPE_STRING, savefailedreason, NULL); m = gst_message_new_element (GST_OBJECT (filter), s); gst_element_post_message (GST_ELEMENT (filter), m); filter->sent_save_error_msg = TRUE; } if (success == -2) { //frame dropped filter->prev_buff_timestamp = filter->cur_buff_timestamp; //free GFREE (datafile); GFREE (motionmaskcoords); GFREE (motionmaskcellsidx); GFREE (motioncellsidx); g_mutex_unlock (filter->propset_mutex); return gst_pad_push (filter->srcpad, buf); } filter->changed_datafile = getChangedDataFile (filter->id); motioncellsidxcnt = getMotionCellsIdxCnt (filter->id); numberOfCells = filter->gridx * filter->gridy; motioncellsnumber = motioncellsidxcnt / MSGLEN; cellsOfInterestNumber = (filter->motioncells_count > 0) ? //how many cells interest for us (filter->motioncells_count) : (numberOfCells); mincellsOfInterestNumber = floor ((double) cellsOfInterestNumber * filter->threshold); motiondetect = (motioncellsnumber >= mincellsOfInterestNumber) ? 1 : 0; if ((motioncellsidxcnt > 0) && (motiondetect == 1)) { char *detectedmotioncells; filter->last_motion_timestamp = GST_BUFFER_TIMESTAMP (buf); detectedmotioncells = getMotionCellsIdx (filter->id); if (detectedmotioncells) { filter->consecutive_motion++; if ((filter->previous_motion == false) && (filter->consecutive_motion >= filter->minimum_motion_frames)) { GstStructure *s; GstMessage *m; filter->previous_motion = true; filter->motion_begin_timestamp = GST_BUFFER_TIMESTAMP (buf); s = gst_structure_new ("motion", "motion_cells_indices", G_TYPE_STRING, detectedmotioncells, "motion_begin", G_TYPE_UINT64, filter->motion_begin_timestamp, NULL); m = gst_message_new_element (GST_OBJECT (filter), s); gst_element_post_message (GST_ELEMENT (filter), m); } else if (filter->postallmotion) { GstStructure *s; GstMessage *m; filter->motion_timestamp = GST_BUFFER_TIMESTAMP (buf); s = gst_structure_new ("motion", "motion_cells_indices", G_TYPE_STRING, detectedmotioncells, "motion", G_TYPE_UINT64, filter->motion_timestamp, NULL); m = gst_message_new_element (GST_OBJECT (filter), s); gst_element_post_message (GST_ELEMENT (filter), m); } } else { GstStructure *s; GstMessage *m; s = gst_structure_new ("motion", "motion_cells_indices", G_TYPE_STRING, "error", NULL); m = gst_message_new_element (GST_OBJECT (filter), s); gst_element_post_message (GST_ELEMENT (filter), m); } } else { filter->consecutive_motion = 0; if ((((GST_BUFFER_TIMESTAMP (buf) - filter->last_motion_timestamp) / 1000000000l) >= filter->gap) && (filter->last_motion_timestamp > 0)) { GST_DEBUG ("POST MOTION FINISHED MSG\n"); if (filter->previous_motion) { GstStructure *s; GstMessage *m; filter->previous_motion = false; s = gst_structure_new ("motion", "motion_finished", G_TYPE_UINT64, filter->last_motion_timestamp, NULL); m = gst_message_new_element (GST_OBJECT (filter), s); gst_element_post_message (GST_ELEMENT (filter), m); } } } if (filter->postnomotion > 0) { guint64 last_buf_timestamp = GST_BUFFER_TIMESTAMP (buf) / 1000000000l; if ((last_buf_timestamp - (filter->last_motion_timestamp / 1000000000l)) >= filter->postnomotion) { GST_DEBUG ("POST NO MOTION MSG\n"); if ((last_buf_timestamp - (filter->last_nomotion_notified / 1000000000l)) >= filter->postnomotion) { GstStructure *s; GstMessage *m; filter->last_nomotion_notified = GST_BUFFER_TIMESTAMP (buf); s = gst_structure_new ("motion", "no_motion", G_TYPE_UINT64, filter->last_motion_timestamp, NULL); m = gst_message_new_element (GST_OBJECT (filter), s); gst_element_post_message (GST_ELEMENT (filter), m); } } } filter->prev_buff_timestamp = filter->cur_buff_timestamp; //free GFREE (datafile); GFREE (motionmaskcoords); GFREE (motionmaskcellsidx); GFREE (motioncellsidx); g_mutex_unlock (filter->propset_mutex); } return gst_pad_push (filter->srcpad, buf); }
int main(int argc, char * const argv[]) { //GArgs args(argc, argv, "hg:c:s:t:o:p:help;genomic-fasta=COV=PID=seq=out=disable-flag;test="); GArgs args(argc, argv, opts); fprintf(stderr, "Command line was:\n"); args.printCmdLine(stderr); args.printError(USAGE, true); //if (args.getOpt('h') || args.getOpt("help")) if (args.getOpt(OPT_HELP)) { GMessage("%s\n", USAGE); exit(1); } if (args.getOpt(OPT_NUM)) { GStr snum(args.getOpt(OPT_NUM)); int num=snum.asInt(); char* numstr=commaprintnum(num); GMessage("Number %d written with commas: %s\n", num, numstr); GFREE(numstr); } //--- GHash<GVec<int> > ends; /* testGPVec(); //exit(0); //uint pos=3; //GStr spos((int)pos); //GVec<int> *ev=ends[spos.chars()]; GPVec<Gint> v; int r(5); int rr=v.Add(new Gint(3)); //if (rr<0) { // GMessage("Error adding 0! (code %d)\n",rr); // } v.Add(new Gint(r)); v.Add(new Gint(2)); v.Add(new Gint(1)); v.Add(new Gint(4)); rr=v.Add(new Gint(0)); v[rr]->v=-1; v.Sort(cmpGint); GMessage("collection has %d elements:\n",v.Count()); for (int i=0;i<v.Count();i++) { GMessage("v[%d]=%d;\n",i,v[i]->v); } exit(0); */ //--- int numopts=args.startOpt(); if (numopts) GMessage("#### Recognized %d option arguments:\n", numopts); int optcode=0; while ((optcode=args.nextCode())) { char* r=args.getOpt(optcode); GMessage("%14s\t= %s\n", args.getOptName(optcode), (r[0]==0)?"True":r); } int numargs=args.startNonOpt(); if (numargs>0) { GMessage("\n#### Found %d non-option arguments given:\n", numargs); char* a=NULL; while ((a=args.nextNonOpt())) { GMessage("%s\n",a); } } GStr s=args.getOpt('t'); if (!s.is_empty()) { GStr token; GMessage("Tokens in \"%s\" :\n",s.chars()); s.startTokenize(";,: \t"); int c=1; while (s.nextToken(token)) { GMessage("token %2d : \"%s\"\n",c,token.chars()); c++; } } if (args.getOpt(OPT_BITVEC)) { uint numbits=4156888234; GBitVec bits(numbits); GMessage(">>> -- BitVec(%u) created (size=%u, mem=%lu) -- \n", numbits, bits.size(), bits.getMemorySize()); bits[405523342]=true; GMessage(" memory size: %lu , size()=%u, count()=%d \n", bits.getMemorySize(), bits.size(), bits.count()); /* //GMessage(">>> -- Start BitVec Test -- \n"); if (bits[1092]) bitError(1092); bits.resize(2049); if (bits[2048]) bitError(2048); bits[2048]=true; if (!bits[2048]) bitError(2048); bits.resize(4097); if (!bits[2048]) bitError(2048); if (bits[4096]) bitError(4096); bits[4096]=true; if (!bits[4096]) bitError(4096); GBitVec bits2(64); Gswap(bits, bits2); if (!bits2[2048]) bitError(2048); if (!bits2[4096]) bitError(4096); */ //GMessage("<<< -- End BitVec Test (size: %d, count: %d, bits2 size=%d, count=%d) --\n", /// bits.size(), bits.count(), bits2.size(), bits2.count()); } }