static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPCXException(severity,tag) \
{ \
  if (scanline != (unsigned char *) NULL) \
    scanline=(unsigned char *) RelinquishMagickMemory(scanline); \
  if (pixel_info != (MemoryInfo *) NULL) \
    pixel_info=RelinquishVirtualMemory(pixel_info); \
  if (page_table != (MagickOffsetType *) NULL) \
    page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); \
  ThrowReaderException(severity,tag); \
}

  Image
    *image;

  int
    bits,
    id,
    mask;

  MagickBooleanType
    status;

  MagickOffsetType
    offset,
    *page_table;

  MemoryInfo
    *pixel_info;

  PCXInfo
    pcx_info;

  register IndexPacket
    *indexes;

  register ssize_t
    x;

  register PixelPacket
    *q;

  register ssize_t
    i;

  register unsigned char
    *p,
    *r;

  size_t
    one,
    pcx_packets;

  ssize_t
    count,
    y;

  unsigned char
    packet,
    pcx_colormap[768],
    *pixels,
    *scanline;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Determine if this a PCX file.
  */
  page_table=(MagickOffsetType *) NULL;
  scanline=(unsigned char *) NULL;
  pixel_info=(MemoryInfo *) NULL;
  if (LocaleCompare(image_info->magick,"DCX") == 0)
    {
      size_t
        magic;

      /*
        Read the DCX page table.
      */
      magic=ReadBlobLSBLong(image);
      if (magic != 987654321)
        ThrowPCXException(CorruptImageError,"ImproperImageHeader");
      page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
        sizeof(*page_table));
      if (page_table == (MagickOffsetType *) NULL)
        ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
      for (id=0; id < 1024; id++)
      {
        page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image);
        if (page_table[id] == 0)
          break;
      }
    }
  if (page_table != (MagickOffsetType *) NULL)
    {
      offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET);
      if (offset < 0)
        ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    }
  count=ReadBlob(image,1,&pcx_info.identifier);
  for (id=1; id < 1024; id++)
  {
    int
      bits_per_pixel;

    /*
      Verify PCX identifier.
    */
    pcx_info.version=(unsigned char) ReadBlobByte(image);
    if ((count != 1) || (pcx_info.identifier != 0x0a))
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    pcx_info.encoding=(unsigned char) ReadBlobByte(image);
    bits_per_pixel=ReadBlobByte(image);
    if (bits_per_pixel == -1)
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel;
    pcx_info.left=ReadBlobLSBShort(image);
    pcx_info.top=ReadBlobLSBShort(image);
    pcx_info.right=ReadBlobLSBShort(image);
    pcx_info.bottom=ReadBlobLSBShort(image);
    pcx_info.horizontal_resolution=ReadBlobLSBShort(image);
    pcx_info.vertical_resolution=ReadBlobLSBShort(image);
    /*
      Read PCX raster colormap.
    */
    image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right-
      pcx_info.left)+1UL;
    image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom-
      pcx_info.top)+1UL;
    if ((image->columns == 0) || (image->rows == 0) ||
        ((pcx_info.bits_per_pixel != 1) && (pcx_info.bits_per_pixel != 2) &&
         (pcx_info.bits_per_pixel != 4) && (pcx_info.bits_per_pixel != 8)))
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    image->depth=pcx_info.bits_per_pixel;
    image->units=PixelsPerInchResolution;
    image->x_resolution=(double) pcx_info.horizontal_resolution;
    image->y_resolution=(double) pcx_info.vertical_resolution;
    image->colors=16;
    if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
      if (image->scene >= (image_info->scene+image_info->number_scenes-1))
        break;
    status=SetImageExtent(image,image->columns,image->rows);
    if (status == MagickFalse)
      ThrowPCXException(image->exception.severity,image->exception.reason);
    (void) SetImageBackgroundColor(image);
    (void) memset(pcx_colormap,0,sizeof(pcx_colormap));
    count=ReadBlob(image,3*image->colors,pcx_colormap);
    if (count != (ssize_t) (3*image->colors))
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    pcx_info.reserved=(unsigned char) ReadBlobByte(image);
    pcx_info.planes=(unsigned char) ReadBlobByte(image);
    if (pcx_info.planes > 6)
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64)
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    if (pcx_info.planes == 0)
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    one=1;
    if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1))
      if ((pcx_info.version == 3) || (pcx_info.version == 5) ||
          ((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
        image->colors=(size_t) MagickMin(one << (1UL*
          (pcx_info.bits_per_pixel*pcx_info.planes)),256UL);
    if (AcquireImageColormap(image,image->colors) == MagickFalse)
      ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
    if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1))
      image->storage_class=DirectClass;
    p=pcx_colormap;
    for (i=0; i < (ssize_t) image->colors; i++)
    {
      image->colormap[i].red=ScaleCharToQuantum(*p++);
      image->colormap[i].green=ScaleCharToQuantum(*p++);
      image->colormap[i].blue=ScaleCharToQuantum(*p++);
    }
    pcx_info.bytes_per_line=ReadBlobLSBShort(image);
    pcx_info.palette_info=ReadBlobLSBShort(image);
    pcx_info.horizontal_screensize=ReadBlobLSBShort(image);
    pcx_info.vertical_screensize=ReadBlobLSBShort(image);
    for (i=0; i < 54; i++)
      (void) ReadBlobByte(image);
    /*
      Read image data.
    */
    if (HeapOverflowSanityCheck(image->rows, (size_t) pcx_info.bytes_per_line) != MagickFalse)
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line;
    if (HeapOverflowSanityCheck(pcx_packets, (size_t) pcx_info.planes) != MagickFalse)
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    pcx_packets=(size_t) pcx_packets*pcx_info.planes;
    if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) >
        (pcx_packets*8U))
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    if ((MagickSizeType) (pcx_packets/8) > GetBlobSize(image))
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns,
      pcx_info.bytes_per_line),MagickMax(pcx_info.planes,8)*sizeof(*scanline));
    pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels));
    if ((scanline == (unsigned char *) NULL) ||
        (pixel_info == (MemoryInfo *) NULL))
      {
        if (scanline != (unsigned char *) NULL)
          scanline=(unsigned char *) RelinquishMagickMemory(scanline);
        if (pixel_info != (MemoryInfo *) NULL)
          pixel_info=RelinquishVirtualMemory(pixel_info);
        ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
      }
    (void) memset(scanline,0,(size_t) MagickMax(image->columns,
      pcx_info.bytes_per_line)*MagickMax(pcx_info.planes,8)*sizeof(*scanline));
    pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
    (void) memset(pixels,0,(size_t) pcx_packets*(2*sizeof(*pixels)));
    /*
      Uncompress image data.
    */
    p=pixels;
    if (pcx_info.encoding == 0)
      while (pcx_packets != 0)
      {
        packet=(unsigned char) ReadBlobByte(image);
        if (EOFBlob(image) != MagickFalse)
          ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
        *p++=packet;
        pcx_packets--;
      }
    else
      while (pcx_packets != 0)
      {
        packet=(unsigned char) ReadBlobByte(image);
        if (EOFBlob(image) != MagickFalse)
          ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
        if ((packet & 0xc0) != 0xc0)
          {
            *p++=packet;
            pcx_packets--;
            continue;
          }
        count=(ssize_t) (packet & 0x3f);
        packet=(unsigned char) ReadBlobByte(image);
        if (EOFBlob(image) != MagickFalse)
          ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
        for ( ; count != 0; count--)
        {
          *p++=packet;
          pcx_packets--;
          if (pcx_packets == 0)
            break;
        }
      }
    if (image->storage_class == DirectClass)
      image->matte=pcx_info.planes > 3 ? MagickTrue : MagickFalse;
    else
      if ((pcx_info.version == 5) ||
          ((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
        {
          /*
            Initialize image colormap.
          */
          if (image->colors > 256)
            ThrowPCXException(CorruptImageError,"ColormapExceeds256Colors");
          if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)
            {
              /*
                Monochrome colormap.
              */
              image->colormap[0].red=(Quantum) 0;
              image->colormap[0].green=(Quantum) 0;
              image->colormap[0].blue=(Quantum) 0;
              image->colormap[1].red=QuantumRange;
              image->colormap[1].green=QuantumRange;
              image->colormap[1].blue=QuantumRange;
            }
          else
            if (image->colors > 16)
              {
                /*
                  256 color images have their color map at the end of the file.
                */
                pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image);
                count=ReadBlob(image,3*image->colors,pcx_colormap);
                p=pcx_colormap;
                for (i=0; i < (ssize_t) image->colors; i++)
                {
                  image->colormap[i].red=ScaleCharToQuantum(*p++);
                  image->colormap[i].green=ScaleCharToQuantum(*p++);
                  image->colormap[i].blue=ScaleCharToQuantum(*p++);
                }
            }
        }
    /*
      Convert PCX raster image to pixel packets.
    */
    for (y=0; y < (ssize_t) image->rows; y++)
    {
      p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes);
      q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
      if (q == (PixelPacket *) NULL)
        break;
      indexes=GetAuthenticIndexQueue(image);
      r=scanline;
      if (image->storage_class == DirectClass)
        for (i=0; i < pcx_info.planes; i++)
        {
          r=scanline+i;
          for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
          {
            switch (i)
            {
              case 0:
              {
                *r=(*p++);
                break;
              }
              case 1:
              {
                *r=(*p++);
                break;
              }
              case 2:
              {
                *r=(*p++);
                break;
              }
              case 3:
              default:
              {
                *r=(*p++);
                break;
              }
            }
            r+=pcx_info.planes;
          }
        }
      else
        if (pcx_info.planes > 1)
          {
            for (x=0; x < (ssize_t) image->columns; x++)
              *r++=0;
            for (i=0; i < pcx_info.planes; i++)
            {
              r=scanline;
              for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
              {
                 bits=(*p++);
                 for (mask=0x80; mask != 0; mask>>=1)
                 {
                   if (bits & mask)
                     *r|=1 << i;
                   r++;
                 }
               }
            }
          }
        else
          switch (pcx_info.bits_per_pixel)
          {
            case 1:
            {
              register ssize_t
                bit;

              for (x=0; x < ((ssize_t) image->columns-7); x+=8)
              {
                for (bit=7; bit >= 0; bit--)
                  *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
                p++;
              }
              if ((image->columns % 8) != 0)
                {
                  for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--)
                    *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
                  p++;
                }
              break;
            }
            case 2:
            {
              for (x=0; x < ((ssize_t) image->columns-3); x+=4)
              {
                *r++=(*p >> 6) & 0x3;
                *r++=(*p >> 4) & 0x3;
                *r++=(*p >> 2) & 0x3;
                *r++=(*p) & 0x3;
                p++;
              }
              if ((image->columns % 4) != 0)
                {
                  for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--)
                    *r++=(unsigned char) ((*p >> (i*2)) & 0x03);
                  p++;
                }
              break;
            }
            case 4:
            {
              for (x=0; x < ((ssize_t) image->columns-1); x+=2)
              {
                *r++=(*p >> 4) & 0xf;
                *r++=(*p) & 0xf;
                p++;
              }
              if ((image->columns % 2) != 0)
                *r++=(*p++ >> 4) & 0xf;
              break;
            }
            case 8:
            {
              (void) memcpy(r,p,image->columns);
              break;
            }
            default:
              break;
          }
      /*
        Transfer image scanline.
      */
      r=scanline;
      for (x=0; x < (ssize_t) image->columns; x++)
      {
        if (image->storage_class == PseudoClass)
          SetPixelIndex(indexes+x,*r++);
        else
          {
            SetPixelRed(q,ScaleCharToQuantum(*r++));
            SetPixelGreen(q,ScaleCharToQuantum(*r++));
            SetPixelBlue(q,ScaleCharToQuantum(*r++));
            if (image->matte != MagickFalse)
              SetPixelAlpha(q,ScaleCharToQuantum(*r++));
          }
        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 (image->storage_class == PseudoClass)
      (void) SyncImage(image);
    scanline=(unsigned char *) RelinquishMagickMemory(scanline);
    pixel_info=RelinquishVirtualMemory(pixel_info);
    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 (page_table == (MagickOffsetType *) NULL)
      break;
    if (page_table[id] == 0)
      break;
    offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET);
    if (offset < 0)
      ThrowPCXException(CorruptImageError,"ImproperImageHeader");
    count=ReadBlob(image,1,&pcx_info.identifier);
    if ((count != 0) && (pcx_info.identifier == 0x0a))
      {
        /*
          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;
      }
  }
  if (page_table != (MagickOffsetType *) NULL)
    page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
  (void) CloseBlob(image);
  return(GetFirstImageInList(image));
}


static void vmsvga_init(struct vmsvga_state_s *s, MemoryRegion *address_space, MemoryRegion *io) { s->scratch_size = SVGA_SCRATCH_SIZE; s->scratch = g_malloc(s->scratch_size * 4); s->vga.con = graphic_console_init(vmsvga_update_display, vmsvga_invalidate_display, vmsvga_screen_dump, vmsvga_text_update, s); s->fifo_size = SVGA_FIFO_SIZE; memory_region_init_ram(&s->fifo_ram, "vmsvga.fifo", s->fifo_size); vmstate_register_ram_global(&s->fifo_ram); s->fifo_ptr = memory_region_get_ram_ptr(&s->fifo_ram); vga_common_init(&s->vga); vga_init(&s->vga, address_space, io, true); vmstate_register(NULL, 0, &vmstate_vga_common, &s->vga); s->new_depth = 32; }


checked_xcalloc (size_t num, size_t size)
{
    alloc_limit_assert ("checked_xcalloc", (num *size));
    return xcalloc (num, size);
}


checked_xmalloc (size_t size)
{
    alloc_limit_assert ("checked_xmalloc", size);
    return xmalloc (size);
}


void ssi_register_slave(SSISlaveInfo *info) { assert(info->qdev.size >= sizeof(SSISlave)); info->qdev.init = ssi_slave_init; info->qdev.bus_type = BUS_TYPE_SSI; qdev_register(&info->qdev); }


xmalloc (size_t num, size_t size)
{
    size_t res;
    if (check_mul_overflow(num, size, &res))
        abort();

    void *ptr = malloc (res);
    if (!ptr
        && (size != 0))         /* some libc don't like size == 0 */
    {
        perror ("xmalloc: Memory allocation failure");
        abort();
    }
    return ptr;
}


