static int smacker_decode_header_tree(SmackVContext *smk, BitstreamContext *bc, int **recodes, int *last, int size) { int res; HuffContext huff; HuffContext tmp1, tmp2; VLC vlc[2] = { { 0 } }; int escapes[3]; DBCtx ctx; int err = 0; if(size >= UINT_MAX>>4){ // (((size + 3) >> 2) + 3) << 2 must not overflow av_log(smk->avctx, AV_LOG_ERROR, "size too large\n"); return AVERROR_INVALIDDATA; } tmp1.length = 256; tmp1.maxlength = 0; tmp1.current = 0; tmp1.bits = av_mallocz(256 * 4); tmp1.lengths = av_mallocz(256 * sizeof(int)); tmp1.values = av_mallocz(256 * sizeof(int)); tmp2.length = 256; tmp2.maxlength = 0; tmp2.current = 0; tmp2.bits = av_mallocz(256 * 4); tmp2.lengths = av_mallocz(256 * sizeof(int)); tmp2.values = av_mallocz(256 * sizeof(int)); if (!tmp1.bits || !tmp1.lengths || !tmp1.values || !tmp2.bits || !tmp2.lengths || !tmp2.values) { err = AVERROR(ENOMEM); goto error; } if (bitstream_read_bit(bc)) { smacker_decode_tree(bc, &tmp1, 0, 0); bitstream_skip(bc, 1); res = init_vlc(&vlc[0], SMKTREE_BITS, tmp1.length, tmp1.lengths, sizeof(int), sizeof(int), tmp1.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE); if(res < 0) { av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n"); err = res; goto error; } } else { av_log(smk->avctx, AV_LOG_ERROR, "Skipping low bytes tree\n"); } if (bitstream_read_bit(bc)) { smacker_decode_tree(bc, &tmp2, 0, 0); bitstream_skip(bc, 1); res = init_vlc(&vlc[1], SMKTREE_BITS, tmp2.length, tmp2.lengths, sizeof(int), sizeof(int), tmp2.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE); if(res < 0) { av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n"); err = res; goto error; } } else { av_log(smk->avctx, AV_LOG_ERROR, "Skipping high bytes tree\n"); } escapes[0] = bitstream_read(bc, 8); escapes[0] |= bitstream_read(bc, 8) << 8; escapes[1] = bitstream_read(bc, 8); escapes[1] |= bitstream_read(bc, 8) << 8; escapes[2] = bitstream_read(bc, 8); escapes[2] |= bitstream_read(bc, 8) << 8; last[0] = last[1] = last[2] = -1; ctx.escapes[0] = escapes[0]; ctx.escapes[1] = escapes[1]; ctx.escapes[2] = escapes[2]; ctx.v1 = &vlc[0]; ctx.v2 = &vlc[1]; ctx.recode1 = tmp1.values; ctx.recode2 = tmp2.values; ctx.last = last; huff.length = ((size + 3) >> 2) + 4; huff.maxlength = 0; huff.current = 0; huff.values = av_mallocz(huff.length * sizeof(int)); if (!huff.values) { err = AVERROR(ENOMEM); goto error; } if ((res = smacker_decode_bigtree(bc, &huff, &ctx)) < 0) err = res; bitstream_skip(bc, 1); if(ctx.last[0] == -1) ctx.last[0] = huff.current++; if(ctx.last[1] == -1) ctx.last[1] = huff.current++; if(ctx.last[2] == -1) ctx.last[2] = huff.current++; if (ctx.last[0] >= huff.length || ctx.last[1] >= huff.length || ctx.last[2] >= huff.length) { av_log(smk->avctx, AV_LOG_ERROR, "Huffman codes out of range\n"); err = AVERROR_INVALIDDATA; } *recodes = huff.values; error: if(vlc[0].table) ff_free_vlc(&vlc[0]); if(vlc[1].table) ff_free_vlc(&vlc[1]); av_free(tmp1.bits); av_free(tmp1.lengths); av_free(tmp1.values); av_free(tmp2.bits); av_free(tmp2.lengths); av_free(tmp2.values); return err; }


static int IntensityCompare(const void *x,const void *y)
{
  double
    intensity;

  PixelInfo
    *color_1,
    *color_2;

  color_1=(PixelInfo *) x;
  color_2=(PixelInfo *) y;
  intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-
    GetPixelInfoIntensity((const Image *) NULL,color_2);
  return((int) intensity);
}


rtsp_read_reply (AVFormatContext *s, RTSPMessageHeader *reply, unsigned char **content_ptr, int return_on_interleaved_data) { RTSPState *rt = s->priv_data; char buf[4096], buf1[1024], *q; unsigned char ch; const char *p; int ret, content_length, line_count = 0; unsigned char *content = NULL; memset(reply, 0, sizeof(*reply)); /* parse reply (XXX: use buffers) */ rt->last_reply[0] = '\0'; for(;;) { q = buf; for(;;) { ret = url_read_complete(rt->rtsp_hd, &ch, 1); #ifdef DEBUG_RTP_TCP dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch); #endif if (ret != 1) return -1; if (ch == '\n') break; if (ch == '$') { /* XXX: only parse it if first char on line ? */ if (return_on_interleaved_data) { return 1; } else rtsp_skip_packet(s); } else if (ch != '\r') { if ((q - buf) < sizeof(buf) - 1) *q++ = ch; } } *q = '\0'; dprintf(s, "line='%s'\n", buf); /* test if last line */ if (buf[0] == '\0') break; p = buf; if (line_count == 0) { /* get reply code */ get_word(buf1, sizeof(buf1), &p); get_word(buf1, sizeof(buf1), &p); reply->status_code = atoi(buf1); } else { rtsp_parse_line(reply, p); av_strlcat(rt->last_reply, p, sizeof(rt->last_reply)); av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply)); } line_count++; } if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0') av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id)); content_length = reply->content_length; if (content_length > 0) { /* leave some room for a trailing '\0' (useful for simple parsing) */ content = av_malloc(content_length + 1); (void)url_read_complete(rt->rtsp_hd, content, content_length); content[content_length] = '\0'; } if (content_ptr) *content_ptr = content; else av_free(content); /* EOS */ if (reply->notice == 2101 /* End-of-Stream Reached */ || reply->notice == 2104 /* Start-of-Stream Reached */ || reply->notice == 2306 /* Continuous Feed Terminated */) rt->state = RTSP_STATE_IDLE; else if (reply->notice >= 4400 && reply->notice < 5500) return AVERROR(EIO); /* data or server error */ else if (reply->notice == 2401 /* Ticket Expired */ || (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ ) return AVERROR(EPERM); return 0; }


PJ_DEF(pj_status_t) pjmedia_rtcp_fb_build_rpsi(
					    pjmedia_rtcp_session *session,
					    void *buf,
					    pj_size_t *length,
					    const pjmedia_rtcp_fb_rpsi *rpsi)
{
    pjmedia_rtcp_common *hdr;
    pj_uint8_t *p;
    unsigned bitlen, padlen, len;

    PJ_ASSERT_RETURN(session && buf && length && rpsi, PJ_EINVAL);

    bitlen = (unsigned)rpsi->rpsi_bit_len + 16;
    padlen = (32 - (bitlen % 32)) % 32;
    len = (3 + (bitlen+padlen)/32) * 4;
    if (len > *length)
	return PJ_ETOOSMALL;

    /* Build RTCP-FB RPSI header */
    hdr = (pjmedia_rtcp_common*)buf;
    pj_memcpy(hdr, &session->rtcp_rr_pkt.common,  sizeof(*hdr));
    hdr->pt = RTCP_PSFB;
    hdr->count = 3; /* FMT = 3 */
    hdr->length = pj_htons((pj_uint16_t)(len/4 - 1));

    /* Build RTCP-FB RPSI FCI */
    p = (pj_uint8_t*)hdr + sizeof(*hdr);
    /* PB (number of padding bits) */
    *p++ = (pj_uint8_t)padlen;
    /* Payload type */
    *p++ = rpsi->pt & 0x7F;
    /* RPSI bit string */
    pj_memcpy(p, rpsi->rpsi.ptr, rpsi->rpsi_bit_len/8);
    p += rpsi->rpsi_bit_len/8;
    if (rpsi->rpsi_bit_len % 8) {
	*p++ = *(rpsi->rpsi.ptr + rpsi->rpsi_bit_len/8);
    }
    /* Zero padding */
    if (padlen >= 8)
	pj_bzero(p, padlen/8);

    /* Finally */
    *length = len;

    return PJ_SUCCESS;
}


static int qemu_rbd_open(BlockDriverState *bs, const char *filename, int flags) { BDRVRBDState *s = bs->opaque; char pool[RBD_MAX_POOL_NAME_SIZE]; char snap_buf[RBD_MAX_SNAP_NAME_SIZE]; char conf[RBD_MAX_CONF_SIZE]; char clientname_buf[RBD_MAX_CONF_SIZE]; char *clientname; int r; if (qemu_rbd_parsename(filename, pool, sizeof(pool), snap_buf, sizeof(snap_buf), s->name, sizeof(s->name), conf, sizeof(conf)) < 0) { return -EINVAL; } s->snap = NULL; if (snap_buf[0] != '\0') { s->snap = g_strdup(snap_buf); } clientname = qemu_rbd_parse_clientname(conf, clientname_buf); r = rados_create(&s->cluster, clientname); if (r < 0) { error_report("error initializing"); return r; } if (strstr(conf, "conf=") == NULL) { r = rados_conf_read_file(s->cluster, NULL); if (r < 0) { error_report("error reading config file"); rados_shutdown(s->cluster); return r; } } if (conf[0] != '\0') { r = qemu_rbd_set_conf(s->cluster, conf); if (r < 0) { error_report("error setting config options"); rados_shutdown(s->cluster); return r; } } r = rados_connect(s->cluster); if (r < 0) { error_report("error connecting"); rados_shutdown(s->cluster); return r; } r = rados_ioctx_create(s->cluster, pool, &s->io_ctx); if (r < 0) { error_report("error opening pool %s", pool); rados_shutdown(s->cluster); return r; } r = rbd_open(s->io_ctx, s->name, &s->image, s->snap); if (r < 0) { error_report("error reading header from %s", s->name); rados_ioctx_destroy(s->io_ctx); rados_shutdown(s->cluster); return r; } bs->read_only = (s->snap != NULL); s->event_reader_pos = 0; r = qemu_pipe(s->fds); if (r < 0) { error_report("error opening eventfd"); goto failed; } fcntl(s->fds[0], F_SETFL, O_NONBLOCK); fcntl(s->fds[1], F_SETFL, O_NONBLOCK); qemu_aio_set_fd_handler(s->fds[RBD_FD_READ], qemu_rbd_aio_event_reader, NULL, qemu_rbd_aio_flush_cb, NULL, s); return 0; failed: rbd_close(s->image); rados_ioctx_destroy(s->io_ctx); rados_shutdown(s->cluster); return r; }


static MagickBooleanType Classify(Image *image,short **extrema,
  const double cluster_threshold,
  const double weighting_exponent,const MagickBooleanType verbose,
  ExceptionInfo *exception)
{
#define SegmentImageTag  "Segment/Image"
#define ThrowClassifyException(severity,tag,label) \
{\
  for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) \
  { \
    next_cluster=cluster->next; \
    cluster=(Cluster *) RelinquishMagickMemory(cluster); \
  } \
  if (squares != (double *) NULL) \
    { \
      squares-=255; \
      free_squares=squares; \
      free_squares=(double *) RelinquishMagickMemory(free_squares); \
    } \
  ThrowBinaryException(severity,tag,label); \
}

  CacheView
    *image_view;

  Cluster
    *cluster,
    *head,
    *last_cluster,
    *next_cluster;

  ExtentPacket
    blue,
    green,
    red;

  MagickOffsetType
    progress;

  double
    *free_squares;

  MagickStatusType
    status;

  register ssize_t
    i;

  register double
    *squares;

  size_t
    number_clusters;

  ssize_t
    count,
    y;

  /*
    Form clusters.
  */
  cluster=(Cluster *) NULL;
  head=(Cluster *) NULL;
  squares=(double *) NULL;
  (void) memset(&red,0,sizeof(red));
  (void) memset(&green,0,sizeof(green));
  (void) memset(&blue,0,sizeof(blue));
  while (DefineRegion(extrema[Red],&red) != 0)
  {
    green.index=0;
    while (DefineRegion(extrema[Green],&green) != 0)
    {
      blue.index=0;
      while (DefineRegion(extrema[Blue],&blue) != 0)
      {
        /*
          Allocate a new class.
        */
        if (head != (Cluster *) NULL)
          {
            cluster->next=(Cluster *) AcquireMagickMemory(
              sizeof(*cluster->next));
            cluster=cluster->next;
          }
        else
          {
            cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
            head=cluster;
          }
        if (cluster == (Cluster *) NULL)
          ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
            image->filename);
        /*
          Initialize a new class.
        */
        cluster->count=0;
        cluster->red=red;
        cluster->green=green;
        cluster->blue=blue;
        cluster->next=(Cluster *) NULL;
      }
    }
  }
  if (head == (Cluster *) NULL)
    {
      /*
        No classes were identified-- create one.
      */
      cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
      if (cluster == (Cluster *) NULL)
        ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
          image->filename);
      /*
        Initialize a new class.
      */
      cluster->count=0;
      cluster->red=red;
      cluster->green=green;
      cluster->blue=blue;
      cluster->next=(Cluster *) NULL;
      head=cluster;
    }
  /*
    Count the pixels for each cluster.
  */
  status=MagickTrue;
  count=0;
  progress=0;
  image_view=AcquireVirtualCacheView(image,exception);
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    register const Quantum
      *p;

    register ssize_t
      x;

    p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
    if (p == (const Quantum *) NULL)
      break;
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
        if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) >=
             (cluster->red.left-SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelRed(image,p)) <=
             (cluster->red.right+SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) >=
             (cluster->green.left-SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p)) <=
             (cluster->green.right+SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) >=
             (cluster->blue.left-SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p)) <=
             (cluster->blue.right+SafeMargin)))
          {
            /*
              Count this pixel.
            */
            count++;
            cluster->red.center+=(double) ScaleQuantumToChar(
              GetPixelRed(image,p));
            cluster->green.center+=(double) ScaleQuantumToChar(
              GetPixelGreen(image,p));
            cluster->blue.center+=(double) ScaleQuantumToChar(
              GetPixelBlue(image,p));
            cluster->count++;
            break;
          }
      p+=GetPixelChannels(image);
    }
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
      {
        MagickBooleanType
          proceed;

#if defined(MAGICKCORE_OPENMP_SUPPORT)
        #pragma omp atomic
#endif
        progress++;
        proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows);
        if (proceed == MagickFalse)
          status=MagickFalse;
      }
  }
  image_view=DestroyCacheView(image_view);
  /*
    Remove clusters that do not meet minimum cluster threshold.
  */
  count=0;
  last_cluster=head;
  next_cluster=head;
  for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
  {
    next_cluster=cluster->next;
    if ((cluster->count > 0) &&
        (cluster->count >= (count*cluster_threshold/100.0)))
      {
        /*
          Initialize cluster.
        */
        cluster->id=count;
        cluster->red.center/=cluster->count;
        cluster->green.center/=cluster->count;
        cluster->blue.center/=cluster->count;
        count++;
        last_cluster=cluster;
        continue;
      }
    /*
      Delete cluster.
    */
    if (cluster == head)
      head=next_cluster;
    else
      last_cluster->next=next_cluster;
    cluster=(Cluster *) RelinquishMagickMemory(cluster);
  }
  number_clusters=(size_t) count;
  if (verbose != MagickFalse)
    {
      /*
        Print cluster statistics.
      */
      (void) FormatLocaleFile(stdout,"Fuzzy C-means Statistics\n");
      (void) FormatLocaleFile(stdout,"===================\n\n");
      (void) FormatLocaleFile(stdout,"\tCluster Threshold = %g\n",(double)
        cluster_threshold);
      (void) FormatLocaleFile(stdout,"\tWeighting Exponent = %g\n",(double)
        weighting_exponent);
      (void) FormatLocaleFile(stdout,"\tTotal Number of Clusters = %.20g\n\n",
        (double) number_clusters);
      /*
        Print the total number of points per cluster.
      */
      (void) FormatLocaleFile(stdout,"\n\nNumber of Vectors Per Cluster\n");
      (void) FormatLocaleFile(stdout,"=============================\n\n");
      for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
        (void) FormatLocaleFile(stdout,"Cluster #%.20g = %.20g\n",(double)
          cluster->id,(double) cluster->count);
      /*
        Print the cluster extents.
      */
      (void) FormatLocaleFile(stdout,
        "\n\n\nCluster Extents:        (Vector Size: %d)\n",MaxDimension);
      (void) FormatLocaleFile(stdout,"================");
      for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
      {
        (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
          cluster->id);
        (void) FormatLocaleFile(stdout,
          "%.20g-%.20g  %.20g-%.20g  %.20g-%.20g\n",(double)
          cluster->red.left,(double) cluster->red.right,(double)
          cluster->green.left,(double) cluster->green.right,(double)
          cluster->blue.left,(double) cluster->blue.right);
      }
      /*
        Print the cluster center values.
      */
      (void) FormatLocaleFile(stdout,
        "\n\n\nCluster Center Values:        (Vector Size: %d)\n",MaxDimension);
      (void) FormatLocaleFile(stdout,"=====================");
      for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
      {
        (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
          cluster->id);
        (void) FormatLocaleFile(stdout,"%g  %g  %g\n",(double)
          cluster->red.center,(double) cluster->green.center,(double)
          cluster->blue.center);
      }
      (void) FormatLocaleFile(stdout,"\n");
    }
  if (number_clusters > 256)
    ThrowClassifyException(ImageError,"TooManyClusters",image->filename);
  /*
    Speed up distance calculations.
  */
  squares=(double *) AcquireQuantumMemory(513UL,sizeof(*squares));
  if (squares == (double *) NULL)
    ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
      image->filename);
  squares+=255;
  for (i=(-255); i <= 255; i++)
    squares[i]=(double) i*(double) i;
  /*
    Allocate image colormap.
  */
  if (AcquireImageColormap(image,number_clusters,exception) == MagickFalse)
    ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed",
      image->filename);
  i=0;
  for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
  {
    image->colormap[i].red=(double) ScaleCharToQuantum((unsigned char)
      (cluster->red.center+0.5));
    image->colormap[i].green=(double) ScaleCharToQuantum((unsigned char)
      (cluster->green.center+0.5));
    image->colormap[i].blue=(double) ScaleCharToQuantum((unsigned char)
      (cluster->blue.center+0.5));
    i++;
  }
  /*
    Do course grain classes.
  */
  image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static) shared(progress,status) \
    magick_number_threads(image,image,image->rows,1)
