MagickExport const ModuleInfo **GetModuleInfoList(const char *pattern,
  size_t *number_modules,ExceptionInfo *exception)
{
  const ModuleInfo
    **modules;

  register const ModuleInfo
    *p;

  register ssize_t
    i;

  /*
    Allocate module list.
  */
  assert(pattern != (char *) NULL);
  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern);
  assert(number_modules != (size_t *) NULL);
  *number_modules=0;
  p=GetModuleInfo("*",exception);
  if (p == (const ModuleInfo *) NULL)
    return((const ModuleInfo **) NULL);
  modules=(const ModuleInfo **) AcquireQuantumMemory((size_t)
    GetNumberOfNodesInSplayTree(module_list)+1UL,sizeof(*modules));
  if (modules == (const ModuleInfo **) NULL)
    return((const ModuleInfo **) NULL);
  /*
    Generate module list.
  */
  LockSemaphoreInfo(module_semaphore);
  ResetSplayTreeIterator(module_list);
  p=(const ModuleInfo *) GetNextValueInSplayTree(module_list);
  for (i=0; p != (const ModuleInfo *) NULL; )
  {
    if ((p->stealth == MagickFalse) &&
        (GlobExpression(p->tag,pattern,MagickFalse) != MagickFalse))
      modules[i++]=p;
    p=(const ModuleInfo *) GetNextValueInSplayTree(module_list);
  }
  UnlockSemaphoreInfo(module_semaphore);
  qsort((void *) modules,(size_t) i,sizeof(*modules),ModuleInfoCompare);
  modules[i]=(ModuleInfo *) NULL;
  *number_modules=(size_t) i;
  return(modules);
}


void AXNodeObject::detach() {
  AXObject::detach();
  m_node = nullptr;
}


__fastcall TOwnConsole::TOwnConsole()
{
  DebugAssert(FInstance == NULL);
  FInstance = this;

  AllocConsole();
  SetConsoleCtrlHandler(HandlerRoutine, true);

  FInput = GetStdHandle(STD_INPUT_HANDLE);
  FOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  FPendingAbort = false;
  FConsoleWindow = NULL;
  FWindowStateTimer = NULL;
  FMinimized = false;
  FTrayIcon = new ::TTrayIcon(0);
  FTrayIcon->OnClick = TrayIconClick;

  if (WinConfiguration->MinimizeToTray)
  {
    FConsoleWindow = GetConsoleWindow();
    if (DebugAlwaysTrue(FConsoleWindow != NULL))
    {
      FWindowStateTimer = new TTimer(Application);
      FWindowStateTimer->OnTimer = WindowStateTimer;
      FWindowStateTimer->Interval = 250;
      FWindowStateTimer->Enabled = true;
    }
  }
}


int ff_img_read_packet(AVFormatContext *s1, AVPacket *pkt)

{

    VideoDemuxData *s = s1->priv_data;

    char filename_bytes[1024];

    char *filename = filename_bytes;

    int i;

    int size[3]           = { 0 }, ret[3] = { 0 };

    AVIOContext *f[3]     = { NULL };

    AVCodecContext *codec = s1->streams[0]->codec;

    if (!s->is_pipe) {

        /* loop over input */

        if (s->loop && s->img_number > s->img_last) {

            s->img_number = s->img_first;

        }

        if (s->img_number > s->img_last)

            return AVERROR_EOF;

        if (s->use_glob) {

#if HAVE_GLOB

            filename = s->globstate.gl_pathv[s->img_number];

#endif

        } else {

        if (av_get_frame_filename(filename_bytes, sizeof(filename_bytes),

                                  s->path,

                                  s->img_number) < 0 && s->img_number > 1)

            return AVERROR(EIO);

        }

        for (i = 0; i < 3; i++) {

            if (avio_open2(&f[i], filename, AVIO_FLAG_READ,

                           &s1->interrupt_callback, NULL) < 0) {

                if (i >= 1)

                    break;

                av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",

                       filename);

                return AVERROR(EIO);

            }

            size[i] = avio_size(f[i]);

            if (!s->split_planes)

                break;

            filename[strlen(filename) - 1] = 'U' + i;

        }

        if (codec->codec_id == AV_CODEC_ID_NONE) {

            AVProbeData pd;

            AVInputFormat *ifmt;

            uint8_t header[PROBE_BUF_MIN + AVPROBE_PADDING_SIZE];

            int ret;

            int score = 0;

            ret = avio_read(f[0], header, PROBE_BUF_MIN);

            if (ret < 0)

                return ret;

            avio_skip(f[0], -ret);

            pd.buf = header;

            pd.buf_size = ret;

            pd.filename = filename;

            ifmt = av_probe_input_format3(&pd, 1, &score);

            if (ifmt && ifmt->read_packet == ff_img_read_packet && ifmt->raw_codec_id)

                codec->codec_id = ifmt->raw_codec_id;

        }

        if (codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->width)

            infer_size(&codec->width, &codec->height, size[0]);

    } else {

        f[0] = s1->pb;

        if (url_feof(f[0]))

            return AVERROR(EIO);

        if (s->frame_size > 0) {

            size[0] = s->frame_size;

        } else {

            size[0] = 4096;

        }

    }

    if (av_new_packet(pkt, size[0] + size[1] + size[2]) < 0)

        return AVERROR(ENOMEM);

    pkt->stream_index = 0;

    pkt->flags       |= AV_PKT_FLAG_KEY;

    if (s->ts_from_file) {

        struct stat img_stat;

        if (stat(filename, &img_stat))

            return AVERROR(EIO);

        pkt->pts = (int64_t)img_stat.st_mtime;

        av_add_index_entry(s1->streams[0], s->img_number, pkt->pts, 0, 0, AVINDEX_KEYFRAME);

    } else if (!s->is_pipe) {

        pkt->pts      = s->pts;

    }

    pkt->size = 0;

    for (i = 0; i < 3; i++) {

        if (f[i]) {

            ret[i] = avio_read(f[i], pkt->data + pkt->size, size[i]);

            if (!s->is_pipe)

                avio_close(f[i]);

            if (ret[i] > 0)

                pkt->size += ret[i];

        }

    }

    if (ret[0] <= 0 || ret[1] < 0 || ret[2] < 0) {

        av_free_packet(pkt);

        return AVERROR(EIO); /* signal EOF */

    } else {

        s->img_count++;

        s->img_number++;

        s->pts++;

        return 0;

    }

}


void InputMethodBase::OnInputMethodChanged() const {
  TextInputClient* client = GetTextInputClient();
  if (!IsTextInputTypeNone())
    client->OnInputMethodChanged();
}


bool RegisterChromeWebContentsDelegateAndroid(JNIEnv* env) {
  return RegisterNativesImpl(env);
}


static int ext4_write_begin(struct file *file, struct address_space *mapping,
			    loff_t pos, unsigned len, unsigned flags,
			    struct page **pagep, void **fsdata)
{
	struct inode *inode = mapping->host;
	int ret, needed_blocks;
	handle_t *handle;
	int retries = 0;
	struct page *page;
	pgoff_t index;
	unsigned from, to;

	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
		return -EIO;

	trace_ext4_write_begin(inode, pos, len, flags);
	/*
	 * Reserve one block more for addition to orphan list in case
	 * we allocate blocks but write fails for some reason
	 */
	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
	index = pos >> PAGE_SHIFT;
	from = pos & (PAGE_SIZE - 1);
	to = from + len;

	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
						    flags, pagep);
		if (ret < 0)
			return ret;
		if (ret == 1)
			return 0;
	}

	/*
	 * grab_cache_page_write_begin() can take a long time if the
	 * system is thrashing due to memory pressure, or if the page
	 * is being written back.  So grab it first before we start
	 * the transaction handle.  This also allows us to allocate
	 * the page (if needed) without using GFP_NOFS.
	 */
retry_grab:
	page = grab_cache_page_write_begin(mapping, index, flags);
	if (!page)
		return -ENOMEM;
	unlock_page(page);

retry_journal:
	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
	if (IS_ERR(handle)) {
		put_page(page);
		return PTR_ERR(handle);
	}

	lock_page(page);
	if (page->mapping != mapping) {
		/* The page got truncated from under us */
		unlock_page(page);
		put_page(page);
		ext4_journal_stop(handle);
		goto retry_grab;
	}
	/* In case writeback began while the page was unlocked */
	wait_for_stable_page(page);

#ifdef CONFIG_FS_ENCRYPTION
	if (ext4_should_dioread_nolock(inode))
		ret = ext4_block_write_begin(page, pos, len,
					     ext4_get_block_unwritten);
	else
		ret = ext4_block_write_begin(page, pos, len,
					     ext4_get_block);
#else
	if (ext4_should_dioread_nolock(inode))
		ret = __block_write_begin(page, pos, len,
					  ext4_get_block_unwritten);
	else
		ret = __block_write_begin(page, pos, len, ext4_get_block);
#endif
	if (!ret && ext4_should_journal_data(inode)) {
		ret = ext4_walk_page_buffers(handle, page_buffers(page),
					     from, to, NULL,
					     do_journal_get_write_access);
	}

	if (ret) {
		bool extended = (pos + len > inode->i_size) &&
				!ext4_verity_in_progress(inode);

		unlock_page(page);
		/*
		 * __block_write_begin may have instantiated a few blocks
		 * outside i_size.  Trim these off again. Don't need
		 * i_size_read because we hold i_mutex.
		 *
		 * Add inode to orphan list in case we crash before
		 * truncate finishes
		 */
		if (extended && ext4_can_truncate(inode))
			ext4_orphan_add(handle, inode);

		ext4_journal_stop(handle);
		if (extended) {
			ext4_truncate_failed_write(inode);
			/*
			 * If truncate failed early the inode might
			 * still be on the orphan list; we need to
			 * make sure the inode is removed from the
			 * orphan list in that case.
			 */
			if (inode->i_nlink)
				ext4_orphan_del(NULL, inode);
		}

		if (ret == -ENOSPC &&
		    ext4_should_retry_alloc(inode->i_sb, &retries))
			goto retry_journal;
		put_page(page);
		return ret;
	}
	*pagep = page;
	return ret;
}


double InputType::ValueAsDouble() const {
  return std::numeric_limits<double>::quiet_NaN();
}