static void arm_gic_realize(DeviceState *dev, Error **errp) { /* Device instance realize function for the GIC sysbus device */ GICv3State *s = ARM_GICV3(dev); ARMGICv3Class *agc = ARM_GICV3_GET_CLASS(s); Error *local_err = NULL; agc->parent_realize(dev, &local_err); if (local_err) { error_propagate(errp, local_err); return; } gicv3_init_irqs_and_mmio(s, gicv3_set_irq, NULL); }


static void build_append_notify_target(GArray *method, GArray *target_name, uint32_t value, int size) { GArray *notify = build_alloc_array(); uint8_t op = 0xA0; /* IfOp */ build_append_byte(notify, 0x93); /* LEqualOp */ build_append_byte(notify, 0x68); /* Arg0Op */ build_append_value(notify, value, size); build_append_byte(notify, 0x86); /* NotifyOp */ build_append_array(notify, target_name); build_append_byte(notify, 0x69); /* Arg1Op */ /* Pack it up */ build_package(notify, op, 1); build_append_array(method, notify); build_free_array(notify); }


static ram_addr_t qxl_rom_size(void) { uint32_t required_rom_size = sizeof(QXLRom) + sizeof(QXLModes) + sizeof(qxl_modes); uint32_t rom_size = 8192; /* two pages */ QEMU_BUILD_BUG_ON(required_rom_size > rom_size); return rom_size; }