#endif
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    Cluster
      *clust;

    register const PixelInfo
      *magick_restrict p;

    register ssize_t
      x;

    register Quantum
      *magick_restrict q;

    if (status == MagickFalse)
      continue;
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
    if (q == (Quantum *) NULL)
      {
        status=MagickFalse;
        continue;
      }
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      SetPixelIndex(image,0,q);
      for (clust=head; clust != (Cluster *) NULL; clust=clust->next)
      {
        if (((ssize_t) ScaleQuantumToChar(GetPixelRed(image,q)) >=
             (clust->red.left-SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelRed(image,q)) <=
             (clust->red.right+SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q)) >=
             (clust->green.left-SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q)) <=
             (clust->green.right+SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q)) >=
             (clust->blue.left-SafeMargin)) &&
            ((ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q)) <=
             (clust->blue.right+SafeMargin)))
          {
            /*
              Classify this pixel.
            */
            SetPixelIndex(image,(Quantum) clust->id,q);
            break;
          }
      }
      if (clust == (Cluster *) NULL)
        {
          double
            distance_squared,
            local_minima,
            numerator,
            ratio,
            sum;

          register ssize_t
            j,
            k;

          /*
            Compute fuzzy membership.
          */
          local_minima=0.0;
          for (j=0; j < (ssize_t) image->colors; j++)
          {
            sum=0.0;
            p=image->colormap+j;
            distance_squared=squares[(ssize_t) ScaleQuantumToChar(
              GetPixelRed(image,q))-(ssize_t)
              ScaleQuantumToChar(ClampToQuantum(p->red))]+squares[(ssize_t)
              ScaleQuantumToChar(GetPixelGreen(image,q))-(ssize_t)
              ScaleQuantumToChar(ClampToQuantum(p->green))]+squares[(ssize_t)
              ScaleQuantumToChar(GetPixelBlue(image,q))-(ssize_t)
              ScaleQuantumToChar(ClampToQuantum(p->blue))];
            numerator=distance_squared;
            for (k=0; k < (ssize_t) image->colors; k++)
            {
              p=image->colormap+k;
                distance_squared=squares[(ssize_t) ScaleQuantumToChar(
                  GetPixelRed(image,q))-(ssize_t)
                  ScaleQuantumToChar(ClampToQuantum(p->red))]+squares[
                  (ssize_t) ScaleQuantumToChar(GetPixelGreen(image,q))-(ssize_t)
                  ScaleQuantumToChar(ClampToQuantum(p->green))]+squares[
                  (ssize_t) ScaleQuantumToChar(GetPixelBlue(image,q))-(ssize_t)
                  ScaleQuantumToChar(ClampToQuantum(p->blue))];
              ratio=numerator/distance_squared;
              sum+=SegmentPower(ratio);
            }
            if ((sum != 0.0) && ((1.0/sum) > local_minima))
              {
                /*
                  Classify this pixel.
                */
                local_minima=1.0/sum;
                SetPixelIndex(image,(Quantum) j,q);
              }
          }
        }
      q+=GetPixelChannels(image);
    }
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
      status=MagickFalse;
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
      {
        MagickBooleanType
          proceed;

#if defined(MAGICKCORE_OPENMP_SUPPORT)
        #pragma omp atomic
#endif
        progress++;
        proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows);
        if (proceed == MagickFalse)
          status=MagickFalse;
      }
  }
  image_view=DestroyCacheView(image_view);
  status&=SyncImage(image,exception);
  /*
    Relinquish resources.
  */
  for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
  {
    next_cluster=cluster->next;
    cluster=(Cluster *) RelinquishMagickMemory(cluster);
  }
  squares-=255;
  free_squares=squares;
  free_squares=(double *) RelinquishMagickMemory(free_squares);
  return(MagickTrue);
}


static int slirp_hostfwd(SlirpState *s, const char *redir_str, int legacy_format) { struct in_addr host_addr = { .s_addr = INADDR_ANY }; struct in_addr guest_addr = { .s_addr = 0 }; int host_port, guest_port; const char *p; char buf[256]; int is_udp; char *end; p = redir_str; if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) { goto fail_syntax; } if (!strcmp(buf, "tcp") || buf[0] == '\0') { is_udp = 0; } else if (!strcmp(buf, "udp")) { is_udp = 1; } else { goto fail_syntax; } if (!legacy_format) { if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) { goto fail_syntax; } if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) { goto fail_syntax; } } if (get_str_sep(buf, sizeof(buf), &p, legacy_format ? ':' : '-') < 0) { goto fail_syntax; } host_port = strtol(buf, &end, 0); if (*end != '\0' || host_port < 0 || host_port > 65535) { goto fail_syntax; } if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) { goto fail_syntax; } if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) { goto fail_syntax; } guest_port = strtol(p, &end, 0); if (*end != '\0' || guest_port < 1 || guest_port > 65535) { goto fail_syntax; } if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr, guest_port) < 0) { error_report("could not set up host forwarding rule '%s'", redir_str); return -1; } return 0; fail_syntax: error_report("invalid host forwarding rule '%s'", redir_str); return -1; }


static inline int unreference_pic ( H264Context * h , Picture * pic , int refmask ) {
 int i ;
 if ( pic -> reference &= refmask ) {
 return 0 ;
 }
 else {
 for ( i = 0 ;
 h -> delayed_pic [ i ] ;
 i ++ ) if ( pic == h -> delayed_pic [ i ] ) {
 pic -> reference = DELAYED_PIC_REF ;
 break ;
 }
 return 1 ;
 }
 }


static inline unsigned short ScaleQuantumToShort(const Quantum quantum)
{
#if !defined(MAGICKCORE_HDRI_SUPPORT)
  return((unsigned short) (257UL*quantum));
#else
  if (quantum <= 0.0)
    return(0);
  if ((257.0*quantum) >= 65535.0)
    return(65535);
  return((unsigned short) (257.0*quantum+0.5));
#endif
}