static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
  char
    explicit_vr[MaxTextExtent],
    implicit_vr[MaxTextExtent],
    magick[MaxTextExtent],
    photometric[MaxTextExtent];

  DCMStreamInfo
    *stream_info;

  Image
    *image;

  int
    *bluemap,
    datum,
    *greenmap,
    *graymap,
    index,
    *redmap;

  MagickBooleanType
    explicit_file,
    explicit_retry,
    polarity,
    sequence,
    use_explicit;

  MagickOffsetType
    offset;

  Quantum
    *scale;

  register IndexPacket
    *indexes;

  register ssize_t
    i,
    x;

  register PixelPacket
    *q;

  register unsigned char
    *p;

  size_t
    bits_allocated,
    bytes_per_pixel,
    colors,
    depth,
    height,
    length,
    mask,
    max_value,
    number_scenes,
    quantum,
    samples_per_pixel,
    signed_data,
    significant_bits,
    status,
    width,
    window_width;

  ssize_t
    count,
    scene,
    window_center,
    y;

  unsigned char
    *data;

  unsigned short
    group,
    element;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  image->depth=8UL;
  image->endian=LSBEndian;
  /*
    Read DCM preamble.
  */
  stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
  if (stream_info == (DCMStreamInfo *) NULL)
    ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
  (void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
  count=ReadBlob(image,128,(unsigned char *) magick);
  if (count != 128)
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  count=ReadBlob(image,4,(unsigned char *) magick);
  if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
    {
      offset=SeekBlob(image,0L,SEEK_SET);
      if (offset < 0)
        ThrowReaderException(CorruptImageError,"ImproperImageHeader");
    }
  /*
    Read DCM Medical image.
  */
  (void) CopyMagickString(photometric,"MONOCHROME1 ",MaxTextExtent);
  bits_allocated=8;
  bytes_per_pixel=1;
  polarity=MagickFalse;
  data=(unsigned char *) NULL;
  depth=8;
  element=0;
  explicit_vr[2]='\0';
  explicit_file=MagickFalse;
  colors=0;
  redmap=(int *) NULL;
  greenmap=(int *) NULL;
  bluemap=(int *) NULL;
  graymap=(int *) NULL;
  height=0;
  max_value=255UL;
  mask=0xffff;
  number_scenes=1;
  samples_per_pixel=1;
  scale=(Quantum *) NULL;
  sequence=MagickFalse;
  signed_data=(~0UL);
  significant_bits=0;
  use_explicit=MagickFalse;
  explicit_retry = MagickFalse;
  width=0;
  window_center=0;
  window_width=0;
  for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
                (sequence != MagickFalse); )
  {
    /*
      Read a group.
    */
    image->offset=(ssize_t) TellBlob(image);
    group=ReadBlobLSBShort(image);
    element=ReadBlobLSBShort(image);
    if ((group != 0x0002) && (image->endian == MSBEndian))
      {
        group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
        element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
      }
    quantum=0;
    /*
      Find corresponding VR for this group and element.
    */
    for (i=0; dicom_info[i].group < 0xffff; i++)
      if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
        break;
    (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MaxTextExtent);
    count=ReadBlob(image,2,(unsigned char *) explicit_vr);
    if (count != 2)
      ThrowReaderException(CorruptImageError,"ImproperImageHeader");
    /*
      Check for "explicitness", but meta-file headers always explicit.
    */
    if ((explicit_file == MagickFalse) && (group != 0x0002))
      explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
        (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
        MagickTrue : MagickFalse;
    use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
      (explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
    if ((use_explicit != MagickFalse) && (strcmp(implicit_vr,"xs") == 0))
      (void) CopyMagickString(implicit_vr,explicit_vr,MaxTextExtent);
    if ((use_explicit == MagickFalse) || (strcmp(implicit_vr,"!!") == 0))
      {
        offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
        if (offset < 0)
          ThrowReaderException(CorruptImageError,"ImproperImageHeader");
        quantum=4;
      }
    else
      {
        /*
          Assume explicit type.
        */
        quantum=2;
        if ((strcmp(explicit_vr,"OB") == 0) ||
            (strcmp(explicit_vr,"UN") == 0) ||
            (strcmp(explicit_vr,"OW") == 0) || (strcmp(explicit_vr,"SQ") == 0))
          {
            (void) ReadBlobLSBShort(image);
            quantum=4;
          }
      }
    datum=0;
    if (quantum == 4)
      {
        if (group == 0x0002)
          datum=(int) ReadBlobLSBLong(image);
        else
          datum=(int) ReadBlobLong(image);
      }
    else
      if (quantum == 2)
        {
          if (group == 0x0002)
            datum=(int) ReadBlobLSBShort(image);
          else
            datum=(int) ReadBlobShort(image);
        }
    quantum=0;
    length=1;
    if (datum != 0)
      {
        if ((strcmp(implicit_vr,"SS") == 0) ||
            (strcmp(implicit_vr,"US") == 0))
          quantum=2;
        else
          if ((strcmp(implicit_vr,"UL") == 0) ||
              (strcmp(implicit_vr,"SL") == 0) ||
              (strcmp(implicit_vr,"FL") == 0))
            quantum=4;
          else
            if (strcmp(implicit_vr,"FD") != 0)
              quantum=1;
            else
              quantum=8;
        if (datum != ~0)
          length=(size_t) datum/quantum;
        else
          {
            /*
              Sequence and item of undefined length.
            */
            quantum=0;
            length=0;
          }
      }
    if (image_info->verbose != MagickFalse)
      {
        /*
          Display Dicom info.
        */
        if (use_explicit == MagickFalse)
          explicit_vr[0]='\0';
        for (i=0; dicom_info[i].description != (char *) NULL; i++)
          if ((group == dicom_info[i].group) &&
              (element == dicom_info[i].element))
            break;
        (void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
          (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
          (unsigned long) group,(unsigned long) element);
        if (dicom_info[i].description != (char *) NULL)
          (void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
        (void) FormatLocaleFile(stdout,": ");
      }
    if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
      {
        if (image_info->verbose != MagickFalse)
          (void) FormatLocaleFile(stdout,"\n");
        break;
      }
    /*
      Allocate space and read an array.
    */
    data=(unsigned char *) NULL;
    if ((length == 1) && (quantum == 1))
      datum=(int) ReadBlobByte(image);
    else
      if ((length == 1) && (quantum == 2))
        {
          if (group == 0x0002)
            datum=(int) ReadBlobLSBShort(image);
          else
            datum=(int) ReadBlobShort(image);
        }
      else
        if ((length == 1) && (quantum == 4))
          {
            if (group == 0x0002)
              datum=(int) ReadBlobLSBLong(image);
            else
              datum=(int) ReadBlobLong(image);
          }
        else
          if ((quantum != 0) && (length != 0))
            {
              if (~length >= 1)
                data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
                  sizeof(*data));
              if (data == (unsigned char *) NULL)
                ThrowReaderException(ResourceLimitError,
                  "MemoryAllocationFailed");
              count=ReadBlob(image,(size_t) quantum*length,data);
              if (count != (ssize_t) (quantum*length))
                {
                  if (image_info->verbose != MagickFalse)
                    (void) FormatLocaleFile(stdout,"count=%d quantum=%d "
                      "length=%d group=%d\n",(int) count,(int) quantum,(int)
                      length,(int) group);
                   ThrowReaderException(CorruptImageError,
                     "InsufficientImageDataInFile");
                }
              data[length*quantum]='\0';
            }
          else
            if ((unsigned int) datum == 0xFFFFFFFFU)
              {
                sequence=MagickTrue;
                continue;
              }
    if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
      {
        if (data != (unsigned char *) NULL)
          data=(unsigned char *) RelinquishMagickMemory(data);
        sequence=MagickFalse;
        continue;
      }
    if (sequence != MagickFalse)
      {
        if (data != (unsigned char *) NULL)
          data=(unsigned char *) RelinquishMagickMemory(data);
        continue;
      }
    switch (group)
    {
      case 0x0002:
      {
        switch (element)
        {
          case 0x0010:
          {
            char
              transfer_syntax[MaxTextExtent];

            /*
              Transfer Syntax.
            */
            if ((datum == 0) && (explicit_retry == MagickFalse))
              {
                explicit_retry=MagickTrue;
                (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
                group=0;
                element=0;
                if (image_info->verbose != MagickFalse)
                  (void) FormatLocaleFile(stdout,
                    "Corrupted image - trying explicit format\n");
                break;
              }
            *transfer_syntax='\0';
            if (data != (unsigned char *) NULL)
              (void) CopyMagickString(transfer_syntax,(char *) data,
                MaxTextExtent);
            if (image_info->verbose != MagickFalse)
              (void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
                (const char *) transfer_syntax);
            if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
              {
                int
                  subtype,
                  type;

                type=0;
                subtype=0;
                (void) sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
                switch (type)
                {
                  case 1:
                  {
                    image->endian=LSBEndian;
                    break;
                  }
                  case 2:
                  {
                    image->endian=MSBEndian;
                    break;
                  }
                  case 4:
                  {
                    if ((subtype >= 80) && (subtype <= 81))
                      image->compression=JPEGCompression;
                    else
                      if ((subtype >= 90) && (subtype <= 93))
                        image->compression=JPEG2000Compression;
                      else
                        image->compression=JPEGCompression;
                    break;
                  }
                  case 5:
                  {
                    image->compression=RLECompression;
                    break;
                  }
                }
              }
            break;
          }
          default:
            break;
        }
        break;
      }
      case 0x0028:
      {
        switch (element)
        {
          case 0x0002:
          {
            /*
              Samples per pixel.
            */
            samples_per_pixel=(size_t) datum;
            break;
          }
          case 0x0004:
          {
            /*
              Photometric interpretation.
            */
            for (i=0; i < (ssize_t) MagickMin(length,MaxTextExtent-1); i++)
              photometric[i]=(char) data[i];
            photometric[i]='\0';
            polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
              MagickTrue : MagickFalse;
            break;
          }
          case 0x0006:
          {
            /*
              Planar configuration.
            */
            if (datum == 1)
              image->interlace=PlaneInterlace;
            break;
          }
          case 0x0008:
          {
            /*
              Number of frames.
            */
            number_scenes=StringToUnsignedLong((char *) data);
            break;
          }
          case 0x0010:
          {
            /*
              Image rows.
            */
            height=(size_t) datum;
            break;
          }
          case 0x0011:
          {
            /*
              Image columns.
            */
            width=(size_t) datum;
            break;
          }
          case 0x0100:
          {
            /*
              Bits allocated.
            */
            bits_allocated=(size_t) datum;
            bytes_per_pixel=1;
            if (datum > 8)
              bytes_per_pixel=2;
            depth=bits_allocated;
            if (depth > 32)
              ThrowReaderException(CorruptImageError,"ImproperImageHeader");
            max_value=(1UL << bits_allocated)-1;
            break;
          }
          case 0x0101:
          {
            /*
              Bits stored.
            */
            significant_bits=(size_t) datum;
            bytes_per_pixel=1;
            if (significant_bits > 8)
              bytes_per_pixel=2;
            depth=significant_bits;
            if (depth > 32)
              ThrowReaderException(CorruptImageError,"ImproperImageHeader");
            max_value=(1UL << significant_bits)-1;
            mask=(size_t) GetQuantumRange(significant_bits);
            break;
          }
          case 0x0102:
          {
            /*
              High bit.
            */
            break;
          }
          case 0x0103:
          {
            /*
              Pixel representation.
            */
            signed_data=(size_t) datum;
            break;
          }
          case 0x1050:
          {
            /*
              Visible pixel range: center.
            */
            if (data != (unsigned char *) NULL)
              window_center=(ssize_t) StringToLong((char *) data);
            break;
          }
          case 0x1051:
          {
            /*
              Visible pixel range: width.
            */
            if (data != (unsigned char *) NULL)
              window_width=StringToUnsignedLong((char *) data);
            break;
          }
          case 0x1200:
          case 0x3006:
          {
            /*
              Populate graymap.
            */
            if (data == (unsigned char *) NULL)
              break;
            colors=(size_t) (length/bytes_per_pixel);
            datum=(int) colors;
            graymap=(int *) AcquireQuantumMemory((size_t) colors,
              sizeof(*graymap));
            if (graymap == (int *) NULL)
              ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
            for (i=0; i < (ssize_t) colors; i++)
              if (bytes_per_pixel == 1)
                graymap[i]=(int) data[i];
              else
                graymap[i]=(int) ((short *) data)[i];
            break;
          }
          case 0x1201:
          {
            unsigned short
              index;

            /*
              Populate redmap.
            */
            if (data == (unsigned char *) NULL)
              break;
            colors=(size_t) (length/2);
            datum=(int) colors;
            redmap=(int *) AcquireQuantumMemory((size_t) colors,
              sizeof(*redmap));
            if (redmap == (int *) NULL)
              ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
            p=data;
            for (i=0; i < (ssize_t) colors; i++)
            {
              if (image->endian == MSBEndian)
                index=(unsigned short) ((*p << 8) | *(p+1));
              else
                index=(unsigned short) (*p | (*(p+1) << 8));
              redmap[i]=(int) index;
              p+=2;
            }
            break;
          }
          case 0x1202:
          {
            unsigned short
              index;

            /*
              Populate greenmap.
            */
            if (data == (unsigned char *) NULL)
              break;
            colors=(size_t) (length/2);
            datum=(int) colors;
            greenmap=(int *) AcquireQuantumMemory((size_t) colors,
              sizeof(*greenmap));
            if (greenmap == (int *) NULL)
              ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
            p=data;
            for (i=0; i < (ssize_t) colors; i++)
            {
              if (image->endian == MSBEndian)
                index=(unsigned short) ((*p << 8) | *(p+1));
              else
                index=(unsigned short) (*p | (*(p+1) << 8));
              greenmap[i]=(int) index;
              p+=2;
            }
            break;
          }
          case 0x1203:
          {
            unsigned short
              index;

            /*
              Populate bluemap.
            */
            if (data == (unsigned char *) NULL)
              break;
            colors=(size_t) (length/2);
            datum=(int) colors;
            bluemap=(int *) AcquireQuantumMemory((size_t) colors,
              sizeof(*bluemap));
            if (bluemap == (int *) NULL)
              ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
            p=data;
            for (i=0; i < (ssize_t) colors; i++)
            {
              if (image->endian == MSBEndian)
                index=(unsigned short) ((*p << 8) | *(p+1));
              else
                index=(unsigned short) (*p | (*(p+1) << 8));
              bluemap[i]=(int) index;
              p+=2;
            }
            break;
          }
          default:
            break;
        }
        break;
      }
      case 0x2050:
      {
        switch (element)
        {
          case 0x0020:
          {
            if ((data != (unsigned char *) NULL) &&
                (strncmp((char*) data,"INVERSE", 7) == 0))
              polarity=MagickTrue;
            break;
          }
          default:
            break;
        }
        break;
      }
      default:
        break;
    }
    if (data != (unsigned char *) NULL)
      {
        char
          *attribute;

        for (i=0; dicom_info[i].description != (char *) NULL; i++)
          if ((group == dicom_info[i].group) &&
              (element == dicom_info[i].element))
            break;
        if (dicom_info[i].description != (char *) NULL)
          {
            attribute=AcquireString("dcm:");
            (void) ConcatenateString(&attribute,dicom_info[i].description);
            for (i=0; i < (ssize_t) MagickMax(length,4); i++)
              if (isprint((int) data[i]) == MagickFalse)
                break;
            if ((i == (ssize_t) length) || (length > 4))
              {
                (void) SubstituteString(&attribute," ","");
                (void) SetImageProperty(image,attribute,(char *) data);
              }
            attribute=DestroyString(attribute);
          }
      }
    if (image_info->verbose != MagickFalse)
      {
        if (data == (unsigned char *) NULL)
          (void) FormatLocaleFile(stdout,"%d\n",datum);
        else
          {
            /*
              Display group data.
            */
            for (i=0; i < (ssize_t) MagickMax(length,4); i++)
              if (isprint((int) data[i]) == MagickFalse)
                break;
            if ((i != (ssize_t) length) && (length <= 4))
              {
                ssize_t
                  j;

                datum=0;
                for (j=(ssize_t) length-1; j >= 0; j--)
                  datum=(256*datum+data[j]);
                (void) FormatLocaleFile(stdout,"%d",datum);
              }
            else
              for (i=0; i < (ssize_t) length; i++)
                if (isprint((int) data[i]) != MagickFalse)
                  (void) FormatLocaleFile(stdout,"%c",data[i]);
                else
                  (void) FormatLocaleFile(stdout,"%c",'.');
            (void) FormatLocaleFile(stdout,"\n");
          }
      }
    if (data != (unsigned char *) NULL)
      data=(unsigned char *) RelinquishMagickMemory(data);
    if (EOFBlob(image) != MagickFalse)
      {
        ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
          image->filename);
        break;
      }
  }
  if ((width == 0) || (height == 0))
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  image->columns=(size_t) width;
  image->rows=(size_t) height;
  if (signed_data == 0xffff)
    signed_data=(size_t) (significant_bits == 16 ? 1 : 0);
  if ((image->compression == JPEGCompression) ||
      (image->compression == JPEG2000Compression))
    {
      Image
        *images;

      ImageInfo
        *read_info;

      int
        c;

      size_t
        length;

      unsigned int
        tag;

      /*
        Read offset table.
      */
      for (i=0; i < (ssize_t) stream_info->remaining; i++)
        (void) ReadBlobByte(image);
      tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
      (void) tag;
      length=(size_t) ReadBlobLSBLong(image);
      stream_info->offset_count=length >> 2;
      if (stream_info->offset_count != 0)
        {
          MagickOffsetType
            offset;

          stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
            stream_info->offset_count,sizeof(*stream_info->offsets));
          if (stream_info->offsets == (ssize_t *) NULL)
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          for (i=0; i < (ssize_t) stream_info->offset_count; i++)
            stream_info->offsets[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
          offset=TellBlob(image);
          for (i=0; i < (ssize_t) stream_info->offset_count; i++)
            stream_info->offsets[i]+=offset;
        }
      /*
        Handle non-native image formats.
      */
      read_info=CloneImageInfo(image_info);
      SetImageInfoBlob(read_info,(void *) NULL,0);
      images=NewImageList();
      for (scene=0; scene < (ssize_t) number_scenes; scene++)
      {
        char
          filename[MaxTextExtent];

        const char
          *property;

        FILE
          *file;

        Image
          *jpeg_image;

        int
          unique_file;

        unsigned int
          tag;

        tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
        length=(size_t) ReadBlobLSBLong(image);
        if (tag == 0xFFFEE0DD)
          break; /* sequence delimiter tag */
        if (tag != 0xFFFEE000)
          ThrowReaderException(CorruptImageError,"ImproperImageHeader");
        file=(FILE *) NULL;
        unique_file=AcquireUniqueFileResource(filename);
        if (unique_file != -1)
          file=fdopen(unique_file,"wb");
        if (file == (FILE *) NULL)
          {
            (void) RelinquishUniqueFileResource(filename);
            ThrowFileException(exception,FileOpenError,
              "UnableToCreateTemporaryFile",filename);
            break;
          }
        for ( ; length != 0; length--)
        {
          c=ReadBlobByte(image);
          if (c == EOF)
            {
              ThrowFileException(exception,CorruptImageError,
                "UnexpectedEndOfFile",image->filename);
              break;
            }
          (void) fputc(c,file);
        }
        (void) fclose(file);
        (void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
          filename);
        if (image->compression == JPEG2000Compression)
          (void) FormatLocaleString(read_info->filename,MaxTextExtent,"j2k:%s",
            filename);
        jpeg_image=ReadImage(read_info,exception);
        if (jpeg_image != (Image *) NULL)
          {
            ResetImagePropertyIterator(image);
            property=GetNextImageProperty(image);
            while (property != (const char *) NULL)
            {
              (void) SetImageProperty(jpeg_image,property,
                GetImageProperty(image,property));
              property=GetNextImageProperty(image);
            }
            AppendImageToList(&images,jpeg_image);
          }
        (void) RelinquishUniqueFileResource(filename);
      }
      read_info=DestroyImageInfo(read_info);
      image=DestroyImage(image);
      return(GetFirstImageInList(images));
    }
  if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
    {
      QuantumAny
        range;

      size_t
        length;

      /*
        Compute pixel scaling table.
      */
      length=(size_t) (GetQuantumRange(depth)+1);
      scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale));
      if (scale == (Quantum *) NULL)
        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
      range=GetQuantumRange(depth);
      for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++)
        scale[i]=ScaleAnyToQuantum((size_t) i,range);
    }
  if (image->compression == RLECompression)
    {
      size_t
        length;

      unsigned int
        tag;

      /*
        Read RLE offset table.
      */
      for (i=0; i < (ssize_t) stream_info->remaining; i++)
        (void) ReadBlobByte(image);
      tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
      (void) tag;
      length=(size_t) ReadBlobLSBLong(image);
      stream_info->offset_count=length >> 2;
      if (stream_info->offset_count != 0)
        {
          MagickOffsetType
            offset;

          stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
            stream_info->offset_count,sizeof(*stream_info->offsets));
          if (stream_info->offsets == (ssize_t *) NULL)
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          for (i=0; i < (ssize_t) stream_info->offset_count; i++)
            stream_info->offsets[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
          offset=TellBlob(image);
          for (i=0; i < (ssize_t) stream_info->offset_count; i++)
            stream_info->offsets[i]+=offset;
        }
    }
  for (scene=0; scene < (ssize_t) number_scenes; scene++)
  {
    if (image_info->ping != MagickFalse)
      break;
     image->columns=(size_t) width;
     image->rows=(size_t) height;
     image->depth=depth;
     image->colorspace=RGBColorspace;
     if ((image->colormap == (PixelPacket *) NULL) && (samples_per_pixel == 1))
       {
        size_t
          one;

        one=1;
        if (colors == 0)
          colors=one << depth;
        if (AcquireImageColormap(image,one << depth) == MagickFalse)
          ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
        if (redmap != (int *) NULL)
          for (i=0; i < (ssize_t) colors; i++)
          {
            index=redmap[i];
            if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
              index=(int) scale[index];
            image->colormap[i].red=(Quantum) index;
          }
        if (greenmap != (int *) NULL)
          for (i=0; i < (ssize_t) colors; i++)
          {
            index=greenmap[i];
            if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
              index=(int) scale[index];
            image->colormap[i].green=(Quantum) index;
          }
        if (bluemap != (int *) NULL)
          for (i=0; i < (ssize_t) colors; i++)
          {
            index=bluemap[i];
            if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
              index=(int) scale[index];
            image->colormap[i].blue=(Quantum) index;
          }
        if (graymap != (int *) NULL)
          for (i=0; i < (ssize_t) colors; i++)
          {
            index=graymap[i];
            if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
              index=(int) scale[index];
            image->colormap[i].red=(Quantum) index;
            image->colormap[i].green=(Quantum) index;
            image->colormap[i].blue=(Quantum) index;
          }
      }
    if (image->compression == RLECompression)
      {
        unsigned int
          tag;

        /*
          Read RLE segment table.
        */
        for (i=0; i < (ssize_t) stream_info->remaining; i++)
          (void) ReadBlobByte(image);
        tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
        stream_info->remaining=(size_t) ReadBlobLSBLong(image);
        if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
            (EOFBlob(image) != MagickFalse))
          ThrowReaderException(CorruptImageError,"ImproperImageHeader");
        stream_info->count=0;
        stream_info->segment_count=ReadBlobLSBLong(image);
        if (stream_info->segment_count > 1)
          {
            bytes_per_pixel=1;
            depth=8;
          }
        for (i=0; i < 15; i++)
          stream_info->segments[i]=(ssize_t) ((int) ReadBlobLSBLong(image));
        stream_info->remaining-=64;
      }
    if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
      {
        /*
          Convert Planar RGB DCM Medical image to pixel packets.
        */
        for (i=0; i < (ssize_t) samples_per_pixel; i++)
        {
          for (y=0; y < (ssize_t) image->rows; y++)
          {
            q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
            if (q == (PixelPacket *) NULL)
              break;
            for (x=0; x < (ssize_t) image->columns; x++)
            {
              switch ((int) i)
              {
                case 0:
                {
                  SetPixelRed(q,ScaleCharToQuantum((unsigned char)
                    ReadDCMByte(stream_info,image)));
                  break;
                }
                case 1:
                {
                  SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
                    ReadDCMByte(stream_info,image)));
                  break;
                }
                case 2:
                {
                  SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
                    ReadDCMByte(stream_info,image)));
                  break;
                }
                case 3:
                {
                  SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
                    ReadDCMByte(stream_info,image)));
                  break;
                }
                default:
                  break;
              }
              q++;
            }
            if (SyncAuthenticPixels(image,exception) == MagickFalse)
              break;
            if (image->previous == (Image *) NULL)
              {
                status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
                  image->rows);
                if (status == MagickFalse)
                  break;
              }
          }
        }
      }
    else
      {
        const char
          *option;

        int
          byte;

        LongPixelPacket
          pixel;

        /*
          Convert DCM Medical image to pixel packets.
        */
        byte=0;
        i=0;
        if ((window_center != 0) && (window_width == 0))
          window_width=(size_t) window_center;
        option=GetImageOption(image_info,"dcm:display-range");
        if (option != (const char *) NULL)
          {
            if (LocaleCompare(option,"reset") == 0)
              window_width=0;
          }
        (void) ResetMagickMemory(&pixel,0,sizeof(pixel));
        for (y=0; y < (ssize_t) image->rows; y++)
        {
          q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
          if (q == (PixelPacket *) NULL)
            break;
          indexes=GetAuthenticIndexQueue(image);
          for (x=0; x < (ssize_t) image->columns; x++)
          {
            if (samples_per_pixel == 1)
              {
                int
                  pixel_value;

                if (bytes_per_pixel == 1)
                  pixel_value=polarity != MagickFalse ? ((int) max_value-
                    ReadDCMByte(stream_info,image)) :
                    ReadDCMByte(stream_info,image);
                else
                  if ((bits_allocated != 12) || (significant_bits != 12))
                    pixel_value=(int) (polarity != MagickFalse ? (max_value-
                      ReadDCMShort(stream_info,image)) :
                      ReadDCMShort(stream_info,image));
                  else
                    {
                      if ((i & 0x01) != 0)
                        pixel_value=(ReadDCMByte(stream_info,image) << 8) |
                          byte;
                      else
                        {
                          pixel_value=(int) ReadDCMShort(stream_info,image);
                          byte=(int) (pixel_value & 0x0f);
                          pixel_value>>=4;
                        }
                      i++;
                    }
                index=pixel_value;
                if (window_width == 0)
                  {
                    if (signed_data == 1)
                      index=pixel_value-32767;
                  }
                else
                  {
                    ssize_t
                      window_max,
                      window_min;

                    window_min=(ssize_t) ceil((double) window_center-
                      (window_width-1.0)/2.0-0.5);
                    window_max=(ssize_t) floor((double) window_center+
                      (window_width-1.0)/2.0+0.5);
                    if ((ssize_t) pixel_value <= window_min)
                      index=0;
                    else
                      if ((ssize_t) pixel_value > window_max)
                        index=(int) max_value;
                      else
                        index=(int) (max_value*(((pixel_value-window_center-
                          0.5)/(window_width-1))+0.5));
                  }
                index&=mask;
                index=(int) ConstrainColormapIndex(image,(size_t) index);
                SetPixelIndex(indexes+x,index);
                pixel.red=1U*image->colormap[index].red;
                pixel.green=1U*image->colormap[index].green;
                pixel.blue=1U*image->colormap[index].blue;
              }
            else
              {
                if (bytes_per_pixel == 1)
                  {
                    pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
                    pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
                    pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
                  }
                else
                  {
                    pixel.red=ReadDCMShort(stream_info,image);
                    pixel.green=ReadDCMShort(stream_info,image);
                    pixel.blue=ReadDCMShort(stream_info,image);
                  }
                pixel.red&=mask;
                pixel.green&=mask;
                pixel.blue&=mask;
                if (scale != (Quantum *) NULL)
                  {
                    pixel.red=scale[pixel.red];
                    pixel.green=scale[pixel.green];
                    pixel.blue=scale[pixel.blue];
                  }
              }
            SetPixelRed(q,pixel.red);
            SetPixelGreen(q,pixel.green);
            SetPixelBlue(q,pixel.blue);
            q++;
          }
          if (SyncAuthenticPixels(image,exception) == MagickFalse)
            break;
          if (image->previous == (Image *) NULL)
            {
              status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
                image->rows);
              if (status == MagickFalse)
                break;
            }
        }
        if (stream_info->segment_count > 1)
          for (y=0; y < (ssize_t) image->rows; y++)
          {
            q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
            if (q == (PixelPacket *) NULL)
              break;
            indexes=GetAuthenticIndexQueue(image);
            for (x=0; x < (ssize_t) image->columns; x++)
            {
              if (samples_per_pixel == 1)
                {
                  int
                    pixel_value;

                  if (bytes_per_pixel == 1)
                    pixel_value=polarity != MagickFalse ? ((int) max_value-
                      ReadDCMByte(stream_info,image)) :
                      ReadDCMByte(stream_info,image);
                  else
                    if ((bits_allocated != 12) || (significant_bits != 12))
                      {
                        pixel_value=(int) (polarity != MagickFalse ? (max_value-
                          ReadDCMShort(stream_info,image)) :
                          ReadDCMShort(stream_info,image));
                        if (signed_data == 1)
                          pixel_value=((signed short) pixel_value);
                      }
                    else
                      {
                        if ((i & 0x01) != 0)
                          pixel_value=(ReadDCMByte(stream_info,image) << 8) |
                            byte;
                        else
                          {
                            pixel_value=(int) ReadDCMShort(stream_info,image);
                            byte=(int) (pixel_value & 0x0f);
                            pixel_value>>=4;
                          }
                        i++;
                      }
                  index=pixel_value;
                  if (window_width == 0)
                    {
                      if (signed_data == 1)
                        index=pixel_value-32767;
                    }
                  else
                    {
                      ssize_t
                        window_max,
                        window_min;

                      window_min=(ssize_t) ceil((double) window_center-
                        (window_width-1.0)/2.0-0.5);
                      window_max=(ssize_t) floor((double) window_center+
                        (window_width-1.0)/2.0+0.5);
                      if ((ssize_t) pixel_value <= window_min)
                        index=0;
                      else
                        if ((ssize_t) pixel_value > window_max)
                          index=(int) max_value;
                        else
                          index=(int) (max_value*(((pixel_value-window_center-
                            0.5)/(window_width-1))+0.5));
                    }
                  index&=mask;
                  index=(int) ConstrainColormapIndex(image,(size_t) index);
                  SetPixelIndex(indexes+x,(((size_t) GetPixelIndex(indexes+x)) |
                    (((size_t) index) << 8)));
                  pixel.red=1U*image->colormap[index].red;
                  pixel.green=1U*image->colormap[index].green;
                  pixel.blue=1U*image->colormap[index].blue;
                }
              else
                {
                  if (bytes_per_pixel == 1)
                    {
                      pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
                      pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
                      pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
                    }
                  else
                    {
                      pixel.red=ReadDCMShort(stream_info,image);
                      pixel.green=ReadDCMShort(stream_info,image);
                      pixel.blue=ReadDCMShort(stream_info,image);
                    }
                  pixel.red&=mask;
                  pixel.green&=mask;
                  pixel.blue&=mask;
                  if (scale != (Quantum *) NULL)
                    {
                      pixel.red=scale[pixel.red];
                      pixel.green=scale[pixel.green];
                      pixel.blue=scale[pixel.blue];
                    }
                }
              SetPixelRed(q,(((size_t) GetPixelRed(q)) |
                (((size_t) pixel.red) << 8)));
              SetPixelGreen(q,(((size_t) GetPixelGreen(q)) |
                (((size_t) pixel.green) << 8)));
              SetPixelBlue(q,(((size_t) GetPixelBlue(q)) |
                (((size_t) pixel.blue) << 8)));
              q++;
            }
            if (SyncAuthenticPixels(image,exception) == MagickFalse)
              break;
            if (image->previous == (Image *) NULL)
              {
                status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
                  image->rows);
                if (status == MagickFalse)
                  break;
              }
          }
      }
    if (IsGrayImage(image,exception) != MagickFalse)
      (void) SetImageColorspace(image,GRAYColorspace);
    if (EOFBlob(image) != MagickFalse)
      {
        ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
          image->filename);
        break;
      }
    /*
      Proceed to next image.
    */
    if (image_info->number_scenes != 0)
      if (image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    if (scene < (ssize_t) (number_scenes-1))
      {
        /*
          Allocate next image structure.
        */
        AcquireNextImage(image_info,image);
        if (GetNextImageInList(image) == (Image *) NULL)
          {
            image=DestroyImageList(image);
            return((Image *) NULL);
          }
        image=SyncNextImageInList(image);
        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
          GetBlobSize(image));
        if (status == MagickFalse)
          break;
      }
  }
  /*
    Free resources.
  */
  if (stream_info->offsets != (ssize_t *) NULL)
    stream_info->offsets=(ssize_t *)
      RelinquishMagickMemory(stream_info->offsets);
  stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
  if (scale != (Quantum *) NULL)
    scale=(Quantum *) RelinquishMagickMemory(scale);
  if (graymap != (int *) NULL)
    graymap=(int *) RelinquishMagickMemory(graymap);
  if (bluemap != (int *) NULL)
    bluemap=(int *) RelinquishMagickMemory(bluemap);
  if (greenmap != (int *) NULL)
    greenmap=(int *) RelinquishMagickMemory(greenmap);
  if (redmap != (int *) NULL)
    redmap=(int *) RelinquishMagickMemory(redmap);
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}