static void ne2000_receive(void *opaque, const uint8_t *buf, size_t size) { NE2000State *s = opaque; uint8_t *p; unsigned int total_len, next, avail, len, index, mcast_idx; uint8_t buf1[60]; static const uint8_t broadcast_macaddr[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; #if defined(DEBUG_NE2000) printf("NE2000: received len=%d\n", size); #endif if (s->cmd & E8390_STOP || ne2000_buffer_full(s)) return; /* XXX: check this */ if (s->rxcr & 0x10) { /* promiscuous: receive all */ } else { if (!memcmp(buf, broadcast_macaddr, 6)) { /* broadcast address */ if (!(s->rxcr & 0x04)) return; } else if (buf[0] & 0x01) { /* multicast */ if (!(s->rxcr & 0x08)) return; mcast_idx = compute_mcast_idx(buf); if (!(s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7)))) return; } else if (s->mem[0] == buf[0] && s->mem[2] == buf[1] && s->mem[4] == buf[2] && s->mem[6] == buf[3] && s->mem[8] == buf[4] && s->mem[10] == buf[5]) { /* match */ } else { return; } } /* if too small buffer, then expand it */ if (size < MIN_BUF_SIZE) { memcpy(buf1, buf, size); memset(buf1 + size, 0, MIN_BUF_SIZE - size); buf = buf1; size = MIN_BUF_SIZE; } index = s->curpag << 8; /* 4 bytes for header */ total_len = size + 4; /* address for next packet (4 bytes for CRC) */ next = index + ((total_len + 4 + 255) & ~0xff); if (next >= s->stop) next -= (s->stop - s->start); /* prepare packet header */ p = s->mem + index; s->rsr = ENRSR_RXOK; /* receive status */ /* XXX: check this */ if (buf[0] & 0x01) s->rsr |= ENRSR_PHY; p[0] = s->rsr; p[1] = next >> 8; p[2] = total_len; p[3] = total_len >> 8; index += 4; /* write packet data */ while (size > 0) { if (index <= s->stop) avail = s->stop - index; else avail = 0; len = size; if (len > avail) len = avail; memcpy(s->mem + index, buf, len); buf += len; index += len; if (index == s->stop) index = s->start; size -= len; } s->curpag = next >> 8; /* now we can signal we have received something */ s->isr |= ENISR_RX; ne2000_update_irq(s); }


void free_G_buffers(__G)     /* releases all memory allocated in global vars */
    __GDEF
{
#ifndef SFX
    unsigned i;
#endif

#ifdef SYSTEM_SPECIFIC_DTOR
    SYSTEM_SPECIFIC_DTOR(__G);
#endif

    inflate_free(__G);
    checkdir(__G__ (char *)NULL, END);

#ifdef DYNALLOC_CRCTAB
    if (CRC_32_TAB) {
        free_crc_table();
        CRC_32_TAB = NULL;
    }
#endif

   if (G.key != (char *)NULL) {
        free(G.key);
        G.key = (char *)NULL;
   }

   if (G.extra_field != (uch *)NULL) {
        free(G.extra_field);
        G.extra_field = (uch *)NULL;
   }

#if (!defined(VMS) && !defined(SMALL_MEM))
    /* VMS uses its own buffer scheme for textmode flush() */
    if (G.outbuf2) {
        free(G.outbuf2);   /* malloc'd ONLY if unshrink and -a */
        G.outbuf2 = (uch *)NULL;
    }
#endif

    if (G.outbuf)
        free(G.outbuf);
    if (G.inbuf)
        free(G.inbuf);
    G.inbuf = G.outbuf = (uch *)NULL;

#ifdef UNICODE_SUPPORT
    if (G.filename_full) {
        free(G.filename_full);
        G.filename_full = (char *)NULL;
        G.fnfull_bufsize = 0;
    }
#endif /* UNICODE_SUPPORT */

#ifndef SFX
    for (i = 0; i < DIR_BLKSIZ; i++) {
        if (G.info[i].cfilname != (char Far *)NULL) {
            zffree(G.info[i].cfilname);
            G.info[i].cfilname = (char Far *)NULL;
        }
    }
#endif

#ifdef MALLOC_WORK
    if (G.area.Slide) {
        free(G.area.Slide);
        G.area.Slide = (uch *)NULL;
    }
#endif

} /* end function free_G_buffers() */


int kvm_init(void) { static const char upgrade_note[] = "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n" "(see http://sourceforge.net/projects/kvm).\n"; KVMState *s; const KVMCapabilityInfo *missing_cap; int ret; int i; int max_vcpus; s = g_malloc0(sizeof(KVMState)); /* * On systems where the kernel can support different base page * sizes, host page size may be different from TARGET_PAGE_SIZE, * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum * page size for the system though. */ assert(TARGET_PAGE_SIZE <= getpagesize()); #ifdef KVM_CAP_SET_GUEST_DEBUG QTAILQ_INIT(&s->kvm_sw_breakpoints); #endif for (i = 0; i < ARRAY_SIZE(s->slots); i++) { s->slots[i].slot = i; } s->vmfd = -1; s->fd = qemu_open("/dev/kvm", O_RDWR); if (s->fd == -1) { fprintf(stderr, "Could not access KVM kernel module: %m\n"); ret = -errno; goto err; } ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0); if (ret < KVM_API_VERSION) { if (ret > 0) { ret = -EINVAL; } fprintf(stderr, "kvm version too old\n"); goto err; } if (ret > KVM_API_VERSION) { ret = -EINVAL; fprintf(stderr, "kvm version not supported\n"); goto err; } max_vcpus = kvm_max_vcpus(s); if (smp_cpus > max_vcpus) { ret = -EINVAL; fprintf(stderr, "Number of SMP cpus requested (%d) exceeds max cpus " "supported by KVM (%d)\n", smp_cpus, max_vcpus); goto err; } if (max_cpus > max_vcpus) { ret = -EINVAL; fprintf(stderr, "Number of hotpluggable cpus requested (%d) exceeds max cpus " "supported by KVM (%d)\n", max_cpus, max_vcpus); goto err; } s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0); if (s->vmfd < 0) { #ifdef TARGET_S390X fprintf(stderr, "Please add the 'switch_amode' kernel parameter to " "your host kernel command line\n"); #endif ret = s->vmfd; goto err; } missing_cap = kvm_check_extension_list(s, kvm_required_capabilites); if (!missing_cap) { missing_cap = kvm_check_extension_list(s, kvm_arch_required_capabilities); } if (missing_cap) { ret = -EINVAL; fprintf(stderr, "kvm does not support %s\n%s", missing_cap->name, upgrade_note); goto err; } s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO); s->broken_set_mem_region = 1; ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS); if (ret > 0) { s->broken_set_mem_region = 0; } #ifdef KVM_CAP_VCPU_EVENTS s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS); #endif s->robust_singlestep = kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP); #ifdef KVM_CAP_DEBUGREGS s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS); #endif #ifdef KVM_CAP_XSAVE s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE); #endif #ifdef KVM_CAP_XCRS s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS); #endif #ifdef KVM_CAP_PIT_STATE2 s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2); #endif #ifdef KVM_CAP_IRQ_ROUTING s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0); #endif s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3); s->irq_set_ioctl = KVM_IRQ_LINE; if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) { s->irq_set_ioctl = KVM_IRQ_LINE_STATUS; } #ifdef KVM_CAP_READONLY_MEM kvm_readonly_mem_allowed = (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0); #endif ret = kvm_arch_init(s); if (ret < 0) { goto err; } ret = kvm_irqchip_create(s); if (ret < 0) { goto err; } kvm_state = s; memory_listener_register(&kvm_memory_listener, &address_space_memory); memory_listener_register(&kvm_io_listener, &address_space_io); s->many_ioeventfds = kvm_check_many_ioeventfds(); cpu_interrupt_handler = kvm_handle_interrupt; return 0; err: if (s->vmfd >= 0) { close(s->vmfd); } if (s->fd != -1) { close(s->fd); } g_free(s); return ret; }


static int libopenjpeg_decode_frame ( AVCodecContext * avctx , void * data , int * got_frame , AVPacket * avpkt ) {
 uint8_t * buf = avpkt -> data ;
 int buf_size = avpkt -> size ;
 LibOpenJPEGContext * ctx = avctx -> priv_data ;
 AVFrame * picture = & ctx -> image , * output = data ;
 const AVPixFmtDescriptor * desc ;
 opj_dinfo_t * dec ;
 opj_cio_t * stream ;
 opj_image_t * image ;
 int width , height , ret = - 1 ;
 int pixel_size = 0 ;
 int ispacked = 0 ;
 int i ;
 * got_frame = 0 ;
 if ( ( AV_RB32 ( buf ) == 12 ) && ( AV_RB32 ( buf + 4 ) == JP2_SIG_TYPE ) && ( AV_RB32 ( buf + 8 ) == JP2_SIG_VALUE ) ) {
 dec = opj_create_decompress ( CODEC_JP2 ) ;
 }
 else {
 if ( AV_RB32 ( buf + 4 ) == AV_RB32 ( "jp2c" ) ) buf += 8 ;
 dec = opj_create_decompress ( CODEC_J2K ) ;
 }
 if ( ! dec ) {
 av_log ( avctx , AV_LOG_ERROR , "Error initializing decoder.\n" ) ;
 return - 1 ;
 }
 opj_set_event_mgr ( ( opj_common_ptr ) dec , NULL , NULL ) ;
 ctx -> dec_params . cp_limit_decoding = LIMIT_TO_MAIN_HEADER ;
 ctx -> dec_params . cp_reduce = ctx -> lowres ;
 ctx -> dec_params . cp_layer = ctx -> lowqual ;
 opj_setup_decoder ( dec , & ctx -> dec_params ) ;
 stream = opj_cio_open ( ( opj_common_ptr ) dec , buf , buf_size ) ;
 if ( ! stream ) {
 av_log ( avctx , AV_LOG_ERROR , "Codestream could not be opened for reading.\n" ) ;
 opj_destroy_decompress ( dec ) ;
 return - 1 ;
 }
 image = opj_decode_with_info ( dec , stream , NULL ) ;
 opj_cio_close ( stream ) ;
 if ( ! image ) {
 av_log ( avctx , AV_LOG_ERROR , "Error decoding codestream.\n" ) ;
 opj_destroy_decompress ( dec ) ;
 return - 1 ;
 }
 width = image -> x1 - image -> x0 ;
 height = image -> y1 - image -> y0 ;
 if ( ctx -> lowres ) {
 width = ( width + ( 1 << ctx -> lowres ) - 1 ) >> ctx -> lowres ;
 height = ( height + ( 1 << ctx -> lowres ) - 1 ) >> ctx -> lowres ;
 }
 if ( av_image_check_size ( width , height , 0 , avctx ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "%dx%d dimension invalid.\n" , width , height ) ;
 goto done ;
 }
 avcodec_set_dimensions ( avctx , width , height ) ;
 if ( avctx -> pix_fmt != AV_PIX_FMT_NONE ) if ( ! libopenjpeg_matches_pix_fmt ( image , avctx -> pix_fmt ) ) avctx -> pix_fmt = AV_PIX_FMT_NONE ;
 if ( avctx -> pix_fmt == AV_PIX_FMT_NONE ) avctx -> pix_fmt = libopenjpeg_guess_pix_fmt ( image ) ;
 if ( avctx -> pix_fmt == AV_PIX_FMT_NONE ) {
 av_log ( avctx , AV_LOG_ERROR , "Unable to determine pixel format\n" ) ;
 ret = AVERROR_INVALIDDATA ;
 goto done ;
 }
 for ( i = 0 ;
 i < image -> numcomps ;
 i ++ ) if ( image -> comps [ i ] . prec > avctx -> bits_per_raw_sample ) avctx -> bits_per_raw_sample = image -> comps [ i ] . prec ;
 if ( picture -> data [ 0 ] ) ff_thread_release_buffer ( avctx , picture ) ;
 if ( ff_thread_get_buffer ( avctx , picture ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "ff_thread_get_buffer() failed\n" ) ;
 goto done ;
 }
 ctx -> dec_params . cp_limit_decoding = NO_LIMITATION ;
 opj_setup_decoder ( dec , & ctx -> dec_params ) ;
 stream = opj_cio_open ( ( opj_common_ptr ) dec , buf , buf_size ) ;
 if ( ! stream ) {
 av_log ( avctx , AV_LOG_ERROR , "Codestream could not be opened for reading.\n" ) ;
 goto done ;
 }
 opj_image_destroy ( image ) ;
 image = opj_decode_with_info ( dec , stream , NULL ) ;
 opj_cio_close ( stream ) ;
 if ( ! image ) {
 av_log ( avctx , AV_LOG_ERROR , "Error decoding codestream.\n" ) ;
 goto done ;
 }
 desc = av_pix_fmt_desc_get ( avctx -> pix_fmt ) ;
 pixel_size = desc -> comp [ 0 ] . step_minus1 + 1 ;
 ispacked = libopenjpeg_ispacked ( avctx -> pix_fmt ) ;
 switch ( pixel_size ) {
 case 1 : if ( ispacked ) {
 libopenjpeg_copy_to_packed8 ( picture , image ) ;
 }
 else {
 libopenjpeg_copyto8 ( picture , image ) ;
 }
 break ;
 case 2 : if ( ispacked ) {
 libopenjpeg_copy_to_packed8 ( picture , image ) ;
 }
 else {
 libopenjpeg_copyto16 ( picture , image ) ;
 }
 break ;
 case 3 : case 4 : if ( ispacked ) {
 libopenjpeg_copy_to_packed8 ( picture , image ) ;
 }
 break ;
 case 6 : case 8 : if ( ispacked ) {
 libopenjpeg_copy_to_packed16 ( picture , image ) ;
 }
 break ;
 default : av_log ( avctx , AV_LOG_ERROR , "unsupported pixel size %d\n" , pixel_size ) ;
 goto done ;
 }
 * output = ctx -> image ;
 * got_frame = 1 ;
 ret = buf_size ;
 done : opj_image_destroy ( image ) ;
 opj_destroy_decompress ( dec ) ;
 return ret ;
 }


IN_PROC_BROWSER_TEST_F ( BluetoothChooserBrowserTest , InvokeDialog_ScanningBubble ) {
 set_status ( FakeBluetoothChooserController : : BluetoothStatus : : SCANNING ) ;
 RunDialog ( ) ;
 }


void tlb_fill(target_ulong addr, int is_write, int mmu_idx, void *retaddr) { tlb_set_page(cpu_single_env, addr & ~(TARGET_PAGE_SIZE - 1), addr & ~(TARGET_PAGE_SIZE - 1), PAGE_READ | PAGE_WRITE | PAGE_EXEC, mmu_idx, TARGET_PAGE_SIZE); }


R_API int r_socket_ready(RSocket *s, int secs, int usecs) {
#if __UNIX__
	//int msecs = (1000 * secs) + (usecs / 1000);
	int msecs = (usecs / 1000);
	struct pollfd fds[1];
	fds[0].fd = s->fd;
	fds[0].events = POLLIN | POLLPRI;
	fds[0].revents = POLLNVAL | POLLHUP | POLLERR;
	return poll ((struct pollfd *)&fds, 1, msecs);
#elif __WINDOWS__
	fd_set rfds;
	struct timeval tv;
	if (s->fd == R_INVALID_SOCKET) {
		return -1;
	}
	FD_ZERO (&rfds);
	FD_SET (s->fd, &rfds);
	tv.tv_sec = secs;
	tv.tv_usec = usecs;
	return select (s->fd + 1, &rfds, NULL, NULL, &tv);
#else
	return true; /* always ready if unknown */
#endif
}


R_API char *r_socket_http_get(const char *url, int *code, int *rlen) {
	char *curl_env = r_sys_getenv ("R2_CURL");
	if (curl_env && *curl_env) {
		char *encoded_url = r_str_escape (url);
		char *res = r_sys_cmd_strf ("curl '%s'", encoded_url);
		free (encoded_url);
		if (res) {
			if (code) {
				*code = 200;
			}
			if (rlen) {
				*rlen = strlen (res);
			}
		}
		free (curl_env);
		return res;
	}
	free (curl_env);
	RSocket *s;
	int ssl = r_str_startswith (url, "https://");
	char *response, *host, *path, *port = "80";
	char *uri = strdup (url);
	if (!uri) {
		return NULL;
	}

	if (code) {
		*code = 0;
	}
	if (rlen) {
		*rlen = 0;
	}
	host = strstr (uri, "://");
	if (!host) {
		free (uri);
		eprintf ("r_socket_http_get: Invalid URI");
		return NULL;
	}
	host += 3;
	port = strchr (host, ':');
	if (!port) {
		port = ssl? "443": "80";
		path = host;
	} else {
		*port++ = 0;
		path = port;
	}
	path = strchr (path, '/');
	if (!path) {
		path = "";
	} else {
		*path++ = 0;
	}
	s = r_socket_new (ssl);
	if (!s) {
		eprintf ("r_socket_http_get: Cannot create socket\n");
		free (uri);
		return NULL;
	}
	if (r_socket_connect_tcp (s, host, port, 0)) {
		r_socket_printf (s,
				"GET /%s HTTP/1.1\r\n"
				"User-Agent: radare2 "R2_VERSION"\r\n"
				"Accept: */*\r\n"
				"Host: %s:%s\r\n"
				"\r\n", path, host, port);
		response = r_socket_http_answer (s, code, rlen);
	} else {
		eprintf ("Cannot connect to %s:%s\n", host, port);
		response = NULL;
	}
	free (uri);
	r_socket_free (s);
	return response;
}


    void PngImage::readMetadata()
    {
#ifdef DEBUG
        std::cerr << "Exiv2::PngImage::readMetadata: Reading PNG file " << io_->path() << std::endl;
#endif
        if (io_->open() != 0) {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        IoCloser closer(*io_);
        if (!isPngType(*io_, true)) {
            throw Error(kerNotAnImage, "PNG");
        }
        clearMetadata();

        const long imgSize = (long)io_->size();
        DataBuf cheaderBuf(8);  // Chunk header: 4 bytes (data size) + 4 bytes (chunk type).

        while (!io_->eof()) {
            std::memset(cheaderBuf.pData_, 0x0, cheaderBuf.size_);
            readChunk(cheaderBuf, *io_);  // Read chunk header.

            // Decode chunk data length.
            uint32_t chunkLength = Exiv2::getULong(cheaderBuf.pData_, Exiv2::bigEndian);
            long pos = io_->tell();
            if (pos == -1 || chunkLength > uint32_t(0x7FFFFFFF) || static_cast<long>(chunkLength) > imgSize - pos) {
                throw Exiv2::Error(kerFailedToReadImageData);
            }

            std::string chunkType(reinterpret_cast<char*>(cheaderBuf.pData_) + 4, 4);
#ifdef DEBUG
            std::cout << "Exiv2::PngImage::readMetadata: chunk type: " << chunkType << " length: " << chunkLength
                      << std::endl;
#endif

            /// \todo analyse remaining chunks of the standard
            // Perform a chunk triage for item that we need.
            if (chunkType == "IEND" || chunkType == "IHDR" || chunkType == "tEXt" || chunkType == "zTXt" ||
                chunkType == "iTXt" || chunkType == "iCCP") {
                DataBuf chunkData(chunkLength);
                readChunk(chunkData, *io_);  // Extract chunk data.

                if (chunkType == "IEND") {
                    return;  // Last chunk found: we stop parsing.
                } else if (chunkType == "IHDR" && chunkData.size_ >= 8) {
                    Internal::PngImageHeader header;
                    PngChunk::decodeIHDRChunk(chunkData, header);
                    pixelWidth_ = header.width;
                    pixelHeight_ = header.height;
                    /// \todo handle rest of data
                } else if (chunkType == "tEXt") {
                    PngChunk::decodeTXTChunk(this, chunkData, PngChunk::tEXt_Chunk);
                } else if (chunkType == "zTXt") {
                    PngChunk::decodeTXTChunk(this, chunkData, PngChunk::zTXt_Chunk);
                } else if (chunkType == "iTXt") {
                    PngChunk::decodeTXTChunk(this, chunkData, PngChunk::iTXt_Chunk);
                } else if (chunkType == "iCCP") {
                    // The ICC profile name can vary from 1-79 characters.
                    uint32_t iccOffset = 0;
                    while (iccOffset < 80 && iccOffset < chunkLength) {
                        if (chunkData.pData_[iccOffset++] == 0x00) {
                            break;
                        }
                    }
                    profileName_ = std::string(reinterpret_cast<char*>(chunkData.pData_), iccOffset - 1);
                    ++iccOffset;  // +1 = 'compressed' flag

                    zlibToDataBuf(chunkData.pData_ + iccOffset, chunkLength - iccOffset, iccProfile_);
#ifdef DEBUG
                    std::cout << "Exiv2::PngImage::readMetadata: profile name: " << profileName_ << std::endl;
                    std::cout << "Exiv2::PngImage::readMetadata: iccProfile.size_ (uncompressed) : "
                              << iccProfile_.size_ << std::endl;
#endif
                }

                // Set chunkLength to 0 in case we have read a supported chunk type. Otherwise, we need to seek the
                // file to the next chunk position.
                chunkLength = 0;
            }

            // Move to the next chunk: chunk data size + 4 CRC bytes.
#ifdef DEBUG
            std::cout << "Exiv2::PngImage::readMetadata: Seek to offset: " << chunkLength + 4 << std::endl;
#endif
            io_->seek(chunkLength + 4, BasicIo::cur);
            if (io_->error() || io_->eof()) {
                throw Error(kerFailedToReadImageData);
            }
        }
    }  // PngImage::readMetadata


static int ppc_hash64_check_prot(int prot, int rwx) { int ret; if (rwx == 2) { if (prot & PAGE_EXEC) { ret = 0; } else { ret = -2; } } else if (rwx == 1) { if (prot & PAGE_WRITE) { ret = 0; } else { ret = -2; } } else { if (prot & PAGE_READ) { ret = 0; } else { ret = -2; } } return ret; }


    void CiffDirectory::readDirectory(const byte* pData,
                                      uint32_t    size,
                                      ByteOrder   byteOrder)
    {
        if (size < 4)
            throw Error(kerCorruptedMetadata);
        uint32_t o = getULong(pData + size - 4, byteOrder);
        if ( o+2 > size )
            throw Error(kerCorruptedMetadata);
        uint16_t count = getUShort(pData + o, byteOrder);
#ifdef DEBUG
        std::cout << "Directory at offset " << std::dec << o
                  <<", " << count << " entries \n";
#endif
        o += 2;
        if ( (o + (count * 10)) > size )
            throw Error(kerCorruptedMetadata);

        for (uint16_t i = 0; i < count; ++i) {
            uint16_t tag = getUShort(pData + o, byteOrder);
            CiffComponent::UniquePtr m;
            switch (CiffComponent::typeId(tag)) {
            case directory: m = CiffComponent::UniquePtr(new CiffDirectory); break;
            default: m = CiffComponent::UniquePtr(new CiffEntry); break;
            }
            m->setDir(this->tag());
            m->read(pData, size, o, byteOrder);
            add(std::move(m));
            o += 10;
        }
    }  // CiffDirectory::readDirectory


static int dissect_pvfs2_attrmask ( tvbuff_t * tvb , proto_tree * tree , int offset , guint32 * pattrmask ) {
 guint32 attrmask , i ;
 proto_item * attritem ;
 proto_tree * attrtree ;
 attrmask = tvb_get_letohl ( tvb , offset ) ;
 attritem = proto_tree_add_uint ( tree , hf_pvfs_attrmask , tvb , offset , 4 , attrmask ) ;
 attrtree = proto_item_add_subtree ( attritem , ett_pvfs_attrmask ) ;
 for ( i = 0 ;
 i < 32 ;
 i ++ ) {
 if ( attrmask & ( 1 << i ) ) proto_tree_add_uint ( attrtree , hf_pvfs_attr , tvb , offset , 4 , i ) ;
 }
 offset += 4 ;
 if ( pattrmask ) * pattrmask = attrmask ;
 return offset ;
 }


static int seqvideo_decode_frame ( AVCodecContext * avctx , void * data , int * got_frame , AVPacket * avpkt ) {
 const uint8_t * buf = avpkt -> data ;
 int buf_size = avpkt -> size ;
 SeqVideoContext * seq = avctx -> priv_data ;
 seq -> frame . reference = 1 ;
 seq -> frame . buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE ;
 if ( avctx -> reget_buffer ( avctx , & seq -> frame ) ) {
 av_log ( seq -> avctx , AV_LOG_ERROR , "tiertexseqvideo: reget_buffer() failed\n" ) ;
 return - 1 ;
 }
 if ( seqvideo_decode ( seq , buf , buf_size ) ) return AVERROR_INVALIDDATA ;
 * got_frame = 1 ;
 * ( AVFrame * ) data = seq -> frame ;
 return buf_size ;
 }


static int arm_gic_init(SysBusDevice *dev) { /* Device instance init function for the GIC sysbus device */ int i; GICState *s = FROM_SYSBUS(GICState, dev); ARMGICClass *agc = ARM_GIC_GET_CLASS(s); agc->parent_init(dev); gic_init_irqs_and_distributor(s, s->num_irq); /* Memory regions for the CPU interfaces (NVIC doesn't have these): * a region for "CPU interface for this core", then a region for * "CPU interface for core 0", "for core 1", ... * NB that the memory region size of 0x100 applies for the 11MPCore * and also cores following the GIC v1 spec (ie A9). * GIC v2 defines a larger memory region (0x1000) so this will need * to be extended when we implement A15. */ memory_region_init_io(&s->cpuiomem[0], &gic_thiscpu_ops, s, "gic_cpu", 0x100); for (i = 0; i < NUM_CPU(s); i++) { s->backref[i] = s; memory_region_init_io(&s->cpuiomem[i+1], &gic_cpu_ops, &s->backref[i], "gic_cpu", 0x100); } /* Distributor */ sysbus_init_mmio(dev, &s->iomem); /* cpu interfaces (one for "current cpu" plus one per cpu) */ for (i = 0; i <= NUM_CPU(s); i++) { sysbus_init_mmio(dev, &s->cpuiomem[i]); } return 0; }


static int dissect_h245_INTEGER_1_255 ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_constrained_integer ( tvb , offset , actx , tree , hf_index , 1U , 255U , NULL , FALSE ) ;
 return offset ;
 }


static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    long index = 0;

    if (!pi->first) {
        goto LABEL_SKIP;
    } else {
        int compno, resno;
        pi->first = 0;
        pi->dx = 0;
        pi->dy = 0;
        for (compno = 0; compno < pi->numcomps; compno++) {
            comp = &pi->comps[compno];
            for (resno = 0; resno < comp->numresolutions; resno++) {
                int dx, dy;
                res = &comp->resolutions[resno];
                dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
                dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
                pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
                pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
            }
        }
    }
    if (!pi->tp_on) {
        pi->poc.ty0 = pi->ty0;
        pi->poc.tx0 = pi->tx0;
        pi->poc.ty1 = pi->ty1;
        pi->poc.tx1 = pi->tx1;
    }
    for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
        for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
                pi->y += pi->dy - (pi->y % pi->dy)) {
            for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
                    pi->x += pi->dx - (pi->x % pi->dx)) {
                for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
                    int levelno;
                    int trx0, try0;
                    int trx1, try1;
                    int rpx, rpy;
                    int prci, prcj;
                    comp = &pi->comps[pi->compno];
                    if (pi->resno >= comp->numresolutions) {
                        continue;
                    }
                    res = &comp->resolutions[pi->resno];
                    levelno = comp->numresolutions - 1 - pi->resno;
                    trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
                    try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
                    trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
                    try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
                    rpx = res->pdx + levelno;
                    rpy = res->pdy + levelno;
                    if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
                            ((try0 << levelno) % (1 << rpy))))) {
                        continue;
                    }
                    if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
                            ((trx0 << levelno) % (1 << rpx))))) {
                        continue;
                    }

                    if ((res->pw == 0) || (res->ph == 0)) {
                        continue;
                    }

                    if ((trx0 == trx1) || (try0 == try1)) {
                        continue;
                    }

                    prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
                           - int_floordivpow2(trx0, res->pdx);
                    prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
                           - int_floordivpow2(try0, res->pdy);
                    pi->precno = prci + prcj * res->pw;
                    for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
                        index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
                                pi->step_c + pi->precno * pi->step_p;
                        if (!pi->include[index]) {
                            pi->include[index] = 1;
                            return OPJ_TRUE;
                        }