static void vc1_put_ver_16b_shift2_mmx(int16_t *dst, const uint8_t *src, x86_reg stride, int rnd, int64_t shift) { __asm__ volatile( "mov $3, %%"REG_c" \n\t" LOAD_ROUNDER_MMX("%5") "movq "MANGLE(ff_pw_9)", %%mm6 \n\t" "1: \n\t" "movd (%0), %%mm2 \n\t" "add %2, %0 \n\t" "movd (%0), %%mm3 \n\t" "punpcklbw %%mm0, %%mm2 \n\t" "punpcklbw %%mm0, %%mm3 \n\t" SHIFT2_LINE( 0, 1, 2, 3, 4) SHIFT2_LINE( 24, 2, 3, 4, 1) SHIFT2_LINE( 48, 3, 4, 1, 2) SHIFT2_LINE( 72, 4, 1, 2, 3) SHIFT2_LINE( 96, 1, 2, 3, 4) SHIFT2_LINE(120, 2, 3, 4, 1) SHIFT2_LINE(144, 3, 4, 1, 2) SHIFT2_LINE(168, 4, 1, 2, 3) "sub %6, %0 \n\t" "add $8, %1 \n\t" "dec %%"REG_c" \n\t" "jnz 1b \n\t" : "+r"(src), "+r"(dst) : "r"(stride), "r"(-2*stride), "m"(shift), "m"(rnd), "r"(9*stride-4) NAMED_CONSTRAINTS_ADD(ff_pw_9) : "%"REG_c, "memory" ); }


PJ_DEF(pj_status_t) pjmedia_wav_player_port_create( pj_pool_t *pool,
						     const char *filename,
						     unsigned ptime,
						     unsigned options,
						     pj_ssize_t buff_size,
						     pjmedia_port **p_port )
{
    pjmedia_wave_hdr wave_hdr;
    pj_ssize_t size_to_read, size_read;
    struct file_reader_port *fport;
    pjmedia_audio_format_detail *ad;
    pj_off_t pos;
    pj_str_t name;
    unsigned samples_per_frame;
    pj_status_t status = PJ_SUCCESS;

    /* Check arguments. */
    PJ_ASSERT_RETURN(pool && filename && p_port, PJ_EINVAL);

    /* Check the file really exists. */
    if (!pj_file_exists(filename)) {
	return PJ_ENOTFOUND;
    }

    /* Normalize ptime */
    if (ptime == 0)
	ptime = 20;

    /* Normalize buff_size */
    if (buff_size < 1) buff_size = PJMEDIA_FILE_PORT_BUFSIZE;

    /* Create fport instance. */
    fport = create_file_port(pool);
    if (!fport) {
	return PJ_ENOMEM;
    }

    /* Get the file size. */
    fport->fsize = pj_file_size(filename);

    /* Size must be more than WAVE header size */
    if (fport->fsize <= sizeof(pjmedia_wave_hdr)) {
	return PJMEDIA_ENOTVALIDWAVE;
    }

    /* Open file. */
    status = pj_file_open( pool, filename, PJ_O_RDONLY, &fport->fd);
    if (status != PJ_SUCCESS)
	return status;

    /* Read the file header plus fmt header only. */
    size_read = size_to_read = sizeof(wave_hdr) - 8;
    status = pj_file_read( fport->fd, &wave_hdr, &size_read);
    if (status != PJ_SUCCESS) {
	pj_file_close(fport->fd);
	return status;
    }
    if (size_read != size_to_read) {
	pj_file_close(fport->fd);
	return PJMEDIA_ENOTVALIDWAVE;
    }

    /* Normalize WAVE header fields values from little-endian to host
     * byte order.
     */
    pjmedia_wave_hdr_file_to_host(&wave_hdr);

    /* Validate WAVE file. */
    if (wave_hdr.riff_hdr.riff != PJMEDIA_RIFF_TAG ||
	wave_hdr.riff_hdr.wave != PJMEDIA_WAVE_TAG ||
	wave_hdr.fmt_hdr.fmt != PJMEDIA_FMT_TAG)
    {
	pj_file_close(fport->fd);
	TRACE_((THIS_FILE,
		"actual value|expected riff=%x|%x, wave=%x|%x fmt=%x|%x",
		wave_hdr.riff_hdr.riff, PJMEDIA_RIFF_TAG,
		wave_hdr.riff_hdr.wave, PJMEDIA_WAVE_TAG,
		wave_hdr.fmt_hdr.fmt, PJMEDIA_FMT_TAG));
	return PJMEDIA_ENOTVALIDWAVE;
    }

    /* Validate format and its attributes (i.e: bits per sample, block align) */
    switch (wave_hdr.fmt_hdr.fmt_tag) {
    case PJMEDIA_WAVE_FMT_TAG_PCM:
	if (wave_hdr.fmt_hdr.bits_per_sample != 16 ||
	    wave_hdr.fmt_hdr.block_align != 2 * wave_hdr.fmt_hdr.nchan)
	    status = PJMEDIA_EWAVEUNSUPP;
	break;

    case PJMEDIA_WAVE_FMT_TAG_ALAW:
    case PJMEDIA_WAVE_FMT_TAG_ULAW:
	if (wave_hdr.fmt_hdr.bits_per_sample != 8 ||
	    wave_hdr.fmt_hdr.block_align != wave_hdr.fmt_hdr.nchan)
	    status = PJMEDIA_ENOTVALIDWAVE;
	break;

    default:
	status = PJMEDIA_EWAVEUNSUPP;
	break;
    }

    if (status != PJ_SUCCESS) {
	pj_file_close(fport->fd);
	return status;
    }

    fport->fmt_tag = (pjmedia_wave_fmt_tag)wave_hdr.fmt_hdr.fmt_tag;
    fport->bytes_per_sample = (pj_uint16_t)
			      (wave_hdr.fmt_hdr.bits_per_sample / 8);

    /* If length of fmt_header is greater than 16, skip the remaining
     * fmt header data.
     */
    if (wave_hdr.fmt_hdr.len > 16) {
	size_to_read = wave_hdr.fmt_hdr.len - 16;
	status = pj_file_setpos(fport->fd, size_to_read, PJ_SEEK_CUR);
	if (status != PJ_SUCCESS) {
	    pj_file_close(fport->fd);
	    return status;
	}
    }

    /* Repeat reading the WAVE file until we have 'data' chunk */
    for (;;) {
	pjmedia_wave_subchunk subchunk;
	size_read = 8;
	status = pj_file_read(fport->fd, &subchunk, &size_read);
	if (status != PJ_SUCCESS || size_read != 8) {
	    pj_file_close(fport->fd);
	    return PJMEDIA_EWAVETOOSHORT;
	}

	/* Normalize endianness */
	PJMEDIA_WAVE_NORMALIZE_SUBCHUNK(&subchunk);

	/* Break if this is "data" chunk */
	if (subchunk.id == PJMEDIA_DATA_TAG) {
	    wave_hdr.data_hdr.data = PJMEDIA_DATA_TAG;
	    wave_hdr.data_hdr.len = subchunk.len;
	    break;
	}

	/* Otherwise skip the chunk contents */
	size_to_read = subchunk.len;
	status = pj_file_setpos(fport->fd, size_to_read, PJ_SEEK_CUR);
	if (status != PJ_SUCCESS) {
	    pj_file_close(fport->fd);
	    return status;
	}
    }

    /* Current file position now points to start of data */
    status = pj_file_getpos(fport->fd, &pos);
    fport->start_data = (unsigned)pos;
    fport->data_len = wave_hdr.data_hdr.len;
    fport->data_left = wave_hdr.data_hdr.len;

    /* Validate length. */
    if (wave_hdr.data_hdr.len > fport->fsize - fport->start_data) {
    	/* Actual data length may be shorter than declared. We should still
    	 * try to play whatever data is there instead of immediately returning
    	 * error.
    	 */
    	wave_hdr.data_hdr.len = (pj_uint32_t)fport->fsize - fport->start_data;
	// pj_file_close(fport->fd);
	// return PJMEDIA_EWAVEUNSUPP;
    }
    if (wave_hdr.data_hdr.len < ptime * wave_hdr.fmt_hdr.sample_rate *
				wave_hdr.fmt_hdr.nchan / 1000)
    {
	pj_file_close(fport->fd);
	return PJMEDIA_EWAVETOOSHORT;
    }

    /* It seems like we have a valid WAVE file. */

    /* Initialize */
    fport->options = options;

    /* Update port info. */
    ad = pjmedia_format_get_audio_format_detail(&fport->base.info.fmt, 1);
    pj_strdup2(pool, &name, filename);
    samples_per_frame = ptime * wave_hdr.fmt_hdr.sample_rate *
		        wave_hdr.fmt_hdr.nchan / 1000;
    pjmedia_port_info_init(&fport->base.info, &name, SIGNATURE,
			   wave_hdr.fmt_hdr.sample_rate,
			   wave_hdr.fmt_hdr.nchan,
			   BITS_PER_SAMPLE,
			   samples_per_frame);

    /* If file is shorter than buffer size, adjust buffer size to file
     * size. Otherwise EOF callback will be called multiple times when
     * fill_buffer() is called.
     */
    if (wave_hdr.data_hdr.len < (unsigned)buff_size)
	buff_size = wave_hdr.data_hdr.len;

    /* Create file buffer.
     */
    fport->bufsize = (pj_uint32_t)buff_size;

    /* samples_per_frame must be smaller than bufsize (because get_frame()
     * doesn't handle this case).
     */
    if (samples_per_frame * fport->bytes_per_sample >= fport->bufsize) {
	pj_file_close(fport->fd);
	return PJ_EINVAL;
    }

    /* Create buffer. */
    fport->buf = (char*) pj_pool_alloc(pool, fport->bufsize);
    if (!fport->buf) {
	pj_file_close(fport->fd);
	return PJ_ENOMEM;
    }

    fport->readpos = fport->buf;

    /* Set initial position of the file. */
    fport->fpos = fport->start_data;

    /* Fill up the buffer. */
    status = fill_buffer(fport);
    if (status != PJ_SUCCESS) {
	pj_file_close(fport->fd);
	return status;
    }

    /* Done. */

    *p_port = &fport->base;

    PJ_LOG(4,(THIS_FILE,
	      "File player '%.*s' created: samp.rate=%d, ch=%d, bufsize=%uKB, "
	      "filesize=%luKB",
	      (int)fport->base.info.name.slen,
	      fport->base.info.name.ptr,
	      ad->clock_rate,
	      ad->channel_count,
	      fport->bufsize / 1000,
	      (unsigned long)(fport->fsize / 1000)));

    return PJ_SUCCESS;
}


static int dissect_h245_JitterIndication ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h245_JitterIndication , JitterIndication_sequence ) ;
 return offset ;
 }


static inline MagickSizeType ScaleQuantumToLongLong(const Quantum quantum)
{
#if !defined(MAGICKCORE_HDRI_SUPPORT)
  return((MagickSizeType) (MagickULLConstant(4294967297)*quantum));
#else
  if (quantum <= 0.0)
    return(0UL);
  if ((4294967297.0*quantum) >= 18446744073709551615.0)
    return(MagickULLConstant(18446744073709551615));
  return((MagickSizeType) (4294967297.0*quantum+0.5));
#endif
}


int xsltCheckWrite ( xsltSecurityPrefsPtr sec , xsltTransformContextPtr ctxt , const xmlChar * URL ) {
 int ret ;
 xmlURIPtr uri ;
 xsltSecurityCheck check ;
 uri = xmlParseURI ( ( const char * ) URL ) ;
 if ( uri == NULL ) {
 uri = xmlCreateURI ( ) ;
 if ( uri == NULL ) {
 xsltTransformError ( ctxt , NULL , NULL , "xsltCheckWrite: out of memory for %s\n" , URL ) ;
 return ( - 1 ) ;
 }
 uri -> path = ( char * ) xmlStrdup ( URL ) ;
 }
 if ( ( uri -> scheme == NULL ) || ( xmlStrEqual ( BAD_CAST uri -> scheme , BAD_CAST "file" ) ) ) {
 # if defined ( WIN32 ) && ! defined ( __CYGWIN__ ) if ( ( uri -> path ) && ( uri -> path [ 0 ] == '/' ) && ( uri -> path [ 1 ] != '\0' ) && ( uri -> path [ 2 ] == ':' ) ) ret = xsltCheckWritePath ( sec , ctxt , uri -> path + 1 ) ;
 else # endif ret = xsltCheckWritePath ( sec , ctxt , uri -> path ) ;
 if ( ret <= 0 ) {
 xmlFreeURI ( uri ) ;
 return ( ret ) ;
 }
 }
 else {
 check = xsltGetSecurityPrefs ( sec , XSLT_SECPREF_WRITE_NETWORK ) ;
 if ( check != NULL ) {
 ret = check ( sec , ctxt , ( const char * ) URL ) ;
 if ( ret == 0 ) {
 xsltTransformError ( ctxt , NULL , NULL , "File write for %s refused\n" , URL ) ;
 xmlFreeURI ( uri ) ;
 return ( 0 ) ;
 }
 }
 }
 xmlFreeURI ( uri ) ;
 return ( 1 ) ;
 }


