Beispiel #1
0
void
UNION(int x, int y)
{
	int fx, fy;

	fx = FIND(x);
	fy = FIND(y);
	if (fx == fy) return;
	f[fx] = fy;
	r[fx] = (r[x] == r[y]? 0: 1);
}
Beispiel #2
0
void handleCommand(string command)
{
	hC_begin

	CMD("look")
		cout << "You see:" << endl;
		for (unsigned i = 0; i < stuff.size(); i++)
			cout << " * " << stuff[i] << endl;
	CMD("open")
		if (args[1] == "door")
			if (has_item("key"))
			{
				cout << "The door opened!" << endl;
				ACHIEVE(DOOR_OPEN);
				goNextLevel();
			}
			else
				cout << "The door is locked!" << endl;
	CMD("take")
		if (args[1] == "comment")
		{
			if (has_achievement(EA_CAPTCHA)) {
				FIND("comment");
			} else
				cout << "You can't! It's not your's!" << endl;
		}
		if (args[1] == "captcha")
			FIND("captcha");
	CMD("say")
		if (args[1] == "captcha")
			if (has_item("captcha"))
			{
				cout << "Man, that captcha was lamer than i thought!" << endl;
				ACHIEVE(CAPTCHA);
			}
			else
				cout << "What does that captcha say? I don't know!" << endl;
	CMD("post")
		if (args[1] == "comment")
			if (has_item("comment"))
			{
				FIND("key");
				ACHIEVE(COMMENT);
			}
			else
				cout << "You can't! It's not your's!" << endl;
	CMD("help")
		cout << "The following commands are availeble:" << endl << " * look\n * open\n * take\n * say\n * post\n";

	hC_end
}
Beispiel #3
0
static int envext(CSOUND *csound, int argc, char **argv)
{
    char        *inputfile = NULL;
    SNDFILE     *infd;
    char        c, *s;
    OPARMS      OO;
    double      window = 0.25;
    SOUNDIN     *p;  /* space allocated by SAsndgetset() */
    char        *outname = NULL;

    memset(&OO, 0, sizeof(OO));

    /* Check arguments */
    if (!(--argc))
      envext_usage(csound, Str("Insufficient arguments"));
    do {
      s = *++argv;
      if (*s++ == '-')                        /* read all flags:  */
        while ((c = *s++) != '\0')
          switch(c) {
          case 'o':
            FIND(Str("no outfilename"))
            outname = s;
            while (*++s);
            break;
          case 'w':
            FIND(Str("No window size"));
            window = atof(s);
            while (*++s);
            break;
          default:
            envext_usage(csound, Str("unknown flag -%c"), c);
          }
      else if (inputfile == NULL) {
        inputfile = --s;
      }
      else envext_usage(csound, Str("too many arguments"));
    } while (--argc);

    /* Read sound file */
    if (UNLIKELY(inputfile==NULL ||
                 (infd = SCsndgetset(csound, &p, inputfile))==NULL)) {
      csound->Message(csound,Str("%s: error while opening %s"), argv[0], inputfile);
      return 1;
    }
    FindEnvelope(csound, infd, p, window, outname);
    return 0;
}
Beispiel #4
0
void VirtualNetwork::removeDevice(NetworkDevice *device)
{
    if (CONTAINS(devices, device)) {
        this->devices.erase(FIND(devices, device));
        device->disconnectFromNetwork();
    }
}
Beispiel #5
0
void Dashboard::removeWidget(DashboardWidget *widget)
{
    auto widget_it = FIND(widgets, widget);
    
    if (widget_it != widgets.end())
        widgets.erase(widget_it);
}
Beispiel #6
0
int
UNION(int x, int y, int d)
{
	int fx, fy;

	fx = FIND(x);
	fy = FIND(y);

	if (fx == fy) return ((r[x] - r[y] + 3) % 3 != d - 1);
	else
	{
		f[fx] = fy;
		r[fx] = (r[y] - r[x] + d + 2) % 3;
		return 0;
	}
}
Beispiel #7
0
GLuint load_texture (const char* filename)
{
	GLuint id;
	glGenTextures(1, &id);
	glBindTexture(GL_TEXTURE_2D, id);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	filename = FIND (filename);
	SDL_Surface* texture = IMG_Load (filename);
	if(texture == NULL) {
		fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
		exit(1);
	}

	if(texture->format->BitsPerPixel != 24) {
		fprintf(stderr, "texture '%s' format must be 24bits\n", filename);
		exit(1);
	}

	GLenum err = gluBuild2DMipmaps(GL_TEXTURE_2D,
			GL_RGB, texture->w, texture->h,
			GL_RGB, GL_UNSIGNED_BYTE,texture->pixels);
	if(err) {
		fprintf(stderr, "gluBuild2DMipmaps(): %s\n", gluErrorString(err));
		exit(1);
	}

	fprintf(stderr, "Display Texture '%s' %dx%d-24bit\n", 
			filename, texture->w, texture->h);

	SDL_FreeSurface(texture);
	return id;
}
Beispiel #8
0
void UNION(int *fathers, int a, int b)
{ int r1, r2, n;

  r1 = FIND(fathers,a);
  r2 = FIND(fathers,b);
  if (r1 != r2)
    { n = fathers[r1]+fathers[r2];
      if (fathers[r1] < fathers[r2])
        { fathers[r2] = r1;
          fathers[r1] = n;
        }
      else
        { fathers[r1] = r2;
          fathers[r2] = n;
        }
    }
}
Beispiel #9
0
TTF_Font *load_font (const char* filename, int size)
{
	filename = FIND (filename);
	TTF_Font *font = TTF_OpenFont(filename, size);
	if(font == NULL) {
		fprintf(stderr, "TTF_OpenFont(%s,%d): %s\n", filename, size, TTF_GetError());
		exit(1);
	}
	return font;
}
Beispiel #10
0
int
FIND(int x)
{
	int t;

	if (f[x] == -1) return x;
	else
	{
		t = FIND(f[x]);
		r[x] = (r[x] == r[f[x]]? 1: 0);
		return f[x] = t;
	}
}
Beispiel #11
0
int
FIND(int x)
{
	int t;

	if (f[x] == -1) return x;
	else
	{
		t = FIND(f[x]);
		r[x] = (r[x] + r[f[x]]) % 3;
		return f[x] = t;
	}
}
Beispiel #12
0
isc_result_t
isc_symtab_define(isc_symtab_t *symtab, const char *key, unsigned int type,
		  isc_symvalue_t value, isc_symexists_t exists_policy)
{
	unsigned int bucket;
	elt_t *elt;

	REQUIRE(VALID_SYMTAB(symtab));
	REQUIRE(key != NULL);
	REQUIRE(type != 0);

	FIND(symtab, key, type, bucket, elt);

	if (exists_policy != isc_symexists_add && elt != NULL) {
		if (exists_policy == isc_symexists_reject)
			return (ISC_R_EXISTS);
		INSIST(exists_policy == isc_symexists_replace);
		UNLINK(symtab->table[bucket], elt, link);
		if (symtab->undefine_action != NULL)
			(symtab->undefine_action)(elt->key, elt->type,
						  elt->value,
						  symtab->undefine_arg);
	} else {
		elt = (elt_t *)isc_mem_get(symtab->mctx, sizeof(*elt));
		if (elt == NULL)
			return (ISC_R_NOMEMORY);
		ISC_LINK_INIT(elt, link);
		symtab->count++;
	}

	/*
	 * Though the "key" can be const coming in, it is not stored as const
	 * so that the calling program can easily have writable access to
	 * it in its undefine_action function.  In the event that it *was*
	 * truly const coming in and then the caller modified it anyway ...
	 * well, don't do that!
	 */
	DE_CONST(key, elt->key);
	elt->type = type;
	elt->value = value;

	/*
	 * We prepend so that the most recent definition will be found.
	 */
	PREPEND(symtab->table[bucket], elt, link);

	if (symtab->count > symtab->maxload)
		grow_table(symtab);

	return (ISC_R_SUCCESS);
}
Beispiel #13
0
void display_init (Display* display, GLfloat near_plane, GLfloat far_plane, Args* args)
{
	memset(display, 0, sizeof(Display));
	display->near_plane = near_plane;
	display->far_plane  = far_plane;

#ifndef _WIN32
	// avoid crash on EeePC's Xandros
	if (NULL == SDL_getenv ("SDL_VIDEO_X11_WMCLASS"))
		SDL_putenv ("SDL_VIDEO_X11_WMCLASS=cave9");
#endif

	Uint32 flags = SDL_INIT_VIDEO;
	if (!args->nosound)
		flags |= SDL_INIT_AUDIO;
	if (SDL_Init (flags) != 0) {
		fprintf (stderr, "SDL_Init(): %s\n", SDL_GetError());
		exit (1);
	}
	atexit(SDL_Quit);

	const char* icon_file = FIND (ICON_FILE);
	display->icon = IMG_Load(icon_file);
	if(display->icon == NULL) {
		fprintf(stderr, "IMG_Load(%s): %s\n", icon_file, IMG_GetError());
		exit(1);
	}

	int w = args->width;
	int h = args->height;
	int f = args->fullscreen;
	if(args->highres) {
#if SDL_VERSION_ATLEAST(1,2,11)
		const SDL_VideoInfo* info = SDL_GetVideoInfo();
		assert(info != NULL);
		w = info->current_w;
		h = info->current_h;
#else
		w = BASE_W;
		h = BASE_H;
#endif
		f = 1;
	}
	viewport(display, w, h, args->bpp, f, args->antialiasing, args->lighting);

	if(TTF_Init() != 0) {
		fprintf(stderr, "TTF_Init(): %s\n", TTF_GetError());
		exit(1);
	}
	atexit(TTF_Quit);
}
Beispiel #14
0
isc_result_t
isc_symtab_lookup(isc_symtab_t *symtab, const char *key, unsigned int type,
		  isc_symvalue_t *value)
{
	unsigned int bucket;
	elt_t *elt;

	REQUIRE(VALID_SYMTAB(symtab));
	REQUIRE(key != NULL);

	FIND(symtab, key, type, bucket, elt);

	if (elt == NULL)
		return (ISC_R_NOTFOUND);

	if (value != NULL)
		*value = elt->value;

	return (ISC_R_SUCCESS);
}
Beispiel #15
0
isc_result_t
isc_symtab_undefine(isc_symtab_t *symtab, const char *key, unsigned int type) {
	unsigned int bucket;
	elt_t *elt;

	REQUIRE(VALID_SYMTAB(symtab));
	REQUIRE(key != NULL);

	FIND(symtab, key, type, bucket, elt);

	if (elt == NULL)
		return (ISC_R_NOTFOUND);

	if (symtab->undefine_action != NULL)
		(symtab->undefine_action)(elt->key, elt->type,
					  elt->value, symtab->undefine_arg);
	UNLINK(symtab->table[bucket], elt, link);
	isc_mem_put(symtab->mctx, elt, sizeof(*elt));

	return (ISC_R_SUCCESS);
}
Beispiel #16
0
static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
{
    AVFilterContext *ctx = inlink->dst;
    CropDetectContext *s = ctx->priv;
    int bpp = s->max_pixsteps[0];
    int w, h, x, y, shrink_by;
    AVDictionary **metadata;
    int outliers, last_y;
    int limit = round(s->limit);

    // ignore first 2 frames - they may be empty
    if (++s->frame_nb > 0) {
        metadata = avpriv_frame_get_metadatap(frame);

        // Reset the crop area every reset_count frames, if reset_count is > 0
        if (s->reset_count > 0 && s->frame_nb > s->reset_count) {
            s->x1 = frame->width  - 1;
            s->y1 = frame->height - 1;
            s->x2 = 0;
            s->y2 = 0;
            s->frame_nb = 1;
        }

#define FIND(DST, FROM, NOEND, INC, STEP0, STEP1, LEN) \
        outliers = 0;\
        for (last_y = y = FROM; NOEND; y = y INC) {\
            if (checkline(ctx, frame->data[0] + STEP0 * y, STEP1, LEN, bpp) > limit) {\
                if (++outliers > s->max_outliers) { \
                    DST = last_y;\
                    break;\
                }\
            } else\
                last_y = y INC;\
        }

        FIND(s->y1,                 0,               y < s->y1, +1, frame->linesize[0], bpp, frame->width);
        FIND(s->y2, frame->height - 1, y > FFMAX(s->y2, s->y1), -1, frame->linesize[0], bpp, frame->width);
        FIND(s->x1,                 0,               y < s->x1, +1, bpp, frame->linesize[0], frame->height);
        FIND(s->x2,  frame->width - 1, y > FFMAX(s->x2, s->x1), -1, bpp, frame->linesize[0], frame->height);


        // round x and y (up), important for yuv colorspaces
        // make sure they stay rounded!
        x = (s->x1+1) & ~1;
        y = (s->y1+1) & ~1;

        w = s->x2 - x + 1;
        h = s->y2 - y + 1;

        // w and h must be divisible by 2 as well because of yuv
        // colorspace problems.
        if (s->round <= 1)
            s->round = 16;
        if (s->round % 2)
            s->round *= 2;

        shrink_by = w % s->round;
        w -= shrink_by;
        x += (shrink_by/2 + 1) & ~1;

        shrink_by = h % s->round;
        h -= shrink_by;
        y += (shrink_by/2 + 1) & ~1;

        SET_META("lavfi.cropdetect.x1", s->x1);
        SET_META("lavfi.cropdetect.x2", s->x2);
        SET_META("lavfi.cropdetect.y1", s->y1);
        SET_META("lavfi.cropdetect.y2", s->y2);
        SET_META("lavfi.cropdetect.w",  w);
        SET_META("lavfi.cropdetect.h",  h);
        SET_META("lavfi.cropdetect.x",  x);
        SET_META("lavfi.cropdetect.y",  y);

        av_log(ctx, AV_LOG_INFO,
               "x1:%d x2:%d y1:%d y2:%d w:%d h:%d x:%d y:%d pts:%"PRId64" t:%f crop=%d:%d:%d:%d\n",
               s->x1, s->x2, s->y1, s->y2, w, h, x, y, frame->pts,
               frame->pts == AV_NOPTS_VALUE ? -1 : frame->pts * av_q2d(inlink->time_base),
               w, h, x, y);
    }

    return ff_filter_frame(inlink->dst->outputs[0], frame);
}
Beispiel #17
0
Clusters *Merge_Segments(Segmentation *segs, Overlaps *ovl)
{ Clusters *clust;
  int      *fathers, *sets, *which;
  int       nsegs, nsets;
  int       j, k;

  nsegs = ovl->totsegs;

  which   = (int *) Guarded_Malloc(sizeof(int)*(2*nsegs+1),Program_Name());
  sets    = which + nsegs;
  fathers = (int *) Guarded_Malloc(sizeof(int)*nsegs,Program_Name());

  for (k = 0; k < nsegs; k++)
    fathers[k] = -1;

  for (k = 0; k < nsegs; k++)
    for (j = ovl->alist[k]; j < ovl->alist[k+1]; j++)
      UNION(fathers,k,ovl->heads[j]);

  nsets = 0;
  for (k = 0; k < nsegs; k++)
    if (fathers[k] < 0)
      { nsets += 1;
        fathers[k] = -nsets;
      }
    else
      fathers[k] = FIND(fathers,k);

  for (k = 0; k < nsegs; k++)
    if (fathers[k] > 0)
      fathers[k] = fathers[fathers[k]];

  for (k = 0; k < nsegs; k++)
    fathers[k] = -(fathers[k]+1);

  for (k = 0; k <= nsets; k++)
    sets[k] = 0;
  for (k = 0; k < nsegs; k++)
    sets[fathers[k]+1] += 1;
  for (k = 2; k <= nsets; k++)
    sets[k] += sets[k-1];
  for (k = 0; k < nsegs; k++)
    { which[sets[fathers[k]]] = k;
      sets[fathers[k]] += 1;
    }
  for (k = nsegs; k > 0; k--)
    sets[k] = sets[k-1];
  sets[0] = 0;

  free(fathers);

  clust = (Clusters *) Guarded_Malloc(sizeof(Clusters),Program_Name());
  clust->inum   = nsets;
  clust->ilist  = sets;
  clust->item   = which;

#ifdef VERBOSE
  printf("\nClusters:\n");
  for (k = 0; k < nsets; k++)
    { printf("  Set %3d:",k);
      for (j = sets[k]; j < sets[k+1]; j++)
        { int c = ovl->chans[which[j]];
          printf(" %c%d",Letter[c],(which[j]-segs[c].base)+1);
        }
      printf("\n");
      fflush(stdout);
    }
  fflush(stdout);
#endif

  return (clust);
}
HaxeMessageSyntax::HaxeMessageSyntax()
{
	DEFINE_VOID("SpaceChar", RANGE(" \n\r\t"));
	DEFINE_VOID("Whitespace", REPEAT(INLINE("SpaceChar")));
	
	specialChar_ =
		DEFINE("SpecialChar",
			GLUE(
				CHAR('&'),
				KEYWORD("gt lt"),
				CHAR(';')
			)
		);
	gt_ = keywordByName("gt");
	lt_ = keywordByName("lt");
	
	value_ =
		DEFINE("Value",
			REPEAT(1,
				CHOICE(
					REF("SpecialChar"),
					GLUE(
						NOT(
							GLUE(
								INLINE("Whitespace"),
								CHAR('<')
							)
						),
						ANY()
					)
				)
			)
		);
	
	typeTip_ =
		DEFINE("TypeTip",
			GLUE(
				STRING("<type>"),
				INLINE("Whitespace"),
				REF("Value"),
				INLINE("Whitespace"),
				STRING("</type>")
			)
		);
	
	memberName_ = DEFINE("MemberName", REPEAT(1, OTHER('\"')));
	memberType_ = DEFINE("MemberType", REPEAT(0, 1, INLINE("Value")));
	memberDescription_ = DEFINE("MemberDescription", REPEAT(0, 1, INLINE("Value")));
	
	member_ =
		DEFINE("Member",
			GLUE(
				STRING("<i n=\""),
				REF("MemberName"),
				STRING("\"><t>"),
				REF("MemberType"),
				STRING("</t><d>"),
				REF("MemberDescription"),
				STRING("</d></i>")
			)
		);
	
	membersTip_ =
		DEFINE("MembersTip",
			GLUE(
				STRING("<list>"),
				REPEAT(1,
					GLUE(
						INLINE("Whitespace"),
						REF("Member")
					)
				),
				INLINE("Whitespace"),
				STRING("</list>")
			)
		);
	
	haxeTip_ =
		DEFINE("HaxeTip",
			FIND(
				GLUE(
					INLINE("Whitespace"),
					CHOICE(
						REF("TypeTip"),
						REF("MembersTip")
					),
					INLINE("Whitespace")
				)
			)
		);
	
	ENTRY("HaxeTip");
}
Beispiel #19
0
type find( char const *calendar ) {
  DEF_END( string_of );
  return FIND( calendar );
}
 char FIND(char item){
     if(parent[item]==item)
         return item;
     else
         return parent[item]=FIND(parent[item]);
 }