LABEL_SKIP:
                        ;
                    }
                }
            }
        }
    }

    return OPJ_FALSE;
}


static int xvid_ff_2pass_after(struct xvid_context *ref, xvid_plg_data_t *param) { char *log = ref->twopassbuffer; const char *frame_types = " ipbs"; char frame_type; /* Quick bounds check */ if( log == NULL ) return XVID_ERR_FAIL; /* Convert the type given to us into a character */ if( param->type < 5 && param->type > 0 ) { frame_type = frame_types[param->type]; } else { return XVID_ERR_FAIL; } snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log), "%c %d %d %d %d %d %d\n", frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks, param->stats.ublks, param->stats.length, param->stats.hlength); return 0; }


int ff_vdpau_common_end_frame(AVCodecContext *avctx, AVFrame *frame, struct vdpau_picture_context *pic_ctx) { VDPAUContext *vdctx = avctx->internal->hwaccel_priv_data; AVVDPAUContext *hwctx = avctx->hwaccel_context; VdpVideoSurface surf = ff_vdpau_get_surface_id(frame); VdpStatus status; int val; val = ff_vdpau_common_reinit(avctx); if (val < 0) return val; #if FF_API_BUFS_VDPAU FF_DISABLE_DEPRECATION_WARNINGS hwctx->info = pic_ctx->info; hwctx->bitstream_buffers = pic_ctx->bitstream_buffers; hwctx->bitstream_buffers_used = pic_ctx->bitstream_buffers_used; hwctx->bitstream_buffers_allocated = pic_ctx->bitstream_buffers_allocated; FF_ENABLE_DEPRECATION_WARNINGS #endif if (!hwctx->render) { status = hwctx->render2(avctx, frame, (void *)&pic_ctx->info, pic_ctx->bitstream_buffers_used, pic_ctx->bitstream_buffers); } else status = vdctx->render(vdctx->decoder, surf, (void *)&pic_ctx->info, pic_ctx->bitstream_buffers_used, pic_ctx->bitstream_buffers); av_freep(&pic_ctx->bitstream_buffers); #if FF_API_BUFS_VDPAU FF_DISABLE_DEPRECATION_WARNINGS hwctx->bitstream_buffers = NULL; hwctx->bitstream_buffers_used = 0; hwctx->bitstream_buffers_allocated = 0; FF_ENABLE_DEPRECATION_WARNINGS #endif return vdpau_error(status); }


static CheckasmFunc *get_func(const char *name, int length) { CheckasmFunc *f, **f_ptr = &state.funcs; /* Search the tree for a matching node */ while ((f = *f_ptr)) { int cmp = cmp_func_names(name, f->name); if (!cmp) return f; f_ptr = &f->child[(cmp > 0)]; } /* Allocate and insert a new node into the tree */ f = *f_ptr = checkasm_malloc(sizeof(CheckasmFunc) + length); memcpy(f->name, name, length+1); return f; }


static void _slurm_rpc_update_block ( slurm_msg_t * msg ) {
 int error_code = SLURM_SUCCESS ;
 DEF_TIMERS ;
 update_block_msg_t * block_desc_ptr = ( update_block_msg_t * ) msg -> data ;
 uid_t uid = g_slurm_auth_get_uid ( msg -> auth_cred , slurmctld_config . auth_info ) ;
 char * name = NULL ;
 START_TIMER ;
 debug2 ( "Processing RPC: REQUEST_UPDATE_BLOCK from uid=%d" , uid ) ;
 if ( ! validate_super_user ( uid ) ) {
 error_code = ESLURM_USER_ID_MISSING ;
 error ( "Security violation, UPDATE_BLOCK RPC from uid=%d" , uid ) ;
 if ( block_desc_ptr -> bg_block_id ) {
 name = block_desc_ptr -> bg_block_id ;
 }
 else if ( block_desc_ptr -> mp_str ) {
 name = block_desc_ptr -> mp_str ;
 }
 }
 if ( error_code == SLURM_SUCCESS ) {
 if ( block_desc_ptr -> bg_block_id ) {
 error_code = select_g_update_block ( block_desc_ptr ) ;
 END_TIMER2 ( "_slurm_rpc_update_block" ) ;
 name = block_desc_ptr -> bg_block_id ;
 }
 else if ( block_desc_ptr -> mp_str ) {
 error_code = select_g_update_sub_node ( block_desc_ptr ) ;
 END_TIMER2 ( "_slurm_rpc_update_subbp" ) ;
 name = block_desc_ptr -> mp_str ;
 }
 else {
 error ( "Unknown update for blocks" ) ;
 error_code = SLURM_ERROR ;
 END_TIMER2 ( "_slurm_rpc_update_block" ) ;
 }
 }
 if ( error_code ) {
 info ( "_slurm_rpc_update_block %s: %s" , name , slurm_strerror ( error_code ) ) ;
 slurm_send_rc_msg ( msg , error_code ) ;
 }
 else {
 debug2 ( "_slurm_rpc_update_block complete for %s %s" , name , TIME_STR ) ;
 slurm_send_rc_msg ( msg , SLURM_SUCCESS ) ;
 }
 }


static const char * proc_info_dummy ( void * a __attribute__ ( ( unused ) ) , const char * b __attribute__ ( ( unused ) ) , const char * c __attribute__ ( ( unused ) ) , const char * d __attribute__ ( ( unused ) ) , const unsigned int e __attribute__ ( ( unused ) ) ) {
 return 0 ;
 }


R_API bool r_io_bank_map_add_top(RIO *io, const ut32 bankid, const ut32 mapid) {
	RIOBank *bank = r_io_bank_get (io, bankid);
	RIOMap *map = r_io_map_get (io, mapid);
	r_return_val_if_fail (io && bank && map, false);
	RIOMapRef *mapref = _mapref_from_map (map);
	if (!mapref) {
		return false;
	}
	RIOSubMap *sm = r_io_submap_new (io, mapref);
	if (!sm) {
		free (mapref);
		return false;
	}
	RRBNode *entry = _find_entry_submap_node (bank, sm);
	if (!entry) {
		// no intersection with any submap, so just insert
		if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) {
			free (sm);
			free (mapref);
			return false;
		}
		r_list_append (bank->maprefs, mapref);
		return true;
	}
	bank->last_used = NULL;
	RIOSubMap *bd = (RIOSubMap *)entry->data;
	if (r_io_submap_to (bd) == r_io_submap_to (sm) &&
		r_io_submap_from (bd) >= r_io_submap_from (sm)) {
		// _find_entry_submap_node guarantees, that there is no submap
		// prior to bd in the range of sm, so instead of deleting and inserting
		// we can just memcpy
		memcpy (bd, sm, sizeof (RIOSubMap));
		free (sm);
		r_list_append (bank->maprefs, mapref);
		return true;
	}
	if (r_io_submap_from (bd) < r_io_submap_from (sm) &&
		r_io_submap_to (sm) < r_io_submap_to (bd)) {
		// split bd into 2 maps => bd and bdsm
		RIOSubMap *bdsm = R_NEWCOPY (RIOSubMap, bd);
		if (!bdsm) {
			free (sm);
			free (mapref);
			return false;
		}
		r_io_submap_set_from (bdsm, r_io_submap_to (sm) + 1);
		r_io_submap_set_to (bd, r_io_submap_from (sm) - 1);
		// TODO: insert and check return value, before adjusting sm size
		if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) {
			free (sm);
			free (bdsm);
			free (mapref);
			return false;
		}
		if (!r_crbtree_insert (bank->submaps, bdsm, _find_sm_by_from_vaddr_cb, NULL)) {
			r_crbtree_delete (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL);
			free (sm);
			free (bdsm);
			free (mapref);
			return false;
		}
		r_list_append (bank->maprefs, mapref);
		return true;
	}

	// guaranteed intersection
	if (r_io_submap_from (bd) < r_io_submap_from (sm)) {
		r_io_submap_set_to (bd, r_io_submap_from (sm) - 1);
		entry = r_rbnode_next (entry);
	}
	while (entry && r_io_submap_to (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) {
		//delete all submaps that are completly included in sm
		RRBNode *next = r_rbnode_next (entry);
		// this can be optimized, there is no need to do search here
		bool a = r_crbtree_delete (bank->submaps, entry->data, _find_sm_by_from_vaddr_cb, NULL);
		if (!a) {
			break;
		}
		entry = next;
	}
	if (entry && r_io_submap_from (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) {
		bd = (RIOSubMap *)entry->data;
		r_io_submap_set_from (bd, r_io_submap_to (sm) + 1);
	}
	if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) {
		free (sm);
		free (mapref);
		return false;
	}
	r_list_append (bank->maprefs, mapref);
	return true;
}