TEST(HeaderMapImplTest, MoveIntoInline) {
  HeaderMapImpl headers;
  HeaderString key;
  key.setCopy(Headers::get().CacheControl.get());
  HeaderString value;
  value.setCopy("hello", 5);
  headers.addViaMove(std::move(key), std::move(value));
  EXPECT_EQ("cache-control", headers.CacheControl()->key().getStringView());
  EXPECT_EQ("hello", headers.CacheControl()->value().getStringView());

  HeaderString key2;
  key2.setCopy(Headers::get().CacheControl.get().c_str(), Headers::get().CacheControl.get().size());
  HeaderString value2;
  value2.setCopy("there", 5);
  headers.addViaMove(std::move(key2), std::move(value2));
  EXPECT_EQ("cache-control", headers.CacheControl()->key().getStringView());
  EXPECT_EQ("hello,there", headers.CacheControl()->value().getStringView());
  EXPECT_EQ(headers.refreshByteSize(), countBytesForTest(headers));
}


static gboolean process_auth_queue(gpointer user_data)
{
	struct btd_adapter *adapter = user_data;
	DBusError err;

	adapter->auth_idle_id = 0;

	dbus_error_init(&err);
	dbus_set_error_const(&err, ERROR_INTERFACE ".Rejected", NULL);

	while (!g_queue_is_empty(adapter->auths)) {
		struct service_auth *auth = adapter->auths->head->data;
		struct btd_device *device = auth->device;

		/* Wait services to be resolved before asking authorization */
		if (auth->svc_id > 0)
			return FALSE;

		if (device_is_trusted(device) == TRUE) {
			auth->cb(NULL, auth->user_data);
			goto next;
		}

		/* If agent is set authorization is already ongoing */
		if (auth->agent)
			return FALSE;

		auth->agent = agent_get(NULL);
		if (auth->agent == NULL) {
			btd_warn(adapter->dev_id,
					"Authentication attempt without agent");
			auth->cb(&err, auth->user_data);
			goto next;
		}

		if (agent_authorize_service(auth->agent, device, auth->uuid,
					agent_auth_cb, adapter, NULL) < 0) {
			auth->cb(&err, auth->user_data);
			goto next;
		}

		break;

next:
		if (auth->agent)
			agent_unref(auth->agent);

		g_free(auth);

		g_queue_pop_head(adapter->auths);
	}

	dbus_error_free(&err);

	return FALSE;
}