Beispiel #21
0
static int dnoise(CSOUND *csound, int argc, char **argv)
{
     OPARMS  O;
     csound->GetOParms(csound, &O);

    MYFLT   beg = -FL(1.0), end = -FL(1.0);
    long    Beg = 0, End = 99999999;

    MYFLT
        *ibuf1,     /* pointer to start of input buffer */
        *ibuf2,     /* pointer to start of input buffer */
        *obuf1,     /* pointer to start of output buffer */
        *obuf2,     /* pointer to start of output buffer */
        *fbuf,      /* pointer to start of FFT buffer */
        *aWin,      /* pointer to center of analysis window */
        *sWin,      /* pointer to center of synthesis window */
        *i0,        /* pointer to real channels */
        *i1,        /* pointer to imaginary channels */
        *j0,        /* pointer to real channels */
        *j1,        /* pointer to imaginary channels */
        *f,         /* pointer to FFT buffer */
        *f0,        /* pointer to real channels */
        *f1,        /* pointer to imaginary channels */
        *w,         /* pointer to window */
        *mbuf,      /* m most recent frames of FFT */
        *nbuf,      /* m most recent frames of FFT */
        *nref,      /* noise reference buffer */
        *rsum,      /* running sum of magnitude-squared spectrum */
        *ssum,      /* running sum of magnitude-squared spectrum */
        *ibp,       /* pointer to next input to be read */
        *ib0,       /* pointer to output buffer */
        *ib1,       /* pointer to output buffer */
        *ib2,       /* pointer to output buffer */
        *obp,       /* pointer to next output to be read */
        *ob0,       /* pointer to output buffer */
        *ob1,       /* pointer to output buffer */
        *ob2;       /* pointer to output buffer */

    int
        N = 0,      /* number of phase vocoder channels (bands) */
        Np2,        /* N+2 */
        M = 0,      /* length of aWin impulse response */
        L = 0,      /* length of sWin impulse response */
        D = 0,      /* decimation factor (default will be M/8) */
        I = 0,      /* interpolation factor (default will be I=D)*/
        W = -1,     /* filter overlap factor (determines M, L) */
        ibuflen,    /* size of ibuf */
        obuflen,    /* size of obuf */
        aLen,       /* half-length of analysis window */
        sLen;       /* half-length of synthesis window */

    long
        oCnt = 0L,  /* number of samples written to output */
        nI,         /* current input (analysis) sample */
        nO,         /* current output (synthesis) sample */
        nImodR,     /* current input sample mod R */
        nMaxOut,    /* last output (synthesis) sample */
        nMin,       /* first input (analysis) sample */
        nMax,       /* last input sample (unless EOF) */
        lnread,     /* total input samples read */
        lj,         /* to satisfy lame Microsoft compiler */
        lk;         /* to satisfy lame Microsoft compiler */

    SNDFILE *fp = NULL; /* noise reference file */

    MYFLT
        Ninv,       /* 1. / N */
      //RoverTwoPi, /* R/D divided by 2*Pi */
      //TwoPioverR, /* 2*Pi divided by R/I */
        sum,        /* scale factor for renormalizing windows */
      //rIn,        /* decimated sampling rate */
      //rOut,       /* pre-interpolated sampling rate */
        invR,       /* 1. / srate */
        time,       /* nI / srate */
        gain,       /* gain of noise gate */
        g0 = -FL(40.0),/* minimum gain for noise gate */
        g0m,        /* 1. - g0 */
        th = FL(30.0), /* threshold above noise reference (dB) */
        avg,        /* average square energy */
        fac,        /* factor in gain computation */
        minv,       /* 1 / m */
        R = -FL(1.0);  /* input sampling rate */

    int    i,j,k,   /* index variables */
        ibs,        /* current starting location in input buffer */
        ibc,        /* current location in input buffer */
        obs,        /* current starting location in output buffer */
        obc,        /* current location in output buffer */
        m = 5,      /* number of frames to save in mbuf */
        mi = 0,     /* frame offset index in mbuf */
        mj,         /* delayed offset index in mbuf */
        md,         /* number of frames of delay in mbuf (m/2) */
        mp,         /* mi * Np2 */
        sh = 1,     /* sharpness control for noise gate gain */
        nread,      /* number of bytes read */
        N2,         /* N/2 */
        Meven = 0,  /* flag for even M */
        Leven = 0,  /* flag for even L */
        Verbose = 0,/* flag for verbose output to stderr */
        Chans = -1, /* number of audio input channels (stereo = 2) */
        chan,       /* channel counter */
        flag = 1,   /* end-of-input flag */
        first = 0;  /* first-time-thru flag */

    SOUNDIN     *p, *pn;
    char        *infile = NULL, *nfile = NULL;
    SNDFILE     *inf = NULL, *outfd = NULL;
    char        c, *s;
    int         channel = ALLCHNLS;
    MYFLT       beg_time  = FL(0.0), input_dur  = FL(0.0), sr  = FL(0.0);
    MYFLT       beg_ntime = FL(0.0), input_ndur = FL(0.0), srn = FL(0.0);
    const char  *envoutyp = NULL;
    unsigned int  outbufsiz = 0U;
    int         nrecs = 0;

    /* audio is now normalised after call to getsndin  */
    /* csound->e0dbfs = csound->dbfs_to_float = FL(1.0); */

    if ((envoutyp = csound->GetEnv(csound, "SFOUTYP")) != NULL) {
      if (strcmp(envoutyp, "AIFF") == 0)
        O.filetyp = TYP_AIFF;
      else if (strcmp(envoutyp, "WAV") == 0)
        O.filetyp = TYP_WAV;
      else if (strcmp(envoutyp, "IRCAM") == 0)
        O.filetyp = TYP_IRCAM;
      else {
        csound->Message(csound, Str("%s not a recognised SFOUTYP env setting"),
                                envoutyp);
        return -1;
      }
    }
    {
      ++argv;
      while (--argc>0) {
        s = *argv++;
        if (*s++ == '-') {                        /* read all flags:  */
          while ((c = *s++) != '\0') {
            switch (c) {
            case 'o':
              FIND("no outfilename");
              O.outfilename = s;                 /* soundout name */
              for ( ; *s != '\0'; s++) ;
              if (strcmp(O.outfilename, "stdin") == 0) {
                csound->Message(csound, Str("-o cannot be stdin\n"));
                return -1;
              }
              break;
            case 'i':
              FIND("no noisefilename");
              nfile = s;
              for ( ; *s != '\0'; s++) ;
              break;
            case 'A':
              if (O.filetyp == TYP_WAV)
                csound->Warning(csound,
                                Str("-A overriding local default WAV out"));
              O.filetyp = TYP_AIFF;    /* AIFF output request*/
              break;
            case 'J':
              if (O.filetyp == TYP_AIFF || O.filetyp == TYP_WAV)
                csound->Warning(csound, Str("-J overriding local default "
                                            "AIFF/WAV out"));
              O.filetyp = TYP_IRCAM;   /* IRCAM output request */
              break;
            case 'W':
              if (O.filetyp == TYP_AIFF)
                csound->Warning(csound,
                                Str("-W overriding local default AIFF out"));
              O.filetyp = TYP_WAV;      /* WAV output request */
              break;
            case 'h':
              O.filetyp = TYP_RAW;
              O.sfheader = 0;           /* skip sfheader  */
              break;
            case 'c':
              O.outformat = AE_CHAR;     /* 8-bit char soundfile */
              break;
            case '8':
              O.outformat = AE_UNCH;     /* 8-bit unsigned char file */
              break;
            case 'a':
              O.outformat = AE_ALAW;     /* a-law soundfile */
              break;
            case 'u':
              O.outformat = AE_ULAW;     /* mu-law soundfile */
              break;
            case 's':
              O.outformat = AE_SHORT;    /* short_int soundfile */
              break;
            case 'l':
              O.outformat = AE_LONG;     /* long_int soundfile */
              break;
            case 'f':
              O.outformat = AE_FLOAT;    /* float soundfile */
              break;
            case 'R':
              O.rewrt_hdr = 1;
              break;
            case 'H':
              if (isdigit(*s)) {
                int n;
                sscanf(s, "%d%n", &O.heartbeat, &n);
                s += n;
              }
              else O.heartbeat = 1;
              break;
            case 't':
              FIND(Str("no t argument"));
#if defined(USE_DOUBLE)
              csound->sscanf(s,"%lf",&th);
#else
              csound->sscanf(s,"%f",&th);
#endif
              while (*++s);
              break;
            case 'S':
              FIND("no s arg");
              sscanf(s,"%d", &sh);
              while (*++s);
              break;
            case 'm':
              FIND("no m arg");
#if defined(USE_DOUBLE)
              csound->sscanf(s,"%lf",&g0);
#else
              csound->sscanf(s,"%f",&g0);
#endif
              while (*++s);
              break;
            case 'n':
              FIND(Str("no n argument"));
              sscanf(s,"%d", &m);
              while (*++s);
              break;
            case 'b':
              FIND(Str("no b argument"));
#if defined(USE_DOUBLE)
              csound->sscanf(s,"%lf",&beg);
#else
              csound->sscanf(s,"%f",&beg);
#endif
              while (*++s);
              break;
            case 'B': FIND(Str("no B argument"));
              sscanf(s,"%ld", &Beg);
              while (*++s);
              break;
            case 'e': FIND("no e arg");
#if defined(USE_DOUBLE)
              csound->sscanf(s,"%lf",&end);
#else
              csound->sscanf(s,"%f",&end);
#endif
              while (*++s);
              break;
            case 'E': FIND(Str("no E argument"));
              sscanf(s,"%ld", &End);
              while (*++s);
              break;
            case 'N': FIND(Str("no N argument"));
              sscanf(s,"%d", &N);
              while (*++s);
              break;
            case 'M': FIND(Str("no M argument"));
              sscanf(s,"%d", &M);
              while (*++s);
              break;
            case 'L': FIND(Str("no L argument"));
              sscanf(s,"%d", &L);
              while (*++s);
              break;
            case 'w': FIND(Str("no w argument"));
              sscanf(s,"%d", &W);
              while (*++s);
              break;
            case 'D': FIND(Str("no D argument"));
              sscanf(s,"%d", &D);
              while (*++s);
              break;
            case 'V':
              Verbose = 1; break;
            default:
              csound->Message(csound, Str("Looking at %c\n"), c);
              return dnoise_usage(csound, -1);  /* this exits with error */
            }
          }
        }
        else if (infile==NULL) {
          infile = --s;
          csound->Message(csound, Str("Infile set to %s\n"), infile);
        }
        else {
          csound->Message(csound, Str("End with %s\n"), s);
          return dnoise_usage(csound, -1);
        }
      }
    }
    if (infile == NULL) {
      csound->Message(csound, Str("dnoise: no input file\n"));
      return dnoise_usage(csound, -1);
    }
    if (nfile == NULL) {
      csound->Message(csound, Str("Must have an example noise file (-i name)\n"));
      return -1;
    }
    if ((inf = csound->SAsndgetset(csound, infile, &p, &beg_time,
                                   &input_dur, &sr, channel)) == NULL) {
      csound->Message(csound, Str("error while opening %s"), infile);
      return -1;
    }
    if (O.outformat == 0) O.outformat = p->format;
    O.sfsampsize = csound->sfsampsize(FORMAT2SF(O.outformat));
    if (O.filetyp == TYP_RAW) {
      O.sfheader = 0;
      O.rewrt_hdr = 0;
    }
    else
      O.sfheader = 1;
    if (O.outfilename == NULL)
      O.outfilename = "test";
    {
      SF_INFO sfinfo;
      char    *name;
      memset(&sfinfo, 0, sizeof(SF_INFO));
      sfinfo.samplerate = (int) p->sr;
      sfinfo.channels = (int) p->nchanls;
      sfinfo.format = TYPE2SF(O.filetyp) | FORMAT2SF(O.outformat);
      if (strcmp(O.outfilename, "stdout") != 0) {
        name = csound->FindOutputFile(csound, O.outfilename, "SFDIR");
        if (name == NULL) {
          csound->Message(csound, Str("cannot open %s.\n"), O.outfilename);
          return -1;
        }
        outfd = sf_open(name, SFM_WRITE, &sfinfo);
        if (outfd != NULL)
          csound->NotifyFileOpened(csound, name,
                      csound->type2csfiletype(O.filetyp, O.outformat), 1, 0);
        csound->Free(csound, name);
      }
      else
        outfd = sf_open_fd(1, SFM_WRITE, &sfinfo, 1);
      if (outfd == NULL) {
        csound->Message(csound, Str("cannot open %s."), O.outfilename);
        return -1;
      }
      /* register file to be closed by csoundReset() */
      (void)csound->CreateFileHandle(csound, &outfd, CSFILE_SND_W,
                                     O.outfilename);
      sf_command(outfd, SFC_SET_CLIPPING, NULL, SF_TRUE);
    }

    csound->SetUtilSr(csound, (MYFLT)p->sr);
    csound->SetUtilNchnls(csound, Chans = p->nchanls);

    /* read header info */
    if (R < FL(0.0))
      R = (MYFLT)p->sr;
    if (Chans < 0)
      Chans = (int) p->nchanls;
    p->nchanls = Chans;

    if (Chans > 2) {
      csound->Message(csound, Str("dnoise: input MUST be mono or stereo\n"));
      return -1;
    }

    /* read noise reference file */

    if ((fp = csound->SAsndgetset(csound, nfile, &pn, &beg_ntime,
                                  &input_ndur, &srn, channel)) == NULL) {
      csound->Message(csound, Str("dnoise: cannot open noise reference file\n"));
      return -1;
    }

    if (sr != srn) {
      csound->Message(csound, Str("Incompatible sample rates\n"));
      return -1;
    }
    /* calculate begin and end times in NOISE file */
    if (beg >= FL(0.0)) Beg = (long) (beg * R);
    if (end >= FL(0.0)) End = (long) (end * R);
    else if (End == 99999999) End = (long) (input_ndur * R);

    nMin = Beg * Chans;            /* total number of samples to skip */
    nMax = End - Beg;            /* number of samples per channel to process */

    /* largest valid FFT size is 8192 */
    if (N == 0)
      N = 1024;
    for (i = 1; i < 4096; i *= 2)
      if (i >= N)
        break;
    if (i != N)
      csound->Message(csound,
                      Str("dnoise: warning - N not a valid power of two; "
                          "revised N = %d\n"),i);
    N = i;
    N2 = N / 2;
    Np2 = N + 2;
    Ninv = FL(1.0) / N;

    if (W != -1) {
      if (M != 0)
        csound->Message(csound,
                        Str("dnoise: warning - do not specify both M and W\n"));
      else if (W == 0)
        M = 4*N;
      else if (W == 1)
        M = 2*N;
      else if (W == 2)
        M = N;
      else if (W == 3)
        M = N2;
      else
        csound->Message(csound, Str("dnoise: warning - invalid W ignored\n"));
    }

    if (M == 0)
      M = N;
    if ((M%2) == 0)
      Meven = 1;

    if (L == 0)
      L = M;
    if ((L%2) == 0)
      Leven = 1;

    if (M < 7) {
      csound->Message(csound, Str("dnoise: warning - M is too small\n"));
      exit(~1);
    }
    if (D == 0)
      D = M / 8;

    I = D;

    lj = (long) M + 3 * (long) D;
    lj *= (long) Chans;
    if (lj > 32767) {
      csound->Message(csound, Str("dnoise: M too large\n"));
      return -1;
    }
    lj = (long) L + 3 * (long) I;
    lj *= (long) Chans;
    if (lj > 32767) {
      csound->Message(csound, Str("dnoise: L too large\n"));
      return -1;
    }

    ibuflen = Chans * (M + 3 * D);
    obuflen = Chans * (L + 3 * I);
    outbufsiz = obuflen * sizeof(MYFLT);                 /* calc outbuf size */
#if 0
    outbuf = csound->Malloc(csound, (size_t) outbufsiz); /* & alloc bufspace */
#endif
    csound->Message(csound, Str("writing %u-byte blks of %s to %s"),
                    outbufsiz, csound->getstrformat(O.outformat),
                    O.outfilename);
    csound->Message(csound, " (%s)\n", csound->type2string(O.filetyp));
/*  spoutran = spoutsf; */

    minv = FL(1.0) / (MYFLT)m;
    md = m / 2;
    g0 = (MYFLT) pow(10.0,(double)(0.05*(double)g0));
    g0m = FL(1.0) - g0;
    th = (MYFLT) pow(10.0,(double)(0.05*(double)th));

    /* set up analysis window: The window is assumed to be symmetric
        with M total points.  After the initial memory allocation,
        aWin always points to the midpoint of the window (or one
        half sample to the right, if M is even); aLen is half the
        true window length (rounded down).  If the window duration
        is longer than the transform (M > N), then the window is
        multiplied by a sin(x)/x function to meet the condition:
        aWin[Ni] = 0 for i != 0.  In either case, the
        window is renormalized so that the phase vocoder amplitude
        estimates are properly scaled.  */

    if ((aWin = (MYFLT*) csound->Calloc(csound,
                                        (M+Meven) * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }

    aLen = M/2;
    aWin += aLen;

    hamming(aWin, aLen, Meven);
    for (i = 1; i <= aLen; i++) {
      aWin[-i] = aWin[i-1];
    }

    if (M > N) {
      if (Meven)
        *aWin *= (MYFLT)N * (MYFLT) sin(PI*0.5/(double)N) /( PI_F*FL(0.5));
      for (i = 1; i <= aLen; i++)
        aWin[i] *= (MYFLT) (N * sin(PI * ((double) i + 0.5 * (double) Meven)
                                    / (double) N)
                            / (PI * (i + 0.5 * (double) Meven)));
      for (i = 1; i <= aLen; i++)
        aWin[-i] = aWin[i - Meven];
    }

    sum = FL(0.0);
    for (i = -aLen; i <= aLen; i++)
      sum += aWin[i];

    sum = FL(2.0) / sum;    /* factor of 2 comes in later in trig identity */

    for (i = -aLen; i <= aLen; i++)
      aWin[i] *= sum;

    /* set up synthesis window:  For the minimal mean-square-error
        formulation (valid for N >= M), the synthesis window
        is identical to the analysis window (except for a
        scale factor), and both are even in length.  If N < M,
        then an interpolating synthesis window is used. */

    if ((sWin = (MYFLT*) csound->Calloc(csound,
                                        (L+Leven) * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }

    sLen = L/2;
    sWin += sLen;

    if (M <= N) {
      hamming(sWin, sLen, Leven);
      for (i = 1; i <= sLen; i++)
        sWin[-i] = sWin[i - Leven];

      for (i = -sLen; i <= sLen; i++)
        sWin[i] *= sum;

      sum = FL(0.0);
      for (i = -sLen; i <= sLen; i+=I)
        sum += sWin[i] * sWin[i];

      sum = FL(1.0) / sum;

      for (i = -sLen; i <= sLen; i++)
        sWin[i] *= sum;
    }
    else {
      hamming(sWin, sLen, Leven);
      for (i = 1; i <= sLen; i++)
        sWin[-i] = sWin[i - Leven];

      if (Leven)
        *sWin *= (MYFLT) (I * sin(PI*0.5/(double) I) / (PI*0.5));
      for (i = 1; i <= sLen; i++)
        sWin[i] *= (MYFLT)(I * sin(PI * ((double) i + 0.5 * (double) Leven)
                                   / (double) I)
                           / (PI * ((double) i + 0.5 * (double) Leven)));
      for (i = 1; i <= sLen; i++)
        sWin[i] = sWin[i - Leven];

      sum = FL(1.0) / sum;

      for (i = -sLen; i <= sLen; i++)
        sWin[i] *= sum;
    }

    /* set up input buffer:  nextIn always points to the next empty
        word in the input buffer (i.e., the sample following
        sample number (n + aLen)).  If the buffer is full,
        then nextIn jumps back to the beginning, and the old
        values are written over. */

    if ((ibuf1 = (MYFLT *) csound->Calloc(csound,
                                          ibuflen * sizeof(MYFLT))) == NULL) {
      ERR("dnoise: insufficient memory\n");
    }
    if ((ibuf2 = (MYFLT *) csound->Calloc(csound,
                                          ibuflen * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }

    /* set up output buffer:  nextOut always points to the next word
        to be shifted out.  The shift is simulated by writing the
        value to the standard output and then setting that word
        of the buffer to zero.  When nextOut reaches the end of
        the buffer, it jumps back to the beginning.  */

    if ((obuf1 = (MYFLT*) csound->Calloc(csound,
                                         obuflen * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }
    if ((obuf2 = (MYFLT*) csound->Calloc(csound,
                                         obuflen * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }

    /* set up analysis buffer for (N/2 + 1) channels: The input is real,
        so the other channels are redundant. */

    if ((fbuf = (MYFLT*) csound->Calloc(csound, Np2 * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }

/* noise reduction: calculate noise reference by taking as many
        consecutive FFT's as possible in noise soundfile, and
        averaging them all together.  Multiply by th*th to
        establish threshold for noise-gating in each bin. */

    if ((nref = (MYFLT*) csound->Calloc(csound,
                                        (N2 + 1) * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }

    if ((mbuf = (MYFLT*) csound->Calloc(csound,
                                        (m * Np2) * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }
    if ((nbuf = (MYFLT*) csound->Calloc(csound,
                                        (m * Np2) * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }
    if ((rsum = (MYFLT*) csound->Calloc(csound,
                                        (N2 + 1) * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }
    if ((ssum = (MYFLT*) csound->Calloc(csound,
                                        (N2 + 1) * sizeof(MYFLT))) == NULL) {
      ERR(Str("dnoise: insufficient memory\n"));
    }

    /* skip over nMin samples */
    while (nMin > (long)ibuflen) {
      if (!csound->CheckEvents(csound))
        csound->LongJmp(csound, 1);
      nread = csound->getsndin(csound, fp, ibuf1, ibuflen, pn);
      for(i=0; i < nread; i++)
        ibuf1[i] *= 1.0/csound->Get0dBFS(csound);
      if (nread < ibuflen) {
        ERR(Str("dnoise: begin time is greater than EOF of noise file!"));
      }
      nMin -= (long) ibuflen;
    }
    if (!csound->CheckEvents(csound))
      csound->LongJmp(csound, 1);
    i = (int) nMin;
    nread = csound->getsndin(csound, fp, ibuf1, i, pn);
    for(i=0; i < nread; i++)
        ibuf1[i] *= 1.0/csound->Get0dBFS(csound);
    if (nread < i) {
      ERR(Str("dnoise: begin time is greater than EOF of noise file!"));
    }
    k = 0;
    lj = Beg;  /* single channel only */
    while (lj < End) {
      if (!csound->CheckEvents(csound))
        csound->LongJmp(csound, 1);
      lj += (long) N;
      nread = csound->getsndin(csound, fp, fbuf, N, pn);
      for(i=0; i < nread; i++)
        fbuf[i] *= 1.0/csound->Get0dBFS(csound);
      if (nread < N)
        break;

      fbuf[N] = FL(0.0);
      fbuf[N + 1] = FL(0.0);

      fast(csound, fbuf, N);

      f = fbuf;
      for (i = 0; i <= N+1; i++, f++)
        *f  *= Ninv;

      f = nref;
      i0 = fbuf;
      i1 = i0 + 1;
      for (i = 0; i <= N2; i++, f++, i0 += 2, i1 += 2) {
        fac = *i0 * *i0;        /* fac = fbuf[2*i] * fbuf[2*i]; */
        fac += *i1 * *i1;       /* fac += fbuf[2*i+1] * fbuf[2*i+1]; */
        *f += fac;              /* nref[i] += fac; */
      }
      k++;
    }
    if (k == 0) {
      ERR(Str("dnoise: not enough samples of noise reference\n"));
    }
    fac = th * th / k;
    f = nref;
    for (i = 0; i <= N2; i++, f++)
      *f *= fac;                   /* nref[i] *= fac; */

    /* initialization: input time starts negative so that the rightmost
        edge of the analysis filter just catches the first non-zero
        input samples; output time equals input time. */

    /* zero ibuf1 to start */
    f = ibuf1;
    for (i = 0; i < ibuflen; i++, f++)
      *f = FL(0.0);
    if (!csound->CheckEvents(csound))
      csound->LongJmp(csound, 1);
    /* fill ibuf2 to start */
    nread = csound->getsndin(csound, inf, ibuf2, ibuflen, p);
/*     nread = read(inf, ibuf2, ibuflen*sizeof(MYFLT)); */
/*     nread /= sizeof(MYFLT); */
    for(i=0; i < nread; i++)
        ibuf2[i] *= 1.0/csound->Get0dBFS(csound);
    lnread = nread;
    f = ibuf2 + nread;
    for (i = nread; i < ibuflen; i++, f++)
      *f = FL(0.0);

    //rIn = ((MYFLT) R / D);
    //rOut = ((MYFLT) R / I);
    invR = FL(1.0) / R;
    nI = -(aLen / D) * D;    /* input time (in samples) */
    nO = nI;                 /* output time (in samples) */
    ibs = ibuflen + Chans * (nI - aLen - 1);    /* starting position in ib1 */
    ib1 = ibuf1;        /* filled with zeros to start */
    ib2 = ibuf2;        /* first buffer of speech */
    obs = Chans * (nO - sLen - 1);    /* starting position in ob1 */
    while (obs < 0) {
      obs += obuflen;
      first++;
    }
    ob1 = obuf1;        /* filled with garbage to start */
    ob2 = obuf2;        /* first output buffer */
    nImodR = nI;        /* for reporting progress */
    mi = 0;
    mj = m - md;
    if (mj >= m)
      mj = 0;
    mp = mi * Np2;

    nMax =  (long)(input_dur * R);          /* Do it all */
    nMaxOut = (long) (nMax * Chans);
    while (nI < (nMax + aLen)) {

      time = nI * invR;

      for (chan = 0; chan < Chans; chan++) {

    /* prepare for analysis: always begin reading from ib1 */
    /*                         always begin writing to ob1 */

        if (ibs >= ibuflen) {    /* done reading from ib1 */
          if (!csound->CheckEvents(csound))
            csound->LongJmp(csound, 1);
          /* swap buffers */
          ib0 = ib1;
          ib1 = ib2;
          ib2 = ib0;
          ibs -= ibuflen;
          /* fill ib2 */
          nread = csound->getsndin(csound, inf, ib2, ibuflen, p);
          for(i=0; i < nread; i++)
               ibuf2[i] *= 1.0/csound->Get0dBFS(csound);
          lnread += nread;
          f = ib2 + nread;
          for (i = nread; i < ibuflen; i++, f++)
            *f = FL(0.0);
        }
        ibc = ibs + chan;
        ibp = ib1 + ibs + chan;

        if (obs >= obuflen) {    /* done writing to ob1 */
          /* dump ob1 (except at beginning) */
          if (first > 0) {
            first--;
          }
          else {
            if ((oCnt + obuflen) < nMaxOut) {
              oCnt += writebuffer(csound, outfd, ob1, obuflen, &nrecs, &O);
            }
            else {
              i = (int) (nMaxOut - oCnt);
              oCnt += writebuffer(csound, outfd, ob1, i, &nrecs, &O);
            }
          }
          /* zero ob1 */
          f = ob1;
          for (i = 0; i < obuflen; i++, f++)
            *f = FL(0.0);
          /* swap buffers */
          ob0 = ob1;
          ob1 = ob2;
          ob2 = ob0;
          obs -= obuflen;
        }
        obc = obs + chan;
        obp = ob1 + obs + chan;

    /* analysis: The analysis subroutine computes the complex output at
        time n of (N/2 + 1) of the phase vocoder channels.  It operates
        on input samples (n - aLen) thru (n + aLen).
        It expects aWin to point to the center of a
        symmetric window of length (2 * aLen + 1).  It is the
        responsibility of the main program to ensure that these values
        are correct.  The results are returned in fbuf as succesive
        pairs of real and imaginary values for the lowest (N/2 + 1)
        channels.   The subroutine fast implements an
        efficient FFT call for a real input sequence.  */

        f = fbuf;
        for (i = 0; i < N+2; i++, f++)
          *f = FL(0.0);

        lk = nI - (long) aLen - 1;            /*time shift*/
        while ((long) lk < 0L)
          lk += (long) N;
        k = (int) (lk % (long) N);

        f = fbuf + k;
        w = aWin - aLen;
        for (i = -aLen; i <= aLen; i++, k++, f++, w++) {
          ibp += Chans;
          ibc += Chans;
          if (ibc >= ibuflen) {
            ibc = chan;
            ibp = ib2 + chan;
          }
          if (k >= N) {
            k = 0;
            f = fbuf;
          }
          *f += *w * *ibp;
        }

        fast(csound, fbuf, N);

        /* noise reduction: for each bin, calculate average magnitude-squared
            and calculate corresponding gain.  Apply this gain to delayed
            FFT values in mbuf[mj*Np2 + i?]. */

        if (chan == 0) {
          f = rsum;
          i0 = mbuf + mp;
          i1 = i0 + 1;
          j0 = mbuf + mj * Np2;
          j1 = j0 + 1;
          f0 = fbuf;
          f1 = f0 + 1;
          for (i = 0; i <= N2;
               i++, f++, i0+=2, i1+=2, f0+=2, f1+=2, j0+=2, j1+=2) {
            /*
             *  ii0 = 2 * i;
             *  ii1 = ii0 + 1;
             *
             *  rsum[i] -= mbuf[mp + ii0] * mbuf[mp + ii0];
             *  rsum[i] -= mbuf[mp + ii1] * mbuf[mp + ii1];
             *  rsum[i] += fbuf[ii0] * fbuf[ii0];
             *  rsum[i] += fbuf[ii1] * fbuf[ii1];
             */
            *f -= *i0 * *i0;
            *f -= *i1 * *i1;
            *f += *f0 * *f0;
            *f += *f1 * *f1;
            avg = minv * *f;        /* avg = minv * rsum[i]; */
            if (avg < FL(0.0))
              avg = FL(0.0);
            if (avg == FL(0.0))
              fac = FL(0.0);
            else
              fac = avg / (avg + nref[i]);
            for (j = 1; j < sh; j++)
              fac *= fac;
            gain = g0m * fac + g0;
            /*
             * mbuf[mp + ii0] = fbuf[ii0];
             * mbuf[mp + ii1] = fbuf[ii1];
             * fbuf[ii0] = gain * mbuf[mj*Np2 + ii0];
             * fbuf[ii1] = gain * mbuf[mj*Np2 + ii1];
             */
            *i0 = *f0;
            *i1 = *f1;
            *f0 = gain * *j0;
            *f1 = gain * *j1;
          }
        }
        else {
          f = ssum;
          i0 = nbuf + mp;
          i1 = i0 + 1;
          j0 = nbuf + mj * Np2;
          j1 = j0 + 1;
          f0 = fbuf;
          f1 = f0 + 1;
          for (i = 0; i <= N2;
               i++, f++, i0+=2, i1+=2, f0+=2, f1+=2, j0+=2, j1+=2) {
            /*
             *  ii0 = 2 * i;
             *  ii1 = ii0 + 1;
             *
             * ssum[i] -= nbuf[mp + ii0] * nbuf[mp + ii0];
             * ssum[i] -= nbuf[mp + ii1] * nbuf[mp + ii1];
             * ssum[i] += fbuf[ii0] * fbuf[ii0];
             * ssum[i] += fbuf[ii1] * fbuf[ii1];
             */
            *f -= *i0 * *i0;
            *f -= *i1 * *i1;
            *f += *f0 * *f0;
            *f += *f1 * *f1;
            avg = minv * *f;      /* avg = minv * ssum[i]; */
            if (avg < FL(0.0))
              avg = FL(0.0);
            if (avg == FL(0.0))
              fac = FL(0.0);
            else
              fac = avg / (avg + nref[i]);
            for (j = 1; j < sh; j++)
              fac *= fac;
            gain = g0m * fac + g0;
            /*
             * nbuf[mp + ii0] = fbuf[ii0];
             * nbuf[mp + ii1] = fbuf[ii1];
             * fbuf[ii0] = gain * nbuf[mj*Np2 + ii0];
             * fbuf[ii1] = gain * nbuf[mj*Np2 + ii1];
             */
            *i0 = *f0;
            *i1 = *f1;
            *f0 = gain * *j0;
            *f1 = gain * *j1;
          }
        }

        if (chan == (Chans - 1)) {
          if (++mi >= m)
            mi = 0;
          if (++mj >= m)
            mj = 0;
          mp = mi * Np2;
        }

    /* synthesis: The synthesis subroutine uses the Weighted Overlap-Add
        technique to reconstruct the time-domain signal.  The (N/2 + 1)
        phase vocoder channel outputs at time n are inverse Fourier
        transformed, windowed, and added into the output array. */

        fsst(csound, fbuf, N);

        lk = nO - (long) sLen - 1;            /*time shift*/
        while (lk < 0)
          lk += (long) N;
        k = (int) (lk % (long) N);

        f = fbuf + k;
        w = sWin - sLen;
        for (i = -sLen; i <= sLen; i++, k++, f++, w++) {
          obp += Chans;
          obc += Chans;
          if (obc >= obuflen) {
            obc = chan;
            obp = ob2 + chan;
          }
          if (k >= N) {
            k = 0;
            f = fbuf;
          }
          *obp += *w * *f;
        }

        if (flag) {
          if (nread < ibuflen) { /* EOF detected */
            flag = 0;
            if ((lnread / Chans) < nMax)
              nMax = (lnread / Chans);
          }
        }

      }

      ibs += (Chans * D);            /* starting point in ibuf */
      obs += (Chans * I);            /* starting point in obuf */

      nI += (long) D;                /* increment time */
      nO += (long) I;

      if (Verbose) {
        nImodR += D;
        if (nImodR > (long) R) {
          nImodR -= (long) R;
          csound->Message(csound,
                          Str("%5.1f seconds of input complete\n"),(time+D*invR));
        }
      }

    }

    nMaxOut = (long) (nMax * Chans);
    i = (int) (nMaxOut - oCnt);
    if (i > obuflen) {
      writebuffer(csound, outfd, ob1, obuflen, &nrecs, &O);
      i -= obuflen;
      ob1 = ob2;
    }
    if (i > 0)
      writebuffer(csound, outfd, ob1, i, &nrecs, &O);

/*  csound->rewriteheader(outfd); */
    csound->Message(csound, "\n\n");
    if (Verbose) {
      csound->Message(csound, Str("processing complete\n"));
      csound->Message(csound, "N = %d\n", N);
      csound->Message(csound, "M = %d\n", M);
      csound->Message(csound, "L = %d\n", L);
      csound->Message(csound, "D = %d\n", D);
    }
    return 0;
}
Beispiel #22
0
__inline__
mos_value _mos_send(mos_message *msg)
{
  mos_value rtnval;
#if mos_TRACE_ENABLED
  static int _mos_trace_lock = 0;
  int this_send_trace = _mos_send_trace;
  static unsigned long msgid;
  static unsigned long traceLevel;
  unsigned long this_traceLevel = traceLevel;
  unsigned long this_msgid = 0;
#endif

  /* save and set global mos_MSG for message stack chaining */
  mos_value old_mos_MSG = mos_MSG;
  mos_MSG = mos_MAKE_REF(msg);

#undef mos_MSG
#define mos_MSG mos_MAKE_REF(msg)

#if mos_TRACE_ENABLED
  if ( ! _mos_trace_lock && this_traceLevel < this_send_trace ) {
    this_msgid = ++ msgid;
    _mos_trace_lock ++;
    traceLevel ++;
    mos_printf(TRACE_OUTPUT, "TRACE: %03ld %ld: LOOKUP: %P\n", traceLevel, this_msgid, mos_MSG);
    _mos_trace_lock --;
  }
#endif
  
  _mos_lookup(msg);
  
  /* If meta lookup fails, search the defaultBehavior object */
  /* Otherwise use the undef::undefinedMethod to raise an error */
  if ( mos_EQ(mos_METH,mos_undef) ) {
    mos_map_slot *ms;
    
    if ( (ms = FIND(mos_o(defaultBehavior), mos_SEL)) ) {
      mos_METH = ms->_value; 
      mos_MIMPL = mos_o(defaultBehavior);
    } else {
      mos_METH = mos_m(undefinedValue,undefinedMethod); 
      mos_MIMPL = mos_undef;
    }
  }

#if mos_TRACE_ENABLED
  if ( ! _mos_trace_lock && this_traceLevel < this_send_trace ) {
    _mos_trace_lock ++;
    mos_printf(TRACE_OUTPUT, "TRACE: %03ld %ld: APPLY: %-P\n", traceLevel, this_msgid, mos_METH);
    _mos_trace_lock --;
  }
#endif

  rtnval = _mos_apply(msg);
  
#if mos_TRACE_ENABLED
  if ( ! _mos_trace_lock && this_traceLevel < this_send_trace ) {
    _mos_trace_lock ++;
    mos_printf(TRACE_OUTPUT, "TRACE: %03ld %ld: RETURN: %-P\n", traceLevel, this_msgid, rtnval);
    traceLevel --;
    _mos_trace_lock --;
  }
#endif

#undef mos_MSG

  mos_MSG = old_mos_MSG;
  
  return rtnval;
}
Beispiel #23
0
static int srconv(CSOUND *csound, int argc, char **argv)
{
    MYFLT
      *input,     /* pointer to start of input buffer */
      *output,    /* pointer to start of output buffer */
      *nextIn,    /* pointer to next empty word in input */
      *nextOut,   /* pointer to next empty word in output */
      *fxval = 0, /* pointer to start of time-array for time-vary function */
      *fyval = 0, /* pointer to start of P-scale-array for time-vary func */
      *i0,        /* pointer */
      *i1;        /* pointer */

    float
      *window,    /* pointer to center of analysis window */
      *wj,        /* pointer to window */
      *wj1;       /* pointer to window */

    int
      M = 2401,   /* length of window impulse response */
      N = 120,    /* length of sinc period */
      L = 120,    /* internal sample rate is L*Rin */
      m,          /* current input sample in buffer */
      o,          /* current input at L*Rin mod L */
      del,        /* increment */
      WinLen,     /* half-length of window at L*Rin */
      wLen,       /* half-length of window at Rin */
      jMin,       /* initial offset in window */
      mMax;       /* maximum valid m */

    long
      n,                        /* current input sample */
      nMax = 2000000000;        /* last input sample (unless EOF) */

    MYFLT
      beta = FL(6.8),           /* parameter for Kaiser window */
      sum,                      /* scale factor for renormalizing windows */
      fdel,                     /* float del */
      idel,                     /* float del */
      fo,                       /* float o */
      of,                       /* fractional o */
      fL = (MYFLT) L,           /* float L */
      iw,                       /* interpolated window */
      tvx0 = 0,                 /* current x value of time-var function */
      tvx1 = 0,                 /* next x value of time-var function */
      tvdx,                     /* tvx1 - tvx0 */
      tvy0 = 0,                 /* current y value of time-var function */
      tvy1 = 0,                 /* next y value of time-var function */
      tvdy,                     /* tvy1 - tvy0 */
      tvslope = 0,              /* tvdy / tvdx */
      time,                     /* n / Rin */
      invRin,                   /* 1. / Rin */
      P = FL(0.0),              /* Rin / Rout */
      Rin = FL(0.0),            /* input sampling rate */
      Rout = FL(0.0);           /* output sample rate */

    int
      i,k,                      /* index variables */
      nread,                    /* number of bytes read */
      tvflg = 0,                /* flag for time-varying time-scaling */
      tvnxt = 0,                /* counter for stepping thru time-var func */
      tvlen,                    /* length of time-varying function */
      Chans = 1,                /* number of channels */
      chan,                     /* current channel */
      Q = 2;                    /* quality factor */

    FILE        *tvfp = NULL;   /* time-vary function file */
    SOUNDIN     *p;
    int         channel = ALLCHNLS;
    MYFLT       beg_time = FL(0.0), input_dur = FL(0.0), sr = FL(0.0);
    char        *infile = NULL, *bfile = NULL;
    SNDFILE     *inf = NULL;
    char        c, *s;
    const char  *envoutyp;
    char        outformch = 's';
    unsigned    outbufsiz = 0U;
    SNDFILE     *outfd = NULL;
    OPARMS      O;
    int         block = 0;
    char        err_msg[256];

    O.outformat = AE_SHORT;
    /* csound->e0dbfs = csound->dbfs_to_float = FL(1.0);*/

    if ((envoutyp = csound->GetEnv(csound, "SFOUTYP")) != NULL) {
      if (strcmp(envoutyp, "AIFF") == 0)
        O.filetyp = TYP_AIFF;
      else if (strcmp(envoutyp, "WAV") == 0)
        O.filetyp = TYP_WAV;
      else if (strcmp(envoutyp, "IRCAM") == 0)
        O.filetyp = TYP_IRCAM;
      else {
        snprintf(err_msg, 256, Str("%s not a recognized SFOUTYP env setting"),
                envoutyp);
        dieu(csound, err_msg);
        return -1;
      }
    }

    /* call getopt to interpret commandline */

    ++argv;
    while (--argc > 0) {
      s = *argv++;
      if (*s++ == '-') {                /* read all flags:  */
        while ((c = *s++) != '\0') {
          switch (c) {
          case 'o':
            FIND(Str("no outfilename"))
            O.outfilename = s;         /* soundout name */
            for ( ; *s != '\0'; s++) ;
            if (strcmp(O.outfilename, "stdin") == 0) {
              csound->ErrorMsg(csound, Str("-o cannot be stdin"));
              return -1;
            }
#if defined WIN32
            if (strcmp(O.outfilename, "stdout") == 0) {
              csound->ErrorMsg(csound, Str("stdout audio not supported"));
              return -1;
            }
#endif
            break;
          case 'A':
            O.filetyp = TYP_AIFF;      /* AIFF output request*/
            break;
          case 'J':
            O.filetyp = TYP_IRCAM;     /* IRCAM output request */
            break;
          case 'W':
            O.filetyp = TYP_WAV;       /* WAV output request */
            break;
          case 'h':
            O.filetyp = TYP_RAW;       /* skip sfheader  */
            break;
          case 'c':
          case '8':
          case 'a':
          case 'u':
          case 's':
          case 'l':
          case '3':
          case 'f':
            outformch = set_output_format(csound, c, outformch, &O);
            break;
          case 'R':
            O.rewrt_hdr = 1;
            break;
          case 'H':
            if (isdigit(*s)) {
              int n;
              sscanf(s, "%d%n", &O.heartbeat, &n);
              s += n;
            }
            else O.heartbeat = 1;
            break;
          case 'N':
            O.ringbell = 1;        /* notify on completion */
            break;
          case 'Q':
            FIND(Str("No Q argument"))
            sscanf(s,"%d", &Q);
            while (*++s);
            break;
          case 'P':
            FIND(Str("No P argument"))
#if defined(USE_DOUBLE)
            csound->sscanf(s,"%lf", &P);
#else
            csound->sscanf(s,"%f", &P);
#endif
            while (*++s);
            break;
          case 'r':
            FIND(Str("No r argument"))
#if defined(USE_DOUBLE)
            csound->sscanf(s,"%lf", &Rout);
#else
            csound->sscanf(s,"%f", &Rout);
#endif
            while (*++s);
            break;
          case 'i':
            FIND(Str("No break file"))
            tvflg = 1;
            bfile = s;
            while ((*s++)) {}; s--;
            break;
          default:
            csound->Message(csound, Str("Looking at %c\n"), c);
            usage(csound);    /* this exits with error */
            return -1;
          }
        }
      }
      else if (infile == NULL) {
        infile = --s;
        csound->Message(csound, Str("Infile set to %s\n"), infile);
      }
      else {
        csound->Message(csound, Str("End with %s\n"), s);
        usage(csound);
        return -1;
      }
    }
    if (infile == NULL) {
      csound->Message(csound, Str("No input given\n"));
      usage(csound);
      return -1;
    }
    if ((inf = csound->SAsndgetset(csound, infile, &p, &beg_time,
                                   &input_dur, &sr, channel)) == NULL) {
      csound->ErrorMsg(csound, Str("error while opening %s"), infile);
      return -1;
    }
    if (Rin == FL(0.0))
      Rin = (MYFLT)p->sr;
    if (Chans == 0)
      Chans = (int) p->nchanls;
    if (Chans == 0)
      Chans = 1;

    if ((P != FL(0.0)) && (Rout != FL(0.0))) {
      strncpy(err_msg, Str("srconv: cannot specify both -r and -P"), 256);
      goto err_rtn_msg;
    }
    if (P != FL(0.0))
      Rout = Rin / P;
    else if (Rout == FL(0.0))
      Rout = Rin;

    if (tvflg) {
      P = FL(0.0);        /* will be reset to max in time-vary function */
      if ((tvfp = fopen(bfile, "r")) == NULL) {
        strncpy(err_msg,
                Str("srconv: cannot open time-vary function file"), 256);
        goto err_rtn_msg;
      }
      /* register file to be closed by csoundReset() */
      (void) csound->CreateFileHandle(csound, &tvfp, CSFILE_STD, bfile);
      if (UNLIKELY(fscanf(tvfp, "%d", &tvlen) != 1))
        csound->Message(csound, Str("Read failure\n"));
      if(tvlen <= 0) {
            strncpy(err_msg, Str("srconv: tvlen <= 0 "), 256);
            goto err_rtn_msg;
       }
      fxval = (MYFLT*) csound->Malloc(csound, tvlen * sizeof(MYFLT));
      fyval = (MYFLT*) csound->Malloc(csound, tvlen * sizeof(MYFLT));
      i0 = fxval;
      i1 = fyval;
      for (i = 0; i < tvlen; i++, i0++, i1++) {
#ifdef USE_DOUBLE
        if ((fscanf(tvfp, "%lf %lf", i0, i1)) != 2)
#else
        if ((fscanf(tvfp, "%f %f", i0, i1)) != 2)
#endif
          {
            strncpy(err_msg, Str("srconv: too few x-y pairs "
                                 "in time-vary function file"), 256);
            goto err_rtn_msg;
          }
        if (*i1 > P)
          P = *i1;
      }
      Rout = Rin / P;    /* this is min Rout */
      tvx0 = fxval[0];
      tvx1 = fxval[1];
      tvy0 = fyval[0];
      tvy1 = fyval[1];
      tvdx = tvx1 - tvx0;
      if (tvx0 != FL(0.0)) {
        strncpy(err_msg, Str("srconv: first x value "
                             "in time-vary function must be 0"), 256);
        goto err_rtn_msg;
      }
      if (tvy0 <= FL(0.0)) {
        strncpy(err_msg, Str("srconv: invalid initial y value "
                             "in time-vary function"),256);
        goto err_rtn_msg;
      }
      if (tvdx <= FL(0.0)) {
        strncpy(err_msg,
                       Str("srconv: invalid x values in time-vary function"),
                       256);
        goto err_rtn_msg;
      }
      tvdy = tvy1 - tvy0;
      tvslope = tvdy / tvdx;
      tvnxt = 1;
    }
    /* This is not right *********  */
    if (P != FL(0.0)) {
      csound->SetUtilSr(csound,Rin);
    }
    if (P == FL(0.0)) {
      csound->SetUtilSr(csound,Rout);
    }

    if (O.outformat == 0)
      O.outformat = AE_SHORT;//p->format;
    O.sfsampsize = csound->sfsampsize(FORMAT2SF(O.outformat));
    if (O.filetyp == TYP_RAW) {
      O.sfheader = 0;
      O.rewrt_hdr = 0;
    }
    else
      O.sfheader = 1;
#ifdef NeXT
    if (O.outfilename == NULL && !O.filetyp)
      O.outfilename = "test.snd";
    else if (O.outfilename == NULL)
      O.outfilename = "test";
#else
    if (O.outfilename == NULL) {
      if (O.filetyp == TYP_WAV)
        O.outfilename = "test.wav";
      else if (O.filetyp == TYP_AIFF)
        O.outfilename = "test.aif";
      else
        O.outfilename = "test";
    }
#endif
    {
      SF_INFO sfinfo;
      char    *name;
      memset(&sfinfo, 0, sizeof(SF_INFO));
      sfinfo.samplerate = (int) ((double) Rout + 0.5);
      sfinfo.channels = (int) p->nchanls;
      //printf("filetyp=%x outformat=%x\n", O.filetyp, O.outformat);
      sfinfo.format = TYPE2SF(O.filetyp) | FORMAT2SF(O.outformat);
      if (strcmp(O.outfilename, "stdout") != 0) {
        name = csound->FindOutputFile(csound, O.outfilename, "SFDIR");
        if (name == NULL) {
          snprintf(err_msg, 256, Str("cannot open %s."), O.outfilename);
          goto err_rtn_msg;
        }
        outfd = sf_open(name, SFM_WRITE, &sfinfo);
        if (outfd != NULL)
          csound->NotifyFileOpened(csound, name,
                                   csound->type2csfiletype(O.filetyp,
                                                           O.outformat),
                                   1, 0);
        else {
          snprintf(err_msg, 256, Str("libsndfile error: %s\n"), sf_strerror(NULL));
          goto err_rtn_msg;
        }
        csound->Free(csound, name);
      }
      else
        outfd = sf_open_fd(1, SFM_WRITE, &sfinfo, 1);
      if (outfd == NULL) {
        snprintf(err_msg, 256, Str("cannot open %s."), O.outfilename);
        goto err_rtn_msg;
      }
      /* register file to be closed by csoundReset() */
      (void) csound->CreateFileHandle(csound, &outfd, CSFILE_SND_W,
                                      O.outfilename);
      sf_command(outfd, SFC_SET_CLIPPING, NULL, SF_TRUE);
    }
    csound->SetUtilSr(csound, (MYFLT)p->sr);
    csound->SetUtilNchnls(csound, Chans = p->nchanls);

    outbufsiz = OBUF * O.sfsampsize;                   /* calc outbuf size */
    csound->Message(csound, Str("writing %d-byte blks of %s to %s"),
                    outbufsiz, csound->getstrformat(O.outformat),
                    O.outfilename);
    csound->Message(csound, " (%s)\n", csound->type2string(O.filetyp));

 /* this program performs arbitrary sample-rate conversion
    with high fidelity.  the method is to step through the
    input at the desired sampling increment, and to compute
    the output points as appropriately weighted averages of
    the surrounding input points.  there are two cases to
    consider: 1) sample rates are in a small-integer ratio -
    weights are obtained from table, 2) sample rates are in
    a large-integer ratio - weights are linearly
    interpolated from table.  */

 /* calculate increment: if decimating, then window is impulse response of low-
    pass filter with cutoff frequency at half of Rout; if interpolating,
    then window is ipulse response of lowpass filter with cutoff frequency
    at half of Rin. */

    fdel = ((MYFLT) (L * Rin) / Rout);
    del = (int) ((double) fdel + 0.5);
    idel = (MYFLT) del;
    if (del > L)
      N = del;
    if ((Q >= 1) && (Q <= 8))
      M = Q * N * 10 + 1;
    if (tvflg)
      fdel = tvy0 * L;

    invRin  =  FL(1.0) / Rin;

    /* make window: the window is the product of a kaiser and a sin(x)/x */
    window = (float*) csound->Calloc(csound, (size_t) (M + 2) * sizeof(float));
    WinLen = (M-1)/2;
    window += WinLen;
    wLen = (M/2 - L) / L;

    kaiser(M, window, WinLen, 1, (double) beta);

    for (i = 1; i <= WinLen; i++) {
      double  tmp = (double) N;
      tmp = tmp * sin(PI * (double) i / tmp) / (PI * (double) i);
      window[i] = (float) ((double) window[i] * tmp);
    }

    if (Rout < Rin) {
#if 0
      sum = (MYFLT) window[0];
      for (i = L-1; i <= WinLen; i += L)
        sum += (MYFLT) window[i];
      sum = FL(2.0) / sum;
#else
      sum = Rout / (Rin * (MYFLT) window[0]);
#endif
    }
    else
      sum = FL(1.0) / (MYFLT) window[0];

    window[0] = (float) ((double) window[0] * (double) sum);
    for (i = 1; i <= WinLen; i++) {
      window[i] = (float) ((double) window[i] * (double) sum);
      *(window - i) = window[i];
    }

    window[WinLen + 1] = 0.0f;

 /* set up input buffer:  nextIn always points to the next empty
    word in the input buffer.  If the buffer is full, then
    nextIn jumps back to the beginning, and the old values
    are written over. */

    input = (MYFLT*) csound->Calloc(csound, (size_t) IBUF * sizeof(MYFLT));

 /* set up output buffer:  nextOut always points to the next empty
    word in the output buffer.  If the buffer is full, then
    it is flushed, and nextOut jumps back to the beginning. */

    output = (MYFLT*) csound->Calloc(csound, (size_t) OBUF * sizeof(MYFLT));
    nextOut = output;

 /* initialization: */

    nread = csound->getsndin(csound, inf, input, IBUF2, p);
    for(i=0; i < nread; i++)
       input[i] *= 1.0/csound->Get0dBFS(csound);
    nMax = (long)(input_dur * p->sr);
    nextIn = input + nread;
    for (i = nread; i < IBUF2; i++)
      *(nextIn++) = FL(0.0);
    jMin = -(wLen + 1) * L;
    mMax = IBUF2;
    o = n = m = 0;
    fo = FL(0.0);

 /* main loop:   If nMax is not specified it is assumed to be very large
    and then readjusted when read detects the end of input. */

    while (n < nMax) {

      time = n * invRin;

      /* case 1:  (Rin / Rout) * 120 = integer  */

      if ((tvflg == 0) && (idel == fdel)) {
        /* apply window (window is sampled at L * Rin) */

        for (chan = 0; chan < Chans; chan++) {
          *nextOut = FL(0.0);
          k = Chans * (m - wLen) + chan - Chans;
          if (k < 0)
            k += IBUF;
          wj = window + jMin - o;
          for (i = -wLen; i <= wLen+1; i++){
            wj += L;
            k += Chans;
            if (k >= IBUF)
              k -= IBUF;
            *nextOut += (MYFLT) *wj * *(input + k);
          }
          nextOut++;
          if (nextOut >= (output + OBUF)) {
            nextOut = output;
            writebuffer(csound, output, &block, outfd, OBUF, &O);
          }
        }

        /* move window (window advances by del samples at L*Rin sample rate) */

        o += del;
        while (o >= L) {
          o -= L;
          n++;
          m++;
          if ((Chans * (m + wLen + 1)) >= mMax) {
            if (!csound->CheckEvents(csound))
              csound->LongJmp(csound, 1);
            mMax += IBUF2;
            if (nextIn >= (input + IBUF))
              nextIn = input;
            nread = csound->getsndin(csound, inf, nextIn, IBUF2, p);
            for(i=0; i < nread; i++)
               input[i] *= 1.0/csound->Get0dBFS(csound);
            nextIn += nread;
            if (nread < IBUF2)
              nMax = n + wLen + (nread / Chans) + 1;
            for (i = nread; i < IBUF2; i++)
              *(nextIn++) = FL(0.0);
          }
          if ((Chans * m) >= IBUF) {
            m = 0;
            mMax = IBUF2;
          }
        }
      }

      /* case 2: (Rin / Rout) * 120 = non-integer constant */

      else {

        /* apply window (window values are linearly interpolated) */

        for (chan = 0; chan < Chans; chan++) {
          *nextOut = FL(0.0);
          o = (int)fo;
          of = fo - o;
          wj = window + jMin - o;
          wj1 = wj + 1;
          k = Chans * (m - wLen) + chan - Chans;
          if (k < 0)
            k += IBUF;
          for (i = -wLen; i <= wLen+1; i++) {
            wj += L;
            wj1 += L;
            k += Chans;
            if (k >= IBUF)
              k -= IBUF;
            iw = (MYFLT) *wj + of * ((MYFLT) *wj1 - (MYFLT) *wj);
            *nextOut += iw * *(input + k);
          }
          nextOut++;
          if (nextOut >= (output + OBUF)) {
            nextOut = output;
            writebuffer(csound, output, &block, outfd, OBUF, &O);
          }
        }

        /* move window */

        fo += fdel;
        while (fo >= fL) {
          fo -= fL;
          n++;
          m++;
          if ((Chans * (m + wLen + 1)) >= mMax) {
            if (!csound->CheckEvents(csound))
              csound->LongJmp(csound, 1);
            mMax += IBUF2;
            if (nextIn >= (input + IBUF))
              nextIn = input;
            nread = csound->getsndin(csound, inf, nextIn, IBUF2, p);
            for(i=0; i < nread; i++)
               input[i] *= 1.0/csound->Get0dBFS(csound);
            nextIn += nread;
            if (nread < IBUF2)
              nMax = n + wLen + (nread / Chans) + 1;
            for (i = nread; i < IBUF2; i++)
              *(nextIn++) = FL(0.0);
          }
          if ((Chans * m) >= IBUF) {
            m = 0;
            mMax = IBUF2;
          }
        }

        if (tvflg && (time > FL(0.0))) {
          while (tvflg && (time >= tvx1)) {
            if (++tvnxt >= tvlen)
              tvflg = 0;
            else {
              tvx0 = tvx1;
              tvx1 = fxval[tvnxt];
              tvy0 = tvy1;
              tvy1 = fyval[tvnxt];
              tvdx = tvx1 - tvx0;
              if (tvdx <= FL(0.0)) {
                strncpy(err_msg, Str("srconv: invalid x values "
                                     "in time-vary function"), 256);
                goto err_rtn_msg;
              }
              tvdy = tvy1 - tvy0;
              tvslope = tvdy / tvdx;
            }
          }
          P = tvy0 + tvslope * (time - tvx0);
          fdel = (MYFLT) L * P;
        }
      }

    }
    nread = nextOut - output;
    writebuffer(csound, output, &block, outfd, nread, &O);
    csound->Message(csound, "\n\n");
    if (O.ringbell)
      csound->MessageS(csound, CSOUNDMSG_REALTIME, "\a");
    return 0;

 err_rtn_msg:
    csound->ErrorMsg(csound, err_msg);
    return -1;
}
Beispiel #24
0
bool
testBasic()
{
    StringMap   map;
    StringMapWriter	writer(map);

    writer.insert(1, 2, "test1");
    writer.insert(10, 20, "test2");

    FIND(find, 0, "")
    FIND(find, 1, "test1")
    FIND(find, 2, "")
    FIND(find, 15, "test2")
    FIND(find, 20, "")
    FIND(find, 100, "")

    FIND(findClosest, 0, "test1")
    FIND(findClosest, 1, "test1")
    FIND(findClosest, 8, "test2")
    FIND(findClosest, 100, "test2")

    writer.erase(1, 2);

    FIND(find, 1, "")

    writer.erase(10, 20);

    if (writer.size())
    {
	fprintf(stderr, "map should be empty\n");
	return false;
    }

    FIND(find, 15, "")
    FIND(findClosest, 15, "")

    return true;
}
Beispiel #25
0
/*  Called at init.
 *  If Env. var  MAKE_COLORS is set, redefines these
 *  variables color_misc_error ....
 */
void apply_make_colors()
{
  const mapping_def_t valid_names[] = {
    {"enter", 0, &color_dir_enter},
    {"leave", 0, &color_dir_leave},
    {"message", 0, &color_misc_message},
    {"error", 0, &color_misc_error},
    {"fatal", 0, &color_misc_fatal},
    {"run", 0, &color_execution},
    {"erase", &erase_in_line_flag, 0},
  };

  int name_index = -1;
  const char * const MAKE_COLORS = getenv("MAKE_COLORS");
  const char * key_pos = MAKE_COLORS;
  const char * colon_pos = NULL;

  char_range_t name = EMPTY_RANGE; /* delimits the keyword in the EnvVar value */
  char_range_t value = EMPTY_RANGE;
  if (! MAKE_COLORS)
    return;

  /* Example: MAKE_COLORS='erase=no:enter=0;42:leave=0;41:message=0' */
  for (; key_pos != 0; key_pos = colon_pos + 1)
    {
      const char * const assign_pos = strchr(key_pos, '=');
      if (! assign_pos) {
              OS (fatal, NILF, "Assignment ('=') missing in MAKE_COLORS: \"%s\"", key_pos);
      }

      colon_pos = strchr(assign_pos, ':');
      if (! colon_pos)
        colon_pos = assign_pos + strlen(assign_pos);

      /* delimit the keyword & value */
      RANGE_SET(name, key_pos, assign_pos);
      RANGE_SET(value, assign_pos + 1, colon_pos);

      if (RANGE_LEN(name) > 0)
        {
          FIND(valid_names, key, name, name_index);
          if (name_index == -1)
            {
              char * const s = RANGE_DUP(name);
              /* so this works even in out-of-memory, when s is NULL: */
              OS (fatal, NILF, "Invalid name in MAKE_COLORS: \"%s\"", PREVENT_NULL(s));
              free(s);
            }
         }
      else
        OS (fatal, NILF, "Empty name in MAKE_COLORS: \"%s\"", key_pos);

      /* Which kind of statement do we have? */
      if (valid_names[name_index].flag_destination)
        {
          /* Boolean statement */
          int * const destination = valid_names[name_index].flag_destination;
          if (RANGE_LEN(value) <= 0)
            {
              const char * const switch_name = valid_names[name_index].key;
              OS (fatal, NILF, "Empty value for switch \"%s\" in MAKE_COLORS", switch_name);
            }
          else if (RANGE_EQUALS(value, "yes"))
            {
              // DB(DB_VERBOSE, ("Erase in line enabled\n"));
              *destination = 1;
            }
          else if (RANGE_EQUALS(value, "no"))
            {
              // DB(DB_VERBOSE, ("Erase in line disabled\n"));
              *destination = 0;
            }
          else
            {
              /* Invalid (i.e. neither "yes" nor "no") */
              const char * const switch_name = valid_names[name_index].key;
              char * const guilty_part = RANGE_DUP(value);
              OSS (fatal, NILF, "Invalid value for switch \"%s\" in MAKE_COLORS: \"%s\"", switch_name, PREVENT_NULL(guilty_part));
              free(guilty_part);
            }
        }
      else
        {
          /* Colorization statement */
          const int value_is_valid = RANGE_LEN(value) > 0;
          if (value_is_valid)
            {
              // const char * const class_name = valid_names[name_index].key;
              const char * const color = PREVENT_NULL(RANGE_DUP(value));
              const char ** const color_destination = valid_names[name_index].color_destination;
              // DB(DB_VERBOSE, ("Applying color \"%s\" to class \"%s\"\n", color, class_name));
              *color_destination = color;
            }
          else
            {
              const char_range_t guilty_range = { key_pos, colon_pos };
              char * const guilty_part = RANGE_DUP(guilty_range);
              OS(fatal, NILF, "Invalid color mapping in MAKE_COLORS: \"%s\"", PREVENT_NULL(guilty_part));
              free(guilty_part);
            }
        }

      /* Done? */
      if (colon_pos[0] == '\0')
        break;
  }
}
Beispiel #26
0
/*-----------------------------------------------------------------------------
 *  load_potential -- load the potential from an object file
 *       This routine depends heavily on the object-loader (loadobj(3NEMO))
 *	BUG: if dataname is NULL, the routines dies when trying f_c interface 
 *		since it can't take strlen(NULL)
 *-----------------------------------------------------------------------------
 */
local proc load_potential(string fname, string parameters, string dataname, char type)
{
    char  name[256], cmd[256], path[256], pname[32];
    char  *fullname, *nemopath, *potpath;
    proc  pot, ini_pot;
    int never=0;

    if (parameters!=NULL && *parameters!=0) {              /* get parameters */
	local_npar = nemoinpd(parameters,local_par,MAXPAR);
        if (local_npar>MAXPAR)
            error ("get_potential: potential has too many parameters (%d)",
                            local_npar);
        if (local_npar<0)
            warning("get_potential: parsing error in: %s",parameters);
    } else
        local_npar=0;
    if (local_npar > 0 && local_par[0] != 0.0) { /* aid multiple potentials */
        local_omega = local_par[0];
        dprintf(1,"get_potential: setting local_omega = %g\n",local_omega);
    }

    if (first) {
        mysymbols(getparam("argv0"));      /* get symbols for this program */
        first = FALSE;			   /* and tell it we've initialized */
    }
    potpath = getenv("POTPATH");	     /* is there customized path ? */
    if (potpath==NULL) {			/* use default path */
       potpath = path;
       strcpy (path,".");
       nemopath = getenv("NEMO");
       if (nemopath==NULL) {
	 strcat(path,":");
	 strcat (path,nemopath);
	 strcat (path,"/obj/potential");		/* ".:$NEMO/obj/potential" */
       }
    }
    strcpy (name,fname);
    strcat (name,".so");
    fullname = pathfind (potpath, name);
    if (fullname!=NULL) {			/* .o found !! */
        dprintf (2,"Attempt to load potential from %s\n",name);
    	loadobj(fullname);
    } else {					/* no .o found */
	strcpy (path,".");	/* just look in current directory */
	strcpy (name,fname);
	strcat (name,".c");
	if (pathfind(".",name)==NULL)
	    error("get_potential: no potential %s found",name);
	dprintf (0,"[Compiling potential %s]\n",name);	
	sprintf (cmd,"make -f $NEMOLIB/Makefile.lib %s.so",name);
	dprintf (1,"%s\n",cmd);
	if (system(cmd)!=0)
	    error ("Error in compiling potential file");
	strcpy (name,fname);
	strcat (name,".so");
	fullname = name;	/* or use: findpath ? */
	loadobj (name);
    }

    /*
     * changed code 17/05/02 WD
     * debugged     18/09/08 WD
     *
     * after finding the .so file, we still need to find the proper 
     * routine to link with. This is controlled by the type.
     * if type = 'r',  behaviour depends on the macro SINGLEPREC:
     *                 If defined, we behave as for type='f', otherwise
     *                 as for type='d'.
     * if type = 'd',  we first look for "potential_double" and
     *                 restore to "potential" if no "potential_double" found
     * if type = 'f',  we only look for "potential_float"
     *
     * macro FIND(POTENTIAL) tries to find routine POTENTIAL          WD
     */
#define FIND(POTENTIAL) {							\
  strcpy(pname,POTENTIAL);                 /*   try potential           */	\
  mapsys(pname);								\
  pot = (proc) findfn (pname);             /*   try C-routine           */ 	\
  if (pot==NULL) {                         /*   IF not found          > */ 	\
    strcat(pname,"_");								\
    pot = (proc) findfn (pname);           /*     try F77-routine       */	\
    if (pot)                               /*     found!                */ 	\
      Qfortran = TRUE;	 	     /*       must be F77 then    */ 		\
  }                                        /*   <                       */ 	\
  if(pot) dprintf(1,"\"%s\" loaded from file \"%s\"\n",POTENTIAL,fullname);	\
}

    char search_type = type=='r'?
#ifdef SINGLEPREC
      'f'
#else
      'd'
#endif
      : type;

    if(search_type=='f') {                   /* IF type=f                 */
      FIND("potential_float");               /*   try "potential_float"   */
    } else if(search_type=='d') {            /* ELIF type=d               */
      FIND("potential_double");              /*   try "potential_double"  */
      if( pot==NULL) {                       /*   IF not found            */
	FIND("potential");                   /*     try "potential"       */
      }
    } else
      error("unknown data type '%c'\n",type);
#undef FIND
    /* it is perhaps possible that some fortran compilers will add __ for */
    /* routines that have embedded _ in their name.... we're not catching */
    /* those here yet !!!                                                 */
    /* e.g.  g77 options:  -fno-underscoring and -fno-second-underscore   */
    /* will fix this problem                                              */
    if (pot==NULL) {
      error("Couldn't find a suitable potential for type %c in %s",type,fname);
      return NULL;
    }

    strcpy(pname,"inipotential");
    mapsys(pname);
    ini_pot = (proc) findfn (pname);              		/* C */
    if (ini_pot==NULL) {
        strcpy(pname,"ini_potential");
        mapsys(pname);
        ini_pot = (proc) findfn (pname);	        	/* C */
        if (ini_pot==NULL) {
            strcpy(pname,"inipotential_");
            mapsys(pname);
            ini_pot = (proc) findfn (pname);		        /* F77 */
            if (ini_pot==NULL) {
                strcpy(pname,"ini_potential_");
                mapsys(pname);
                ini_pot = (proc) findfn (pname);        	/* F77 */
            }
        }
    }
    if (ini_pot)
        if (!Qfortran)
            (*ini_pot)(&local_npar,local_par,dataname); 	/* C */
        else {
            if (dataname==NULL)
                (*ini_pot)(&local_npar,local_par,dataname,0);   /* F77 */
            else
                (*ini_pot)(&local_npar,local_par,dataname,strlen(dataname)); /* F77 */

        }
    else {
        printf ("Warning: inipotential(_) not present in %s", fname);
        printf (",default taken\n");
    }
    l_potential = pot;            /* save these two for later references */
    l_inipotential = ini_pot;
    if (local_npar > 0 && local_par[0] != local_omega) {
    	local_omega = local_par[0];
    	dprintf(1,"get_potential: modified omega=%g\n",local_omega);
    }
    if (pot==NULL) potential_dummy_for_c();    /* should never be called */
    return pot;
}
Beispiel #27
0
bool dbBtreePage::find(dbDatabase* db, dbSearchContext& sc, int type, int height)
{
    int l = 0, n = nItems, r = n;
    dbTableDescriptor* table = &sc.cursor->table;
    height -= 1;

    switch (type) { 
      case dbField::tpBool:
      case dbField::tpInt1:
	FIND(keyInt1, int1);
      case dbField::tpInt2:
	FIND(keyInt2, int2);
      case dbField::tpInt4:
	FIND(keyInt4, int4);
      case dbField::tpInt8:
	FIND(keyInt8, int8);
#undef  CHECK
#define CHECK(a, b, inclusion) (a > b || (a == b && !inclusion))
      case dbField::tpReal4:
	FIND(keyReal4, real4);
      case dbField::tpReal8:
	FIND(keyReal8, real8);
      case dbField::tpString:
	if (sc.firstKey != NULL) { 
	    char* firstKey = sc.firstKey;
	    while (l < r)  {
		int i = (l+r) >> 1;
		if (strcmp(firstKey, &keyChar[keyStr[i].offs]) 
		    >= sc.firstKeyInclusion) 
		{
		    l = i + 1; 
		} else { 
		    r = i;
		}
	    }
	    assert(r == l); 
	}
	if (sc.lastKey != NULL) { 
	    char* lastKey = sc.lastKey;
	    if (height == 0) { 
		while (l < n) { 
		    if (strcmp(&keyChar[keyStr[l].offs], 
			       lastKey) >= sc.lastKeyInclusion) 
		    { 
			return false;
		    }
		    if (!sc.condition 
			|| db->evaluate(sc.condition, keyStr[l].oid, table))
		    {
			if (!sc.cursor->add(keyStr[l].oid)) { 
			    return false;
			}
		    }
		    l += 1;
		}
	    } else { 
		do {
		    dbBtreePage* pg = (dbBtreePage*)db->get(keyStr[l].oid);
		    if (!pg->find(db, sc, type, height)) {
			db->pool.unfix(pg);
			return false;
		    }
		    db->pool.unfix(pg);
		    if (l == n) { 
			return true;
		    }
		} while (strcmp(&keyChar[keyStr[l++].offs], lastKey) <= 0);
		return false;
	    }
	} else { 
	    if (height == 0) { 
		if (sc.condition) { 
		    while (l < n) { 
			if (db->evaluate(sc.condition, keyStr[l].oid, table)) {
			    if (!sc.cursor->add(keyStr[l].oid)) { 
				return false;
			    }
			}
			l += 1;
		    }
		} else { 
		    while (l < n) { 
			if (!sc.cursor->add(keyStr[l].oid)) { 
			    return false;
			}
			l += 1;
		    }
		}
	    } else {
		do {
		    dbBtreePage* pg = (dbBtreePage*)db->get(keyStr[l].oid);
		    if (!pg->find(db, sc, type, height)) {
			db->pool.unfix(pg);
			return false;
		    }
		    db->pool.unfix(pg);
		} while (++l <= n);
	    }
	}
	return true;
      default:
	assert(false);
    }
Beispiel #28
0
WireSyntax::WireSyntax()
{
    SYNTAX("Wire");

    DEFINE_VOID("Comment",
                CHOICE(
                    GLUE(
                        STRING("//"),
                        CHOICE(
                            FIND(AHEAD(CHAR('\n'))),
                            FIND(EOI())
                        )
                    ),
                    GLUE(
                        STRING("/*"),
                        REPEAT(
                            CHOICE(
                                INLINE("Comment"),
                                GLUE(
                                    NOT(STRING("*/")),
                                    ANY()
                                )
                            )
                        ),
                        STRING("*/")
                    )
                )
               );

    DEFINE_VOID("Whitespace",
                REPEAT(
                    CHOICE(
                        RANGE(" \t\n"),
                        INLINE("Comment")
                    )
                )
               );

    DEFINE("Name",
           REPEAT(1, EXCEPT(" \t\n:;"))
          );

    DEFINE("Value",
           CHOICE(
               REF("Atom"),
               REF("Properties"),
               REF("Items")
           )
          );

    DEFINE("Object",
           GLUE(
               REPEAT(0, 1,
                      GLUE(
                          REF("Name"),
                          INLINE("Whitespace"),
                          CHAR(':'),
                          INLINE("Whitespace")
                      )
                     ),
               INLINE("Value")
           )
          );

    DEFINE("Atom",
           REPEAT(
               GLUE(
                   NOT(
                       CHOICE(
                           GLUE(
                               REPEAT(RANGE(" \t")),
                               INLINE("Name"),
                               REPEAT(RANGE(" \t")),
                               CHAR(':')
                           ),
                           GLUE(
                               REPEAT(RANGE(" \t")),
                               RANGE("};,")
                           ),
                           STRING("\n\n")
                       )
                   ),
                   ANY()
               )
           )
          );

    DEFINE("Properties",
           GLUE(
               CHAR('{'),
               INLINE("Whitespace"),
               REPEAT(
                   GLUE(
                       REF("Object"),
                       INLINE("Whitespace"),
                       RANGE(";,"),
                       INLINE("Whitespace")
                   )
               ),
               CHAR('}')
           )
          );

    DEFINE("Items",
           GLUE(
               CHAR('['),
               INLINE("Whitespace"),
               REPEAT(
                   GLUE(
                       REF("Value"),
                       INLINE("Whitespace"),
                       RANGE(";,"),
                       INLINE("Whitespace")
                   )
               ),
               CHAR(']')
           )
          );

    ENTRY("Object");
}
Beispiel #29
0
static void
init (void)
{
  static int ready;

  if (ready)
    return;

  FD_ZERO (&v4v_fds);
  FD_ZERO (&v4v_afs);

#if 0
  v4v_dgram_inode.st_dev = (dev_t) (-1L);
  v4v_dgram_inode.st_ino = (ino_t) (-1L);
#endif

  FIND (socket);
  FIND (close);
  FIND (bind);
  FIND (connect);
  FIND (accept);
  FIND (listen);
  FIND (send);
  FIND (sendmsg);
  FIND (sendto);
  FIND (recv);
  FIND (recvmsg);
  FIND (recvfrom);
  FIND (dup);
  FIND (dup2);
  FIND (dup3);
  FIND (setsockopt);
  FIND (getsockopt);
  FIND (getsockname);
  FIND (getpeername);
  FIND (shutdown);

  ready++;
}
/* Analyze significant events from the events array, to form a
 * timeline of activities.
 */
void
construct_timeline (void)
{
  size_t i, j, k;
  struct pass_data *data;
  struct activity *activity;
  const char *first_kernel_message;

  for (i = 0; i < NR_TEST_PASSES; ++i) {
    data = &pass_data[i];

    /* Find an activity, by matching an event with the condition
     * `begin_cond' through to the second event `end_cond'.  Create an
     * activity object in the timeline from the result.
     */
#define FIND(name, flags, begin_cond, end_cond)                         \
    do {                                                                \
      activity = NULL;                                                  \
      for (j = 0; j < data->nr_events; ++j) {                           \
        if (begin_cond) {                                               \
          for (k = j+1; k < data->nr_events; ++k) {                     \
            if (end_cond) {                                             \
              if (i == 0)                                               \
                activity = add_activity (name, flags);                  \
              else                                                      \
                activity = find_activity (name);                        \
              break;                                                    \
            }                                                           \
          }                                                             \
          break;                                                        \
        }                                                               \
      }                                                                 \
      if (activity) {                                                   \
        activity->start_event[i] = j;                                   \
        activity->end_event[i] = k;                                     \
      }                                                                 \
      else                                                              \
        error (EXIT_FAILURE, 0, "could not find activity '%s' in pass '%zu'", \
               name, i);                                                \
    } while (0)

    /* Same as FIND() macro, but if no matching events are found,
     * ignore it.
     */
#define FIND_OPTIONAL(name, flags, begin_cond, end_cond)                \
    do {                                                                \
      activity = NULL;                                                  \
      for (j = 0; j < data->nr_events; ++j) {                           \
        if (begin_cond) {                                               \
          for (k = j+1; k < data->nr_events; ++k) {                     \
            if (end_cond) {                                             \
              if (i == 0)                                               \
                activity = add_activity (name, flags);                  \
              else                                                      \
                activity = find_activity (name);                        \
              break;                                                    \
            }                                                           \
          }                                                             \
          break;                                                        \
        }                                                               \
      }                                                                 \
      if (activity) {                                                   \
        activity->start_event[i] = j;                                   \
        activity->end_event[i] = k;                                     \
      }                                                                 \
    } while (0)

    /* Find multiple entries, where we check for:
     *   next_cond
     *   next_cond
     *   next_cond
     *   end_cond
     */
#define FIND_MULTIPLE(debug_name, flags, next_cond, end_cond, translate_message) \
    do {                                                                \
      activity = NULL;                                                  \
      for (j = 0; j < data->nr_events; ++j) {                           \
        if (next_cond) {                                                \
          CLEANUP_FREE char *message = translate_message (data->events[j].message); \
          if (activity)                                                 \
            activity->end_event[i] = j;                                 \
          if (i == 0)                                                   \
            activity = add_activity (message, flags);                   \
          else                                                          \
            activity = find_activity (message);                         \
          activity->start_event[i] = j;                                 \
        }                                                               \
        else if (end_cond)                                              \
          break;                                                        \
      }                                                                 \
      if (j < data->nr_events && activity)                              \
        activity->end_event[i] = j;                                     \
      else                                                              \
        error (EXIT_FAILURE, 0, "could not find activity '%s' in pass '%zu'", \
               debug_name, i);                                          \
    } while (0)

    /* Add one activity which is going to cover the whole process
     * from launch to close.  The launch event is always event 0.
     * NB: This activity must be called "run" (see below).
     */
    FIND ("run", LONG_ACTIVITY,
          j == 0, data->events[k].source == GUESTFS_EVENT_CLOSE);

    /* Find where we invoke supermin --build.  This should be a null
     * operation, but it still takes time to run the external command.
     */
    FIND ("supermin:build", 0,
          data->events[j].source == GUESTFS_EVENT_LIBRARY &&
          strstr (data->events[j].message,
                  "begin building supermin appliance"),
          data->events[k].source == GUESTFS_EVENT_LIBRARY &&
          strstr (data->events[k].message,
                  "finished building supermin appliance"));

    /* Find where we invoke qemu to test features. */
    FIND_OPTIONAL ("qemu:feature-detect", 0,
                   data->events[j].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[j].message,
                           "begin testing qemu features"),
                   data->events[k].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[k].message,
                           "finished testing qemu features"));

    /* Find where we run qemu. */
    FIND_OPTIONAL ("qemu", LONG_ACTIVITY,
                   data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
                   strstr (data->events[j].message, "-no-user-config"),
                   data->events[k].source == GUESTFS_EVENT_CLOSE);

    /* For the libvirt backend, connecting to libvirt, getting
     * capabilities, parsing capabilities etc.
     */
    FIND_OPTIONAL ("libvirt:connect", 0,
                   data->events[j].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[j].message, "connect to libvirt"),
                   data->events[k].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[k].message, "successfully opened libvirt handle"));
    FIND_OPTIONAL ("libvirt:get-libvirt-capabilities", 0,
                   data->events[j].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[j].message, "get libvirt capabilities"),
                   data->events[k].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[k].message, "parsing capabilities XML"));

    FIND_OPTIONAL ("libguestfs:parse-libvirt-capabilities", 0,
                   data->events[j].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[j].message, "parsing capabilities XML"),
                   data->events[k].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[k].message, "get_backend_setting"));

    FIND_OPTIONAL ("libguestfs:create-libvirt-xml", 0,
                   data->events[j].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[j].message, "create libvirt XML"),
                   data->events[k].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[k].message, "libvirt XML:"));

#if defined(__aarch64__)
#define FIRST_FIRMWARE_MESSAGE "UEFI firmware starting"
#else
#define SGABIOS_STRING "\033[1;256r\033[256;256H\033[6n"
#define FIRST_FIRMWARE_MESSAGE SGABIOS_STRING
#endif

    /* Try to determine the first message that the kernel prints. */
#if defined(__aarch64__)
    first_kernel_message = "Booting Linux on physical CPU";
#else
    first_kernel_message = "Probing EDD";
    for (j = 0; j < data->nr_events; ++j)
      if (data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, first_kernel_message))
        goto found_first_kernel_message;
    first_kernel_message = "Linux version ";
    for (j = 0; j < data->nr_events; ++j)
      if (data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, first_kernel_message))
        goto found_first_kernel_message;
    error (EXIT_FAILURE, 0, "could not determine first message printed by the kernel");
  found_first_kernel_message:
#endif

    /* For the libvirt backend, find the overhead of libvirt. */
    FIND_OPTIONAL ("libvirt:overhead", 0,
                   data->events[j].source == GUESTFS_EVENT_LIBRARY &&
                   strstr (data->events[j].message, "launch libvirt guest"),
                   data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
                   strstr (data->events[k].message, FIRST_FIRMWARE_MESSAGE));

    /* From starting qemu up to entering the BIOS is the qemu overhead. */
    FIND_OPTIONAL ("qemu:overhead", 0,
                   data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
                   strstr (data->events[j].message, "-no-user-config"),
                   data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
                   strstr (data->events[k].message, FIRST_FIRMWARE_MESSAGE));

    /* From entering the BIOS to starting the kernel is the BIOS overhead. */
    FIND_OPTIONAL ("bios:overhead", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, FIRST_FIRMWARE_MESSAGE),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, first_kernel_message));

#if defined(__i386__) || defined(__x86_64__)
    /* SGABIOS (option ROM). */
    FIND_OPTIONAL ("sgabios", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, SGABIOS_STRING),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "SeaBIOS (version"));
#endif

#if defined(__i386__) || defined(__x86_64__)
    /* SeaBIOS. */
    FIND ("seabios", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "SeaBIOS (version"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, first_kernel_message));
#endif

#if defined(__i386__) || defined(__x86_64__)
    /* SeaBIOS - only available when using debug messages. */
    FIND_OPTIONAL ("seabios:pci-probe", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "Searching bootorder for: /pci@"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "Scan for option roms"));
#endif

    /* Find where we run the guest kernel. */
    FIND ("kernel", LONG_ACTIVITY,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, first_kernel_message),
          data->events[k].source == GUESTFS_EVENT_CLOSE);

    /* Kernel startup to userspace. */
    FIND ("kernel:overhead", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, first_kernel_message),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "supermin:") &&
          strstr (data->events[k].message, "starting up"));

    /* The time taken to get into start_kernel function. */
    FIND_OPTIONAL ("kernel:entry", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, first_kernel_message),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "Linux version "));