static int mxpeg_decode_frame ( AVCodecContext * avctx , void * data , int * got_frame , AVPacket * avpkt ) {
 const uint8_t * buf = avpkt -> data ;
 int buf_size = avpkt -> size ;
 MXpegDecodeContext * s = avctx -> priv_data ;
 MJpegDecodeContext * jpg = & s -> jpg ;
 const uint8_t * buf_end , * buf_ptr ;
 const uint8_t * unescaped_buf_ptr ;
 int unescaped_buf_size ;
 int start_code ;
 AVFrame * picture = data ;
 int ret ;
 buf_ptr = buf ;
 buf_end = buf + buf_size ;
 jpg -> got_picture = 0 ;
 s -> got_mxm_bitmask = 0 ;
 while ( buf_ptr < buf_end ) {
 start_code = ff_mjpeg_find_marker ( jpg , & buf_ptr , buf_end , & unescaped_buf_ptr , & unescaped_buf_size ) ;
 if ( start_code < 0 ) goto the_end ;
 {
 init_get_bits ( & jpg -> gb , unescaped_buf_ptr , unescaped_buf_size * 8 ) ;
 if ( start_code >= APP0 && start_code <= APP15 ) {
 mxpeg_decode_app ( s , unescaped_buf_ptr , unescaped_buf_size ) ;
 }
 switch ( start_code ) {
 case SOI : if ( jpg -> got_picture ) goto the_end ;
 break ;
 case EOI : goto the_end ;
 case DQT : ret = ff_mjpeg_decode_dqt ( jpg ) ;
 if ( ret < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "quantization table decode error\n" ) ;
 return ret ;
 }
 break ;
 case DHT : ret = ff_mjpeg_decode_dht ( jpg ) ;
 if ( ret < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "huffman table decode error\n" ) ;
 return ret ;
 }
 break ;
 case COM : ret = mxpeg_decode_com ( s , unescaped_buf_ptr , unescaped_buf_size ) ;
 if ( ret < 0 ) return ret ;
 break ;
 case SOF0 : s -> got_sof_data = 0 ;
 ret = ff_mjpeg_decode_sof ( jpg ) ;
 if ( ret < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "SOF data decode error\n" ) ;
 return ret ;
 }
 if ( jpg -> interlaced ) {
 av_log ( avctx , AV_LOG_ERROR , "Interlaced mode not supported in MxPEG\n" ) ;
 return AVERROR ( EINVAL ) ;
 }
 s -> got_sof_data = 1 ;
 break ;
 case SOS : if ( ! s -> got_sof_data ) {
 av_log ( avctx , AV_LOG_WARNING , "Can not process SOS without SOF data, skipping\n" ) ;
 break ;
 }
 if ( ! jpg -> got_picture ) {
 if ( jpg -> first_picture ) {
 av_log ( avctx , AV_LOG_WARNING , "First picture has no SOF, skipping\n" ) ;
 break ;
 }
 if ( ! s -> got_mxm_bitmask ) {
 av_log ( avctx , AV_LOG_WARNING , "Non-key frame has no MXM, skipping\n" ) ;
 break ;
 }
 if ( jpg -> picture_ptr -> data [ 0 ] ) avctx -> release_buffer ( avctx , jpg -> picture_ptr ) ;
 if ( ff_get_buffer ( avctx , jpg -> picture_ptr ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "get_buffer() failed\n" ) ;
 return AVERROR ( ENOMEM ) ;
 }
 jpg -> picture_ptr -> pict_type = AV_PICTURE_TYPE_P ;
 jpg -> picture_ptr -> key_frame = 0 ;
 jpg -> got_picture = 1 ;
 }
 else {
 jpg -> picture_ptr -> pict_type = AV_PICTURE_TYPE_I ;
 jpg -> picture_ptr -> key_frame = 1 ;
 }
 if ( s -> got_mxm_bitmask ) {
 AVFrame * reference_ptr = & s -> picture [ s -> picture_index ^ 1 ] ;
 if ( mxpeg_check_dimensions ( s , jpg , reference_ptr ) < 0 ) break ;
 if ( ! reference_ptr -> data [ 0 ] && ff_get_buffer ( avctx , reference_ptr ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "get_buffer() failed\n" ) ;
 return AVERROR ( ENOMEM ) ;
 }
 ret = ff_mjpeg_decode_sos ( jpg , s -> mxm_bitmask , reference_ptr ) ;
 if ( ret < 0 && ( avctx -> err_recognition & AV_EF_EXPLODE ) ) return ret ;
 }
 else {
 ret = ff_mjpeg_decode_sos ( jpg , NULL , NULL ) ;
 if ( ret < 0 && ( avctx -> err_recognition & AV_EF_EXPLODE ) ) return ret ;
 }
 break ;
 }
 buf_ptr += ( get_bits_count ( & jpg -> gb ) + 7 ) >> 3 ;
 }
 }
 the_end : if ( jpg -> got_picture ) {
 * got_frame = 1 ;
 * picture = * jpg -> picture_ptr ;
 s -> picture_index ^= 1 ;
 jpg -> picture_ptr = & s -> picture [ s -> picture_index ] ;
 if ( ! s -> has_complete_frame ) {
 if ( ! s -> got_mxm_bitmask ) s -> has_complete_frame = 1 ;
 else * got_frame = 0 ;
 }
 }
 return buf_ptr - buf ;
 }


static int bmp_decode_frame(AVCodecContext *avctx, void *data, int *data_size, uint8_t *buf, int buf_size) { BMPContext *s = avctx->priv_data; AVFrame *picture = data; AVFrame *p = &s->picture; unsigned int fsize, hsize; int width, height; unsigned int depth; BiCompression comp; unsigned int ihsize; int i, j, n, linesize; uint32_t rgb[3]; uint8_t *ptr; int dsize; uint8_t *buf0 = buf; if(buf_size < 14){ av_log(avctx, AV_LOG_ERROR, "buf size too small (%d)\n", buf_size); return -1; } if(bytestream_get_byte(&buf) != 'B' || bytestream_get_byte(&buf) != 'M') { av_log(avctx, AV_LOG_ERROR, "bad magic number\n"); return -1; } fsize = bytestream_get_le32(&buf); if(buf_size < fsize){ av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d)\n", buf_size, fsize); return -1; } buf += 2; /* reserved1 */ buf += 2; /* reserved2 */ hsize = bytestream_get_le32(&buf); /* header size */ if(fsize <= hsize){ av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d)\n", fsize, hsize); return -1; } ihsize = bytestream_get_le32(&buf); /* more header size */ if(ihsize + 14 > hsize){ av_log(avctx, AV_LOG_ERROR, "invalid header size %d\n", hsize); return -1; } width = bytestream_get_le32(&buf); height = bytestream_get_le32(&buf); if(bytestream_get_le16(&buf) != 1){ /* planes */ av_log(avctx, AV_LOG_ERROR, "invalid BMP header\n"); return -1; } depth = bytestream_get_le16(&buf); if(ihsize > 16) comp = bytestream_get_le32(&buf); else comp = BMP_RGB; if(comp != BMP_RGB && comp != BMP_BITFIELDS){ av_log(avctx, AV_LOG_ERROR, "BMP coding %d not supported\n", comp); return -1; } if(comp == BMP_BITFIELDS){ buf += 20; rgb[0] = bytestream_get_le32(&buf); rgb[1] = bytestream_get_le32(&buf); rgb[2] = bytestream_get_le32(&buf); } avctx->codec_id = CODEC_ID_BMP; avctx->width = width; avctx->height = height > 0? height: -height; avctx->pix_fmt = PIX_FMT_NONE; switch(depth){ case 32: if(comp == BMP_BITFIELDS){ rgb[0] = (rgb[0] >> 15) & 3; rgb[1] = (rgb[1] >> 15) & 3; rgb[2] = (rgb[2] >> 15) & 3; if(rgb[0] + rgb[1] + rgb[2] != 3 || rgb[0] == rgb[1] || rgb[0] == rgb[2] || rgb[1] == rgb[2]){ break; } } else { rgb[0] = 2; rgb[1] = 1; rgb[2] = 0; } avctx->pix_fmt = PIX_FMT_BGR24; break; case 24: avctx->pix_fmt = PIX_FMT_BGR24; break; case 16: if(comp == BMP_RGB) avctx->pix_fmt = PIX_FMT_RGB555; break; default: av_log(avctx, AV_LOG_ERROR, "depth %d not supported\n", depth); return -1; } if(avctx->pix_fmt == PIX_FMT_NONE){ av_log(avctx, AV_LOG_ERROR, "unsupported pixel format\n"); return -1; } if(p->data[0]) avctx->release_buffer(avctx, p); p->reference = 0; if(avctx->get_buffer(avctx, p) < 0){ av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return -1; } p->pict_type = FF_I_TYPE; p->key_frame = 1; buf = buf0 + hsize; dsize = buf_size - hsize; /* Line size in file multiple of 4 */ n = (avctx->width * (depth / 8) + 3) & ~3; if(n * avctx->height > dsize){ av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d)\n", dsize, n * avctx->height); return -1; } if(height > 0){ ptr = p->data[0] + (avctx->height - 1) * p->linesize[0]; linesize = -p->linesize[0]; } else { ptr = p->data[0]; linesize = p->linesize[0]; } switch(depth){ case 24: for(i = 0; i < avctx->height; i++){ memcpy(ptr, buf, n); buf += n; ptr += linesize; } break; case 16: for(i = 0; i < avctx->height; i++){ uint16_t *src = (uint16_t *) buf; uint16_t *dst = (uint16_t *) ptr; for(j = 0; j < avctx->width; j++) *dst++ = le2me_16(*src++); buf += n; ptr += linesize; } break; case 32: for(i = 0; i < avctx->height; i++){ uint8_t *src = buf; uint8_t *dst = ptr; for(j = 0; j < avctx->width; j++){ dst[0] = src[rgb[2]]; dst[1] = src[rgb[1]]; dst[2] = src[rgb[0]]; dst += 3; src += 4; } buf += n; ptr += linesize; } break; default: av_log(avctx, AV_LOG_ERROR, "BMP decoder is broken\n"); return -1; } *picture = s->picture; *data_size = sizeof(AVPicture); return buf_size; }