static bool is_sst_request_valid(const std::string &msg) {
  size_t method_len = strlen(msg.c_str());

  if (method_len == 0) {
    return false;
  }

  std::string method = msg.substr(0, method_len);

  // Is this method allowed?
  auto res = std::find(std::begin(allowed_sst_methods),
                       std::end(allowed_sst_methods), method);
  if (res == std::end(allowed_sst_methods)) {
    return false;
  }

  const char *data_ptr = msg.c_str() + method_len + 1;
  size_t data_len = strlen(data_ptr);

  // method + null + data + null
  if (method_len + 1 + data_len + 1 != msg.length()) {
    // Someone tries to piggyback after 2nd null
    return false;
  }

  if (data_len > 0) {
    /* We allow custom sst scripts, so data can be anything.

      We could create and maintain the list of forbidden
      characters and the ways they could be used to inject the command to
      the OS. However this approach seems to be too error prone.
      Instead of this we will just allow alpha-num + a few special characters
      (colon, slash, dot, underscore, square brackets). */
    std::string data = msg.substr(method_len + 1, data_len);
    static const std::regex allowed_chars_regex("[\\w:\\/\\.\\[\\]]+");
    if (!std::regex_match(data, allowed_chars_regex)) {
      return false;
    }
  }
  return true;
}


void cpu_exec_realizefn(CPUState *cpu, Error **errp) { CPUClass *cc = CPU_GET_CLASS(cpu); cpu_list_add(cpu); if (tcg_enabled() && !cc->tcg_initialized) { cc->tcg_initialized = true; cc->tcg_initialize(); } #ifndef CONFIG_USER_ONLY if (qdev_get_vmsd(DEVICE(cpu)) == NULL) { vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu); } if (cc->vmsd != NULL) { vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu); } #endif }


static gcry_error_t sexp_sscan ( gcry_sexp_t * retsexp , size_t * erroff , const char * buffer , size_t length , int argflag , void * * arg_list , ... ) {
 gcry_error_t rc ;
 va_list arg_ptr ;
 va_start ( arg_ptr , arg_list ) ;
 rc = vsexp_sscan ( retsexp , erroff , buffer , length , argflag , arg_list , arg_ptr ) ;
 va_end ( arg_ptr ) ;
 return rc ;
 }


static void test_wait_event_notifier(void) { EventNotifierTestData data = { .n = 0, .active = 1 }; event_notifier_init(&data.e, false); aio_set_event_notifier(ctx, &data.e, event_ready_cb); g_assert(!aio_poll(ctx, false)); g_assert_cmpint(data.n, ==, 0); g_assert_cmpint(data.active, ==, 1); event_notifier_set(&data.e); g_assert(aio_poll(ctx, false)); g_assert_cmpint(data.n, ==, 1); g_assert_cmpint(data.active, ==, 0); g_assert(!aio_poll(ctx, false)); g_assert_cmpint(data.n, ==, 1); g_assert_cmpint(data.active, ==, 0); aio_set_event_notifier(ctx, &data.e, NULL); g_assert(!aio_poll(ctx, false)); g_assert_cmpint(data.n, ==, 1); event_notifier_cleanup(&data.e); }


static int vp3_update_thread_context ( AVCodecContext * dst , const AVCodecContext * src ) {
 Vp3DecodeContext * s = dst -> priv_data , * s1 = src -> priv_data ;
 int qps_changed = 0 , i , err ;
 # define copy_fields ( to , from , start_field , end_field ) memcpy ( & to -> start_field , & from -> start_field , ( char * ) & to -> end_field - ( char * ) & to -> start_field ) if ( ! s1 -> current_frame . data [ 0 ] || s -> width != s1 -> width || s -> height != s1 -> height ) {
 if ( s != s1 ) copy_fields ( s , s1 , golden_frame , current_frame ) ;
 return - 1 ;
 }
 if ( s != s1 ) {
 if ( ! s -> current_frame . data [ 0 ] ) {
 int y_fragment_count , c_fragment_count ;
 s -> avctx = dst ;
 err = allocate_tables ( dst ) ;
 if ( err ) return err ;
 y_fragment_count = s -> fragment_width [ 0 ] * s -> fragment_height [ 0 ] ;
 c_fragment_count = s -> fragment_width [ 1 ] * s -> fragment_height [ 1 ] ;
 memcpy ( s -> motion_val [ 0 ] , s1 -> motion_val [ 0 ] , y_fragment_count * sizeof ( * s -> motion_val [ 0 ] ) ) ;
 memcpy ( s -> motion_val [ 1 ] , s1 -> motion_val [ 1 ] , c_fragment_count * sizeof ( * s -> motion_val [ 1 ] ) ) ;
 }
 copy_fields ( s , s1 , golden_frame , dsp ) ;
 for ( i = 0 ;
 i < 3 ;
 i ++ ) {
 if ( s -> qps [ i ] != s1 -> qps [ 1 ] ) {
 qps_changed = 1 ;
 memcpy ( & s -> qmat [ i ] , & s1 -> qmat [ i ] , sizeof ( s -> qmat [ i ] ) ) ;
 }
 }
 if ( s -> qps [ 0 ] != s1 -> qps [ 0 ] ) memcpy ( & s -> bounding_values_array , & s1 -> bounding_values_array , sizeof ( s -> bounding_values_array ) ) ;
 if ( qps_changed ) copy_fields ( s , s1 , qps , superblock_count ) ;
 # undef copy_fields }
 update_frames ( dst ) ;
 return 0 ;
 }


int pmixp_coll_ring_unpack(Buf buf, pmixp_coll_type_t *type,
			   pmixp_coll_ring_msg_hdr_t *ring_hdr,
			   pmixp_proc_t **r, size_t *nr)
{
	pmixp_proc_t *procs = NULL;
	uint32_t nprocs = 0;
	uint32_t tmp;
	int rc, i;

	/* 1. extract the type of collective */
	if (SLURM_SUCCESS != (rc = unpack32(&tmp, buf))) {
		PMIXP_ERROR("Cannot unpack collective type");
		return rc;
	}
	*type = tmp;

	/* 2. get the number of ranges */
	if (SLURM_SUCCESS != (rc = unpack32(&nprocs, buf))) {
		PMIXP_ERROR("Cannot unpack collective type");
		return rc;
	}
	*nr = nprocs;

	procs = xmalloc(sizeof(pmixp_proc_t) * nprocs);
	*r = procs;

	/* 3. get namespace/rank of particular process */
	for (i = 0; i < (int)nprocs; i++) {
		rc = unpackmem(procs[i].nspace, &tmp, buf);
		if (SLURM_SUCCESS != rc) {
			PMIXP_ERROR("Cannot unpack namespace for process #%d",
				    i);
			return rc;
		}
		procs[i].nspace[tmp] = '\0';

		rc = unpack32(&tmp, buf);
		procs[i].rank = tmp;
		if (SLURM_SUCCESS != rc) {
			PMIXP_ERROR("Cannot unpack ranks for process #%d, nsp=%s",
				    i, procs[i].nspace);
			return rc;
		}
	}

	/* 4. extract the ring info */
	if (SLURM_SUCCESS != (rc = unpackmem((char *)ring_hdr, &tmp, buf))) {
		PMIXP_ERROR("Cannot unpack ring info");
		return rc;
	}

	return SLURM_SUCCESS;
}


void vp9_rc_compute_frame_size_bounds ( const VP9_COMP * cpi , int frame_target , int * frame_under_shoot_limit , int * frame_over_shoot_limit ) {
 if ( cpi -> oxcf . rc_mode == VPX_Q ) {
 * frame_under_shoot_limit = 0 ;
 * frame_over_shoot_limit = INT_MAX ;
 }
 else {
 const int tolerance = ( cpi -> sf . recode_tolerance * frame_target ) / 100 ;
 * frame_under_shoot_limit = MAX ( frame_target - tolerance - 200 , 0 ) ;
 * frame_over_shoot_limit = MIN ( frame_target + tolerance + 200 , cpi -> rc . max_frame_bandwidth ) ;
 }
 }


static double ApplyEvaluateOperator(RandomInfo *random_info,const Quantum pixel,
  const MagickEvaluateOperator op,const double value)
{
  double
    result;

  result=0.0;
  switch (op)
  {
    case UndefinedEvaluateOperator:
      break;
    case AbsEvaluateOperator:
    {
      result=(double) fabs((double) (pixel+value));
      break;
    }
    case AddEvaluateOperator:
    {
      result=(double) (pixel+value);
      break;
    }
    case AddModulusEvaluateOperator:
    {
      /*
        This returns a 'floored modulus' of the addition which is a positive
        result.  It differs from % or fmod() that returns a 'truncated modulus'
        result, where floor() is replaced by trunc() and could return a
        negative result (which is clipped).
      */
      result=pixel+value;
      result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));
      break;
    }
    case AndEvaluateOperator:
    {
      result=(double) ((ssize_t) pixel & (ssize_t) (value+0.5));
      break;
    }
    case CosineEvaluateOperator:
    {
      result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*
        QuantumScale*pixel*value))+0.5));
      break;
    }
    case DivideEvaluateOperator:
    {
      result=pixel/(value == 0.0 ? 1.0 : value);
      break;
    }
    case ExponentialEvaluateOperator:
    {
      result=(double) (QuantumRange*exp((double) (value*QuantumScale*pixel)));
      break;
    }
    case GaussianNoiseEvaluateOperator:
    {
      result=(double) GenerateDifferentialNoise(random_info,pixel,
        GaussianNoise,value);
      break;
    }
    case ImpulseNoiseEvaluateOperator:
    {
      result=(double) GenerateDifferentialNoise(random_info,pixel,ImpulseNoise,
        value);
      break;
    }
    case LaplacianNoiseEvaluateOperator:
    {
      result=(double) GenerateDifferentialNoise(random_info,pixel,
        LaplacianNoise,value);
      break;
    }
    case LeftShiftEvaluateOperator:
    {
      result=(double) ((ssize_t) pixel << (ssize_t) (value+0.5));
      break;
    }
    case LogEvaluateOperator:
    {
      if ((QuantumScale*pixel) >= MagickEpsilon)
        result=(double) (QuantumRange*log((double) (QuantumScale*value*pixel+
          1.0))/log((double) (value+1.0)));
      break;
    }
    case MaxEvaluateOperator:
    {
      result=(double) EvaluateMax((double) pixel,value);
      break;
    }
    case MeanEvaluateOperator:
    {
      result=(double) (pixel+value);
      break;
    }
    case MedianEvaluateOperator:
    {
      result=(double) (pixel+value);
      break;
    }
    case MinEvaluateOperator:
    {
      result=(double) MagickMin((double) pixel,value);
      break;
    }
    case MultiplicativeNoiseEvaluateOperator:
    {
      result=(double) GenerateDifferentialNoise(random_info,pixel,
        MultiplicativeGaussianNoise,value);
      break;
    }
    case MultiplyEvaluateOperator:
    {
      result=(double) (value*pixel);
      break;
    }
    case OrEvaluateOperator:
    {
      result=(double) ((ssize_t) pixel | (ssize_t) (value+0.5));
      break;
    }
    case PoissonNoiseEvaluateOperator:
    {
      result=(double) GenerateDifferentialNoise(random_info,pixel,PoissonNoise,
        value);
      break;
    }
    case PowEvaluateOperator:
    {
      result=(double) (QuantumRange*pow((double) (QuantumScale*pixel),(double)
        value));
      break;
    }
    case RightShiftEvaluateOperator:
    {
      result=(double) ((ssize_t) pixel >> (ssize_t) (value+0.5));
      break;
    }
    case RootMeanSquareEvaluateOperator:
    {
      result=(double) (pixel*pixel+value);
      break;
    }
    case SetEvaluateOperator:
    {
      result=value;
      break;
    }
    case SineEvaluateOperator:
    {
      result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*
        QuantumScale*pixel*value))+0.5));
      break;
    }
    case SubtractEvaluateOperator:
    {
      result=(double) (pixel-value);
      break;
    }
    case SumEvaluateOperator:
    {
      result=(double) (pixel+value);
      break;
    }
    case ThresholdEvaluateOperator:
    {
      result=(double) (((double) pixel <= value) ? 0 : QuantumRange);
      break;
    }
    case ThresholdBlackEvaluateOperator:
    {
      result=(double) (((double) pixel <= value) ? 0 : pixel);
      break;
    }
    case ThresholdWhiteEvaluateOperator:
    {
      result=(double) (((double) pixel > value) ? QuantumRange : pixel);
      break;
    }
    case UniformNoiseEvaluateOperator:
    {
      result=(double) GenerateDifferentialNoise(random_info,pixel,UniformNoise,
        value);
      break;
    }
    case XorEvaluateOperator:
    {
      result=(double) ((ssize_t) pixel ^ (ssize_t) (value+0.5));
      break;
    }
  }
  return(result);
}