tr_variant* tr_variantListAdd(tr_variant* list)
{
    TR_ASSERT(tr_variantIsList(list));

    containerReserve(list, 1);

    tr_variant* child = &list->val.l.vals[list->val.l.count++];
    child->key = 0;
    tr_variantInit(child, TR_VARIANT_TYPE_INT);

    return child;
}


static int pack_offset_sort ( const void * _a , const void * _b ) {
 const struct object_entry * a = * ( struct object_entry * * ) _a ;
 const struct object_entry * b = * ( struct object_entry * * ) _b ;
 if ( ! a -> in_pack && ! b -> in_pack ) return hashcmp ( a -> idx . sha1 , b -> idx . sha1 ) ;
 if ( a -> in_pack < b -> in_pack ) return - 1 ;
 if ( a -> in_pack > b -> in_pack ) return 1 ;
 return a -> in_pack_offset < b -> in_pack_offset ? - 1 : ( a -> in_pack_offset > b -> in_pack_offset ) ;
 }


static void optionsObjectMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    if (UNLIKELY(info.Length() < 1)) {
        throwTypeError(ExceptionMessages::failedToExecute("optionsObject", "TestObject", ExceptionMessages::notEnoughArguments(1, info.Length())), info.GetIsolate());
        return;
    }
    TestObject* imp = V8TestObject::toNative(info.Holder());
    V8TRYCATCH_VOID(Dictionary, oo, Dictionary(info[0], info.GetIsolate()));
    if (!oo.isUndefinedOrNull() && !oo.isObject()) {
        throwTypeError(ExceptionMessages::failedToExecute("optionsObject", "TestObject", "parameter 1 ('oo') is not an object."), info.GetIsolate());
        return;
    }
    V8TRYCATCH_VOID(Dictionary, ooo, Dictionary(info[1], info.GetIsolate()));
    if (!ooo.isUndefinedOrNull() && !ooo.isObject()) {
        throwTypeError(ExceptionMessages::failedToExecute("optionsObject", "TestObject", "parameter 2 ('ooo') is not an object."), info.GetIsolate());
        return;
    }
    imp->optionsObject(oo, ooo);
}