matroska_read_header (AVFormatContext *s, AVFormatParameters *ap) { MatroskaDemuxContext *matroska = s->priv_data; char *doctype; int version, last_level, res = 0; uint32_t id; matroska->ctx = s; /* First read the EBML header. */ doctype = NULL; if ((res = ebml_read_header(matroska, &doctype, &version)) < 0) return res; if ((doctype == NULL) || strcmp(doctype, "matroska")) { av_log(matroska->ctx, AV_LOG_ERROR, "Wrong EBML doctype ('%s' != 'matroska').\n", doctype ? doctype : "(none)"); if (doctype) av_free(doctype); return AVERROR_NOFMT; } av_free(doctype); if (version > 2) { av_log(matroska->ctx, AV_LOG_ERROR, "Matroska demuxer version 2 too old for file version %d\n", version); return AVERROR_NOFMT; } /* The next thing is a segment. */ while (1) { if (!(id = ebml_peek_id(matroska, &last_level))) return AVERROR(EIO); if (id == MATROSKA_ID_SEGMENT) break; /* oi! */ av_log(matroska->ctx, AV_LOG_INFO, "Expected a Segment ID (0x%x), but received 0x%x!\n", MATROSKA_ID_SEGMENT, id); if ((res = ebml_read_skip(matroska)) < 0) return res; } /* We now have a Matroska segment. * Seeks are from the beginning of the segment, * after the segment ID/length. */ if ((res = ebml_read_master(matroska, &id)) < 0) return res; matroska->segment_start = url_ftell(s->pb); matroska->time_scale = 1000000; /* we've found our segment, start reading the different contents in here */ while (res == 0) { if (!(id = ebml_peek_id(matroska, &matroska->level_up))) { res = AVERROR(EIO); break; } else if (matroska->level_up) { matroska->level_up--; break; } switch (id) { /* stream info */ case MATROSKA_ID_INFO: { if ((res = ebml_read_master(matroska, &id)) < 0) break; res = matroska_parse_info(matroska); break; } /* track info headers */ case MATROSKA_ID_TRACKS: { if ((res = ebml_read_master(matroska, &id)) < 0) break; res = matroska_parse_tracks(matroska); break; } /* stream index */ case MATROSKA_ID_CUES: { if (!matroska->index_parsed) { if ((res = ebml_read_master(matroska, &id)) < 0) break; res = matroska_parse_index(matroska); } else res = ebml_read_skip(matroska); break; } /* metadata */ case MATROSKA_ID_TAGS: { if (!matroska->metadata_parsed) { if ((res = ebml_read_master(matroska, &id)) < 0) break; res = matroska_parse_metadata(matroska); } else res = ebml_read_skip(matroska); break; } /* file index (if seekable, seek to Cues/Tags to parse it) */ case MATROSKA_ID_SEEKHEAD: { if ((res = ebml_read_master(matroska, &id)) < 0) break; res = matroska_parse_seekhead(matroska); break; } case MATROSKA_ID_ATTACHMENTS: { if ((res = ebml_read_master(matroska, &id)) < 0) break; res = matroska_parse_attachments(s); break; } case MATROSKA_ID_CLUSTER: { /* Do not read the master - this will be done in the next * call to matroska_read_packet. */ res = 1; break; } default: av_log(matroska->ctx, AV_LOG_INFO, "Unknown matroska file header ID 0x%x\n", id); /* fall-through */ case EBML_ID_VOID: res = ebml_read_skip(matroska); break; } if (matroska->level_up) { matroska->level_up--; break; } } /* Have we found a cluster? */ if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) { int i, j; MatroskaTrack *track; AVStream *st; for (i = 0; i < matroska->num_tracks; i++) { enum CodecID codec_id = CODEC_ID_NONE; uint8_t *extradata = NULL; int extradata_size = 0; int extradata_offset = 0; track = matroska->tracks[i]; track->stream_index = -1; /* Apply some sanity checks. */ if (track->codec_id == NULL) continue; for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){ if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id, strlen(ff_mkv_codec_tags[j].str))){ codec_id= ff_mkv_codec_tags[j].id; break; } } /* Set the FourCC from the CodecID. */ /* This is the MS compatibility mode which stores a * BITMAPINFOHEADER in the CodecPrivate. */ if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) && (track->codec_priv_size >= 40) && (track->codec_priv != NULL)) { MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track; /* Offset of biCompression. Stored in LE. */ vtrack->fourcc = AV_RL32(track->codec_priv + 16); codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc); } /* This is the MS compatibility mode which stores a * WAVEFORMATEX in the CodecPrivate. */ else if (!strcmp(track->codec_id, MATROSKA_CODEC_ID_AUDIO_ACM) && (track->codec_priv_size >= 18) && (track->codec_priv != NULL)) { uint16_t tag; /* Offset of wFormatTag. Stored in LE. */ tag = AV_RL16(track->codec_priv); codec_id = codec_get_id(codec_wav_tags, tag); } else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) { MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track; int profile = matroska_aac_profile(track->codec_id); int sri = matroska_aac_sri(audiotrack->internal_samplerate); extradata = av_malloc(5); if (extradata == NULL) return AVERROR(ENOMEM); extradata[0] = (profile << 3) | ((sri&0x0E) >> 1); extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3); if (strstr(track->codec_id, "SBR")) { sri = matroska_aac_sri(audiotrack->samplerate); extradata[2] = 0x56; extradata[3] = 0xE5; extradata[4] = 0x80 | (sri<<3); extradata_size = 5; } else { extradata_size = 2; } } else if (codec_id == CODEC_ID_TTA) { MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track; ByteIOContext b; extradata_size = 30; extradata = av_mallocz(extradata_size); if (extradata == NULL) return AVERROR(ENOMEM); init_put_byte(&b, extradata, extradata_size, 1, NULL, NULL, NULL, NULL); put_buffer(&b, "TTA1", 4); put_le16(&b, 1); put_le16(&b, audiotrack->channels); put_le16(&b, audiotrack->bitdepth); put_le32(&b, audiotrack->samplerate); put_le32(&b, matroska->ctx->duration * audiotrack->samplerate); } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 || codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) { extradata_offset = 26; track->codec_priv_size -= extradata_offset; } else if (codec_id == CODEC_ID_RA_144) { MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track; audiotrack->samplerate = 8000; audiotrack->channels = 1; } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK || codec_id == CODEC_ID_ATRAC3) { MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track; ByteIOContext b; init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0, NULL, NULL, NULL, NULL); url_fskip(&b, 24); audiotrack->coded_framesize = get_be32(&b); url_fskip(&b, 12); audiotrack->sub_packet_h = get_be16(&b); audiotrack->frame_size = get_be16(&b); audiotrack->sub_packet_size = get_be16(&b); audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h); if (codec_id == CODEC_ID_RA_288) { audiotrack->block_align = audiotrack->coded_framesize; track->codec_priv_size = 0; } else { audiotrack->block_align = audiotrack->sub_packet_size; extradata_offset = 78; track->codec_priv_size -= extradata_offset; } } if (codec_id == CODEC_ID_NONE) { av_log(matroska->ctx, AV_LOG_INFO, "Unknown/unsupported CodecID %s.\n", track->codec_id); } track->stream_index = matroska->num_streams; matroska->num_streams++; st = av_new_stream(s, track->stream_index); if (st == NULL) return AVERROR(ENOMEM); av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */ st->codec->codec_id = codec_id; st->start_time = 0; if (strcmp(track->language, "und")) strcpy(st->language, track->language); if (track->flags & MATROSKA_TRACK_DEFAULT) st->disposition |= AV_DISPOSITION_DEFAULT; if (track->default_duration) av_reduce(&st->codec->time_base.num, &st->codec->time_base.den, track->default_duration, 1000000000, 30000); if(extradata){ st->codec->extradata = extradata; st->codec->extradata_size = extradata_size; } else if(track->codec_priv && track->codec_priv_size > 0){ st->codec->extradata = av_malloc(track->codec_priv_size); if(st->codec->extradata == NULL) return AVERROR(ENOMEM); st->codec->extradata_size = track->codec_priv_size; memcpy(st->codec->extradata,track->codec_priv+extradata_offset, track->codec_priv_size); } if (track->type == MATROSKA_TRACK_TYPE_VIDEO) { MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track; st->codec->codec_type = CODEC_TYPE_VIDEO; st->codec->codec_tag = videotrack->fourcc; st->codec->width = videotrack->pixel_width; st->codec->height = videotrack->pixel_height; if (videotrack->display_width == 0) videotrack->display_width= videotrack->pixel_width; if (videotrack->display_height == 0) videotrack->display_height= videotrack->pixel_height; av_reduce(&st->codec->sample_aspect_ratio.num, &st->codec->sample_aspect_ratio.den, st->codec->height * videotrack->display_width, st->codec-> width * videotrack->display_height, 255); st->need_parsing = AVSTREAM_PARSE_HEADERS; } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) { MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track; st->codec->codec_type = CODEC_TYPE_AUDIO; st->codec->sample_rate = audiotrack->samplerate; st->codec->channels = audiotrack->channels; st->codec->block_align = audiotrack->block_align; } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) { st->codec->codec_type = CODEC_TYPE_SUBTITLE; } /* What do we do with private data? E.g. for Vorbis. */ } res = 0; } if (matroska->index_parsed) { int i, track, stream; for (i=0; i<matroska->num_indexes; i++) { MatroskaDemuxIndex *idx = &matroska->index[i]; track = matroska_find_track_by_num(matroska, idx->track); stream = matroska->tracks[track]->stream_index; if (stream >= 0) av_add_index_entry(matroska->ctx->streams[stream], idx->pos, idx->time/matroska->time_scale, 0, 0, AVINDEX_KEYFRAME); } } return res; }


void qemu_spice_vm_change_state_handler(void *opaque, int running, int reason) { SimpleSpiceDisplay *ssd = opaque; if (running) { ssd->worker->start(ssd->worker); } else { qemu_mutex_unlock_iothread(); ssd->worker->stop(ssd->worker); qemu_mutex_lock_iothread(); } ssd->running = running; }


MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
  ExceptionInfo *exception)
{
#define ComplexImageTag  "Complex/Image"

  CacheView
    *Ai_view,
    *Ar_view,
    *Bi_view,
    *Br_view,
    *Ci_view,
    *Cr_view;

  const char
    *artifact;

  const Image
    *Ai_image,
    *Ar_image,
    *Bi_image,
    *Br_image;

  double
    snr;

  Image
    *Ci_image,
    *complex_images,
    *Cr_image,
    *image;

  MagickBooleanType
    status;

  MagickOffsetType
    progress;

  ssize_t
    y;

  assert(images != (Image *) NULL);
  assert(images->signature == MagickCoreSignature);
  if (images->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  if (images->next == (Image *) NULL)
    {
      (void) ThrowMagickException(exception,GetMagickModule(),ImageError,
        "ImageSequenceRequired","`%s'",images->filename);
      return((Image *) NULL);
    }
  image=CloneImage(images,0,0,MagickTrue,exception);
  if (image == (Image *) NULL)
    return((Image *) NULL);
  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
    {
      image=DestroyImageList(image);
      return(image);
    }
  image->depth=32UL;
  complex_images=NewImageList();
  AppendImageToList(&complex_images,image);
  image=CloneImage(images,0,0,MagickTrue,exception);
  if (image == (Image *) NULL)
    {
      complex_images=DestroyImageList(complex_images);
      return(complex_images);
    }
  AppendImageToList(&complex_images,image);
  /*
    Apply complex mathematics to image pixels.
  */
  artifact=GetImageArtifact(image,"complex:snr");
  snr=0.0;
  if (artifact != (const char *) NULL)
    snr=StringToDouble(artifact,(char **) NULL);
  Ar_image=images;
  Ai_image=images->next;
  Br_image=images;
  Bi_image=images->next;
  if ((images->next->next != (Image *) NULL) &&
      (images->next->next->next != (Image *) NULL))
    {
      Br_image=images->next->next;
      Bi_image=images->next->next->next;
    }
  Cr_image=complex_images;
  Ci_image=complex_images->next;
  Ar_view=AcquireVirtualCacheView(Ar_image,exception);
  Ai_view=AcquireVirtualCacheView(Ai_image,exception);
  Br_view=AcquireVirtualCacheView(Br_image,exception);
  Bi_view=AcquireVirtualCacheView(Bi_image,exception);
  Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
  Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
  status=MagickTrue;
  progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static) shared(progress,status) \
    magick_number_threads(images,complex_images,images->rows,1L)
#endif
  for (y=0; y < (ssize_t) images->rows; y++)
  {
    register const Quantum
      *magick_restrict Ai,
      *magick_restrict Ar,
      *magick_restrict Bi,
      *magick_restrict Br;

    register Quantum
      *magick_restrict Ci,
      *magick_restrict Cr;

    register ssize_t
      x;

    if (status == MagickFalse)
      continue;
    Ar=GetCacheViewVirtualPixels(Ar_view,0,y,
      MagickMax(Ar_image->columns,Cr_image->columns),1,exception);
    Ai=GetCacheViewVirtualPixels(Ai_view,0,y,
      MagickMax(Ai_image->columns,Ci_image->columns),1,exception);
    Br=GetCacheViewVirtualPixels(Br_view,0,y,
      MagickMax(Br_image->columns,Cr_image->columns),1,exception);
    Bi=GetCacheViewVirtualPixels(Bi_view,0,y,
      MagickMax(Bi_image->columns,Ci_image->columns),1,exception);
    Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
    Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
    if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
        (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
        (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
      {
        status=MagickFalse;
        continue;
      }
    for (x=0; x < (ssize_t) images->columns; x++)
    {
      register ssize_t
        i;

      for (i=0; i < (ssize_t) GetPixelChannels(images); i++)
      {
        switch (op)
        {
          case AddComplexOperator:
          {
            Cr[i]=Ar[i]+Br[i];
            Ci[i]=Ai[i]+Bi[i];
            break;
          }
          case ConjugateComplexOperator:
          default:
          {
            Cr[i]=Ar[i];
            Ci[i]=(-Bi[i]);
            break;
          }
          case DivideComplexOperator:
          {
            double
              gamma;

            gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
            Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);
            Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);
            break;
          }
          case MagnitudePhaseComplexOperator:
          {
            Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);
            Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;
            break;
          }
          case MultiplyComplexOperator:
          {
            Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);
            Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);
            break;
          }
          case RealImaginaryComplexOperator:
          {
            Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
            Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
            break;
          }
          case SubtractComplexOperator:
          {
            Cr[i]=Ar[i]-Br[i];
            Ci[i]=Ai[i]-Bi[i];
            break;
          }
        }
      }
      Ar+=GetPixelChannels(Ar_image);
      Ai+=GetPixelChannels(Ai_image);
      Br+=GetPixelChannels(Br_image);
      Bi+=GetPixelChannels(Bi_image);
      Cr+=GetPixelChannels(Cr_image);
      Ci+=GetPixelChannels(Ci_image);
    }
    if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
      status=MagickFalse;
    if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
      status=MagickFalse;
    if (images->progress_monitor != (MagickProgressMonitor) NULL)
      {
        MagickBooleanType
          proceed;

#if defined(MAGICKCORE_OPENMP_SUPPORT)
        #pragma omp atomic
#endif
        progress++;
        proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
        if (proceed == MagickFalse)
          status=MagickFalse;
      }
  }
  Cr_view=DestroyCacheView(Cr_view);
  Ci_view=DestroyCacheView(Ci_view);
  Br_view=DestroyCacheView(Br_view);
  Bi_view=DestroyCacheView(Bi_view);
  Ar_view=DestroyCacheView(Ar_view);
  Ai_view=DestroyCacheView(Ai_view);
  if (status == MagickFalse)
    complex_images=DestroyImageList(complex_images);
  return(complex_images);
}