_blit_xrgb32_lerp_spans (void *abstract_renderer, int y, int h,
			 const cairo_half_open_span_t *spans, unsigned num_spans)
{
    cairo_image_span_renderer_t *r = abstract_renderer;

    if (num_spans == 0)
	return CAIRO_STATUS_SUCCESS;

    if (likely(h == 1)) {
	uint8_t *src = r->u.blit.src_data + y*r->u.blit.src_stride;
	uint8_t *dst = r->u.blit.data + y*r->u.blit.stride;
	do {
	    uint8_t a = mul8_8 (spans[0].coverage, r->op);
	    if (a) {
		uint32_t *s = (uint32_t*)src + spans[0].x;
		uint32_t *d = (uint32_t*)dst + spans[0].x;
		int len = spans[1].x - spans[0].x;
		if (a == 0xff) {
		    if (len == 1)
			*d = *s;
		    else
			memcpy(d, s, len*4);
		} else {
		    while (len--) {
			*d = lerp8x4 (*s, a, *d);
			s++, d++;
		    }
		}
	    }
	    spans++;
	} while (--num_spans > 1);
    } else {
	do {
	    uint8_t a = mul8_8 (spans[0].coverage, r->op);
	    if (a) {
		int yy = y, hh = h;
		do {
		    uint32_t *s = (uint32_t *)(r->u.blit.src_data + yy*r->u.blit.src_stride + spans[0].x * 4);
		    uint32_t *d = (uint32_t *)(r->u.blit.data + yy*r->u.blit.stride + spans[0].x * 4);
		    int len = spans[1].x - spans[0].x;
		    if (a == 0xff) {
			if (len == 1)
			    *d = *s;
			else
			    memcpy(d, s, len * 4);
		    } else {
			while (len--) {
			    *d = lerp8x4 (*s, a, *d);
			    s++, d++;
			}
		    }
		    yy++;
		} while (--hh);
	    }
	    spans++;
	} while (--num_spans > 1);
    }

    return CAIRO_STATUS_SUCCESS;
}


static int raw_decode ( AVCodecContext * avctx , void * data , int * got_frame , AVPacket * avpkt ) {
 const AVPixFmtDescriptor * desc = av_pix_fmt_desc_get ( avctx -> pix_fmt ) ;
 RawVideoContext * context = avctx -> priv_data ;
 const uint8_t * buf = avpkt -> data ;
 int buf_size = avpkt -> size ;
 int res ;
 AVFrame * frame = data ;
 AVPicture * picture = data ;
 frame -> pict_type = avctx -> coded_frame -> pict_type ;
 frame -> interlaced_frame = avctx -> coded_frame -> interlaced_frame ;
 frame -> top_field_first = avctx -> coded_frame -> top_field_first ;
 frame -> reordered_opaque = avctx -> reordered_opaque ;
 frame -> pkt_pts = avctx -> pkt -> pts ;
 if ( buf_size < context -> length - ( avctx -> pix_fmt == AV_PIX_FMT_PAL8 ? AVPALETTE_SIZE : 0 ) ) return - 1 ;
 if ( context -> buffer ) {
 int i ;
 uint8_t * dst = context -> buffer ;
 buf_size = context -> length - AVPALETTE_SIZE ;
 if ( avctx -> bits_per_coded_sample == 4 ) {
 for ( i = 0 ;
 2 * i + 1 < buf_size ;
 i ++ ) {
 dst [ 2 * i + 0 ] = buf [ i ] >> 4 ;
 dst [ 2 * i + 1 ] = buf [ i ] & 15 ;
 }
 }
 else {
 for ( i = 0 ;
 4 * i + 3 < buf_size ;
 i ++ ) {
 dst [ 4 * i + 0 ] = buf [ i ] >> 6 ;
 dst [ 4 * i + 1 ] = buf [ i ] >> 4 & 3 ;
 dst [ 4 * i + 2 ] = buf [ i ] >> 2 & 3 ;
 dst [ 4 * i + 3 ] = buf [ i ] & 3 ;
 }
 }
 buf = dst ;
 }
 if ( avctx -> codec_tag == MKTAG ( 'A' , 'V' , '1' , 'x' ) || avctx -> codec_tag == MKTAG ( 'A' , 'V' , 'u' , 'p' ) ) buf += buf_size - context -> length ;
 if ( ( res = avpicture_fill ( picture , buf , avctx -> pix_fmt , avctx -> width , avctx -> height ) ) < 0 ) return res ;
 if ( ( avctx -> pix_fmt == AV_PIX_FMT_PAL8 && buf_size < context -> length ) || ( desc -> flags & PIX_FMT_PSEUDOPAL ) ) {
 frame -> data [ 1 ] = context -> palette ;
 }
 if ( avctx -> pix_fmt == AV_PIX_FMT_PAL8 ) {
 const uint8_t * pal = av_packet_get_side_data ( avpkt , AV_PKT_DATA_PALETTE , NULL ) ;
 if ( pal ) {
 memcpy ( frame -> data [ 1 ] , pal , AVPALETTE_SIZE ) ;
 frame -> palette_has_changed = 1 ;
 }
 }
 if ( avctx -> pix_fmt == AV_PIX_FMT_BGR24 && ( ( frame -> linesize [ 0 ] + 3 ) & ~ 3 ) * avctx -> height <= buf_size ) frame -> linesize [ 0 ] = ( frame -> linesize [ 0 ] + 3 ) & ~ 3 ;
 if ( context -> flip ) flip ( avctx , picture ) ;
 if ( avctx -> codec_tag == MKTAG ( 'Y' , 'V' , '1' , '2' ) || avctx -> codec_tag == MKTAG ( 'Y' , 'V' , '1' , '6' ) || avctx -> codec_tag == MKTAG ( 'Y' , 'V' , '2' , '4' ) || avctx -> codec_tag == MKTAG ( 'Y' , 'V' , 'U' , '9' ) ) FFSWAP ( uint8_t * , picture -> data [ 1 ] , picture -> data [ 2 ] ) ;
 if ( avctx -> codec_tag == AV_RL32 ( "yuv2" ) && avctx -> pix_fmt == AV_PIX_FMT_YUYV422 ) {
 int x , y ;
 uint8_t * line = picture -> data [ 0 ] ;
 for ( y = 0 ;
 y < avctx -> height ;
 y ++ ) {
 for ( x = 0 ;
 x < avctx -> width ;
 x ++ ) line [ 2 * x + 1 ] ^= 0x80 ;
 line += picture -> linesize [ 0 ] ;
 }
 }
 * got_frame = 1 ;
 return buf_size ;
 }


static inline void e1000e_read_lgcy_rx_descr ( E1000ECore * core , uint8_t * desc , hwaddr * buff_addr ) {
 struct e1000_rx_desc * d = ( struct e1000_rx_desc * ) desc ;
 * buff_addr = le64_to_cpu ( d -> buffer_addr ) ;
 }


av_cold int ff_ivi_init_tiles(IVIPlaneDesc *planes, int tile_width, int tile_height) { int p, b, x, y, x_tiles, y_tiles, t_width, t_height; IVIBandDesc *band; IVITile *tile, *ref_tile; for (p = 0; p < 3; p++) { t_width = !p ? tile_width : (tile_width + 3) >> 2; t_height = !p ? tile_height : (tile_height + 3) >> 2; if (!p && planes[0].num_bands == 4) { t_width >>= 1; t_height >>= 1; } if(t_width<=0 || t_height<=0) return AVERROR(EINVAL); for (b = 0; b < planes[p].num_bands; b++) { band = &planes[p].bands[b]; x_tiles = IVI_NUM_TILES(band->width, t_width); y_tiles = IVI_NUM_TILES(band->height, t_height); band->num_tiles = x_tiles * y_tiles; av_freep(&band->tiles); band->tiles = av_mallocz(band->num_tiles * sizeof(IVITile)); if (!band->tiles) return AVERROR(ENOMEM); tile = band->tiles; /* use the first luma band as reference for motion vectors * and quant */ ref_tile = planes[0].bands[0].tiles; for (y = 0; y < band->height; y += t_height) { for (x = 0; x < band->width; x += t_width) { tile->xpos = x; tile->ypos = y; tile->mb_size = band->mb_size; tile->width = FFMIN(band->width - x, t_width); tile->height = FFMIN(band->height - y, t_height); tile->is_empty = tile->data_size = 0; /* calculate number of macroblocks */ tile->num_MBs = IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size); av_freep(&tile->mbs); tile->mbs = av_malloc(tile->num_MBs * sizeof(IVIMbInfo)); if (!tile->mbs) return AVERROR(ENOMEM); tile->ref_mbs = 0; if (p || b) { tile->ref_mbs = ref_tile->mbs; ref_tile++; } tile++; } } }// for b }// for p return 0; }


static void gen_write_xer(TCGv src) { tcg_gen_andi_tl(cpu_xer, src, ~((1u << XER_SO) | (1u << XER_OV) | (1u << XER_CA))); tcg_gen_extract_tl(cpu_so, src, XER_SO, 1); tcg_gen_extract_tl(cpu_ov, src, XER_OV, 1); tcg_gen_extract_tl(cpu_ca, src, XER_CA, 1); }


int event_reinit ( struct event_base * base ) {
 const struct eventop * evsel = base -> evsel ;
 void * evbase = base -> evbase ;
 int res = 0 ;
 struct event * ev ;
 # if 0 if ( ! evsel -> need_reinit ) return ( 0 ) ;
 # endif if ( base -> sig . ev_signal_added ) {
 event_queue_remove ( base , & base -> sig . ev_signal , EVLIST_INSERTED ) ;
 if ( base -> sig . ev_signal . ev_flags & EVLIST_ACTIVE ) event_queue_remove ( base , & base -> sig . ev_signal , EVLIST_ACTIVE ) ;
 base -> sig . ev_signal_added = 0 ;
 }
 if ( base -> evsel -> dealloc != NULL ) base -> evsel -> dealloc ( base , base -> evbase ) ;
 evbase = base -> evbase = evsel -> init ( base ) ;
 if ( base -> evbase == NULL ) event_errx ( 1 , "%s: could not reinitialize event mechanism" , __func__ ) ;
 TAILQ_FOREACH ( ev , & base -> eventqueue , ev_next ) {
 if ( evsel -> add ( evbase , ev ) == - 1 ) res = - 1 ;
 }
 return ( res ) ;
 }