static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma,
		unsigned long address, pte_t *page_table, pmd_t *pmd,
		unsigned int flags, pte_t orig_pte)
{
	spinlock_t *ptl;
	struct page *page, *swapcache;
	struct mem_cgroup *memcg;
	swp_entry_t entry;
	pte_t pte;
	int locked;
	int exclusive = 0;
	int ret = 0;

	if (!pte_unmap_same(mm, pmd, page_table, orig_pte))
		goto out;

	entry = pte_to_swp_entry(orig_pte);
	if (unlikely(non_swap_entry(entry))) {
		if (is_migration_entry(entry)) {
			migration_entry_wait(mm, pmd, address);
		} else if (is_hwpoison_entry(entry)) {
			ret = VM_FAULT_HWPOISON;
		} else {
			print_bad_pte(vma, address, orig_pte, NULL);
			ret = VM_FAULT_SIGBUS;
		}
		goto out;
	}
	delayacct_set_flag(DELAYACCT_PF_SWAPIN);
	page = lookup_swap_cache(entry);
	if (!page) {
		page = swapin_readahead(entry,
					GFP_HIGHUSER_MOVABLE, vma, address);
		if (!page) {
			/*
			 * Back out if somebody else faulted in this pte
			 * while we released the pte lock.
			 */
			page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
			if (likely(pte_same(*page_table, orig_pte)))
				ret = VM_FAULT_OOM;
			delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
			goto unlock;
		}

		/* Had to read the page from swap area: Major fault */
		ret = VM_FAULT_MAJOR;
		count_vm_event(PGMAJFAULT);
		mem_cgroup_count_vm_event(mm, PGMAJFAULT);
	} else if (PageHWPoison(page)) {
		/*
		 * hwpoisoned dirty swapcache pages are kept for killing
		 * owner processes (which may be unknown at hwpoison time)
		 */
		ret = VM_FAULT_HWPOISON;
		delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
		swapcache = page;
		goto out_release;
	}

	swapcache = page;
	locked = lock_page_or_retry(page, mm, flags);

	delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
	if (!locked) {
		ret |= VM_FAULT_RETRY;
		goto out_release;
	}

	/*
	 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
	 * release the swapcache from under us.  The page pin, and pte_same
	 * test below, are not enough to exclude that.  Even if it is still
	 * swapcache, we need to check that the page's swap has not changed.
	 */
	if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
		goto out_page;

	page = ksm_might_need_to_copy(page, vma, address);
	if (unlikely(!page)) {
		ret = VM_FAULT_OOM;
		page = swapcache;
		goto out_page;
	}

	if (mem_cgroup_try_charge(page, mm, GFP_KERNEL, &memcg)) {
		ret = VM_FAULT_OOM;
		goto out_page;
	}

	/*
	 * Back out if somebody else already faulted in this pte.
	 */
	page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
	if (unlikely(!pte_same(*page_table, orig_pte)))
		goto out_nomap;

	if (unlikely(!PageUptodate(page))) {
		ret = VM_FAULT_SIGBUS;
		goto out_nomap;
	}

	/*
	 * The page isn't present yet, go ahead with the fault.
	 *
	 * Be careful about the sequence of operations here.
	 * To get its accounting right, reuse_swap_page() must be called
	 * while the page is counted on swap but not yet in mapcount i.e.
	 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
	 * must be called after the swap_free(), or it will never succeed.
	 */

	inc_mm_counter_fast(mm, MM_ANONPAGES);
	dec_mm_counter_fast(mm, MM_SWAPENTS);
	pte = mk_pte(page, vma->vm_page_prot);
	if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) {
		pte = maybe_mkwrite(pte_mkdirty(pte), vma);
		flags &= ~FAULT_FLAG_WRITE;
		ret |= VM_FAULT_WRITE;
		exclusive = 1;
	}
	flush_icache_page(vma, page);
	if (pte_swp_soft_dirty(orig_pte))
		pte = pte_mksoft_dirty(pte);
	set_pte_at(mm, address, page_table, pte);
	if (page == swapcache) {
		do_page_add_anon_rmap(page, vma, address, exclusive);
		mem_cgroup_commit_charge(page, memcg, true);
	} else { /* ksm created a completely new copy */
		page_add_new_anon_rmap(page, vma, address);
		mem_cgroup_commit_charge(page, memcg, false);
		lru_cache_add_active_or_unevictable(page, vma);
	}

	swap_free(entry);
	if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
		try_to_free_swap(page);
	unlock_page(page);
	if (page != swapcache) {
		/*
		 * Hold the lock to avoid the swap entry to be reused
		 * until we take the PT lock for the pte_same() check
		 * (to avoid false positives from pte_same). For
		 * further safety release the lock after the swap_free
		 * so that the swap count won't change under a
		 * parallel locked swapcache.
		 */
		unlock_page(swapcache);
		page_cache_release(swapcache);
	}

	if (flags & FAULT_FLAG_WRITE) {
		ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte);
		if (ret & VM_FAULT_ERROR)
			ret &= VM_FAULT_ERROR;
		goto out;
	}

	/* No need to invalidate - it was non-present before */
	update_mmu_cache(vma, address, page_table);
unlock:
	pte_unmap_unlock(page_table, ptl);
out:
	return ret;
out_nomap:
	mem_cgroup_cancel_charge(page, memcg);
	pte_unmap_unlock(page_table, ptl);
out_page:
	unlock_page(page);
out_release:
	page_cache_release(page);
	if (page != swapcache) {
		unlock_page(swapcache);
		page_cache_release(swapcache);
	}
	return ret;
}


OMX::buffer_id OMXNodeInstance::makeBufferID(OMX_BUFFERHEADERTYPE *bufferHeader) {
 if (bufferHeader == NULL) {
 return 0;
 }
 Mutex::Autolock autoLock(mBufferIDLock);
    OMX::buffer_id buffer;
 do { // handle the very unlikely case of ID overflow
 if (++mBufferIDCount == 0) {
 ++mBufferIDCount;
 }
        buffer = (OMX::buffer_id)mBufferIDCount;
 } while (mBufferIDToBufferHeader.indexOfKey(buffer) >= 0);
    mBufferIDToBufferHeader.add(buffer, bufferHeader);
    mBufferHeaderToBufferID.add(bufferHeader, buffer);

     return buffer;
 }


void vp9_rc_postencode_update ( VP9_COMP * cpi , uint64_t bytes_used ) {
 const VP9_COMMON * const cm = & cpi -> common ;
 const VP9EncoderConfig * const oxcf = & cpi -> oxcf ;
 RATE_CONTROL * const rc = & cpi -> rc ;
 const int qindex = cm -> base_qindex ;
 rc -> projected_frame_size = ( int ) ( bytes_used << 3 ) ;
 vp9_rc_update_rate_correction_factors ( cpi , ( cpi -> sf . recode_loop >= ALLOW_RECODE_KFARFGF || oxcf -> rc_mode == VPX_CBR ) ? 2 : 0 ) ;
 if ( cm -> frame_type == KEY_FRAME ) {
 rc -> last_q [ KEY_FRAME ] = qindex ;
 rc -> avg_frame_qindex [ KEY_FRAME ] = ROUND_POWER_OF_TWO ( 3 * rc -> avg_frame_qindex [ KEY_FRAME ] + qindex , 2 ) ;
 }
 else {
 if ( rc -> is_src_frame_alt_ref || ! ( cpi -> refresh_golden_frame || cpi -> refresh_alt_ref_frame ) || ( cpi -> use_svc && oxcf -> rc_mode == VPX_CBR ) ) {
 rc -> last_q [ INTER_FRAME ] = qindex ;
 rc -> avg_frame_qindex [ INTER_FRAME ] = ROUND_POWER_OF_TWO ( 3 * rc -> avg_frame_qindex [ INTER_FRAME ] + qindex , 2 ) ;
 rc -> ni_frames ++ ;
 rc -> tot_q += vp9_convert_qindex_to_q ( qindex , cm -> bit_depth ) ;
 rc -> avg_q = rc -> tot_q / rc -> ni_frames ;
 rc -> ni_tot_qi += qindex ;
 rc -> ni_av_qi = rc -> ni_tot_qi / rc -> ni_frames ;
 }
 }
 if ( ( qindex < rc -> last_boosted_qindex ) || ( ( ( cm -> frame_type == KEY_FRAME ) || cpi -> refresh_alt_ref_frame || ( cpi -> refresh_golden_frame && ! rc -> is_src_frame_alt_ref ) ) ) ) {
 rc -> last_boosted_qindex = qindex ;
 }
 if ( cm -> frame_type == KEY_FRAME ) rc -> last_kf_qindex = qindex ;
 update_buffer_level ( cpi , rc -> projected_frame_size ) ;
 if ( cm -> frame_type != KEY_FRAME ) {
 rc -> rolling_target_bits = ROUND_POWER_OF_TWO ( rc -> rolling_target_bits * 3 + rc -> this_frame_target , 2 ) ;
 rc -> rolling_actual_bits = ROUND_POWER_OF_TWO ( rc -> rolling_actual_bits * 3 + rc -> projected_frame_size , 2 ) ;
 rc -> long_rolling_target_bits = ROUND_POWER_OF_TWO ( rc -> long_rolling_target_bits * 31 + rc -> this_frame_target , 5 ) ;
 rc -> long_rolling_actual_bits = ROUND_POWER_OF_TWO ( rc -> long_rolling_actual_bits * 31 + rc -> projected_frame_size , 5 ) ;
 }
 rc -> total_actual_bits += rc -> projected_frame_size ;
 rc -> total_target_bits += cm -> show_frame ? rc -> avg_frame_bandwidth : 0 ;
 rc -> total_target_vs_actual = rc -> total_actual_bits - rc -> total_target_bits ;
 if ( is_altref_enabled ( cpi ) && cpi -> refresh_alt_ref_frame && ( cm -> frame_type != KEY_FRAME ) ) update_alt_ref_frame_stats ( cpi ) ;
 else update_golden_frame_stats ( cpi ) ;
 if ( cm -> frame_type == KEY_FRAME ) rc -> frames_since_key = 0 ;
 if ( cm -> show_frame ) {
 rc -> frames_since_key ++ ;
 rc -> frames_to_key -- ;
 }
 }


std::string SafeBrowsingPrivateEventRouter::GetProfileUserName() {
  return identity_manager_ && identity_manager_->HasPrimaryAccount()
             ? identity_manager_->GetPrimaryAccountInfo().email
             : std::string();
}


  psh_hint_table_done( PSH_Hint_Table  table,
                       FT_Memory       memory )
  {
    FT_FREE( table->zones );
    table->num_zones = 0;
    table->zone      = 0;

    FT_FREE( table->sort );
    FT_FREE( table->hints );
    table->num_hints   = 0;
    table->max_hints   = 0;
    table->sort_global = 0;
  }