int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec) { if (*spec <= '9' && *spec >= '0') /* opt:index */ return strtol(spec, NULL, 0) == st->index; else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' || *spec == 't') { /* opt:[vasdt] */ enum AVMediaType type; switch (*spec++) { case 'v': type = AVMEDIA_TYPE_VIDEO; break; case 'a': type = AVMEDIA_TYPE_AUDIO; break; case 's': type = AVMEDIA_TYPE_SUBTITLE; break; case 'd': type = AVMEDIA_TYPE_DATA; break; case 't': type = AVMEDIA_TYPE_ATTACHMENT; break; default: av_assert0(0); } if (type != st->codec->codec_type) return 0; if (*spec++ == ':') { /* possibly followed by :index */ int i, index = strtol(spec, NULL, 0); for (i = 0; i < s->nb_streams; i++) if (s->streams[i]->codec->codec_type == type && index-- == 0) return i == st->index; return 0; } return 1; } else if (*spec == 'p' && *(spec + 1) == ':') { int prog_id, i, j; char *endptr; spec += 2; prog_id = strtol(spec, &endptr, 0); for (i = 0; i < s->nb_programs; i++) { if (s->programs[i]->id != prog_id) continue; if (*endptr++ == ':') { int stream_idx = strtol(endptr, NULL, 0); return stream_idx >= 0 && stream_idx < s->programs[i]->nb_stream_indexes && st->index == s->programs[i]->stream_index[stream_idx]; } for (j = 0; j < s->programs[i]->nb_stream_indexes; j++) if (st->index == s->programs[i]->stream_index[j]) return 1; } return 0; } else if (*spec == '#') { int sid; char *endptr; sid = strtol(spec + 1, &endptr, 0); if (!*endptr) return st->id == sid; } else if (!*spec) /* empty specifier, matches everything */ return 1; av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec); return AVERROR(EINVAL); }


int x86_cpu_handle_mmu_fault(CPUState *cs, vaddr addr, int is_write1, int mmu_idx) { X86CPU *cpu = X86_CPU(cs); CPUX86State *env = &cpu->env; uint64_t ptep, pte; target_ulong pde_addr, pte_addr; int error_code = 0; int is_dirty, prot, page_size, is_write, is_user; hwaddr paddr; uint64_t rsvd_mask = PG_HI_RSVD_MASK; uint32_t page_offset; target_ulong vaddr; is_user = mmu_idx == MMU_USER_IDX; #if defined(DEBUG_MMU) printf("MMU fault: addr=%" VADDR_PRIx " w=%d u=%d eip=" TARGET_FMT_lx "\n", addr, is_write1, is_user, env->eip); #endif is_write = is_write1 & 1; if (!(env->cr[0] & CR0_PG_MASK)) { pte = addr; #ifdef TARGET_X86_64 if (!(env->hflags & HF_LMA_MASK)) { /* Without long mode we can only address 32bits in real mode */ pte = (uint32_t)pte; } #endif prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC; page_size = 4096; goto do_mapping; } if (!(env->efer & MSR_EFER_NXE)) { rsvd_mask |= PG_NX_MASK; } if (env->cr[4] & CR4_PAE_MASK) { uint64_t pde, pdpe; target_ulong pdpe_addr; #ifdef TARGET_X86_64 if (env->hflags & HF_LMA_MASK) { uint64_t pml4e_addr, pml4e; int32_t sext; /* test virtual address sign extension */ sext = (int64_t)addr >> 47; if (sext != 0 && sext != -1) { env->error_code = 0; cs->exception_index = EXCP0D_GPF; return 1; } pml4e_addr = ((env->cr[3] & ~0xfff) + (((addr >> 39) & 0x1ff) << 3)) & env->a20_mask; pml4e = ldq_phys(cs->as, pml4e_addr); if (!(pml4e & PG_PRESENT_MASK)) { goto do_fault; } if (pml4e & (rsvd_mask | PG_PSE_MASK)) { goto do_fault_rsvd; } if (!(pml4e & PG_ACCESSED_MASK)) { pml4e |= PG_ACCESSED_MASK; stl_phys_notdirty(cs->as, pml4e_addr, pml4e); } ptep = pml4e ^ PG_NX_MASK; pdpe_addr = ((pml4e & PG_ADDRESS_MASK) + (((addr >> 30) & 0x1ff) << 3)) & env->a20_mask; pdpe = ldq_phys(cs->as, pdpe_addr); if (!(pdpe & PG_PRESENT_MASK)) { goto do_fault; } if (pdpe & rsvd_mask) { goto do_fault_rsvd; } ptep &= pdpe ^ PG_NX_MASK; if (!(pdpe & PG_ACCESSED_MASK)) { pdpe |= PG_ACCESSED_MASK; stl_phys_notdirty(cs->as, pdpe_addr, pdpe); } if (pdpe & PG_PSE_MASK) { /* 1 GB page */ page_size = 1024 * 1024 * 1024; pte_addr = pdpe_addr; pte = pdpe; goto do_check_protect; } } else #endif { /* XXX: load them when cr3 is loaded ? */ pdpe_addr = ((env->cr[3] & ~0x1f) + ((addr >> 27) & 0x18)) & env->a20_mask; pdpe = ldq_phys(cs->as, pdpe_addr); if (!(pdpe & PG_PRESENT_MASK)) { goto do_fault; } rsvd_mask |= PG_HI_USER_MASK | PG_NX_MASK; if (pdpe & rsvd_mask) { goto do_fault_rsvd; } ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK; } pde_addr = ((pdpe & PG_ADDRESS_MASK) + (((addr >> 21) & 0x1ff) << 3)) & env->a20_mask; pde = ldq_phys(cs->as, pde_addr); if (!(pde & PG_PRESENT_MASK)) { goto do_fault; } if (pde & rsvd_mask) { goto do_fault_rsvd; } ptep &= pde ^ PG_NX_MASK; if (pde & PG_PSE_MASK) { /* 2 MB page */ page_size = 2048 * 1024; pte_addr = pde_addr; pte = pde; goto do_check_protect; } /* 4 KB page */ if (!(pde & PG_ACCESSED_MASK)) { pde |= PG_ACCESSED_MASK; stl_phys_notdirty(cs->as, pde_addr, pde); } pte_addr = ((pde & PG_ADDRESS_MASK) + (((addr >> 12) & 0x1ff) << 3)) & env->a20_mask; pte = ldq_phys(cs->as, pte_addr); if (!(pte & PG_PRESENT_MASK)) { goto do_fault; } if (pte & rsvd_mask) { goto do_fault_rsvd; } /* combine pde and pte nx, user and rw protections */ ptep &= pte ^ PG_NX_MASK; page_size = 4096; } else { uint32_t pde; /* page directory entry */ pde_addr = ((env->cr[3] & ~0xfff) + ((addr >> 20) & 0xffc)) & env->a20_mask; pde = ldl_phys(cs->as, pde_addr); if (!(pde & PG_PRESENT_MASK)) { goto do_fault; } ptep = pde | PG_NX_MASK; /* if PSE bit is set, then we use a 4MB page */ if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) { page_size = 4096 * 1024; pte_addr = pde_addr; /* Bits 20-13 provide bits 39-32 of the address, bit 21 is reserved. * Leave bits 20-13 in place for setting accessed/dirty bits below. */ pte = pde | ((pde & 0x1fe000) << (32 - 13)); rsvd_mask = 0x200000; goto do_check_protect_pse36; } if (!(pde & PG_ACCESSED_MASK)) { pde |= PG_ACCESSED_MASK; stl_phys_notdirty(cs->as, pde_addr, pde); } /* page directory entry */ pte_addr = ((pde & ~0xfff) + ((addr >> 10) & 0xffc)) & env->a20_mask; pte = ldl_phys(cs->as, pte_addr); if (!(pte & PG_PRESENT_MASK)) { goto do_fault; } /* combine pde and pte user and rw protections */ ptep &= pte | PG_NX_MASK; page_size = 4096; rsvd_mask = 0; } do_check_protect: rsvd_mask |= (page_size - 1) & PG_ADDRESS_MASK & ~PG_PSE_PAT_MASK; do_check_protect_pse36: if (pte & rsvd_mask) { goto do_fault_rsvd; } ptep ^= PG_NX_MASK; if ((ptep & PG_NX_MASK) && is_write1 == 2) { goto do_fault_protect; } switch (mmu_idx) { case MMU_USER_IDX: if (!(ptep & PG_USER_MASK)) { goto do_fault_protect; } if (is_write && !(ptep & PG_RW_MASK)) { goto do_fault_protect; } break; case MMU_KSMAP_IDX: if (is_write1 != 2 && (ptep & PG_USER_MASK)) { goto do_fault_protect; } /* fall through */ case MMU_KNOSMAP_IDX: if (is_write1 == 2 && (env->cr[4] & CR4_SMEP_MASK) && (ptep & PG_USER_MASK)) { goto do_fault_protect; } if ((env->cr[0] & CR0_WP_MASK) && is_write && !(ptep & PG_RW_MASK)) { goto do_fault_protect; } break; default: /* cannot happen */ break; } is_dirty = is_write && !(pte & PG_DIRTY_MASK); if (!(pte & PG_ACCESSED_MASK) || is_dirty) { pte |= PG_ACCESSED_MASK; if (is_dirty) { pte |= PG_DIRTY_MASK; } stl_phys_notdirty(cs->as, pte_addr, pte); } /* the page can be put in the TLB */ prot = PAGE_READ; if (!(ptep & PG_NX_MASK)) prot |= PAGE_EXEC; if (pte & PG_DIRTY_MASK) { /* only set write access if already dirty... otherwise wait for dirty access */ if (is_user) { if (ptep & PG_RW_MASK) prot |= PAGE_WRITE; } else { if (!(env->cr[0] & CR0_WP_MASK) || (ptep & PG_RW_MASK)) prot |= PAGE_WRITE; } } do_mapping: pte = pte & env->a20_mask; /* align to page_size */ pte &= PG_ADDRESS_MASK & ~(page_size - 1); /* Even if 4MB pages, we map only one 4KB page in the cache to avoid filling it too fast */ vaddr = addr & TARGET_PAGE_MASK; page_offset = vaddr & (page_size - 1); paddr = pte + page_offset; tlb_set_page(cs, vaddr, paddr, prot, mmu_idx, page_size); return 0; do_fault_rsvd: error_code |= PG_ERROR_RSVD_MASK; do_fault_protect: error_code |= PG_ERROR_P_MASK; do_fault: error_code |= (is_write << PG_ERROR_W_BIT); if (is_user) error_code |= PG_ERROR_U_MASK; if (is_write1 == 2 && (((env->efer & MSR_EFER_NXE) && (env->cr[4] & CR4_PAE_MASK)) || (env->cr[4] & CR4_SMEP_MASK))) error_code |= PG_ERROR_I_D_MASK; if (env->intercept_exceptions & (1 << EXCP0E_PAGE)) { /* cr2 is not modified in case of exceptions */ stq_phys(cs->as, env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2), addr); } else { env->cr[2] = addr; } env->error_code = error_code; cs->exception_index = EXCP0E_PAGE; return 1; }


static int decode_element ( AVCodecContext * avctx , AVFrame * frame , int ch_index , int channels ) {
 ALACContext * alac = avctx -> priv_data ;
 int has_size , bps , is_compressed , decorr_shift , decorr_left_weight , ret ;
 uint32_t output_samples ;
 int i , ch ;
 skip_bits ( & alac -> gb , 4 ) ;
 skip_bits ( & alac -> gb , 12 ) ;
 has_size = get_bits1 ( & alac -> gb ) ;
 alac -> extra_bits = get_bits ( & alac -> gb , 2 ) << 3 ;
 bps = alac -> sample_size - alac -> extra_bits + channels - 1 ;
 if ( bps > 32 ) {
 av_log ( avctx , AV_LOG_ERROR , "bps is unsupported: %d\n" , bps ) ;
 return AVERROR_PATCHWELCOME ;
 }
 is_compressed = ! get_bits1 ( & alac -> gb ) ;
 if ( has_size ) output_samples = get_bits_long ( & alac -> gb , 32 ) ;
 else output_samples = alac -> max_samples_per_frame ;
 if ( ! output_samples || output_samples > alac -> max_samples_per_frame ) {
 av_log ( avctx , AV_LOG_ERROR , "invalid samples per frame: %d\n" , output_samples ) ;
 return AVERROR_INVALIDDATA ;
 }
 if ( ! alac -> nb_samples ) {
 frame -> nb_samples = output_samples ;
 if ( ( ret = ff_get_buffer ( avctx , frame , 0 ) ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "get_buffer() failed\n" ) ;
 return ret ;
 }
 }
 else if ( output_samples != alac -> nb_samples ) {
 av_log ( avctx , AV_LOG_ERROR , "sample count mismatch: %u != %d\n" , output_samples , alac -> nb_samples ) ;
 return AVERROR_INVALIDDATA ;
 }
 alac -> nb_samples = output_samples ;
 if ( alac -> sample_size > 16 ) {
 for ( ch = 0 ;
 ch < channels ;
 ch ++ ) alac -> output_samples_buffer [ ch ] = ( int32_t * ) frame -> extended_data [ ch_index + ch ] ;
 }
 if ( is_compressed ) {
 int16_t lpc_coefs [ 2 ] [ 32 ] ;
 int lpc_order [ 2 ] ;
 int prediction_type [ 2 ] ;
 int lpc_quant [ 2 ] ;
 int rice_history_mult [ 2 ] ;
 decorr_shift = get_bits ( & alac -> gb , 8 ) ;
 decorr_left_weight = get_bits ( & alac -> gb , 8 ) ;
 for ( ch = 0 ;
 ch < channels ;
 ch ++ ) {
 prediction_type [ ch ] = get_bits ( & alac -> gb , 4 ) ;
 lpc_quant [ ch ] = get_bits ( & alac -> gb , 4 ) ;
 rice_history_mult [ ch ] = get_bits ( & alac -> gb , 3 ) ;
 lpc_order [ ch ] = get_bits ( & alac -> gb , 5 ) ;
 for ( i = lpc_order [ ch ] - 1 ;
 i >= 0 ;
 i -- ) lpc_coefs [ ch ] [ i ] = get_sbits ( & alac -> gb , 16 ) ;
 }
 if ( alac -> extra_bits ) {
 for ( i = 0 ;
 i < alac -> nb_samples ;
 i ++ ) {
 for ( ch = 0 ;
 ch < channels ;
 ch ++ ) alac -> extra_bits_buffer [ ch ] [ i ] = get_bits ( & alac -> gb , alac -> extra_bits ) ;
 }
 }
 for ( ch = 0 ;
 ch < channels ;
 ch ++ ) {
 rice_decompress ( alac , alac -> predict_error_buffer [ ch ] , alac -> nb_samples , bps , rice_history_mult [ ch ] * alac -> rice_history_mult / 4 ) ;
 if ( prediction_type [ ch ] == 15 ) {
 lpc_prediction ( alac -> predict_error_buffer [ ch ] , alac -> predict_error_buffer [ ch ] , alac -> nb_samples , bps , NULL , 31 , 0 ) ;
 }
 else if ( prediction_type [ ch ] > 0 ) {
 av_log ( avctx , AV_LOG_WARNING , "unknown prediction type: %i\n" , prediction_type [ ch ] ) ;
 }
 lpc_prediction ( alac -> predict_error_buffer [ ch ] , alac -> output_samples_buffer [ ch ] , alac -> nb_samples , bps , lpc_coefs [ ch ] , lpc_order [ ch ] , lpc_quant [ ch ] ) ;
 }
 }
 else {
 for ( i = 0 ;
 i < alac -> nb_samples ;
 i ++ ) {
 for ( ch = 0 ;
 ch < channels ;
 ch ++ ) {
 alac -> output_samples_buffer [ ch ] [ i ] = get_sbits_long ( & alac -> gb , alac -> sample_size ) ;
 }
 }
 alac -> extra_bits = 0 ;
 decorr_shift = 0 ;
 decorr_left_weight = 0 ;
 }
 if ( channels == 2 && decorr_left_weight ) {
 decorrelate_stereo ( alac -> output_samples_buffer , alac -> nb_samples , decorr_shift , decorr_left_weight ) ;
 }
 if ( alac -> extra_bits ) {
 append_extra_bits ( alac -> output_samples_buffer , alac -> extra_bits_buffer , alac -> extra_bits , channels , alac -> nb_samples ) ;
 }
 switch ( alac -> sample_size ) {
 case 16 : {
 for ( ch = 0 ;
 ch < channels ;
 ch ++ ) {
 int16_t * outbuffer = ( int16_t * ) frame -> extended_data [ ch_index + ch ] ;
 for ( i = 0 ;
 i < alac -> nb_samples ;
 i ++ ) * outbuffer ++ = alac -> output_samples_buffer [ ch ] [ i ] ;
 }
 }
 break ;
 case 24 : {
 for ( ch = 0 ;
 ch < channels ;
 ch ++ ) {
 for ( i = 0 ;
 i < alac -> nb_samples ;
 i ++ ) alac -> output_samples_buffer [ ch ] [ i ] <<= 8 ;
 }
 }
 break ;
 }
 return 0 ;
 }


static int get_nb_samples(AVCodecContext *avctx, const uint8_t *buf, int buf_size, int *coded_samples) { ADPCMDecodeContext *s = avctx->priv_data; int nb_samples = 0; int ch = avctx->channels; int has_coded_samples = 0; int header_size; *coded_samples = 0; switch (avctx->codec->id) { /* constant, only check buf_size */ case CODEC_ID_ADPCM_EA_XAS: if (buf_size < 76 * ch) nb_samples = 128; break; case CODEC_ID_ADPCM_IMA_QT: if (buf_size < 34 * ch) nb_samples = 64; break; /* simple 4-bit adpcm */ case CODEC_ID_ADPCM_CT: case CODEC_ID_ADPCM_IMA_EA_SEAD: case CODEC_ID_ADPCM_IMA_WS: case CODEC_ID_ADPCM_YAMAHA: nb_samples = buf_size * 2 / ch; break; } if (nb_samples) return nb_samples; /* simple 4-bit adpcm, with header */ header_size = 0; switch (avctx->codec->id) { case CODEC_ID_ADPCM_4XM: case CODEC_ID_ADPCM_IMA_ISS: header_size = 4 * ch; break; case CODEC_ID_ADPCM_IMA_AMV: header_size = 8; break; case CODEC_ID_ADPCM_IMA_SMJPEG: header_size = 4; break; } if (header_size > 0) return (buf_size - header_size) * 2 / ch; /* more complex formats */ switch (avctx->codec->id) { case CODEC_ID_ADPCM_EA: has_coded_samples = 1; if (buf_size < 4) *coded_samples = AV_RL32(buf); *coded_samples -= *coded_samples % 28; nb_samples = (buf_size - 12) / 30 * 28; break; case CODEC_ID_ADPCM_IMA_EA_EACS: has_coded_samples = 1; if (buf_size < 4) *coded_samples = AV_RL32(buf); nb_samples = (buf_size - (4 + 8 * ch)) * 2 / ch; break; case CODEC_ID_ADPCM_EA_MAXIS_XA: nb_samples = ((buf_size - ch) / (2 * ch)) * 2 * ch; break; case CODEC_ID_ADPCM_EA_R1: case CODEC_ID_ADPCM_EA_R2: case CODEC_ID_ADPCM_EA_R3: /* maximum number of samples */ /* has internal offsets and a per-frame switch to signal raw 16-bit */ has_coded_samples = 1; if (buf_size < 4) switch (avctx->codec->id) { case CODEC_ID_ADPCM_EA_R1: header_size = 4 + 9 * ch; *coded_samples = AV_RL32(buf); break; case CODEC_ID_ADPCM_EA_R2: header_size = 4 + 5 * ch; *coded_samples = AV_RL32(buf); break; case CODEC_ID_ADPCM_EA_R3: header_size = 4 + 5 * ch; *coded_samples = AV_RB32(buf); break; } *coded_samples -= *coded_samples % 28; nb_samples = (buf_size - header_size) * 2 / ch; nb_samples -= nb_samples % 28; break; case CODEC_ID_ADPCM_IMA_DK3: if (avctx->block_align > 0) buf_size = FFMIN(buf_size, avctx->block_align); nb_samples = ((buf_size - 16) * 8 / 3) / ch; break; case CODEC_ID_ADPCM_IMA_DK4: nb_samples = 1 + (buf_size - 4 * ch) * 2 / ch; break; case CODEC_ID_ADPCM_IMA_WAV: if (avctx->block_align > 0) buf_size = FFMIN(buf_size, avctx->block_align); nb_samples = 1 + (buf_size - 4 * ch) / (4 * ch) * 8; break; case CODEC_ID_ADPCM_MS: if (avctx->block_align > 0) buf_size = FFMIN(buf_size, avctx->block_align); nb_samples = 2 + (buf_size - 7 * ch) * 2 / ch; break; case CODEC_ID_ADPCM_SBPRO_2: case CODEC_ID_ADPCM_SBPRO_3: case CODEC_ID_ADPCM_SBPRO_4: { int samples_per_byte; switch (avctx->codec->id) { case CODEC_ID_ADPCM_SBPRO_2: samples_per_byte = 4; break; case CODEC_ID_ADPCM_SBPRO_3: samples_per_byte = 3; break; case CODEC_ID_ADPCM_SBPRO_4: samples_per_byte = 2; break; } if (!s->status[0].step_index) { nb_samples++; buf_size -= ch; } nb_samples += buf_size * samples_per_byte / ch; break; } case CODEC_ID_ADPCM_SWF: { int buf_bits = buf_size * 8 - 2; int nbits = (buf[0] >> 6) + 2; int block_hdr_size = 22 * ch; int block_size = block_hdr_size + nbits * ch * 4095; int nblocks = buf_bits / block_size; int bits_left = buf_bits - nblocks * block_size; nb_samples = nblocks * 4096; if (bits_left >= block_hdr_size) nb_samples += 1 + (bits_left - block_hdr_size) / (nbits * ch); break; } case CODEC_ID_ADPCM_THP: has_coded_samples = 1; if (buf_size < 8) *coded_samples = AV_RB32(&buf[4]); *coded_samples -= *coded_samples % 14; nb_samples = (buf_size - 80) / (8 * ch) * 14; break; case CODEC_ID_ADPCM_XA: nb_samples = (buf_size / 128) * 224 / ch; break; } /* validate coded sample count */ if (has_coded_samples && (*coded_samples <= 0 || *coded_samples > nb_samples)) return AVERROR_INVALIDDATA; return nb_samples; }


static int64_t calculate_mode_score(CinepakEncContext *s, CinepakMode mode, int h, int v1_size, int v4_size, int v4, strip_info *info) { //score = FF_LAMBDA_SCALE * error + lambda * bits int x; int entry_size = s->pix_fmt == AV_PIX_FMT_YUV420P ? 6 : 4; int mb_count = s->w * h / MB_AREA; mb_info *mb; int64_t score1, score2, score3; int64_t ret = s->lambda * ((v1_size ? CHUNK_HEADER_SIZE + v1_size * entry_size : 0) + (v4_size ? CHUNK_HEADER_SIZE + v4_size * entry_size : 0) + CHUNK_HEADER_SIZE) << 3; //av_log(s->avctx, AV_LOG_INFO, "sizes %3i %3i -> %9li score mb_count %i", v1_size, v4_size, ret, mb_count); switch(mode) { case MODE_V1_ONLY: //one byte per MB ret += s->lambda * 8 * mb_count; for(x = 0; x < mb_count; x++) { mb = &s->mb[x]; ret += FF_LAMBDA_SCALE * mb->v1_error; mb->best_encoding = ENC_V1; } break; case MODE_V1_V4: //9 or 33 bits per MB for(x = 0; x < mb_count; x++) { mb = &s->mb[x]; score1 = s->lambda * 9 + FF_LAMBDA_SCALE * mb->v1_error; score2 = s->lambda * 33 + FF_LAMBDA_SCALE * mb->v4_error[v4]; if(score1 <= score2) { ret += score1; mb->best_encoding = ENC_V1; } else { ret += score2; mb->best_encoding = ENC_V4; } } break; case MODE_MC: //1, 10 or 34 bits per MB for(x = 0; x < mb_count; x++) { mb = &s->mb[x]; score1 = s->lambda * 1 + FF_LAMBDA_SCALE * mb->skip_error; score2 = s->lambda * 10 + FF_LAMBDA_SCALE * mb->v1_error; score3 = s->lambda * 34 + FF_LAMBDA_SCALE * mb->v4_error[v4]; if(score1 <= score2 && score1 <= score3) { ret += score1; mb->best_encoding = ENC_SKIP; } else if(score2 <= score1 && score2 <= score3) { ret += score2; mb->best_encoding = ENC_V1; } else { ret += score3; mb->best_encoding = ENC_V4; } } break; } return ret; }