static int decode_frame ( AVCodecContext * avctx , void * data , int * got_frame , AVPacket * avpkt ) {
 Indeo3DecodeContext * ctx = avctx -> priv_data ;
 const uint8_t * buf = avpkt -> data ;
 int buf_size = avpkt -> size ;
 AVFrame * frame = data ;
 int res ;
 res = decode_frame_headers ( ctx , avctx , buf , buf_size ) ;
 if ( res < 0 ) return res ;
 if ( res ) {
 * got_frame = 0 ;
 return buf_size ;
 }
 if ( ctx -> frame_flags & BS_NONREF && ( avctx -> skip_frame >= AVDISCARD_NONREF ) ) return 0 ;
 if ( ! ( ctx -> frame_flags & BS_KEYFRAME ) && avctx -> skip_frame >= AVDISCARD_NONKEY ) return 0 ;
 ctx -> buf_sel = ( ctx -> frame_flags >> BS_BUFFER ) & 1 ;
 if ( ( res = decode_plane ( ctx , avctx , ctx -> planes , ctx -> y_data_ptr , ctx -> y_data_size , 40 ) ) ) return res ;
 if ( ( res = decode_plane ( ctx , avctx , & ctx -> planes [ 1 ] , ctx -> u_data_ptr , ctx -> u_data_size , 10 ) ) ) return res ;
 if ( ( res = decode_plane ( ctx , avctx , & ctx -> planes [ 2 ] , ctx -> v_data_ptr , ctx -> v_data_size , 10 ) ) ) return res ;
 if ( ( res = ff_get_buffer ( avctx , frame , 0 ) ) < 0 ) {
 av_log ( ctx -> avctx , AV_LOG_ERROR , "get_buffer() failed\n" ) ;
 return res ;
 }
 output_plane ( & ctx -> planes [ 0 ] , ctx -> buf_sel , frame -> data [ 0 ] , frame -> linesize [ 0 ] , avctx -> height ) ;
 output_plane ( & ctx -> planes [ 1 ] , ctx -> buf_sel , frame -> data [ 1 ] , frame -> linesize [ 1 ] , ( avctx -> height + 3 ) >> 2 ) ;
 output_plane ( & ctx -> planes [ 2 ] , ctx -> buf_sel , frame -> data [ 2 ] , frame -> linesize [ 2 ] , ( avctx -> height + 3 ) >> 2 ) ;
 * got_frame = 1 ;
 return buf_size ;
 }


static void test_select_direct ( ) {
 int rc ;
 MYSQL_RES * result ;
 myheader ( "test_select_direct" ) ;
 rc = mysql_autocommit ( mysql , TRUE ) ;
 myquery ( rc ) ;
 rc = mysql_query ( mysql , "DROP TABLE IF EXISTS test_select" ) ;
 myquery ( rc ) ;
 rc = mysql_query ( mysql , "CREATE TABLE test_select(id int, id1 tinyint, " " id2 float, " " id3 double, " " name varchar(50))" ) ;
 myquery ( rc ) ;
 rc = mysql_query ( mysql , "INSERT INTO test_select VALUES(10, 5, 2.3, 4.5, 'venu')" ) ;
 myquery ( rc ) ;
 rc = mysql_commit ( mysql ) ;
 myquery ( rc ) ;
 rc = mysql_query ( mysql , "SELECT * FROM test_select" ) ;
 myquery ( rc ) ;
 result = mysql_store_result ( mysql ) ;
 mytest ( result ) ;
 ( void ) my_process_result_set ( result ) ;
 mysql_free_result ( result ) ;
 }


static void xhci_intr_raise ( XHCIState * xhci , int v ) {
 PCIDevice * pci_dev = PCI_DEVICE ( xhci ) ;
 xhci -> intr [ v ] . erdp_low |= ERDP_EHB ;
 xhci -> intr [ v ] . iman |= IMAN_IP ;
 xhci -> usbsts |= USBSTS_EINT ;
 if ( ! ( xhci -> intr [ v ] . iman & IMAN_IE ) ) {
 return ;
 }
 if ( ! ( xhci -> usbcmd & USBCMD_INTE ) ) {
 return ;
 }
 if ( msix_enabled ( pci_dev ) ) {
 trace_usb_xhci_irq_msix ( v ) ;
 msix_notify ( pci_dev , v ) ;
 return ;
 }
 if ( msi_enabled ( pci_dev ) ) {
 trace_usb_xhci_irq_msi ( v ) ;
 msi_notify ( pci_dev , v ) ;
 return ;
 }
 if ( v == 0 ) {
 trace_usb_xhci_irq_intx ( 1 ) ;
 pci_irq_assert ( pci_dev ) ;
 }
 }


static int qemu_rbd_send_pipe(BDRVRBDState *s, RADOSCB *rcb) { int ret = 0; while (1) { fd_set wfd; int fd = s->fds[RBD_FD_WRITE]; /* send the op pointer to the qemu thread that is responsible for the aio/op completion. Must do it in a qemu thread context */ ret = write(fd, (void *)&rcb, sizeof(rcb)); if (ret >= 0) { break; } if (errno == EINTR) { continue; } if (errno != EAGAIN) { break; } FD_ZERO(&wfd); FD_SET(fd, &wfd); do { ret = select(fd + 1, NULL, &wfd, NULL, NULL); } while (ret < 0 && errno == EINTR); } return ret; }


const char * SSL_rstate_string_long ( const SSL * s ) {
 switch ( s -> rlayer . rstate ) {
 case SSL_ST_READ_HEADER : return "read header" ;
 case SSL_ST_READ_BODY : return "read body" ;
 case SSL_ST_READ_DONE : return "read done" ;
 default : return "unknown" ;
 }
 }


TEST(IndexBoundsBuilderTest, TranslateNotEqualToNullShouldBuildExactBoundsOnReverseIndex) {
    BSONObj indexPattern = BSON("a" << -1);
    auto testIndex = buildSimpleIndexEntry(indexPattern);

    BSONObj obj = BSON("a" << BSON("$ne" << BSONNULL));
    auto expr = parseMatchExpression(obj);

    OrderedIntervalList oil;
    IndexBoundsBuilder::BoundsTightness tightness;
    IndexBoundsBuilder::translate(
        expr.get(), indexPattern.firstElement(), testIndex, &oil, &tightness);

    // Bounds should be [MinKey, undefined), (null, MaxKey].
    ASSERT_EQUALS(oil.name, "a");
    ASSERT_EQUALS(tightness, IndexBoundsBuilder::EXACT);
    assertBoundsRepresentNotEqualsNull(oil);
}


int net_init_tap(const NetClientOptions *opts, const char *name, NetClientState *peer) { const NetdevTapOptions *tap; int fd, vnet_hdr = 0, i = 0, queues; /* for the no-fd, no-helper case */ const char *script = NULL; /* suppress wrong "uninit'd use" gcc warning */ const char *downscript = NULL; const char *vhostfdname; char ifname[128]; assert(opts->kind == NET_CLIENT_OPTIONS_KIND_TAP); tap = opts->tap; queues = tap->has_queues ? tap->queues : 1; vhostfdname = tap->has_vhostfd ? tap->vhostfd : NULL; /* QEMU vlans does not support multiqueue tap, in this case peer is set. * For -netdev, peer is always NULL. */ if (peer && (tap->has_queues || tap->has_fds || tap->has_vhostfds)) { error_report("Multiqueue tap cannot be used with QEMU vlans"); return -1; } if (tap->has_fd) { if (tap->has_ifname || tap->has_script || tap->has_downscript || tap->has_vnet_hdr || tap->has_helper || tap->has_queues || tap->has_fds) { error_report("ifname=, script=, downscript=, vnet_hdr=, " "helper=, queues=, and fds= are invalid with fd="); return -1; } fd = monitor_handle_fd_param(cur_mon, tap->fd); if (fd == -1) { return -1; } fcntl(fd, F_SETFL, O_NONBLOCK); vnet_hdr = tap_probe_vnet_hdr(fd); if (net_init_tap_one(tap, peer, "tap", name, NULL, script, downscript, vhostfdname, vnet_hdr, fd)) { return -1; } } else if (tap->has_fds) { char *fds[MAX_TAP_QUEUES]; char *vhost_fds[MAX_TAP_QUEUES]; int nfds, nvhosts; if (tap->has_ifname || tap->has_script || tap->has_downscript || tap->has_vnet_hdr || tap->has_helper || tap->has_queues || tap->has_fd) { error_report("ifname=, script=, downscript=, vnet_hdr=, " "helper=, queues=, and fd= are invalid with fds="); return -1; } nfds = get_fds(tap->fds, fds, MAX_TAP_QUEUES); if (tap->has_vhostfds) { nvhosts = get_fds(tap->vhostfds, vhost_fds, MAX_TAP_QUEUES); if (nfds != nvhosts) { error_report("The number of fds passed does not match the " "number of vhostfds passed"); return -1; } } for (i = 0; i < nfds; i++) { fd = monitor_handle_fd_param(cur_mon, fds[i]); if (fd == -1) { return -1; } fcntl(fd, F_SETFL, O_NONBLOCK); if (i == 0) { vnet_hdr = tap_probe_vnet_hdr(fd); } else if (vnet_hdr != tap_probe_vnet_hdr(fd)) { error_report("vnet_hdr not consistent across given tap fds"); return -1; } if (net_init_tap_one(tap, peer, "tap", name, ifname, script, downscript, tap->has_vhostfds ? vhost_fds[i] : NULL, vnet_hdr, fd)) { return -1; } } } else if (tap->has_helper) { if (tap->has_ifname || tap->has_script || tap->has_downscript || tap->has_vnet_hdr || tap->has_queues || tap->has_fds) { error_report("ifname=, script=, downscript=, and vnet_hdr= " "queues=, and fds= are invalid with helper="); return -1; } fd = net_bridge_run_helper(tap->helper, DEFAULT_BRIDGE_INTERFACE); if (fd == -1) { return -1; } fcntl(fd, F_SETFL, O_NONBLOCK); vnet_hdr = tap_probe_vnet_hdr(fd); if (net_init_tap_one(tap, peer, "bridge", name, ifname, script, downscript, vhostfdname, vnet_hdr, fd)) { return -1; } } else { script = tap->has_script ? tap->script : DEFAULT_NETWORK_SCRIPT; downscript = tap->has_downscript ? tap->downscript : DEFAULT_NETWORK_DOWN_SCRIPT; if (tap->has_ifname) { pstrcpy(ifname, sizeof ifname, tap->ifname); } else { ifname[0] = '\0'; } for (i = 0; i < queues; i++) { fd = net_tap_init(tap, &vnet_hdr, i >= 1 ? "no" : script, ifname, sizeof ifname, queues > 1); if (fd == -1) { return -1; } if (queues > 1 && i == 0 && !tap->has_ifname) { if (tap_fd_get_ifname(fd, ifname)) { error_report("Fail to get ifname"); return -1; } } if (net_init_tap_one(tap, peer, "tap", name, ifname, i >= 1 ? "no" : script, i >= 1 ? "no" : downscript, vhostfdname, vnet_hdr, fd)) { return -1; } } } return 0; }


static double get_scene_score(AVFilterContext *ctx, AVFilterBufferRef *picref) { double ret = 0; SelectContext *select = ctx->priv; AVFilterBufferRef *prev_picref = select->prev_picref; if (prev_picref && picref->video->h == prev_picref->video->h && picref->video->w == prev_picref->video->w && picref->linesize[0] == prev_picref->linesize[0]) { int x, y; int64_t sad = 0; double mafd, diff; uint8_t *p1 = picref->data[0]; uint8_t *p2 = prev_picref->data[0]; const int linesize = picref->linesize[0]; for (y = 0; y < picref->video->h; y += 8) for (x = 0; x < linesize; x += 8) sad += select->c.sad[1](select, p1 + y * linesize + x, p2 + y * linesize + x, linesize, 8); emms_c(); mafd = sad / (picref->video->h * picref->video->w * 3); diff = fabs(mafd - select->prev_mafd); ret = av_clipf(FFMIN(mafd, diff) / 100., 0, 1); select->prev_mafd = mafd; avfilter_unref_buffer(prev_picref); } select->prev_picref = avfilter_ref_buffer(picref, ~0); return ret; }


void s390_pci_iommu_enable(S390PCIBusDevice *pbdev) { uint64_t size = pbdev->pal - pbdev->pba + 1; memory_region_init_iommu(&pbdev->iommu_mr, OBJECT(&pbdev->mr), &s390_iommu_ops, "iommu-s390", size); memory_region_add_subregion(&pbdev->mr, pbdev->pba, &pbdev->iommu_mr); pbdev->iommu_enabled = true; }