void initServerConfig(void) {
    int j;

    getRandomHexChars(server.runid,CONFIG_RUN_ID_SIZE);
    server.configfile = NULL;
    server.executable = NULL;
    server.hz = CONFIG_DEFAULT_HZ;
    server.runid[CONFIG_RUN_ID_SIZE] = '\0';
    server.arch_bits = (sizeof(long) == 8) ? 64 : 32;
    server.port = CONFIG_DEFAULT_SERVER_PORT;
    server.tcp_backlog = CONFIG_DEFAULT_TCP_BACKLOG;
    server.bindaddr_count = 0;
    server.unixsocket = NULL;
    server.unixsocketperm = CONFIG_DEFAULT_UNIX_SOCKET_PERM;
    server.ipfd_count = 0;
    server.sofd = -1;
    server.protected_mode = CONFIG_DEFAULT_PROTECTED_MODE;
    server.dbnum = CONFIG_DEFAULT_DBNUM;
    server.verbosity = CONFIG_DEFAULT_VERBOSITY;
    server.maxidletime = CONFIG_DEFAULT_CLIENT_TIMEOUT;
    server.tcpkeepalive = CONFIG_DEFAULT_TCP_KEEPALIVE;
    server.active_expire_enabled = 1;
    server.client_max_querybuf_len = PROTO_MAX_QUERYBUF_LEN;
    server.saveparams = NULL;
    server.loading = 0;
    server.logfile = zstrdup(CONFIG_DEFAULT_LOGFILE);
    server.syslog_enabled = CONFIG_DEFAULT_SYSLOG_ENABLED;
    server.syslog_ident = zstrdup(CONFIG_DEFAULT_SYSLOG_IDENT);
    server.syslog_facility = LOG_LOCAL0;
    server.daemonize = CONFIG_DEFAULT_DAEMONIZE;
    server.supervised = 0;
    server.supervised_mode = SUPERVISED_NONE;
    server.aof_state = AOF_OFF;
    server.aof_fsync = CONFIG_DEFAULT_AOF_FSYNC;
    server.aof_no_fsync_on_rewrite = CONFIG_DEFAULT_AOF_NO_FSYNC_ON_REWRITE;
    server.aof_rewrite_perc = AOF_REWRITE_PERC;
    server.aof_rewrite_min_size = AOF_REWRITE_MIN_SIZE;
    server.aof_rewrite_base_size = 0;
    server.aof_rewrite_scheduled = 0;
    server.aof_last_fsync = time(NULL);
    server.aof_rewrite_time_last = -1;
    server.aof_rewrite_time_start = -1;
    server.aof_lastbgrewrite_status = C_OK;
    server.aof_delayed_fsync = 0;
    server.aof_fd = -1;
    server.aof_selected_db = -1; /* Make sure the first time will not match */
    server.aof_flush_postponed_start = 0;
    server.aof_rewrite_incremental_fsync = CONFIG_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC;
    server.aof_load_truncated = CONFIG_DEFAULT_AOF_LOAD_TRUNCATED;
    server.pidfile = NULL;
    server.rdb_filename = zstrdup(CONFIG_DEFAULT_RDB_FILENAME);
    server.aof_filename = zstrdup(CONFIG_DEFAULT_AOF_FILENAME);
    server.requirepass = NULL;
    server.rdb_compression = CONFIG_DEFAULT_RDB_COMPRESSION;
    server.rdb_checksum = CONFIG_DEFAULT_RDB_CHECKSUM;
    server.stop_writes_on_bgsave_err = CONFIG_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR;
    server.activerehashing = CONFIG_DEFAULT_ACTIVE_REHASHING;
    server.notify_keyspace_events = 0;
    server.maxclients = CONFIG_DEFAULT_MAX_CLIENTS;
    server.bpop_blocked_clients = 0;
    server.maxmemory = CONFIG_DEFAULT_MAXMEMORY;
    server.maxmemory_policy = CONFIG_DEFAULT_MAXMEMORY_POLICY;
    server.maxmemory_samples = CONFIG_DEFAULT_MAXMEMORY_SAMPLES;
    server.hash_max_ziplist_entries = OBJ_HASH_MAX_ZIPLIST_ENTRIES;
    server.hash_max_ziplist_value = OBJ_HASH_MAX_ZIPLIST_VALUE;
    server.list_max_ziplist_size = OBJ_LIST_MAX_ZIPLIST_SIZE;
    server.list_compress_depth = OBJ_LIST_COMPRESS_DEPTH;
    server.set_max_intset_entries = OBJ_SET_MAX_INTSET_ENTRIES;
    server.zset_max_ziplist_entries = OBJ_ZSET_MAX_ZIPLIST_ENTRIES;
    server.zset_max_ziplist_value = OBJ_ZSET_MAX_ZIPLIST_VALUE;
    server.hll_sparse_max_bytes = CONFIG_DEFAULT_HLL_SPARSE_MAX_BYTES;
    server.shutdown_asap = 0;
    server.repl_ping_slave_period = CONFIG_DEFAULT_REPL_PING_SLAVE_PERIOD;
    server.repl_timeout = CONFIG_DEFAULT_REPL_TIMEOUT;
    server.repl_min_slaves_to_write = CONFIG_DEFAULT_MIN_SLAVES_TO_WRITE;
    server.repl_min_slaves_max_lag = CONFIG_DEFAULT_MIN_SLAVES_MAX_LAG;
    server.cluster_enabled = 0;
    server.cluster_node_timeout = CLUSTER_DEFAULT_NODE_TIMEOUT;
    server.cluster_migration_barrier = CLUSTER_DEFAULT_MIGRATION_BARRIER;
    server.cluster_slave_validity_factor = CLUSTER_DEFAULT_SLAVE_VALIDITY;
    server.cluster_require_full_coverage = CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE;
    server.cluster_configfile = zstrdup(CONFIG_DEFAULT_CLUSTER_CONFIG_FILE);
    server.migrate_cached_sockets = dictCreate(&migrateCacheDictType,NULL);
    server.next_client_id = 1; /* Client IDs, start from 1 .*/
    server.loading_process_events_interval_bytes = (1024*1024*2);

    server.lruclock = getLRUClock();
    resetServerSaveParams();

    appendServerSaveParams(60*60,1);  /* save after 1 hour and 1 change */
    appendServerSaveParams(300,100);  /* save after 5 minutes and 100 changes */
    appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
    /* Replication related */
    server.masterauth = NULL;
    server.masterhost = NULL;
    server.masterport = 6379;
    server.master = NULL;
    server.cached_master = NULL;
    server.repl_master_initial_offset = -1;
    server.repl_state = REPL_STATE_NONE;
    server.repl_syncio_timeout = CONFIG_REPL_SYNCIO_TIMEOUT;
    server.repl_serve_stale_data = CONFIG_DEFAULT_SLAVE_SERVE_STALE_DATA;
    server.repl_slave_ro = CONFIG_DEFAULT_SLAVE_READ_ONLY;
    server.repl_down_since = 0; /* Never connected, repl is down since EVER. */
    server.repl_disable_tcp_nodelay = CONFIG_DEFAULT_REPL_DISABLE_TCP_NODELAY;
    server.repl_diskless_sync = CONFIG_DEFAULT_REPL_DISKLESS_SYNC;
    server.repl_diskless_sync_delay = CONFIG_DEFAULT_REPL_DISKLESS_SYNC_DELAY;
    server.slave_priority = CONFIG_DEFAULT_SLAVE_PRIORITY;
    server.slave_announce_ip = CONFIG_DEFAULT_SLAVE_ANNOUNCE_IP;
    server.slave_announce_port = CONFIG_DEFAULT_SLAVE_ANNOUNCE_PORT;
    server.master_repl_offset = 0;

    /* Replication partial resync backlog */
    server.repl_backlog = NULL;
    server.repl_backlog_size = CONFIG_DEFAULT_REPL_BACKLOG_SIZE;
    server.repl_backlog_histlen = 0;
    server.repl_backlog_idx = 0;
    server.repl_backlog_off = 0;
    server.repl_backlog_time_limit = CONFIG_DEFAULT_REPL_BACKLOG_TIME_LIMIT;
    server.repl_no_slaves_since = time(NULL);

    /* Client output buffer limits */
    for (j = 0; j < CLIENT_TYPE_OBUF_COUNT; j++)
        server.client_obuf_limits[j] = clientBufferLimitsDefaults[j];

    /* Double constants initialization */
    R_Zero = 0.0;
    R_PosInf = 1.0/R_Zero;
    R_NegInf = -1.0/R_Zero;
    R_Nan = R_Zero/R_Zero;

    /* Command table -- we initiialize it here as it is part of the
     * initial configuration, since command names may be changed via
     * redis.conf using the rename-command directive. */
    server.commands = dictCreate(&commandTableDictType,NULL);
    server.orig_commands = dictCreate(&commandTableDictType,NULL);
    populateCommandTable();
    server.delCommand = lookupCommandByCString("del");
    server.multiCommand = lookupCommandByCString("multi");
    server.lpushCommand = lookupCommandByCString("lpush");
    server.lpopCommand = lookupCommandByCString("lpop");
    server.rpopCommand = lookupCommandByCString("rpop");
    server.sremCommand = lookupCommandByCString("srem");
    server.execCommand = lookupCommandByCString("exec");

    /* Slow log */
    server.slowlog_log_slower_than = CONFIG_DEFAULT_SLOWLOG_LOG_SLOWER_THAN;
    server.slowlog_max_len = CONFIG_DEFAULT_SLOWLOG_MAX_LEN;

    /* Latency monitor */
    server.latency_monitor_threshold = CONFIG_DEFAULT_LATENCY_MONITOR_THRESHOLD;

    /* Debugging */
    server.assert_failed = "<no assertion failed>";
    server.assert_file = "<no file>";
    server.assert_line = 0;
    server.bug_report_start = 0;
    server.watchdog_period = 0;
}


static struct omap_lpg_s *omap_lpg_init(MemoryRegion *system_memory,

                                        hwaddr base, omap_clk clk)

{

    struct omap_lpg_s *s = (struct omap_lpg_s *)

            g_malloc0(sizeof(struct omap_lpg_s));

    s->tm = timer_new_ms(QEMU_CLOCK_VIRTUAL, omap_lpg_tick, s);

    omap_lpg_reset(s);

    memory_region_init_io(&s->iomem, NULL, &omap_lpg_ops, s, "omap-lpg", 0x800);

    memory_region_add_subregion(system_memory, base, &s->iomem);

    omap_clk_adduser(clk, qemu_allocate_irqs(omap_lpg_clk_update, s, 1)[0]);

    return s;

}


int MemBackendImpl::CalculateSizeOfEntriesBetween(
    base::Time initial_time,
    base::Time end_time,
    const CompletionCallback& callback) {
  if (end_time.is_null())
    end_time = Time::Max();
  DCHECK_GE(end_time, initial_time);

  int size = 0;
  base::LinkNode<MemEntryImpl>* node = lru_list_.head();
  while (node != lru_list_.end() && node->value()->GetLastUsed() < initial_time)
    node = node->next();
  while (node != lru_list_.end() && node->value()->GetLastUsed() < end_time) {
    MemEntryImpl* entry = node->value();
    size += entry->GetStorageSize();
    node = node->next();
  }
  return size;
}


svcxdr_tmpalloc(struct nfsd4_compoundargs *argp, u32 len)
{
	struct svcxdr_tmpbuf *tb;

	tb = kmalloc(sizeof(*tb) + len, GFP_KERNEL);
	if (!tb)
		return NULL;
	tb->next = argp->to_free;
	argp->to_free = tb;
	return tb->buf;
}


static size_t GetBytesPerRow(size_t columns,
  size_t samples_per_pixel,size_t bits_per_pixel,
  MagickBooleanType pad)
{
  size_t
    bytes_per_row;

  switch (bits_per_pixel)
  {
    case 1:
    {
      bytes_per_row=4*(((size_t) samples_per_pixel*columns*
        bits_per_pixel+31)/32);
      break;
    }
    case 8:
    default:
    {
      bytes_per_row=4*(((size_t) samples_per_pixel*columns*
        bits_per_pixel+31)/32);
      break;
    }
    case 10:
    {
      if (pad == MagickFalse)
        {
          bytes_per_row=4*(((size_t) samples_per_pixel*columns*
            bits_per_pixel+31)/32);
          break;
        }
      bytes_per_row=4*(((size_t) (32*((samples_per_pixel*columns+2)/3))+31)/32);
      break;
    }
    case 12:
    {
      if (pad == MagickFalse)
        {
          bytes_per_row=4*(((size_t) samples_per_pixel*columns*
            bits_per_pixel+31)/32);
          break;
        }
      bytes_per_row=2*(((size_t) (16*samples_per_pixel*columns)+15)/16);
      break;
    }
    case 16:
    {
      bytes_per_row=2*(((size_t) samples_per_pixel*columns*
        bits_per_pixel+8)/16);
      break;
    }
    case 32:
    {
      bytes_per_row=4*(((size_t) samples_per_pixel*columns*
        bits_per_pixel+31)/32);
      break;
    }
    case 64:
    {
      bytes_per_row=8*(((size_t) samples_per_pixel*columns*
        bits_per_pixel+63)/64);
      break;
    }
  }
  return(bytes_per_row);
}