#if defined(__i386__) || defined(__x86_64__)
    /* Alternatives patching instructions (XXX not very accurate we
     * really need some debug messages inserted into the code).
     */
    FIND ("kernel:alternatives", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "Last level dTLB entries"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "Freeing SMP alternatives"));
#endif

    /* ftrace patching instructions. */
    FIND_OPTIONAL ("kernel:ftrace", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "ftrace: allocating"),
          1);

    /* All initcall functions, before we enter userspace. */
    FIND ("kernel:initcalls-before-userspace", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "calling  "),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "Freeing unused kernel memory"));

    /* Find where we run supermin mini-initrd. */
    FIND ("supermin:mini-initrd", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "supermin:") &&
          strstr (data->events[j].message, "starting up"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "supermin: chroot"));

    /* Loading kernel modules from supermin initrd. */
    FIND_MULTIPLE
      ("supermin insmod", 0,
       data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
       strstr (data->events[j].message, "supermin: internal insmod"),
       data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
       strstr (data->events[j].message, "supermin: picked"),
       translate_supermin_insmod_message);

    /* Find where we run the /init script. */
    FIND ("/init", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "supermin: chroot"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "guestfsd --verbose"));

    /* Everything from the chroot to the first echo in the /init
     * script counts as bash overhead.
     */
    FIND ("bash:overhead", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "supermin: chroot"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "Starting /init script"));

    /* /init: Mount special filesystems. */
    FIND ("/init:mount-special", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "*guestfs_boot_analysis=1*"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "kmod static-nodes"));

    /* /init: Run kmod static-nodes */
    FIND ("/init:kmod-static-nodes", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "kmod static-nodes"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "systemd-tmpfiles"));

    /* /init: systemd-tmpfiles. */
    FIND ("/init:systemd-tmpfiles", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "systemd-tmpfiles"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "udev"));

    /* /init: start udevd. */
    FIND ("/init:udev-overhead", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "udevd --daemon"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "nullglob"));

    /* /init: set up network. */
    FIND ("/init:network-overhead", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "+ ip addr"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "+ test"));

    /* /init: probe MD arrays. */
    FIND ("/init:md-probe", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "+ mdadm"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "+ modprobe dm_mod"));

    /* /init: probe DM/LVM. */
    FIND ("/init:lvm-probe", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "+ modprobe dm_mod"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "+ ldmtool"));

    /* /init: probe Windows dynamic disks. */
    FIND ("/init:windows-dynamic-disks-probe", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "+ ldmtool"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "+ test"));

    /* Find where we run guestfsd. */
    FIND ("guestfsd", 0,
          data->events[j].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[j].message, "guestfsd --verbose"),
          data->events[k].source == GUESTFS_EVENT_APPLIANCE &&
          strstr (data->events[k].message, "fsync /dev/sda"));

    /* Shutdown process. */
    FIND ("shutdown", 0,
          data->events[j].source == GUESTFS_EVENT_TRACE &&
          STREQ (data->events[j].message, "close"),
          data->events[k].source == GUESTFS_EVENT_CLOSE);
  }

  construct_initcall_timeline ();
}