static void cmd_network_list ( void ) {
 GString * str ;
 GSList * tmp ;
 str = g_string_new ( NULL ) ;
 printformat ( NULL , NULL , MSGLEVEL_CLIENTCRAP , IRCTXT_NETWORK_HEADER ) ;
 for ( tmp = chatnets ;
 tmp != NULL ;
 tmp = tmp -> next ) {
 IRC_CHATNET_REC * rec = tmp -> data ;
 if ( ! IS_IRCNET ( rec ) ) continue ;
 g_string_truncate ( str , 0 ) ;
 if ( rec -> nick != NULL ) g_string_append_printf ( str , "nick: %s, " , rec -> nick ) ;
 if ( rec -> alternate_nick != NULL ) g_string_append_printf ( str , "alternate_nick: %s, " , rec -> alternate_nick ) ;
 if ( rec -> username != NULL ) g_string_append_printf ( str , "username: %s, " , rec -> username ) ;
 if ( rec -> realname != NULL ) g_string_append_printf ( str , "realname: %s, " , rec -> realname ) ;
 if ( rec -> own_host != NULL ) g_string_append_printf ( str , "host: %s, " , rec -> own_host ) ;
 if ( rec -> autosendcmd != NULL ) g_string_append_printf ( str , "autosendcmd: %s, " , rec -> autosendcmd ) ;
 if ( rec -> usermode != NULL ) g_string_append_printf ( str , "usermode: %s, " , rec -> usermode ) ;
 if ( rec -> sasl_mechanism != NULL ) g_string_append_printf ( str , "sasl_mechanism: %s, " , rec -> sasl_mechanism ) ;
 if ( rec -> sasl_username != NULL ) g_string_append_printf ( str , "sasl_username: %s, " , rec -> sasl_username ) ;
 if ( rec -> sasl_password != NULL ) g_string_append_printf ( str , "sasl_password: (pass), " ) ;
 if ( rec -> cmd_queue_speed > 0 ) g_string_append_printf ( str , "cmdspeed: %d, " , rec -> cmd_queue_speed ) ;
 if ( rec -> max_cmds_at_once > 0 ) g_string_append_printf ( str , "cmdmax: %d, " , rec -> max_cmds_at_once ) ;
 if ( rec -> max_query_chans > 0 ) g_string_append_printf ( str , "querychans: %d, " , rec -> max_query_chans ) ;
 if ( rec -> max_kicks > 0 ) g_string_append_printf ( str , "max_kicks: %d, " , rec -> max_kicks ) ;
 if ( rec -> max_msgs > 0 ) g_string_append_printf ( str , "max_msgs: %d, " , rec -> max_msgs ) ;
 if ( rec -> max_modes > 0 ) g_string_append_printf ( str , "max_modes: %d, " , rec -> max_modes ) ;
 if ( rec -> max_whois > 0 ) g_string_append_printf ( str , "max_whois: %d, " , rec -> max_whois ) ;
 if ( str -> len > 1 ) g_string_truncate ( str , str -> len - 2 ) ;
 printformat ( NULL , NULL , MSGLEVEL_CLIENTCRAP , IRCTXT_NETWORK_LINE , rec -> name , str -> str ) ;
 }
 g_string_free ( str , TRUE ) ;
 printformat ( NULL , NULL , MSGLEVEL_CLIENTCRAP , IRCTXT_NETWORK_FOOTER ) ;
 }


static Jsi_RC jsi_ArrayPushCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
    Jsi_Value **ret, Jsi_Func *funcPtr)
{
    Jsi_Obj *obj;

    if (_this->vt != JSI_VT_OBJECT || !Jsi_ObjIsArray(interp, _this->d.obj)) {
        Jsi_ValueMakeNumber(interp, ret, 0);
        return JSI_OK;
    }
    obj = _this->d.obj;

    int argc = Jsi_ValueGetLength(interp, args);
    int curlen = jsi_SizeOfArray(interp, obj);
    int i;
    for (i = 0; i < argc; ++i) {
        Jsi_Value *ov = Jsi_ValueArrayIndex(interp, args, i);
        if (!ov) { Jsi_LogBug("Arguments Error"); ov = Jsi_ValueNew(interp); }
        Jsi_ValueInsertArray(interp, _this, curlen + i, ov, 0);
    }

    Jsi_ValueMakeNumber(interp, ret, jsi_SizeOfArray(interp, obj));
    return JSI_OK;
}


void TopologyManager::onServerRTTUpdated(HostAndPort hostAndPort, IsMasterRTT rtt) {
    {
        stdx::lock_guard<mongo::Mutex> lock(_mutex);

        auto oldServerDescription = _topologyDescription->findServerByAddress(hostAndPort);
        if (oldServerDescription) {
            auto newServerDescription = (*oldServerDescription)->cloneWithRTT(rtt);

            auto oldTopologyDescription = _topologyDescription;
            _topologyDescription = std::make_shared<TopologyDescription>(*_topologyDescription);
            _topologyDescription->installServerDescription(newServerDescription);

            _publishTopologyDescriptionChanged(oldTopologyDescription, _topologyDescription);

            return;
        }
    }
    // otherwise, the server was removed from the topology. Nothing to do.
    LOGV2(4333201,
          "Not updating RTT. Server {server} does not exist in {replicaSet}",
          "Not updating RTT. The server does not exist in the replica set",
          "server"_attr = hostAndPort,
          "replicaSet"_attr = getTopologyDescription()->getSetName());
}


void vp8_plane_add_noise_c ( unsigned char * Start , char * noise , char blackclamp [ 16 ] , char whiteclamp [ 16 ] , char bothclamp [ 16 ] , unsigned int Width , unsigned int Height , int Pitch ) {
 unsigned int i , j ;
 for ( i = 0 ;
 i < Height ;
 i ++ ) {
 unsigned char * Pos = Start + i * Pitch ;
 char * Ref = ( char * ) ( noise + ( rand ( ) & 0xff ) ) ;
 for ( j = 0 ;
 j < Width ;
 j ++ ) {
 if ( Pos [ j ] < blackclamp [ 0 ] ) Pos [ j ] = blackclamp [ 0 ] ;
 if ( Pos [ j ] > 255 + whiteclamp [ 0 ] ) Pos [ j ] = 255 + whiteclamp [ 0 ] ;
 Pos [ j ] += Ref [ j ] ;
 }
 }
 }


void arm_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr, vaddr addr, unsigned size, MMUAccessType access_type, int mmu_idx, MemTxAttrs attrs, MemTxResult response, uintptr_t retaddr) { ARMCPU *cpu = ARM_CPU(cs); ARMMMUFaultInfo fi = {}; /* now we have a real cpu fault */ cpu_restore_state(cs, retaddr); /* The EA bit in syndromes and fault status registers is an * IMPDEF classification of external aborts. ARM implementations * usually use this to indicate AXI bus Decode error (0) or * Slave error (1); in QEMU we follow that. */ fi.ea = (response != MEMTX_DECODE_ERROR); fi.type = ARMFault_SyncExternal; deliver_fault(cpu, addr, access_type, mmu_idx, &fi); }


void * xmlHashLookup ( xmlHashTablePtr table , const xmlChar * name ) {
 return ( xmlHashLookup3 ( table , name , NULL , NULL ) ) ;
 }


int print_unknown_data ( netdissect_options * ndo , const u_char * cp , const char * ident , int len ) {
 if ( len < 0 ) {
 ND_PRINT ( ( ndo , "%sDissector error: print_unknown_data called with negative length" , ident ) ) ;
 return ( 0 ) ;
 }
 if ( ndo -> ndo_snapend - cp < len ) len = ndo -> ndo_snapend - cp ;
 if ( len < 0 ) {
 ND_PRINT ( ( ndo , "%sDissector error: print_unknown_data called with pointer past end of packet" , ident ) ) ;
 return ( 0 ) ;
 }
 hex_print ( ndo , ident , cp , len ) ;
 return ( 1 ) ;
 }


static long snd_rawmidi_kernel_write1(struct snd_rawmidi_substream *substream,
				      const unsigned char __user *userbuf,
				      const unsigned char *kernelbuf,
				      long count)
{
	unsigned long flags;
	long count1, result;
	struct snd_rawmidi_runtime *runtime = substream->runtime;
	unsigned long appl_ptr;

	if (!kernelbuf && !userbuf)
		return -EINVAL;
	if (snd_BUG_ON(!runtime->buffer))
		return -EINVAL;

	result = 0;
	spin_lock_irqsave(&runtime->lock, flags);
	if (substream->append) {
		if ((long)runtime->avail < count) {
			spin_unlock_irqrestore(&runtime->lock, flags);
			return -EAGAIN;
		}
	}
	while (count > 0 && runtime->avail > 0) {
		count1 = runtime->buffer_size - runtime->appl_ptr;
		if (count1 > count)
			count1 = count;
		if (count1 > (long)runtime->avail)
			count1 = runtime->avail;

		/* update runtime->appl_ptr before unlocking for userbuf */
		appl_ptr = runtime->appl_ptr;
		runtime->appl_ptr += count1;
		runtime->appl_ptr %= runtime->buffer_size;
		runtime->avail -= count1;

		if (kernelbuf)
			memcpy(runtime->buffer + appl_ptr,
			       kernelbuf + result, count1);
		else if (userbuf) {
			spin_unlock_irqrestore(&runtime->lock, flags);
			if (copy_from_user(runtime->buffer + appl_ptr,
					   userbuf + result, count1)) {
				spin_lock_irqsave(&runtime->lock, flags);
				result = result > 0 ? result : -EFAULT;
				goto __end;
			}
			spin_lock_irqsave(&runtime->lock, flags);
		}
		result += count1;
		count -= count1;
	}
      __end:
	count1 = runtime->avail < runtime->buffer_size;
	spin_unlock_irqrestore(&runtime->lock, flags);
	if (count1)
		snd_rawmidi_output_trigger(substream, 1);
	return result;
}