static bool parseStopNode(QSvgStyleProperty *parent,
                          const QXmlStreamAttributes &attributes,
                          QSvgHandler *handler)
{
    if (parent->type() != QSvgStyleProperty::GRADIENT)
        return false;
    QString nodeIdStr     = someId(attributes);
    QString xmlClassStr   = attributes.value(QLatin1String("class")).toString();

    //### nasty hack because stop gradients are not in the rendering tree
    //    we force a dummy node with the same id and class into a rendering
    //    tree to figure out whether the selector has a style for it
    //    QSvgStyleSelector should be coded in a way that could avoid it
    QSvgAnimation anim;
    anim.setNodeId(nodeIdStr);
    anim.setXmlClass(xmlClassStr);

    QXmlStreamAttributes xmlAttr = attributes;

#ifndef QT_NO_CSSPARSER
    QCss::StyleSelector::NodePtr cssNode;
    cssNode.ptr = &anim;
    QList<QCss::Declaration> decls = handler->selector()->declarationsForNode(cssNode);

    for (int i = 0; i < decls.count(); ++i) {
        const QCss::Declaration &decl = decls.at(i);

        if (decl.d->property.isEmpty())
            continue;
        if (decl.d->values.count() != 1)
            continue;
        QCss::Value val = decl.d->values.first();
        QString valueStr = val.toString();
        if (val.type == QCss::Value::Uri) {
            valueStr.prepend(QLatin1String("url("));
            valueStr.append(QLatin1Char(')'));
        }
        xmlAttr.append(QString(), decl.d->property, valueStr);
    }

#endif

    QSvgAttributes attrs(xmlAttr, handler);

    QSvgGradientStyle *style =
        static_cast<QSvgGradientStyle*>(parent);
    QStringView colorStr    = attrs.stopColor;
    QColor color;

    bool ok = true;
    qreal offset = convertToNumber(attrs.offset, handler, &ok);
    if (!ok)
        offset = 0.0;
    QString black = QString::fromLatin1("#000000");
    if (colorStr.isEmpty()) {
        colorStr = black;
    }

    constructColor(colorStr, attrs.stopOpacity, color, handler);

    QGradient *grad = style->qgradient();

    offset = qMin(qreal(1), qMax(qreal(0), offset)); // Clamp to range [0, 1]
    QGradientStops stops;
    if (style->gradientStopsSet()) {
        stops = grad->stops();
        // If the stop offset equals the one previously added, add an epsilon to make it greater.
        if (offset <= stops.back().first)
            offset = stops.back().first + FLT_EPSILON;
    }

    // If offset is greater than one, it must be clamped to one.
    if (offset > 1.0) {
        if ((stops.size() == 1) || (stops.at(stops.size() - 2).first < 1.0 - FLT_EPSILON)) {
            stops.back().first = 1.0 - FLT_EPSILON;
            grad->setStops(stops);
        }
        offset = 1.0;
    }

    grad->setColorAt(offset, color);
    style->setGradientStopsSet(true);
    return true;
}


static av_cold void avcodec_init(void)
{
    static int initialized = 0;

    if (initialized != 0)
        return;
    initialized = 1;

    if (CONFIG_ME_CMP)
        ff_me_cmp_init_static();
}


Luv24fromXYZ(LogLuvState* sp, uint8* op, tmsize_t n)
{
	uint32* luv = (uint32*) sp->tbuf;
	float* xyz = (float*) op;

	while (n-- > 0) {
		*luv++ = LogLuv24fromXYZ(xyz, sp->encode_meth);
		xyz += 3;
	}
}


static gint dissect_amf0_value_type ( tvbuff_t * tvb , gint offset , proto_tree * tree , gboolean * amf3_encoding , proto_item * parent_ti ) {
 guint8 iObjType ;
 proto_item * ti ;
 proto_tree * val_tree ;
 gint iValueOffset = offset ;
 guint32 iIntegerValue ;
 double iDoubleValue ;
 gboolean iBooleanValue ;
 guint iStringLength ;
 gchar * iStringValue ;
 guint iArrayLength ;
 guint i ;
 nstime_t t ;
 gint64 iInteger64Value ;
 guint count ;
 iObjType = tvb_get_guint8 ( tvb , offset ) ;
 if ( parent_ti != NULL ) proto_item_append_text ( parent_ti , " %s" , val_to_str_const ( iObjType , amf0_type_vals , "Unknown" ) ) ;
 switch ( iObjType ) {
 case AMF0_OBJECT : ti = proto_tree_add_item ( tree , hf_amf_object , tvb , offset , - 1 , ENC_NA ) ;
 val_tree = proto_item_add_subtree ( ti , ett_amf_value ) ;
 break ;
 case AMF0_ECMA_ARRAY : ti = proto_tree_add_item ( tree , hf_amf_ecmaarray , tvb , offset , - 1 , ENC_NA ) ;
 val_tree = proto_item_add_subtree ( ti , ett_amf_value ) ;
 break ;
 case AMF0_STRICT_ARRAY : ti = proto_tree_add_item ( tree , hf_amf_strictarray , tvb , offset , - 1 , ENC_NA ) ;
 val_tree = proto_item_add_subtree ( ti , ett_amf_value ) ;
 break ;
 default : val_tree = proto_tree_add_subtree ( tree , tvb , offset , - 1 , ett_amf_value , & ti , val_to_str_const ( iObjType , amf0_type_vals , "Unknown" ) ) ;
 break ;
 }
 proto_tree_add_uint ( val_tree , hf_amf_amf0_type , tvb , iValueOffset , 1 , iObjType ) ;
 iValueOffset ++ ;
 switch ( iObjType ) {
 case AMF0_NUMBER : iDoubleValue = tvb_get_ntohieee_double ( tvb , iValueOffset ) ;
 proto_tree_add_double ( val_tree , hf_amf_number , tvb , iValueOffset , 8 , iDoubleValue ) ;
 iValueOffset += 8 ;
 proto_item_append_text ( ti , " %." G_STRINGIFY ( DBL_DIG ) "g" , iDoubleValue ) ;
 if ( parent_ti != NULL ) proto_item_append_text ( parent_ti , " %." G_STRINGIFY ( DBL_DIG ) "g" , iDoubleValue ) ;
 break ;
 case AMF0_BOOLEAN : iBooleanValue = tvb_get_guint8 ( tvb , iValueOffset ) ;
 proto_tree_add_boolean ( val_tree , hf_amf_boolean , tvb , iValueOffset , 1 , iBooleanValue ) ;
 iValueOffset += 1 ;
 proto_item_append_text ( ti , iBooleanValue ? " true" : " false" ) ;
 if ( parent_ti != NULL ) proto_item_append_text ( parent_ti , iBooleanValue ? " true" : " false" ) ;
 break ;
 case AMF0_STRING : iStringLength = tvb_get_ntohs ( tvb , iValueOffset ) ;
 proto_tree_add_uint ( val_tree , hf_amf_stringlength , tvb , iValueOffset , 2 , iStringLength ) ;
 iValueOffset += 2 ;
 iStringValue = tvb_get_string_enc ( wmem_packet_scope ( ) , tvb , iValueOffset , iStringLength , ENC_UTF_8 | ENC_NA ) ;
 if ( iStringLength != 0 ) proto_tree_add_string ( val_tree , hf_amf_string , tvb , iValueOffset , iStringLength , iStringValue ) ;
 iValueOffset += iStringLength ;
 proto_item_append_text ( ti , " '%s'" , iStringValue ) ;
 if ( parent_ti != NULL ) proto_item_append_text ( parent_ti , " '%s'" , iStringValue ) ;
 break ;
 case AMF0_OBJECT : iValueOffset = dissect_amf0_property_list ( tvb , iValueOffset , val_tree , & count , amf3_encoding ) ;
 proto_item_append_text ( ti , " (%u items)" , count ) ;
 break ;
 case AMF0_NULL : case AMF0_UNDEFINED : break ;
 case AMF0_REFERENCE : iIntegerValue = tvb_get_ntohs ( tvb , iValueOffset ) ;
 proto_tree_add_uint ( val_tree , hf_amf_object_reference , tvb , iValueOffset , 2 , iIntegerValue ) ;
 iValueOffset += 2 ;
 proto_item_append_text ( ti , " %d" , iIntegerValue ) ;
 break ;
 case AMF0_ECMA_ARRAY : iArrayLength = tvb_get_ntohl ( tvb , iValueOffset ) ;
 proto_tree_add_uint ( val_tree , hf_amf_arraylength , tvb , iValueOffset , 4 , iArrayLength ) ;
 iValueOffset += 4 ;
 iValueOffset = dissect_amf0_property_list ( tvb , iValueOffset , val_tree , & count , amf3_encoding ) ;
 proto_item_append_text ( ti , " (%u items)" , count ) ;
 break ;
 case AMF0_END_OF_OBJECT : proto_tree_add_item ( tree , hf_amf_end_of_object_marker , tvb , iValueOffset , 3 , ENC_NA ) ;
 iValueOffset += 3 ;
 break ;
 case AMF0_STRICT_ARRAY : iArrayLength = tvb_get_ntohl ( tvb , iValueOffset ) ;
 proto_tree_add_uint ( val_tree , hf_amf_arraylength , tvb , iValueOffset , 4 , iArrayLength ) ;
 iValueOffset += 4 ;
 for ( i = 0 ;
 i < iArrayLength ;
 i ++ ) iValueOffset = dissect_amf0_value_type ( tvb , iValueOffset , val_tree , amf3_encoding , NULL ) ;
 proto_item_append_text ( ti , " (%u items)" , iArrayLength ) ;
 break ;
 case AMF0_DATE : iDoubleValue = tvb_get_ntohieee_double ( tvb , iValueOffset ) ;
 t . secs = ( time_t ) ( iDoubleValue / 1000 ) ;
 t . nsecs = ( int ) ( ( iDoubleValue - 1000 * ( double ) t . secs ) * 1000000 ) ;
 proto_tree_add_time ( val_tree , hf_amf_date , tvb , iValueOffset , 8 , & t ) ;
 iValueOffset += 8 ;
 proto_item_append_text ( ti , " %s" , abs_time_to_str ( wmem_packet_scope ( ) , & t , ABSOLUTE_TIME_LOCAL , TRUE ) ) ;
 if ( parent_ti != NULL ) proto_item_append_text ( parent_ti , " %s" , abs_time_to_str ( wmem_packet_scope ( ) , & t , ABSOLUTE_TIME_LOCAL , TRUE ) ) ;
 iValueOffset += 2 ;
 break ;
 case AMF0_LONG_STRING : case AMF0_XML : iStringLength = tvb_get_ntohl ( tvb , iValueOffset ) ;
 proto_tree_add_uint ( val_tree , hf_amf_stringlength , tvb , iValueOffset , 2 , iStringLength ) ;
 iValueOffset += 4 ;
 iStringValue = tvb_get_string_enc ( wmem_packet_scope ( ) , tvb , iValueOffset , iStringLength , ENC_UTF_8 | ENC_NA ) ;
 if ( iStringLength != 0 ) proto_tree_add_string ( val_tree , ( iObjType == AMF0_XML ) ? hf_amf_xml_doc : hf_amf_longstring , tvb , iValueOffset , iStringLength , iStringValue ) ;
 iValueOffset += iStringLength ;
 proto_item_append_text ( ti , " '%s'" , iStringValue ) ;
 if ( parent_ti != NULL ) proto_item_append_text ( parent_ti , " '%s'" , iStringValue ) ;
 break ;
 case AMF0_UNSUPPORTED : break ;
 case AMF0_TYPED_OBJECT : iStringLength = tvb_get_ntohs ( tvb , iValueOffset ) ;
 proto_tree_add_uint ( val_tree , hf_amf_stringlength , tvb , iValueOffset , 2 , iStringLength ) ;
 iValueOffset += 2 ;
 iStringValue = tvb_get_string_enc ( wmem_packet_scope ( ) , tvb , iValueOffset , iStringLength , ENC_UTF_8 | ENC_NA ) ;
 proto_tree_add_string ( val_tree , hf_amf_string , tvb , iValueOffset , iStringLength , iStringValue ) ;
 iValueOffset += iStringLength ;
 iValueOffset = dissect_amf0_property_list ( tvb , iValueOffset , val_tree , & count , amf3_encoding ) ;
 break ;
 case AMF0_AMF3_MARKER : * amf3_encoding = TRUE ;
 break ;
 case AMF0_INT64 : iInteger64Value = tvb_get_ntoh64 ( tvb , iValueOffset ) ;
 proto_tree_add_int64 ( val_tree , hf_amf_int64 , tvb , iValueOffset , 8 , iInteger64Value ) ;
 iValueOffset += 8 ;
 proto_item_append_text ( ti , " %" G_GINT64_MODIFIER "d" , iInteger64Value ) ;
 if ( parent_ti != NULL ) proto_item_append_text ( parent_ti , " %" G_GINT64_MODIFIER "d" , iInteger64Value ) ;
 break ;
 default : iValueOffset = tvb_reported_length ( tvb ) ;
 break ;
 }
 proto_item_set_end ( ti , tvb , iValueOffset ) ;
 return iValueOffset ;
 }


    void finishCurrentOverlapTestingContext()
    {
        m_overlapStack[m_overlapStack.size() - 2].unite(m_overlapStack.last());
        m_overlapStack.removeLast();
    }