static int kvm_ppc_register_host_cpu_type(void) { TypeInfo type_info = { .name = TYPE_HOST_POWERPC_CPU, .class_init = kvmppc_host_cpu_class_init, }; PowerPCCPUClass *pvr_pcc; DeviceClass *dc; int i; pvr_pcc = kvm_ppc_get_host_cpu_class(); if (pvr_pcc == NULL) { return -1; } type_info.parent = object_class_get_name(OBJECT_CLASS(pvr_pcc)); type_register(&type_info); #if defined(TARGET_PPC64) type_info.name = g_strdup_printf("%s-"TYPE_SPAPR_CPU_CORE, "host"); type_info.parent = TYPE_SPAPR_CPU_CORE, type_info.instance_size = sizeof(sPAPRCPUCore); type_info.instance_init = NULL; type_info.class_init = spapr_cpu_core_class_init; type_info.class_data = (void *) "host"; type_register(&type_info); g_free((void *)type_info.name); #endif /* * Update generic CPU family class alias (e.g. on a POWER8NVL host, * we want "POWER8" to be a "family" alias that points to the current * host CPU type, too) */ dc = DEVICE_CLASS(ppc_cpu_get_family_class(pvr_pcc)); for (i = 0; ppc_cpu_aliases[i].alias != NULL; i++) { if (strcmp(ppc_cpu_aliases[i].alias, dc->desc) == 0) { ObjectClass *oc = OBJECT_CLASS(pvr_pcc); char *suffix; ppc_cpu_aliases[i].model = g_strdup(object_class_get_name(oc)); suffix = strstr(ppc_cpu_aliases[i].model, "-"TYPE_POWERPC_CPU); if (suffix) { *suffix = 0; } ppc_cpu_aliases[i].oc = oc; break; } } return 0; }


static void put_audio_specific_config(AVCodecContext *avctx) { PutBitContext pb; AACEncContext *s = avctx->priv_data; init_put_bits(&pb, avctx->extradata, avctx->extradata_size*8); put_bits(&pb, 5, 2); //object type - AAC-LC put_bits(&pb, 4, s->samplerate_index); //sample rate index put_bits(&pb, 4, s->channels); //GASpecificConfig put_bits(&pb, 1, 0); //frame length - 1024 samples put_bits(&pb, 1, 0); //does not depend on core coder put_bits(&pb, 1, 0); //is not extension //Explicitly Mark SBR absent put_bits(&pb, 11, 0x2b7); //sync extension put_bits(&pb, 5, AOT_SBR); put_bits(&pb, 1, 0); flush_put_bits(&pb); }


static void error_setv(Error **errp, ErrorClass err_class, const char *fmt, va_list ap) { Error *err; int saved_errno = errno; if (errp == NULL) { return; } assert(*errp == NULL); err = g_malloc0(sizeof(*err)); err->msg = g_strdup_vprintf(fmt, ap); err->err_class = err_class; if (errp == &error_abort) { error_report_err(err); abort(); } *errp = err; errno = saved_errno; }


static void unpin_rcv_pages(struct hfi1_filedata *fd,
			    struct tid_user_buf *tidbuf,
			    struct tid_rb_node *node,
			    unsigned int idx,
			    unsigned int npages,
			    bool mapped)
{
	struct page **pages;
	struct hfi1_devdata *dd = fd->uctxt->dd;

	if (mapped) {
		pci_unmap_single(dd->pcidev, node->dma_addr,
				 node->npages * PAGE_SIZE, PCI_DMA_FROMDEVICE);
		pages = &node->pages[idx];
	} else {
		pages = &tidbuf->pages[idx];
	}
	hfi1_release_user_pages(fd->mm, pages, npages, mapped);
	fd->tid_n_pinned -= npages;
}


static int ac3_decode_init(AVCodecContext *avctx) { AC3DecodeContext *ctx = avctx->priv_data; ac3_common_init(); ff_mdct_init(&ctx->imdct_ctx_256, 8, 1); ff_mdct_init(&ctx->imdct_ctx_512, 9, 1); ctx->samples = av_mallocz(6 * 256 * sizeof (float)); if (!ctx->samples) { av_log(avctx, AV_LOG_ERROR, "Cannot allocate memory for samples\n"); return -1; } dither_seed(&ctx->state, 0); return 0; }


static Jsi_Value *jsi_hashFmtKey(Jsi_MapEntry* h, struct Jsi_MapOpts *opts, int flags)
{
    Jsi_HashEntry* hPtr = (Jsi_HashEntry*)h;
    void *key = Jsi_HashKeyGet(hPtr);
    if (opts->keyType == JSI_KEYS_ONEWORD)
        return Jsi_ValueNewNumber(opts->interp, (Jsi_Number)(intptr_t)key);
    char nbuf[JSI_MAX_NUMBER_STRING];
    snprintf(nbuf, sizeof(nbuf), "%p", key);
    return Jsi_ValueNewStringDup(opts->interp, nbuf);
}


IN_PROC_BROWSER_TEST_F ( DownloadExtensionTest , DISABLED_DownloadExtensionTest_OnDeterminingFilename_InterruptedResume ) {
 LoadExtension ( "downloads_split" ) ;
 ASSERT_TRUE ( StartEmbeddedTestServer ( ) ) ;
 GoOnTheRecord ( ) ;
 content : : RenderProcessHost * host = AddFilenameDeterminer ( ) ;
 DownloadItem * item = NULL ;
 {
 DownloadManager * manager = GetCurrentManager ( ) ;
 std : : unique_ptr < content : : DownloadTestObserver > observer ( new JustInProgressDownloadObserver ( manager , 1 ) ) ;
 ASSERT_EQ ( 0 , manager -> InProgressCount ( ) ) ;
 ASSERT_EQ ( 0 , manager -> NonMaliciousInProgressCount ( ) ) ;
 ui_test_utils : : NavigateToURLWithDisposition ( current_browser ( ) , GURL ( net : : URLRequestSlowDownloadJob : : kUnknownSizeUrl ) , WindowOpenDisposition : : CURRENT_TAB , ui_test_utils : : BROWSER_TEST_NONE ) ;
 observer -> WaitForFinished ( ) ;
 EXPECT_EQ ( 1u , observer -> NumDownloadsSeenInState ( DownloadItem : : IN_PROGRESS ) ) ;
 DownloadManager : : DownloadVector items ;
 manager -> GetAllDownloads ( & items ) ;
 for ( DownloadManager : : DownloadVector : : iterator iter = items . begin ( ) ;
 iter != items . end ( ) ;
 ++ iter ) {
 if ( ( * iter ) -> GetState ( ) == DownloadItem : : IN_PROGRESS ) {
 EXPECT_EQ ( NULL , item ) ;
 item = * iter ;
 }
 }
 ASSERT_TRUE ( item ) ;
 }
 ScopedCancellingItem canceller ( item ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnCreated : : kEventName , base : : StringPrintf ( "[{
\"danger\": \"safe\"," " \"incognito\": false," " \"id\": %d," " \"mime\": \"application/octet-stream\"," " \"paused\": false}
]" , item -> GetId ( ) ) ) ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnDeterminingFilename : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"incognito\": false," " \"filename\":\"download-unknown-size\"}
]" , item -> GetId ( ) ) ) ) ;
 ASSERT_TRUE ( item -> GetTargetFilePath ( ) . empty ( ) ) ;
 ASSERT_EQ ( DownloadItem : : IN_PROGRESS , item -> GetState ( ) ) ;
 ClearEvents ( ) ;
 ui_test_utils : : NavigateToURLWithDisposition ( current_browser ( ) , GURL ( net : : URLRequestSlowDownloadJob : : kErrorDownloadUrl ) , WindowOpenDisposition : : NEW_BACKGROUND_TAB , ui_test_utils : : BROWSER_TEST_WAIT_FOR_NAVIGATION ) ;
 std : : string error ;
 ASSERT_TRUE ( ExtensionDownloadsEventRouter : : DetermineFilename ( current_browser ( ) -> profile ( ) , false , GetExtensionId ( ) , item -> GetId ( ) , base : : FilePath ( FILE_PATH_LITERAL ( "42.txt" ) ) , downloads : : FILENAME_CONFLICT_ACTION_UNIQUIFY , & error ) ) << error ;
 EXPECT_EQ ( "" , error ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnChanged : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"filename\": {
" " \"previous\": \"\"," " \"current\": \"%s\"}
}
]" , item -> GetId ( ) , GetFilename ( "42.txt" ) . c_str ( ) ) ) ) ;
 content : : DownloadUpdatedObserver interrupted ( item , base : : Bind ( ItemIsInterrupted ) ) ;
 ASSERT_TRUE ( interrupted . WaitForEvent ( ) ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnChanged : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"error\":{
\"current\":\"NETWORK_FAILED\"}
," " \"state\":{
" " \"previous\":\"in_progress\"," " \"current\":\"interrupted\"}
}
]" , item -> GetId ( ) ) ) ) ;
 ClearEvents ( ) ;
 RemoveFilenameDeterminer ( host ) ;
 item -> Resume ( ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnChanged : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"error\":{
\"previous\":\"NETWORK_FAILED\"}
," " \"state\":{
" " \"previous\":\"interrupted\"," " \"current\":\"in_progress\"}
}
]" , item -> GetId ( ) ) ) ) ;
 ClearEvents ( ) ;
 FinishFirstSlowDownloads ( ) ;
 ASSERT_TRUE ( WaitFor ( downloads : : OnChanged : : kEventName , base : : StringPrintf ( "[{
\"id\": %d," " \"state\": {
" " \"previous\": \"in_progress\"," " \"current\": \"complete\"}
}
]" , item -> GetId ( ) ) ) ) ;
 }


static void mdbEvalSetColumn(MyDbEvalContext *p, int iCol, Jsi_DString *dStr) {
    //Jsi_Interp *interp = p->jdb->interp;
    char nbuf[200];
    MysqlPrep *prep = p->prep;
    SqlFieldResults *field = prep->fieldResult+iCol;
    Jsi_Interp *interp = p->jdb->interp;
    if (field->isnull)
        return;

    switch(field->jsiTypeMap) {
        case JSI_OPTION_STRING: {
            int bytes = field->len;
            const char *zBlob = field->buffer.vstring;

            if( !zBlob ) {
                const char *nv = p->jdb->optPtr->nullvalue;
                Jsi_DSAppend(dStr, nv?nv:"null", NULL);
                return;
            }
            Jsi_DSAppendLen(dStr, zBlob, bytes);
            return;
        }
        case JSI_OPTION_BOOL: {
            snprintf(nbuf, sizeof(nbuf), "%s", field->buffer.vchar?"true":"false");
            Jsi_DSAppend(dStr, nbuf, NULL);
            return;
        }
        case JSI_OPTION_INT64: {
            snprintf(nbuf, sizeof(nbuf), "%lld", field->buffer.vlonglong);
            Jsi_DSAppend(dStr, nbuf, NULL);
            return;
        }
        //case JSI_OPTION_TIME_T:
        case JSI_OPTION_TIME_D:
        case JSI_OPTION_TIME_W: {
            Jsi_Number jtime = mdbMyTimeToJS(&field->buffer.timestamp);
            Jsi_NumberToString(interp, jtime, nbuf, sizeof(nbuf));
            Jsi_DSAppend(dStr, nbuf, NULL);
            return;
        }
        case JSI_OPTION_DOUBLE: {
            Jsi_NumberToString(interp, field->buffer.vdouble, nbuf, sizeof(nbuf));
            Jsi_DSAppend(dStr, nbuf, NULL);
            return;
        }
        default:
            Jsi_LogWarn("unknown type: %d", field->jsiTypeMap);

    }
}


static void generic_loader_realize(DeviceState *dev, Error **errp) { GenericLoaderState *s = GENERIC_LOADER(dev); hwaddr entry; int big_endian; int size = 0; s->set_pc = false; /* Perform some error checking on the user's options */ if (s->data || s->data_len || s->data_be) { /* User is loading memory values */ if (s->file) { error_setg(errp, "Specifying a file is not supported when loading " "memory values"); return; } else if (s->force_raw) { error_setg(errp, "Specifying force-raw is not supported when " "loading memory values"); return; } else if (!s->data_len) { /* We can't check for !data here as a value of 0 is still valid. */ error_setg(errp, "Both data and data-len must be specified"); return; } else if (s->data_len > 8) { error_setg(errp, "data-len cannot be greater then 8 bytes"); return; } } else if (s->file || s->force_raw) { /* User is loading an image */ if (s->data || s->data_len || s->data_be) { error_setg(errp, "data can not be specified when loading an " "image"); return; } /* The user specified a file, only set the PC if they also specified * a CPU to use. */ if (s->cpu_num != CPU_NONE) { s->set_pc = true; } } else if (s->addr) { /* User is setting the PC */ if (s->data || s->data_len || s->data_be) { error_setg(errp, "data can not be specified when setting a " "program counter"); return; } else if (!s->cpu_num) { error_setg(errp, "cpu_num must be specified when setting a " "program counter"); return; } s->set_pc = true; } else { /* Did the user specify anything? */ error_setg(errp, "please include valid arguments"); return; } qemu_register_reset(generic_loader_reset, dev); if (s->cpu_num != CPU_NONE) { s->cpu = qemu_get_cpu(s->cpu_num); if (!s->cpu) { error_setg(errp, "Specified boot CPU#%d is nonexistent", s->cpu_num); return; } } else { s->cpu = first_cpu; } #ifdef TARGET_WORDS_BIGENDIAN big_endian = 1; #else big_endian = 0; #endif if (s->file) { if (!s->force_raw) { size = load_elf_as(s->file, NULL, NULL, &entry, NULL, NULL, big_endian, 0, 0, 0, s->cpu->as); if (size < 0) { size = load_uimage_as(s->file, &entry, NULL, NULL, NULL, NULL, s->cpu->as); } } if (size < 0 || s->force_raw) { /* Default to the maximum size being the machine's ram size */ size = load_image_targphys_as(s->file, s->addr, ram_size, s->cpu->as); } else { s->addr = entry; } if (size < 0) { error_setg(errp, "Cannot load specified image %s", s->file); return; } } /* Convert the data endiannes */ if (s->data_be) { s->data = cpu_to_be64(s->data); } else { s->data = cpu_to_le64(s->data); } }


static Jsi_RC NumberToExponentialCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
    Jsi_Value **ret, Jsi_Func *funcPtr)
{
    char buf[100];
    int prec = 0, skip = 0;
    Jsi_Number num;
    Jsi_Value *v;
    ChkStringN(_this, funcPtr, v);
    if (Jsi_GetIntFromValue(interp, Jsi_ValueArrayIndex(interp, args, skip), &prec) != JSI_OK)
        return JSI_ERROR;
    if (prec<0) prec = 0;
    Jsi_GetDoubleFromValue(interp, v, &num);
    snprintf(buf, sizeof(buf), "%.*" JSI_NUMEFMT, prec, num);
#ifdef __WIN32
    char *e = strrchr(buf, 'e');
    if (e && (e[1]=='+' || e[1]=='-')) {
        e++;
        int eNum = atoi(e);
        if (e[0]=='-')
            eNum = -eNum;
        e++;
        snprintf(e, (e-buf), "%02d", eNum);
    }
#endif
    Jsi_ValueMakeStringDup(interp, ret, buf);
    return JSI_OK;
}