static BOOL update_send_cache_bitmap_v2(rdpContext* context,
                                        CACHE_BITMAP_V2_ORDER* cache_bitmap_v2)
{
	wStream* s;
	size_t bm, em;
	BYTE orderType;
	int headerLength;
	UINT16 extraFlags;
	INT16 orderLength;
	rdpUpdate* update = context->update;
	extraFlags = 0;
	headerLength = 6;
	orderType = cache_bitmap_v2->compressed ?
	            ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2;

	if (context->settings->NoBitmapCompressionHeader)
		cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR;

	update_check_flush(context,
	                   headerLength + update_approximate_cache_bitmap_v2_order(cache_bitmap_v2,
	                           cache_bitmap_v2->compressed, &extraFlags));
	s = update->us;

	if (!s)
		return FALSE;

	bm = Stream_GetPosition(s);

	if (!Stream_EnsureRemainingCapacity(s, headerLength))
		return FALSE;

	Stream_Seek(s, headerLength);

	if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2,
	                                        cache_bitmap_v2->compressed, &extraFlags))
		return FALSE;

	em = Stream_GetPosition(s);
	orderLength = (em - bm) - 13;
	Stream_SetPosition(s, bm);
	Stream_Write_UINT8(s, ORDER_STANDARD |
	                   ORDER_SECONDARY); /* controlFlags (1 byte) */
	Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */
	Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */
	Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */
	Stream_SetPosition(s, em);
	update->numberOrders++;
	return TRUE;
}


void RTCVoidRequestImpl::requestFailed(const String& error)
{
    if (m_errorCallback.get())
        m_errorCallback->handleEvent(error);

    clear();
}


void V8TestObject::VoidMethodUnsignedShortArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
  RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_voidMethodUnsignedShortArg");

  test_object_v8_internal::VoidMethodUnsignedShortArgMethod(info);
}


u32 gf_isom_get_track_flags(GF_ISOFile *the_file, u32 trackNumber)
{
	GF_TrackBox *trak;
	trak = gf_isom_get_track_from_file(the_file, trackNumber);
	if (!trak) return 0;
	return trak->Header->flags;
}


void RenderFrameHostImpl::InsertVisualStateCallback(
    const VisualStateCallback& callback) {
  static uint64_t next_id = 1;
  uint64_t key = next_id++;
  Send(new FrameMsg_VisualStateRequest(routing_id_, key));
  visual_state_callbacks_.insert(std::make_pair(key, callback));
}


vrrp_bfd_thread(thread_t * thread)
{
	bfd_event_t evt;

	bfd_thread = thread_add_read(master, vrrp_bfd_thread, NULL,
				     thread->u.fd, TIMER_NEVER);

	if (thread->type != THREAD_READY_FD)
		return 0;

	while (read(thread->u.fd, &evt, sizeof(bfd_event_t)) != -1)
		vrrp_handle_bfd_event(&evt);

	return 0;
}


void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset) {
	bloc = *offset;
	while (node && node->symbol == INTERNAL_NODE) {
		if (get_bit(fin)) {
			node = node->right;
		} else {
			node = node->left;
		}
	}
	if (!node) {
		*ch = 0;
		return;
//		Com_Error(ERR_DROP, "Illegal tree!");
	}
	*ch = node->symbol;
	*offset = bloc;
}


static int i40e_get_phys_port_id(struct net_device *netdev,
				 struct netdev_phys_item_id *ppid)
{
	struct i40e_netdev_priv *np = netdev_priv(netdev);
	struct i40e_pf *pf = np->vsi->back;
	struct i40e_hw *hw = &pf->hw;

	if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
		return -EOPNOTSUPP;

	ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
	memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);

	return 0;
}


queued_state_to_string (NMDeviceState state)
{
	if ((gsize) state < G_N_ELEMENTS (state_table))
		return state_table[state];
	return state_table[NM_DEVICE_STATE_UNKNOWN];
}


static AsfStream * gst_asf_demux_parse_stream_object ( GstASFDemux * demux , guint8 * data , guint64 size ) {
 AsfCorrectionType correction_type ;
 AsfStreamType stream_type ;
 GstClockTime time_offset ;
 gboolean is_encrypted G_GNUC_UNUSED ;
 guint16 stream_id ;
 guint16 flags ;
 ASFGuid guid ;
 guint stream_specific_size ;
 guint type_specific_size G_GNUC_UNUSED ;
 guint unknown G_GNUC_UNUSED ;
 gboolean inspect_payload = FALSE ;
 AsfStream * stream = NULL ;
 if ( size < ( 16 + 16 + 8 + 4 + 4 + 2 + 4 ) ) goto not_enough_data ;
 gst_asf_demux_get_guid ( & guid , & data , & size ) ;
 stream_type = gst_asf_demux_identify_guid ( asf_stream_guids , & guid ) ;
 gst_asf_demux_get_guid ( & guid , & data , & size ) ;
 correction_type = gst_asf_demux_identify_guid ( asf_correction_guids , & guid ) ;
 time_offset = gst_asf_demux_get_uint64 ( & data , & size ) * 100 ;
 type_specific_size = gst_asf_demux_get_uint32 ( & data , & size ) ;
 stream_specific_size = gst_asf_demux_get_uint32 ( & data , & size ) ;
 flags = gst_asf_demux_get_uint16 ( & data , & size ) ;
 stream_id = flags & 0x7f ;
 is_encrypted = ! ! ( ( flags & 0x8000 ) << 15 ) ;
 unknown = gst_asf_demux_get_uint32 ( & data , & size ) ;
 GST_DEBUG_OBJECT ( demux , "Found stream %u, time_offset=%" GST_TIME_FORMAT , stream_id , GST_TIME_ARGS ( time_offset ) ) ;
 if ( stream_type == ASF_STREAM_EXT_EMBED_HEADER ) {
 AsfExtStreamType ext_stream_type ;
 gst_asf_demux_get_guid ( & guid , & data , & size ) ;
 ext_stream_type = gst_asf_demux_identify_guid ( asf_ext_stream_guids , & guid ) ;
 if ( ext_stream_type == ASF_EXT_STREAM_AUDIO ) {
 inspect_payload = TRUE ;
 gst_asf_demux_get_guid ( & guid , & data , & size ) ;
 gst_asf_demux_get_uint32 ( & data , & size ) ;
 gst_asf_demux_get_uint32 ( & data , & size ) ;
 gst_asf_demux_get_uint32 ( & data , & size ) ;
 gst_asf_demux_get_guid ( & guid , & data , & size ) ;
 gst_asf_demux_get_uint32 ( & data , & size ) ;
 stream_type = ASF_STREAM_AUDIO ;
 }
 }
 switch ( stream_type ) {
 case ASF_STREAM_AUDIO : {
 asf_stream_audio audio_object ;
 if ( ! gst_asf_demux_get_stream_audio ( & audio_object , & data , & size ) ) goto not_enough_data ;
 GST_INFO ( "Object is an audio stream with %u bytes of additional data" , audio_object . size ) ;
 stream = gst_asf_demux_add_audio_stream ( demux , & audio_object , stream_id , & data , & size ) ;
 switch ( correction_type ) {
 case ASF_CORRECTION_ON : {
 guint span , packet_size , chunk_size , data_size , silence_data ;
 GST_INFO ( "Using error correction" ) ;
 if ( size < ( 1 + 2 + 2 + 2 + 1 ) ) goto not_enough_data ;
 span = gst_asf_demux_get_uint8 ( & data , & size ) ;
 packet_size = gst_asf_demux_get_uint16 ( & data , & size ) ;
 chunk_size = gst_asf_demux_get_uint16 ( & data , & size ) ;
 data_size = gst_asf_demux_get_uint16 ( & data , & size ) ;
 silence_data = gst_asf_demux_get_uint8 ( & data , & size ) ;
 stream -> span = span ;
 GST_DEBUG_OBJECT ( demux , "Descrambling ps:%u cs:%u ds:%u s:%u sd:%u" , packet_size , chunk_size , data_size , span , silence_data ) ;
 if ( stream -> span > 1 ) {
 if ( chunk_size == 0 || ( ( packet_size / chunk_size ) <= 1 ) ) {
 stream -> span = 0 ;
 }
 else {
 stream -> ds_packet_size = packet_size ;
 stream -> ds_chunk_size = chunk_size ;
 }
 }
 else {
 stream -> ds_packet_size = packet_size ;
 stream -> ds_chunk_size = chunk_size ;
 }
 # if 0 if ( data_size > 1 ) gst_bytestream_flush ( demux -> bs , data_size - 1 ) ;
 # else if ( data_size > 1 ) {
 if ( ! gst_asf_demux_skip_bytes ( data_size - 1 , & data , & size ) ) {
 goto not_enough_data ;
 }
 }
 # endif break ;
 }
 case ASF_CORRECTION_OFF : {
 GST_INFO ( "Error correction off" ) ;
 if ( ! gst_asf_demux_skip_bytes ( stream_specific_size , & data , & size ) ) goto not_enough_data ;
 break ;
 }
 default : GST_ELEMENT_ERROR ( demux , STREAM , DEMUX , ( NULL ) , ( "Audio stream using unknown error correction" ) ) ;
 return NULL ;
 }
 break ;
 }
 case ASF_STREAM_VIDEO : {
 asf_stream_video_format video_format_object ;
 asf_stream_video video_object ;
 guint16 vsize ;
 if ( ! gst_asf_demux_get_stream_video ( & video_object , & data , & size ) ) goto not_enough_data ;
 vsize = video_object . size - 40 ;
 GST_INFO ( "object is a video stream with %u bytes of " "additional data" , vsize ) ;
 if ( ! gst_asf_demux_get_stream_video_format ( & video_format_object , & data , & size ) ) {
 goto not_enough_data ;
 }
 stream = gst_asf_demux_add_video_stream ( demux , & video_format_object , stream_id , & data , & size ) ;
 break ;
 }
 default : GST_WARNING_OBJECT ( demux , "Unknown stream type for stream %u" , stream_id ) ;
 demux -> other_streams = g_slist_append ( demux -> other_streams , GINT_TO_POINTER ( stream_id ) ) ;
 break ;
 }
 if ( stream ) stream -> inspect_payload = inspect_payload ;
 return stream ;
 not_enough_data : {
 GST_WARNING_OBJECT ( demux , "Unexpected end of data parsing stream object" ) ;
 return NULL ;
 }
 }


srcip_matches(struct sockaddr *srcaddr, struct sockaddr *rhs)
{
	switch (srcaddr->sa_family) {
	case AF_UNSPEC:
		return (rhs->sa_family == AF_UNSPEC);
	case AF_INET: {
		struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
		struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
		return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
	}
	case AF_INET6: {
		struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
		struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)&rhs;
		return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
	}
	default:
		WARN_ON(1);
		return false; /* don't expect to be here */
	}
}


static void jpc_com_destroyparms(jpc_ms_t *ms)
{
	jpc_com_t *com = &ms->parms.com;
	if (com->data) {
		jas_free(com->data);
	}
}


inline strhash_t StringData::hash(const char* s, size_t len) {
  return hash_string_i(s, len);
}