Exemple #1
0
bool Inventory::readRecipe(const std::string& recipeFile)
{
  std::ifstream ifs(recipeFile.c_str());

  if (ifs.fail())
  {
    LOG2(ERROR, "Could not find: " + recipeFile);
    ifs.close();
    return false;
  }

  //LOG(INFO, "Inventory", "Reading: " + recipeFile);

  std::string temp;

  int height = 0, width = 0, outCount = 0;
  int16_t outType = 0, outHealth = 0;

  // Reading row at a time
  int del;
  bool readingRecipe = false;
  std::vector<std::string> line;
  std::vector<ItemPtr> recipetable;
  std::string text;
  while (getline(ifs, temp))
  {
    //If empty line
    if (temp.empty())
    {
      continue;
    }

    // If commentline -> skip to next
    if (temp[0] == COMMENTPREFIX)
    {
      continue;
    }

    // Init vars
    del = 0;
    line.clear();

    // Process line
    while (!temp.empty())
    {
      // Remove white spaces
      while (temp[0] == ' ')
      {
        temp = temp.substr(1);
      }

      // Split words
      del = temp.find(' ');
      if (del > -1)
      {
        line.push_back(temp.substr(0, del));
        temp = temp.substr(del + 1);
      }
      else
      {
        line.push_back(temp);
        break;
      }
    }

    // Begin recipe
    if (line.size() == 1 && line[0] == "<-")
    {
      readingRecipe = true;
      continue;
    }
    // Begin recipe
    if (line.size() == 1 && line[0] == "->")
    {
      readingRecipe = false;
      continue;
    }

    if (readingRecipe)
    {
      for (unsigned int i = 0; i < line.size(); i++)
      {
        std::string data(line[i]);
        ItemPtr item(new Item);
        item->setCount(1);
        item->setHealth(-1);
        int location = data.find("x");
        if (location > -1)
        {
          // Quantity before ID
          item->setCount(atoi(data.substr(0, location).c_str()));
          data = data.substr(location + 1, std::string::npos);
        }
        location = data.find(":");
        if (location > -1)
        {
          // Meta after ID
          item->setHealth(atoi(data.substr(location + 1, std::string::npos).c_str()));
          data = data.substr(0, location);
        }
        item->setType(atoi(data.c_str()));
        recipetable.push_back(item);
      }
      continue;
    }
    else
    {
      // Keywords
      if (line[0] == "width")
      {
        width = atoi(line[1].c_str());
      }
      if (line[0] == "height")
      {
        height = atoi(line[1].c_str());
      }
      if (line[0] == "outputcount")
      {
        outCount = atoi(line[1].c_str());
      }
      if (line[0] == "outputtype")
      {
        outType = atoi(line[1].c_str());
      }
      if (line[0] == "outputhealth")
      {
        outHealth = atoi(line[1].c_str());
      }
    }
  }
  ifs.close();

  addRecipe(width, height, recipetable, outCount, outType, outHealth);

  return true;
}
Exemple #2
0
//---------------------------------------------------------------------------
//
//	バイト書き込み
//
//---------------------------------------------------------------------------
void FASTCALL CRTC::WriteByte(uint32_t addr, uint32_t data)
{
	int reg;

	ASSERT(this);
	ASSERT((addr >= memdev.first) && (addr <= memdev.last));

	// $800単位でループ
	addr &= 0x7ff;

	// ウェイト
	scheduler->Wait(1);

	// $E80000-$E803FF : レジスタエリア
	if (addr < 0x400) {
		addr &= 0x3f;
		if (addr >= 0x30) {
			return;
		}

		// 書き込み(エンディアンを反転させる)
		addr ^= 1;
		if (crtc.reg[addr] == data) {
			return;
		}
		crtc.reg[addr] = (uint8_t)data;

		// GVRAMアドレス構成
		if (addr == 0x29) {
			if (data & 0x10) {
				crtc.tmem = TRUE;
			}
			else {
				crtc.tmem = FALSE;
			}
			if (data & 0x08) {
				crtc.gmem = TRUE;
			}
			else {
				crtc.gmem = FALSE;
			}
			crtc.siz = (data & 4) >> 2;
			crtc.col = (data & 3);

			// グラフィックVRAMへ通知
			gvram->SetType(data & 0x0f);
			return;
		}

		// 解像度変更
		if ((addr <= 15) || (addr == 40)) {
			// スプライトメモリの接続・切断は瞬時に行う(OS-9/68000)
			if (addr == 0x28) {
				if ((crtc.reg[0x28] & 3) >= 2) {
					sprite->Connect(FALSE);
				}
				else {
					sprite->Connect(TRUE);
				}
			}

			// 次の周期で再計算
			crtc.changed = TRUE;
			return;
		}

		// ラスタ割り込み
		if ((addr == 18) || (addr == 19)) {
			crtc.raster_int = (crtc.reg[19] << 8) + crtc.reg[18];
			crtc.raster_int &= 0x3ff;
			CheckRaster();
			return;
		}

		// テキストスクロール
		if ((addr >= 20) && (addr <= 23)) {
			crtc.text_scrlx = (crtc.reg[21] << 8) + crtc.reg[20];
			crtc.text_scrlx &= 0x3ff;
			crtc.text_scrly = (crtc.reg[23] << 8) + crtc.reg[22];
			crtc.text_scrly &= 0x3ff;
			render->TextScrl(crtc.text_scrlx, crtc.text_scrly);

			CRTC_LOG(LOG2(Log::Normal, "テキストスクロール x=%d y=%d", crtc.text_scrlx, crtc.text_scrly));
			return;
		}

		// グラフィックスクロール
		if ((addr >= 24) && (addr <= 39)) {
			reg = addr & ~3;
			addr -= 24;
			addr >>= 2;
			ASSERT(addr <= 3);
			crtc.grp_scrlx[addr] = (crtc.reg[reg+1] << 8) + crtc.reg[reg+0];
			crtc.grp_scrly[addr] = (crtc.reg[reg+3] << 8) + crtc.reg[reg+2];
			if (addr == 0) {
				crtc.grp_scrlx[addr] &= 0x3ff;
				crtc.grp_scrly[addr] &= 0x3ff;
			}
			else {
				crtc.grp_scrlx[addr] &= 0x1ff;
				crtc.grp_scrly[addr] &= 0x1ff;
			}
			render->GrpScrl(addr, crtc.grp_scrlx[addr], crtc.grp_scrly[addr]);
			return;
		}
Exemple #3
0
///询价通知
void CMdSpi::OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *pForQuoteRsp)
{
	LOG2("Subscribed Quote Response for InstrmentID: ", pForQuoteRsp->InstrumentID);
}
TWmDrmStoreState CWmDrmDataStore::DataStoreStateL()
    {
    TWmDrmStoreState state;
    TInt64 freeSpace( 0 );
    TInt64 freeSpace2( 0 );
    TInt dataStoreSize( 0 );
    TInt dummyDbSize( 0 );
    TInt ratio( 0 );
    TInt ratio2( 0 );
    TBool internalMassDriveNotFull( ETrue );

    LOGFN( "CWmDrmDataStore::DataStoreStateL" );
    freeSpace = iServer->FreeSpaceL( EFalse );

    if ( iWmDrmRightsConfigFound )
        {
        // Check free space from the configured drive, too.
        freeSpace2 = iServer->FreeSpaceL( ETrue );

        if ( freeSpace2 < iMinFreeSpace2 )
            {
            internalMassDriveNotFull = EFalse;
            }

        dummyDbSize = DummyDBSizeL( ETrue );
        dataStoreSize = DataStoreSizeL( ETrue );
        ratio2 = dataStoreSize * 100 / iInitialFreeSpace2;
        freeSpace2 += dummyDbSize;
#ifdef _LOGGING
        TBuf<KMaxTInt64BufLength> free2;
        LOG1( "CWmDrmDataStore::DataStoreStateL: Free space (2): ");
        free2.AppendNumUC( freeSpace2, EDecimal );
        LOG( free2 );
        TBuf<KMaxTInt64BufLength> free2Min;
        LOG1( "CWmDrmDataStore::DataStoreStateL: Minimum free space (2): ");
        free2Min.AppendNumUC( iMinFreeSpace2, EDecimal );
        LOG( free2Min );
#endif
        }

    // Check the system drive storage space next.
    dummyDbSize = DummyDBSizeL( EFalse );
    dataStoreSize = DataStoreSizeL( EFalse );
    ratio = dataStoreSize * 100 / iInitialFreeSpace;
    freeSpace += dummyDbSize;
#ifdef _LOGGING
    TBuf<KMaxTInt64BufLength> free;
    LOG1( "CWmDrmDataStore::DataStoreStateL: Free space: ");
    free.AppendNumUC( freeSpace, EDecimal );
    LOG( free );
    TBuf<KMaxTInt64BufLength> freeMin;
    LOG1( "CWmDrmDataStore::DataStoreStateL: Minimum free space: ");
    freeMin.AppendNumUC( iMinFreeSpace, EDecimal );
    LOG( freeMin );
#endif

    // Select the state of the storage space.
    if ( ( freeSpace > iMinFreeSpace ) && internalMassDriveNotFull )
        {
        LOG1( "CWmDrmDataStore::DataStoreStateL: Store space Ok" );
        state = EStoreSpaceOK;
        }
    else
        {
        // The configured drive is running out of space. The system drive
        // may also be running out of storage space, but calculate
        // the ratio of database size to initial free drive space and the
        // state of the drive storage space from the configured drive because
        // it is likely to fill up faster since the media files may be synced to it.
        if ( !internalMassDriveNotFull )
            {
            LOG2( "Ratio (2): %d", ratio2 );
            if ( ratio2 <= iMaxSpaceRatio2 )
                {
                LOG1( "CWmDrmDataStore::DataStoreStateL: Store space low (2)" );
                state = EStoreSpaceLow;
                }
            else
                {
                LOG1( "CWmDrmDataStore::DataStoreStateL: Store space full (2)" );
                state = EStoreSpaceFull;
                }
            }
        else
            // Only the system drive is running out of storage space.
            {
            LOG2( "Ratio: %d", ratio );
            if ( ratio <= iMaxSpaceRatio )
                {
                LOG1( "CWmDrmDataStore::DataStoreStateL Store space low" );
                state = EStoreSpaceLow;
                }
            else
                {
                LOG1( "CWmDrmDataStore::DataStoreStateL Store space full" );
                state = EStoreSpaceFull;
                }
            }
        }

    LOG2( "DataStoreState: %d", state );
    return state;
    }
Exemple #5
0
 int get_pool() { return LOG2(ItemSize)-4; }
Exemple #6
0
void apollo_kbd_device::mouse::read_mouse()
{
	if (m_tx_pending > 0)
	{
		m_tx_pending -= 5; // we will be called every 5ms
	}
	else
	{
		int b = m_device->m_io_mouse1->read();
		int x = m_device->m_io_mouse2->read();
		int y = m_device->m_io_mouse3->read();

		/* sign extend values < 0 */
		if (x & 0x80)
			x |= 0xffffff00;
		if (y & 0x80)
			y |= 0xffffff00;
		y = -y;

		if (m_last_b < 0)
		{
			m_last_b = b;
			m_last_x = x;
			m_last_y = y;
		}
		else if (b != m_last_b || x != m_last_x || y != m_last_y)
		{
			UINT8 mouse_data[4];
			int mouse_data_size;

			int dx = x - m_last_x;
			int dy = y - m_last_y;

			LOG2(("read_mouse: b=%02x x=%d y=%d dx=%d dy=%d", b, x, y, dx, dy));

			if (m_device->m_mode == KBD_MODE_0_COMPATIBILITY)
			{
				mouse_data[0] = 0xdf;
				mouse_data[1] = 0xf0 ^ b;
				mouse_data[2] = dx;
				mouse_data[3] = dy;
				mouse_data_size = 4;
			}
			else
			{
				if (m_device->m_mode != KBD_MODE_2_RELATIVE_CURSOR_CONTROL)
				{
					m_device->set_mode(KBD_MODE_2_RELATIVE_CURSOR_CONTROL);
				}

				mouse_data[0] = 0xf0 ^ b;
				mouse_data[1] = dx;
				mouse_data[2] = dy;
				mouse_data_size = 3;
			}

			for (int md = 0; md < mouse_data_size; md++)
			{
				m_device->xmit_char(mouse_data[md]);
			}

			// mouse data submitted; update current mouse state
			m_last_b = b;
			m_last_x += dx;
			m_last_y += dy;
			m_tx_pending = 100; // mouse data packet will take 40 ms
		}
	}
}
Exemple #7
0
int blk_get_device_part_str(const char *ifname, const char *dev_part_str,
			     struct blk_desc **dev_desc,
			     disk_partition_t *info, int allow_whole_dev)
{
	int ret = -1;
	const char *part_str;
	char *dup_str = NULL;
	const char *dev_str;
	int dev;
	char *ep;
	int p;
	int part;
	disk_partition_t tmpinfo;

#ifdef CONFIG_SANDBOX
	/*
	 * Special-case a pseudo block device "hostfs", to allow access to the
	 * host's own filesystem.
	 */
	if (0 == strcmp(ifname, "hostfs")) {
		*dev_desc = NULL;
		info->start = 0;
		info->size = 0;
		info->blksz = 0;
		info->bootable = 0;
		strcpy((char *)info->type, BOOT_PART_TYPE);
		strcpy((char *)info->name, "Sandbox host");
#if CONFIG_IS_ENABLED(PARTITION_UUIDS)
		info->uuid[0] = 0;
#endif
#ifdef CONFIG_PARTITION_TYPE_GUID
		info->type_guid[0] = 0;
#endif

		return 0;
	}
#endif

#ifdef CONFIG_CMD_UBIFS
	/*
	 * Special-case ubi, ubi goes through a mtd, rathen then through
	 * a regular block device.
	 */
	if (0 == strcmp(ifname, "ubi")) {
		if (!ubifs_is_mounted()) {
			printf("UBIFS not mounted, use ubifsmount to mount volume first!\n");
			return -1;
		}

		*dev_desc = NULL;
		memset(info, 0, sizeof(*info));
		strcpy((char *)info->type, BOOT_PART_TYPE);
		strcpy((char *)info->name, "UBI");
#if CONFIG_IS_ENABLED(PARTITION_UUIDS)
		info->uuid[0] = 0;
#endif
		return 0;
	}
#endif

	/* If no dev_part_str, use bootdevice environment variable */
	if (!dev_part_str || !strlen(dev_part_str) ||
	    !strcmp(dev_part_str, "-"))
		dev_part_str = env_get("bootdevice");

	/* If still no dev_part_str, it's an error */
	if (!dev_part_str) {
		printf("** No device specified **\n");
		goto cleanup;
	}

	/* Separate device and partition ID specification */
	part_str = strchr(dev_part_str, ':');
	if (part_str) {
		dup_str = strdup(dev_part_str);
		dup_str[part_str - dev_part_str] = 0;
		dev_str = dup_str;
		part_str++;
	} else {
		dev_str = dev_part_str;
	}

	/* Look up the device */
	dev = blk_get_device_by_str(ifname, dev_str, dev_desc);
	if (dev < 0)
		goto cleanup;

	/* Convert partition ID string to number */
	if (!part_str || !*part_str) {
		part = PART_UNSPECIFIED;
	} else if (!strcmp(part_str, "auto")) {
		part = PART_AUTO;
	} else {
		/* Something specified -> use exactly that */
		part = (int)simple_strtoul(part_str, &ep, 16);
		/*
		 * Less than whole string converted,
		 * or request for whole device, but caller requires partition.
		 */
		if (*ep || (part == 0 && !allow_whole_dev)) {
			printf("** Bad partition specification %s %s **\n",
			    ifname, dev_part_str);
			goto cleanup;
		}
	}

	/*
	 * No partition table on device,
	 * or user requested partition 0 (entire device).
	 */
	if (((*dev_desc)->part_type == PART_TYPE_UNKNOWN) ||
	    (part == 0)) {
		if (!(*dev_desc)->lba) {
			printf("** Bad device size - %s %s **\n", ifname,
			       dev_str);
			goto cleanup;
		}

		/*
		 * If user specified a partition ID other than 0,
		 * or the calling command only accepts partitions,
		 * it's an error.
		 */
		if ((part > 0) || (!allow_whole_dev)) {
			printf("** No partition table - %s %s **\n", ifname,
			       dev_str);
			goto cleanup;
		}

		(*dev_desc)->log2blksz = LOG2((*dev_desc)->blksz);

		part_get_info_whole_disk(*dev_desc, info);

		ret = 0;
		goto cleanup;
	}

	/*
	 * Now there's known to be a partition table,
	 * not specifying a partition means to pick partition 1.
	 */
	if (part == PART_UNSPECIFIED)
		part = 1;

	/*
	 * If user didn't specify a partition number, or did specify something
	 * other than "auto", use that partition number directly.
	 */
	if (part != PART_AUTO) {
		ret = part_get_info(*dev_desc, part, info);
		if (ret) {
			printf("** Invalid partition %d **\n", part);
			goto cleanup;
		}
	} else {
		/*
		 * Find the first bootable partition.
		 * If none are bootable, fall back to the first valid partition.
		 */
		part = 0;
		for (p = 1; p <= MAX_SEARCH_PARTITIONS; p++) {
			ret = part_get_info(*dev_desc, p, info);
			if (ret)
				continue;

			/*
			 * First valid partition, or new better partition?
			 * If so, save partition ID.
			 */
			if (!part || info->bootable)
				part = p;

			/* Best possible partition? Stop searching. */
			if (info->bootable)
				break;

			/*
			 * We now need to search further for best possible.
			 * If we what we just queried was the best so far,
			 * save the info since we over-write it next loop.
			 */
			if (part == p)
				tmpinfo = *info;
		}
		/* If we found any acceptable partition */
		if (part) {
			/*
			 * If we searched all possible partition IDs,
			 * return the first valid partition we found.
			 */
			if (p == MAX_SEARCH_PARTITIONS + 1)
				*info = tmpinfo;
		} else {
			printf("** No valid partitions found **\n");
			ret = -1;
			goto cleanup;
		}
	}
	if (strncmp((char *)info->type, BOOT_PART_TYPE, sizeof(info->type)) != 0) {
		printf("** Invalid partition type \"%.32s\""
			" (expect \"" BOOT_PART_TYPE "\")\n",
			info->type);
		ret  = -1;
		goto cleanup;
	}

	(*dev_desc)->log2blksz = LOG2((*dev_desc)->blksz);

	ret = part;
	goto cleanup;

cleanup:
	free(dup_str);
	return ret;
}
Exemple #8
0
static void clear_sense_data(omti8621_state *state) {
	LOG2(("clear_sense_data"));
	memset(state->sense_data, 0, sizeof(state->sense_data));
}
void FaceDetector::skinTypeDetect(ia_frame *frame)
{
    LOG2("@%s", __FUNCTION__);
    Mutex::Autolock lock(mLock);
    ia_face_detect_skin(mContext, frame);
}
void CMMADisplay::SourceSizeChanged(const TSize& aSourceSize)
{
    LOG(EJavaMMAPI,EInfo,"CMMADisplay::SourceSizeChanged");

#ifdef RD_JAVA_NGA_ENABLED
    if (iWindow)
    {
        iWindow->SetVideoCropRegion(TRect(iUserRect.iTl, aSourceSize));
    }
#endif

    iSourceSize = aSourceSize;
    LOG1(EJavaMMAPI,EInfo,"MMA::CMMADisplay::SourceSizeChanged %d",
         aSourceSize.iWidth);
    LOG1(EJavaMMAPI,EInfo,"MMA::CMMADisplay::SourceSizeChanged %d",
         aSourceSize.iHeight);
    jmethodID getDisplayWidthID = iJni->GetMethodID(
                                      iJavaDisplayClass,
                                      "getDisplayWidth",
                                      "()I");

    jmethodID getDisplayHeightID = iJni->GetMethodID(
                                       iJavaDisplayClass,
                                       "getDisplayHeight",
                                       "()I");


    TInt x =  iJni->CallIntMethod(iJavaDisplayObject,getDisplayWidthID);
    TInt y = iJni->CallIntMethod(iJavaDisplayObject,getDisplayHeightID);
    LOG2(EJavaMMAPI,EInfo,"CMMADisplay.cpp : SourceSizeChanged () iFullScreenSize is x = %d ,y = %d ",x,y);
    // get the ScreenSize from canvas in java
    TSize canvasSize(x, y);
    iFullScreenSize = canvasSize;
    TBool sourceIsBigger = (aSourceSize.iWidth > iFullScreenSize.iWidth ||
                            aSourceSize.iHeight > iFullScreenSize.iHeight);

    if (sourceIsBigger)
    {
        // Source is larger than display area.
        // Shrink draw are to fit in display.
        iWindow->SetDrawRect(ScaleToFullScreen(iFullScreenSize, iSourceSize));
    }
    else
    {
        // source is smaller than display area
        iWindow->SetDrawRect(TRect(iUserRect.iTl, iSourceSize));
    }

    SetClippingRegion();

    if (iUserRect.IsEmpty())
    {
        // Java side hasn't set size.
        iUserRect = iWindow->DrawRect();

        if (!sourceIsBigger)
        {
            // Addjusting rect to top left corner.
            iUserRect = TRect(iUserRect.Size());
        }
    }
}
Exemple #11
0
static void set_interrupt(const omti8621_state *state, enum line_state line_state) {
	if (state->irq_handler != NULL) {
		LOG2(("set_interrupt: status_port=%x", state->status_port));
		(*state->irq_handler)(&state->device->machine(), line_state);
	}
}
	bool DiffOfGaussianKernel<T, U>::Initialize_()
	{
		//if (m_dimension<5) return false;

		// create two gaussian deriv kernels

		PGCore::GaussianKernel<T, U> kernelOuter(m_sigmaOuter, m_dimension);
		PGCore::GaussianKernel<T, U> kernelInner(m_sigmaInner, m_dimension);
	
		

		kernelOuter-= kernelInner;
		
		memcpy(m_buffer, kernelOuter.GetBuffer(), m_dimension*sizeof(float));
		
		for(int i=0;i<(m_dimension);i++)
		{
			m_buffer[i]*=10;//m_dimension;		
		}
		

		/*
		float sum=0;
		for(int i=0;i<(m_dimension);i++)
		{
			m_buffer[i]*=50;//m_dimension;
			sum += m_buffer[i];			
		}
		
		if (sum<0)
		{
			float offset=abs(sum)/m_dimension;
			for (int i=0; i<(m_dimension); i++)
			{
				m_buffer[i] = offset;
			}			
		}		
		*/

#ifdef _DEBUG
		LOG0("{ The filter coefficients difference of gaussian are:");
		for(int i=0;i<(m_dimension);i++)
		{
			LOG2("Kernel[%d] = %f", i, (double)m_buffer[i]);
		}
		LOG0("} The filter coefficients.");
#endif

		//Reset()

		// experimental
		//  0	-1	-2	 -1	 0
		// -1	-2	-4	 -2	 1
		// -2	-4	 0	  4	 2
		// -1	 2	 4	  2	 1
		//  0	 1	 2	  1	 0
/*
		if (!m_orientY)
		{

			// fill up the buffer here
			SetValue(1, 0, (T)(-1.0f)); SetValue(3, 0, (T)(-1.0f));
			SetValue(1, 1, (T)(-2.0f)); SetValue(3, 1, (T)(-2.0f));
			SetValue(1, 3, (T)(2.0f));  SetValue(3, 3, (T)(2.0f));
			SetValue(1, 4, (T)(1.0f));  SetValue(3, 4, (T)(1.0f));

			SetValue(2, 0, (T)(-2.0f)); 
			SetValue(2, 1, (T)(-4.0f)); 
			SetValue(2, 3, (T)(4.0f));  
			SetValue(2, 4, (T)(2.0f));  

		} else
		{
			// fill up the buffer here
			SetValue(0, 1, (T)(-1.0f)); SetValue(0, 3, (T)(-1.0f));
			SetValue(1, 1, (T)(-2.0f)); SetValue(1, 3, (T)(-2.0f));
			SetValue(3, 1, (T)(2.0f));  SetValue(3, 3, (T)(2.0f));
			SetValue(4, 1, (T)(1.0f));  SetValue(4, 3, (T)(1.0f));

			SetValue(0, 2, (T)(-2.0f)); 
			SetValue(1, 2, (T)(-4.0f)); 
			SetValue(3, 2, (T)(4.0f));  
			SetValue(4, 2, (T)(2.0f));  

		}*/
		return true;
	}
Exemple #13
0
void client_callback(int fd,
                     short ev,
                     void* arg)
{
  User* user = (User*)arg;
  /*
  std::vector<User *>::const_iterator it = std::find (Mineserver::get()->users().begin(),
                                                      Mineserver::get()->users().end(), user);
  if(it == Mineserver::get()->users().end())
  {
    LOG2(INFO, "Using dead player!!!");
    return;
  }
  */
  if (ev & EV_READ)
  {

    int read   = 1;

    uint8_t* buf = new uint8_t[2048];

    read = recv(fd, (char*)buf, 2048, 0);
    if (read == 0)
    {
      LOG2(INFO, "Socket closed properly");

      delete user;
      user = (User*)1;
      delete[] buf;
      return;
    }

    if (read == SOCKET_ERROR)
    {
      LOG2(INFO, "Socket had no data to read");

      delete user;
      user = (User*)2;
      delete[] buf;
      return;
    }

    user->lastData = time(NULL);

    user->buffer.addToRead(buf, read);

    delete[] buf;

    user->buffer.reset();

    while (user->buffer >> (int8_t&)user->action)
    {
      //Variable len package
      if (Mineserver::get()->packetHandler()->packets[user->action].len == PACKET_VARIABLE_LEN)
      {
        //Call specific function
        int (PacketHandler::*function)(User*) =
          Mineserver::get()->packetHandler()->packets[user->action].function;
        bool disconnecting = user->action == 0xFF;
        int curpos = (Mineserver::get()->packetHandler()->*function)(user);
        if (curpos == PACKET_NEED_MORE_DATA)
        {
          user->waitForData = true;
          event_set(user->GetEvent(), fd, EV_READ, client_callback, user);
          event_add(user->GetEvent(), NULL);
          return;
        }

        if (disconnecting) // disconnect -- player gone
        {
          delete user;
          user = (User*)4;
          return;
        }
      }
      else if (Mineserver::get()->packetHandler()->packets[user->action].len == PACKET_DOES_NOT_EXIST)
      {
        std::ostringstream str;
        str << "Unknown action: 0x" << std::hex << user->action;
        LOG2(DEBUG, str.str());

        delete user;
        user = (User*)3;
        return;
      }
      else
      {
        if (!user->buffer.haveData(Mineserver::get()->packetHandler()->packets[user->action].len))
        {
          user->waitForData = true;
          event_set(user->GetEvent(), fd, EV_READ, client_callback, user);
          event_add(user->GetEvent(), NULL);
          return;
        }

        //Call specific function
        int (PacketHandler::*function)(User*) = Mineserver::get()->packetHandler()->packets[user->action].function;
        (Mineserver::get()->packetHandler()->*function)(user);
      }
    } //End while
  }
Exemple #14
0
bool Inventory::canBeArmour(int slot, int type)
{
  if (slot == 5)
  {
    // Helmet slot. Lots of fun here
    if (ServerInstance->m_only_helmets)
    {
      switch (type)
      {
      case ITEM_LEATHER_HELMET:
      case ITEM_CHAINMAIL_HELMET:
      case ITEM_IRON_HELMET:
      case ITEM_DIAMOND_HELMET:
      case ITEM_GOLD_HELMET:
        return true;
        break;
      }
      return false;
    }
    else
    {
      return true;
    }
  }
  else if (slot == 6)
  {
    switch (type)
    {
    case ITEM_LEATHER_CHESTPLATE:
    case ITEM_CHAINMAIL_CHESTPLATE:
    case ITEM_IRON_CHESTPLATE:
    case ITEM_DIAMOND_CHESTPLATE:
    case ITEM_GOLD_CHESTPLATE:
      return true;
      break;
    }
    return false;
  }
  else if (slot == 7)
  {
    switch (type)
    {
    case ITEM_LEATHER_LEGGINGS:
    case ITEM_CHAINMAIL_LEGGINGS:
    case ITEM_IRON_LEGGINGS:
    case ITEM_DIAMOND_LEGGINGS:
    case ITEM_GOLD_LEGGINGS:
      return true;
      break;
    }
    return false;
  }
  else if (slot == 8)
  {
    switch (type)
    {
    case ITEM_LEATHER_BOOTS:
    case ITEM_CHAINMAIL_BOOTS:
    case ITEM_IRON_BOOTS:
    case ITEM_DIAMOND_BOOTS:
    case ITEM_GOLD_BOOTS:
      return true;
      break;
    }
    return false;
  }
  LOG2(WARNING, "Unknown armour slot.");
  return false;
}
Exemple #15
0
void apollo_kbd_device::beeper::reset()
{
	LOG2(("reset apollo_kbd::beeper"));
	on();
}
// FaceDBLoaderThread interface defination.
FaceDetector::FaceDBLoaderThread::FaceDBLoaderThread(FaceDetector* faceDetector) :
    mFaceDetector(faceDetector)
{
    LOG2("@%s", __FUNCTION__);
}
Exemple #17
0
void apollo_kbd_device::mouse::start(apollo_kbd_device *device)
{
	m_device = device;
	LOG2(("start apollo_kbd::mouse"));
}
FaceDetector::FaceDBLoaderThread::~FaceDBLoaderThread()
{
    LOG2("@%s", __FUNCTION__);
}
Exemple #19
0
int apollo_kbd_device::push_scancode(UINT8 code, UINT8 repeat)
{
	int n_chars = 0;
	UINT16 key_code = 0;
	UINT8 caps = BIT(machine().root_device().ioport("keyboard4")->read(),0);
	UINT8 shift = BIT(machine().root_device().ioport("keyboard4")->read(),1) | BIT(machine().root_device().ioport("keyboard4")->read(),5);
	UINT8 ctrl = BIT(machine().root_device().ioport("keyboard4")->read(),2);
	UINT8 numlock = BIT(machine().root_device().ioport("keyboard4")->read(),6);
	UINT16 index;

	if (keyboard_is_german())
	{
		// map special keys for German keyboard
		switch (code)
		{
		case 0x00: code = 0x68; break; // _
		case 0x0e: code = 0x6b; break; // #
		case 0x29: code = 0x69; break; // <>
		case 0x42: code = 0x6f; break; // NP-
		case 0x46: code = 0x6e; break; // NP+
		case 0x4e: code = 0x73; break; // NP ENTER
		}
	}

#if MAP_APOLLO_KEYS
	if (numlock)
	{
		// don't map function keys to Apollo left keypad
		switch (code)
		{
		case 0x52: code = 0x75; break; // F1
		case 0x53: code = 0x76; break; // F2
		case 0x54: code = 0x77; break; // F3
		case 0x55: code = 0x78; break; // F4
		case 0x56: code = 0x79; break; // F5
		case 0x57: code = 0x7a; break; // F6
		case 0x58: code = 0x7b; break; // F7
		case 0x59: code = 0x7c; break; // F8
		case 0x5a: code = 0x7d; break; // F9
		case 0x5b: code = 0x74; break; // F0 = F10
		}
	}
#endif

	index = (code & 0x7f) * CODE_TABLE_ENTRY_SIZE;
	if (m_mode == KBD_MODE_0_COMPATIBILITY)
	{
		if (code & 0x80)
		{
			// skip up code in ASCII mode
		}
		else if (repeat > 0
				&& m_code_table[index + CODE_TABLE_AUTO_REPEAT_CODE] != Yes)
		{
			// skip repeat in ASCII mode
		}
		else if (ctrl)
		{
			key_code = m_code_table[index + CODE_TABLE_CONTROL_CODE];
		}
		else if (shift)
		{
			key_code = m_code_table[index + CODE_TABLE_SHIFTED_CODE];
		}
		else if (caps)
		{
			key_code = m_code_table[index + CODE_TABLE_CAPS_LOCK_CODE];
		}
		else
		{
			key_code = m_code_table[index + CODE_TABLE_UNSHIFTED_CODE];
		}
	}
	else
	{
		if (repeat > 0)
		{
			if (repeat == 1)
			{
				// auto repeat (but only for first scanned key)
				key_code = 0x7f;
			}
		}
		else if (code & 0x80)
		{
			key_code = m_code_table[index + CODE_TABLE_UP_CODE];
		}
		else
		{
			key_code = m_code_table[index + CODE_TABLE_DOWN_CODE];
		}
	}

	if (key_code != 0)
	{
		LOG2(("scan_code = 0x%02x key_code = 0x%04x",code, key_code));
		if (m_mode > KBD_MODE_1_KEYSTATE)
		{
			set_mode(KBD_MODE_1_KEYSTATE);
		}

		if (key_code & 0xff00)
		{
			xmit_char(key_code >> 8);
			n_chars++;
		}
Exemple #20
0
void	clkhandler()
{
	static uint32 count1000 = 1000;	/* variable to count 1000ms */

	volatile struct am335x_timer1ms *csrptr = 0x44E31000;
					/* Pointer to timer CSR	    */

	/* If there is no interrupt, return */

	if((csrptr->tisr & AM335X_TIMER1MS_TISR_OVF_IT_FLAG) == 0) {
		return;
	}

	LOG2(DEBUG_VERBOSE,DEBUG_SCHEDULER,
			"\nClkInt: a clock tick is being handled, ms was %d, secs were %d\n", 1000-count1000,clktime);

	/* Acknowledge the interrupt */

	csrptr->tisr = AM335X_TIMER1MS_TISR_OVF_IT_FLAG;

	/* Decrement 1000ms counter */

	count1000--;

	/* After 1 sec, increment clktime */

	if(count1000 == 0) {
		clktime++;
		count1000 = 1000;

		/* if EV_DTIMER env var is turned on then run the associated debugging output on a psuedo timer */
		if(envtab[EV_DTIMER].val && !(clktime%(envtab[EV_DTIMER].val))) {
			dtimer();
		}
	}

	/* if still NULL, update the pointer to the millisecond tracker so millisecond timestamps can be generated */
	if(!clktimems) {
		clktimems = &count1000;
	}

	/* check if sleep queue is empty */

	if(!isempty(sleepq)) {

		/* sleepq nonempty, decrement the key of */
		/* topmost process on sleepq		 */

		if((--queuetab[firstid(sleepq)].qkey) == 0) {

			wakeup();
		}
	}

	/* Decrement the preemption counter */
	/* Reschedule if necessary	    */

	if((--preempt) == 0) {
		LOG2(DEBUG_VERBOSE,DEBUG_SCHEDULER,"\nClkInt: preemption time \n");
		preempt = QUANTUM;
		resched();
	}
}
Exemple #21
0
static void JNICALL
cpu_loop_function(jvmtiEnv *jvmti, JNIEnv *env, void *p)
{
    int         loop_trip_counter;
    jboolean    cpu_loop_running;

    loop_trip_counter          = 0;

    rawMonitorEnter(gdata->cpu_loop_lock); {
        gdata->cpu_loop_running = JNI_TRUE;
        cpu_loop_running = gdata->cpu_loop_running;
        /* Notify cpu_sample_init() that we have started */
        rawMonitorNotifyAll(gdata->cpu_loop_lock);
    } rawMonitorExit(gdata->cpu_loop_lock);

    rawMonitorEnter(gdata->cpu_sample_lock); /* Only waits inside loop let go */

    while ( cpu_loop_running ) {

        ++loop_trip_counter;

        LOG3("cpu_loop()", "iteration", loop_trip_counter);

        /* If a dump is in progress, we pause sampling. */
        rawMonitorEnter(gdata->dump_lock); {
            if (gdata->dump_in_process) {
                gdata->pause_cpu_sampling = JNI_TRUE;
            }
        } rawMonitorExit(gdata->dump_lock);

        /* Check to see if we need to pause sampling (listener_loop command) */
        if (gdata->pause_cpu_sampling) {

            /*
             * Pause sampling for now. Reset sample controls if
             * sampling is resumed again.
             */

            rawMonitorWait(gdata->cpu_sample_lock, 0);

            rawMonitorEnter(gdata->cpu_loop_lock); {
                cpu_loop_running = gdata->cpu_loop_running;
            } rawMonitorExit(gdata->cpu_loop_lock);

            /* Continue the while loop, which will terminate if done. */
            continue;
        }

        /* This is the normal short timed wait before getting a sample */
        rawMonitorWait(gdata->cpu_sample_lock,  (jlong)gdata->sample_interval);

        /* Make sure we really want to continue */
        rawMonitorEnter(gdata->cpu_loop_lock); {
            cpu_loop_running = gdata->cpu_loop_running;
        } rawMonitorExit(gdata->cpu_loop_lock);

        /* Break out if we are done */
        if ( !cpu_loop_running ) {
            break;
        }

        /*
         * If a dump request came in after we checked at the top of
         * the while loop, then we catch that fact here. We
         * don't want to perturb the data that is being dumped so
         * we just ignore the data from this sampling loop.
         */
        rawMonitorEnter(gdata->dump_lock); {
            if (gdata->dump_in_process) {
                gdata->pause_cpu_sampling = JNI_TRUE;
            }
        } rawMonitorExit(gdata->dump_lock);

        /* Sample all the threads and update trace costs */
        if ( !gdata->pause_cpu_sampling) {
            tls_sample_all_threads(env);
        }

        /* Check to see if we need to finish */
        rawMonitorEnter(gdata->cpu_loop_lock); {
            cpu_loop_running = gdata->cpu_loop_running;
        } rawMonitorExit(gdata->cpu_loop_lock);

    }
    rawMonitorExit(gdata->cpu_sample_lock);

    rawMonitorEnter(gdata->cpu_loop_lock); {
        /* Notify cpu_sample_term() that we are done. */
        rawMonitorNotifyAll(gdata->cpu_loop_lock);
    } rawMonitorExit(gdata->cpu_loop_lock);

    LOG2("cpu_loop()", "clean termination");
}
/*
** A "local" function of main().  Handles a #messageType# message arrived on
** #sd# accompanied by #dataSize# bytes of data.
*/
static void
ProcessRequest(Socket *sd,
               MessageType messageType,
               size_t dataSize) {

  char *contents;
  DataDescriptor contentsDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
  AutoFetchInfo *expandedAutoFetches;
  unsigned long expiration;
  DataDescriptor expirationDescriptor = SIMPLE_DATA(UNSIGNED_LONG_TYPE, 1);
  int i;
  struct state stateDesc;
  char *stateNames;
  DataDescriptor stateNamesDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);

  switch(messageType) {

  case FETCH_STATE:
    if(!RecvData(*sd,
                 &stateDesc,
                 stateDescriptor,
                 stateDescriptorLength,
                 PktTimeOut(*sd))) {
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: state receive failed\n");
      return;
    }
    contents = (char *)malloc(stateDesc.rec_count * MAX_RECORD_SIZE);
    if(contents == NULL) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      if(ReadState(FileOfState(memoryDir, stateDesc.id),
                   contents,
                   stateDesc.rec_count,
                   stateDesc.rec_count * MAX_RECORD_SIZE,
                   stateDesc.seq_no,
                   &stateDesc.time_out,
                   &stateDesc.seq_no,
                   &stateDesc.rec_count,
                   &stateDesc.rec_size)) {
        if(stateDesc.rec_count > 0) {
          contentsDescriptor.repetitions =
            stateDesc.rec_size * stateDesc.rec_count;
          (void)SendMessageAndDatas(*sd,
                                    STATE_FETCHED,
                                    &stateDesc,
                                    stateDescriptor,
                                    stateDescriptorLength,
                                    contents,
                                    &contentsDescriptor,
                                    1,
                                    PktTimeOut(*sd));
        }
        else {
          (void)SendMessageAndData(*sd,
                                   STATE_FETCHED,
                                   &stateDesc,
                                   stateDescriptor,
                                   stateDescriptorLength,
                                   PktTimeOut(*sd));
        }
      }
      else {
        (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
        if(errno == EMFILE) {
          CheckConnections();
        }
      }
      free(contents);
    }
    break;

  case STORE_STATE:
    if(!RecvData(*sd,
                 &stateDesc,
                 stateDescriptor,
                 stateDescriptorLength,
                 PktTimeOut(*sd))) {
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: state receive failed\n");
      return;
    }
    contentsDescriptor.repetitions = stateDesc.rec_size * stateDesc.rec_count;
    contents = (char *)malloc(contentsDescriptor.repetitions + 1);
    if(contents == NULL) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      contents[contentsDescriptor.repetitions] = '\0';
      if(!RecvData(*sd,
                   contents,
                   &contentsDescriptor,
                   1,
                   PktTimeOut(*sd))) {
        DROP_SOCKET(sd);
        ERROR("ProcessRequest: data receive failed\n");
      }
      else {
        (void)SendMessage(*sd,
                          KeepState(&memLogLocation,
                                    &stateDesc,
                                    contents,
                                    contentsDescriptor.repetitions) ?
                          STATE_STORED : MEMORY_FAILED,
                          PktTimeOut(*sd));
        for(i = 0; i < autoFetchCount; i++) {
          if(strstr(autoFetches[i].stateNames, stateDesc.id) != NULL) {
            if(!SendMessageAndDatas(autoFetches[i].clientSock,
                                    STATE_FETCHED,
                                    &stateDesc,
                                    stateDescriptor,
                                    stateDescriptorLength,
                                    contents,
                                    &contentsDescriptor,
                                    1,
                                    PktTimeOut(autoFetches[i].clientSock))) {
              DROP_SOCKET(&autoFetches[i].clientSock);
              free(autoFetches[i].stateNames);
              autoFetches[i] = autoFetches[--autoFetchCount];
            }
          }
        }
      }
      free(contents);
    }
    break;

  case AUTOFETCH_BEGIN:
    stateNamesDescriptor.repetitions = dataSize;
    stateNames = (char *)malloc(dataSize);
    if(stateNames == NULL) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: out of memory\n");
    }
    else if(!RecvData(*sd,
                      stateNames,
                      &stateNamesDescriptor,
                      1,
                      PktTimeOut(*sd))) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      DROP_SOCKET(sd);
      free(stateNames);
      ERROR("ProcessRequest: data receive failed\n");
    }
    else if(*stateNames == '\0') {
      free(stateNames);
      EndAutoFetch(*sd);
      (void)SendMessage(*sd, AUTOFETCH_ACK, PktTimeOut(*sd));
    }
    else {
      for(i=0; (i < autoFetchCount) && (autoFetches[i].clientSock != *sd); i++)
        ; /* Nothing more to do. */
      if(i == autoFetchCount) {
        expandedAutoFetches =
          REALLOC(autoFetches, (autoFetchCount + 1) * sizeof(AutoFetchInfo));
        if(expandedAutoFetches == NULL) {
          (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
          DROP_SOCKET(sd);
          ERROR("ProcessRequest: out of memory\n");
          break;
        }
        autoFetches = expandedAutoFetches;
        autoFetches[i].clientSock = *sd;
        autoFetchCount++;
      }
      else {
        free(autoFetches[i].stateNames);
      }
      autoFetches[i].stateNames = stateNames;
      (void)SendMessage(*sd, AUTOFETCH_ACK, PktTimeOut(*sd));
    }
    break;

  case MEMORY_CLEAN:
    if(!RecvData(*sd, &expiration, &expirationDescriptor, 1, PktTimeOut(*sd))) {
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: data receive failed\n");
    }
    else {
      (void)SendMessage(*sd, MEMORY_CLEANED, PktTimeOut(*sd));
      (void)DoClean(expiration);
    }
    break;

#ifdef WITH_NETLOGGER	  
  case MEMORY_LOGDEST: /* config message contains log location */
	  if(!RecvData(*sd,
		  &memLogLocation,
		  loglocationDescriptor,
		  loglocationDescriptorLength,
		  PktTimeOut(*sd))) {
		  DROP_SOCKET(sd);
		  ERROR("ProcessRequest: loglocation receive failed\n");
		  return;
	  }else
	  {
		  (void)SendMessage(*sd, MEMORY_LOGDEST_ACK, PktTimeOut(*sd));
	  }
	  LOG2("ProcessRequest: loglocation %d .%s.\n", memLogLocation.loc_type, memLogLocation.path);
 
	  break;
#endif /* WITH_NETLOGGER */	  	

  default:
    DROP_SOCKET(sd);
    ERROR1("ProcessRequest: unknown message %d\n", messageType);

  }

}
void CWmDrmDataStore::UpdateDummyDbFileL( TInt aSize, TBool aConfiguredDrive )
    {
    LOGFN( "CWmDrmDataStore::UpdateDummyDbFileL" );
    LOG2( "aSize: %d", aSize );
    if ( aSize > 0 )
        {
        TInt dummyDbSize( DummyDBSizeL( aConfiguredDrive ) );
        LOG2( "dummyDbSize: %d", dummyDbSize );
        if ( aSize <= dummyDbSize )
            {
            if ( aConfiguredDrive )
                {
                User::LeaveIfError( iDummyDb2.SetSize( dummyDbSize - aSize ) );
                }
            else
                {
                User::LeaveIfError( iDummyDb.SetSize( dummyDbSize - aSize ) );
                }
            }
        else
            {
            if ( aConfiguredDrive )
                {
                User::LeaveIfError( iDummyDb2.SetSize( 0 ) );
                }
            else
                {
                User::LeaveIfError( iDummyDb.SetSize( 0 ) );
                }
            }
        }
    else
        {
        TInt dataStoreSize( DataStoreSizeL( aConfiguredDrive ) );
        LOG2( "dataStoreSize: %d", dataStoreSize );
        if ( aConfiguredDrive )
            {
            if ( dataStoreSize <= iDummyDbInitialSize2 )
                {
                User::LeaveIfError(
                    iDummyDb2.SetSize( iDummyDbInitialSize2 - dataStoreSize ) );
                }
            else
                {
                User::LeaveIfError( iDummyDb2.SetSize( 0 ) );
                }
            }
        else
            {
            if ( dataStoreSize <= iDummyDbInitialSize )
                {
                User::LeaveIfError(
                    iDummyDb.SetSize( iDummyDbInitialSize - dataStoreSize ) );
                }
            else
                {
                User::LeaveIfError( iDummyDb.SetSize( 0 ) );
                }
            }
        }
    }
void CameraClient::copyFrameAndPostCopiedFrame(
        int32_t msgType, const sp<ICameraClient>& client,
        const sp<IMemoryHeap>& heap, size_t offset, size_t size,
        camera_frame_metadata_t *metadata) {
    LOG2("copyFrameAndPostCopiedFrame");
    // It is necessary to copy out of pmem before sending this to
    // the callback. For efficiency, reuse the same MemoryHeapBase
    // provided it's big enough. Don't allocate the memory or
    // perform the copy if there's no callback.
    // hold the preview lock while we grab a reference to the preview buffer
    sp<MemoryHeapBase> previewBuffer;

    if (mPreviewBuffer == 0) {
        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
    } else if (size > mPreviewBuffer->virtualSize()) {
        mPreviewBuffer.clear();
        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
    }
    if (mPreviewBuffer == 0) {
        ALOGE("failed to allocate space for preview buffer");
//!++
#if 1
#else
        mLock.unlock();
#endif
//!--
        return;
    }
    previewBuffer = mPreviewBuffer;

    void* previewBufferBase = previewBuffer->base();
    void* heapBase = heap->base();

    if (heapBase == MAP_FAILED) {
        ALOGE("%s: Failed to mmap heap for preview frame.", __FUNCTION__);
        mLock.unlock();
        return;
    } else if (previewBufferBase == MAP_FAILED) {
        ALOGE("%s: Failed to mmap preview buffer for preview frame.", __FUNCTION__);
        mLock.unlock();
        return;
    }

    memcpy(previewBufferBase, (uint8_t *) heapBase + offset, size);

    sp<MemoryBase> frame = new MemoryBase(previewBuffer, 0, size);
    if (frame == 0) {
        ALOGE("failed to allocate space for frame callback");
//!++
#if 1
#else
        mLock.unlock();
#endif
//!--
        return;
    }

//!++
#if 1
#else
    mLock.unlock();
#endif
//!--
    client->dataCallback(msgType, frame, metadata);
}
EXPORT_C TInt CElementParser::ParseElementsL(const TDesC8& aData)
/** Parses a data buffer into the currently set MSdpElementBuilder interface.

If a whole number of data elements can not be parsed out of aData, the number 
of bytes left unparsed is returned. Those bytes should be prepended to the 
buffer when the function is next called. 

@param aData Buffer to parse
@return Number of bytes not consumed */
	{
	TUint8* ptr = (TUint8*)aData.Ptr();
	const TUint8* ptrE = ptr + aData.Length();

	CloseListsL();
	while ((ptr < ptrE) && (iBuilder != NULL))
		{

		// Remember start of this data element
		TUint8* ptrStart = ptr;

		// We know there's at least one byte already..
		TUint8 type = (TUint8)(*ptr>>KSdpElemHdrTypeShift);
		TUint8 sizedesc  = (TUint8)(*ptr&KSdpElemHdrSizeMask);
		++ptr;

		if ( type >= sizeof(KSdpElementValidSizes) ||
			 !(KSdpElementValidSizes[type]&(1<<sizedesc)) )
			{// Invalid size desc for type.
			LOG2(_L("SDP: Invalid size descriptor %d for type %d!"), sizedesc, type);
			User::Leave(KErrSdpParserInvalidSizeForType);
			}

		TUint elementLen;
		if (type == ETypeNil)
			{// we've already checked that sizedesc == 0
			elementLen = 0;
			}
		else if(sizedesc<=ESizeSixteenBytes)
			{
			elementLen = 1<<sizedesc;
			}
		else
			{
			TUint addSzBytes = 1<<(sizedesc-ESizeOneAdditional);
			if((addSzBytes)>TUint(ptrE-ptr))
				return (ptrE-ptrStart);
			elementLen = SdpUtil::GetUint(TPtrC8(ptr, addSzBytes));
			ptr += addSzBytes;
			}

		if (!iListStack->IsEmpty() && 
			(TInt)((ptr-ptrStart)+elementLen) > iListStack->Head())
			{// Error! This item is longer than the list it is in!!
			User::Leave(KErrSdpParserInvalidSizeForParentList);
			}

		TUint compositeLen = 0;
		if (IsComposite(type))
			{//Composite node. We'll parse down into it.
			compositeLen = elementLen;
			elementLen = 0;		// composites have no element length.
			}

		if((elementLen)>TUint(ptrE-ptr))return (ptrE-ptrStart);

		TPtrC8 data(ptr,elementLen);

		switch (type)
			{
		case ETypeNil:
			iBuilder=iBuilder->BuildNilL();
			break;
		case ETypeUint:
			iBuilder=iBuilder->BuildUintL(data);
			break;
		case ETypeInt:
			iBuilder=iBuilder->BuildIntL(data);
			break;
		case ETypeUUID:
			{
			TUUID uuid;
			uuid.SetL(data);
			iBuilder=iBuilder->BuildUUIDL(uuid);
			}
			break;
		case ETypeString:
			iBuilder=iBuilder->BuildStringL(data);
			break;
		case ETypeBoolean:
			iBuilder=iBuilder->BuildBooleanL(SdpUtil::GetUint(data));
			break;		
		case ETypeURL:
			iBuilder=iBuilder->BuildURLL(data);
			break;
		case ETypeDES:
			iBuilder=iBuilder->BuildDESL();
			break;
		case ETypeDEA:
			iBuilder=iBuilder->BuildDEAL();
			break;
		default:
			iBuilder=iBuilder->BuildUnknownL(type, sizedesc, data);
			break;
			};

		ptr += elementLen;


		if (!iListStack->IsEmpty())
			{// Adjust size of existing head entry so we know when the DES/DEA is finished
			iListStack->Head() -= (ptr-ptrStart)+compositeLen;
			}

		if (IsComposite(type))
			{ // push the length of the DES/DEA on top of the stack and mark the list
			iBuilder=iBuilder->StartListL();
			iListStack->PushL(compositeLen);
			}

		CloseListsL();
		}

	__ASSERT_DEBUG(ptr<=ptrE, ParsePanic(EFrameOverrun));

	return ptrE-ptr;
	}
status_t PanoramaThread::handleMessageFinalize()
{
    LOG1("@%s", __FUNCTION__);
    status_t status = NO_ERROR;

    if (mState == PANORAMA_STARTED) {
        LOG1("@%s: nothing to finalize", __FUNCTION__);
        return status;
    }

    mPanoramaStitchThread->flush();

    int checkCnt = 0;
    // ia_panorama_check_stitch_status() should always return 0, as all remained stiching
    // is processed in flush()
    while (ia_panorama_check_stitch_status(mContext) != 0 && checkCnt < STITCH_CHECK_LIMIT) {
        LOG2("Polling ia_panorama_check_stitch_status()");
        usleep(STITCH_CHECK_INTERVAL_USEC);
        ++checkCnt;
    }

    if (checkCnt == STITCH_CHECK_LIMIT) {
        LOGE("Panorama stitching error: stitch check retries exceeded");
        return UNKNOWN_ERROR;
    }

    ia_frame *pFrame = ia_panorama_finalize(mContext);
    if (!pFrame) {
        Mutex::Autolock lock(mStitchLock);

        if (mStopInProgress) {
            LOGD("ia_panorama_finalize() aborted, because of stop panorama in progress");
            return NO_ERROR;
        } else {
            LOGE("ia_panorama_finalize() failed");
            return UNKNOWN_ERROR;
        }
    }

    mPanoramaTotalCount = 0;
    mCurrentMetadata.direction = 0;
    mCurrentMetadata.motion_blur = false;
    mCurrentMetadata.horizontal_displacement = 0;
    mCurrentMetadata.vertical_displacement = 0;

    // create AtomBuffer descriptor for panorama engine memory (ia_frame)
    AtomBuffer img = AtomBufferFactory::createAtomBuffer(ATOM_BUFFER_PANORAMA);
    img.width = pFrame->width;
    img.height = pFrame->height;
    img.bpl = pFrame->stride;
    img.fourcc = V4L2_PIX_FMT_NV12;
    img.size = frameSize(V4L2_PIX_FMT_NV12, img.bpl, img.height); // because pFrame->size from panorama is currently incorrectly zero
    img.buff = NULL;
    img.owner = this;
    img.dataPtr = pFrame->data;
    // return panorama image via callback to PostProcThread, which passes it onwards

    if (mThumbnailWidth > 0 && mThumbnailHeight > 0) {
        AtomBuffer pvImg = AtomBufferFactory::createAtomBuffer(ATOM_BUFFER_POSTVIEW);
        pvImg.width = mThumbnailWidth;
        pvImg.height = mThumbnailHeight;
        pvImg.bpl = mThumbnailWidth;
        pvImg.fourcc = V4L2_PIX_FMT_NV12;
        pvImg.size = frameSize(V4L2_PIX_FMT_NV12, pvImg.bpl, pvImg.height);
        pvImg.owner = this;
        mCallbacks->allocateMemory(&pvImg, pvImg.size);
        if (pvImg.dataPtr == NULL) {
            LOGE("Failed to allocate panorama snapshot memory.");
            return NO_MEMORY;
        }

        float thumbRatio = (float) mThumbnailWidth / mThumbnailHeight;
        float imgRatio = (float) img.width / img.height;
        int startPixel = 0; // used to skip startPixel amount of left side of image
        int skipLinesTop = 0; // used to skip top of the image
        int skipLinesBottom = 0; // used to skip bottom of the image
        int srcWidth, srcHeight;

        if (imgRatio > thumbRatio) {
            fullHeightSrcForThumb(img, srcWidth, srcHeight, startPixel);
        } else if (1 / imgRatio > thumbRatio) {
            fullWidthSrcForThumb(img, srcWidth, srcHeight, skipLinesTop, skipLinesBottom);
        } else {
            // image is rather square, choose method based on which thumbnail dimension is bigger
            if (mThumbnailWidth > mThumbnailHeight) {
                fullWidthSrcForThumb(img, srcWidth, srcHeight, skipLinesTop, skipLinesBottom);
            } else {
                fullHeightSrcForThumb(img, srcWidth, srcHeight, startPixel);
            }
        }

        ImageScaler::downScaleImage(((char *)img.dataPtr) + startPixel, pvImg.dataPtr, mThumbnailWidth,
                mThumbnailHeight, mThumbnailWidth, srcWidth, srcHeight, img.bpl, V4L2_PIX_FMT_NV12,
                skipLinesTop, skipLinesBottom);

        mPanoramaCallback->panoramaFinalized(&img, &pvImg);
    } else
        mPanoramaCallback->panoramaFinalized(&img, NULL);

    if (mState == PANORAMA_DETECTING_OVERLAP || mState == PANORAMA_WAITING_FOR_SNAPSHOT)
        handleMessageStopPanoramaCapture(); // drops state to PANORAMA_STARTED

    return status;
}
Exemple #27
0
/* pvfs_bufmap_initialize()
 *
 * initializes the mapped buffer interface
 *
 * returns 0 on success, -errno on failure
 */
int pvfs_bufmap_initialize(struct PVFS_dev_map_desc *user_desc)
{
    int ret = -EINVAL;
    int i = 0;
    int offset = 0;

    gossip_debug(GOSSIP_BUFMAP_DEBUG, "pvfs_bufmap_initialize: called "
                 "(ptr (%p) sz (%d) cnt(%d).\n",
                 user_desc->ptr, user_desc->size, user_desc->count);

    down_write(&bufmap_init_sem);
    if (bufmap_init == 1)
    {
        gossip_err("pvfs2: error: bufmap already initialized.\n");
        ret = -EALREADY;
        goto init_failure;
    }

    /* sanity check alignment and size of buffer that caller wants to
     * work with
     */
    if (PAGE_ALIGN((unsigned long)user_desc->ptr) != 
        (unsigned long)user_desc->ptr)
    {
        gossip_err("pvfs2 error: memory alignment (front). %p\n",
                user_desc->ptr);
        goto init_failure;
    }

    if (PAGE_ALIGN(((unsigned long)user_desc->ptr + user_desc->total_size)) != 
        (unsigned long)(user_desc->ptr + user_desc->total_size))
    {
        gossip_err("pvfs2 error: memory alignment (back).(%p + %d)\n",
                user_desc->ptr, user_desc->total_size);
        goto init_failure;
    }

    if (user_desc->total_size != (user_desc->size * user_desc->count))
    {
        gossip_err("pvfs2 error: user provided an oddly "
                    "sized buffer...(%d, %d, %d)\n",
                    user_desc->total_size, user_desc->size, user_desc->count);
        goto init_failure;
    }

    if ((user_desc->size % PAGE_SIZE) != 0)
    {
        gossip_err("pvfs2 error: bufmap size not page size "
                    "divisible (%d).\n", user_desc->size);
        goto init_failure;
    }
    /* Initialize critical variables */
    pvfs2_bufmap_total_size = user_desc->total_size;
    pvfs2_bufmap_desc_count = user_desc->count;
    pvfs2_bufmap_desc_size  = user_desc->size;
    pvfs2_bufmap_desc_shift = LOG2(pvfs2_bufmap_desc_size);
    bufmap_page_count = pvfs2_bufmap_total_size / PAGE_SIZE;
    pages_per_desc    = pvfs2_bufmap_desc_size / PAGE_SIZE;
    /* Initialize descriptor arrays */
    if ((ret = initialize_bufmap_descriptors(pvfs2_bufmap_desc_count)) < 0)
    {
        goto init_failure;
    }

    /* allocate storage to track our page mappings */
    bufmap_page_array = kmalloc(bufmap_page_count * sizeof(*bufmap_page_array), 
                                PVFS2_BUFMAP_GFP_FLAGS);
    if (!bufmap_page_array)
    {
        ret = -ENOMEM;
        goto init_failure;
    }

    /* map the pages */
    down_write(&current->mm->mmap_sem);

    ret = get_user_pages(
        current, current->mm, (unsigned long)user_desc->ptr,
        bufmap_page_count, 1, 0, bufmap_page_array, NULL);

    up_write(&current->mm->mmap_sem);

    if (ret < 0)
    {
        kfree(bufmap_page_array);
        goto init_failure;
    }

    /*
      in theory we could run with what we got, but I will just treat
      it as an error for simplicity's sake right now
    */
    if (ret != bufmap_page_count)
    {
        gossip_err("pvfs2 error: asked for %d pages, only got %d.\n",
                    (int) bufmap_page_count, ret);

        for(i = 0; i < ret; i++)
        {
            SetPageError(bufmap_page_array[i]);
            page_cache_release(bufmap_page_array[i]);
        }
        kfree(bufmap_page_array);
        ret = -ENOMEM;
        goto init_failure;
    }

    /*
      ideally we want to get kernel space pointers for each page, but
      we can't kmap that many pages at once if highmem is being used.
      so instead, we just kmap/kunmap the page address each time the
      kaddr is needed.  this loop used to kmap every page, but now it
      only ensures every page is marked reserved (non-pageable) NOTE:
      setting PageReserved in 2.6.x seems to cause more trouble than
      it's worth.  in 2.4.x, marking the pages does what's expected
      and doesn't try to swap out our pages
    */
    for(i = 0; i < bufmap_page_count; i++)
    {
        flush_dcache_page(bufmap_page_array[i]);
        pvfs2_set_page_reserved(bufmap_page_array[i]);
    }

    /* build a list of available descriptors */
    for(offset = 0, i = 0; i < pvfs2_bufmap_desc_count; i++)
    {
        desc_array[i].page_array = &bufmap_page_array[offset];
        desc_array[i].array_count = pages_per_desc;
        desc_array[i].uaddr =
            (user_desc->ptr + (i * pages_per_desc * PAGE_SIZE));
        offset += pages_per_desc;
    }

    /* clear any previously used buffer indices */
    spin_lock(&buffer_index_lock);
    for(i = 0; i < pvfs2_bufmap_desc_count; i++)
    {
        buffer_index_array[i] = 0;
    }
    spin_unlock(&buffer_index_lock);
    spin_lock(&readdir_index_lock);
    for (i = 0; i < PVFS2_READDIR_DEFAULT_DESC_COUNT; i++)
    {
        readdir_index_array[i] = 0;
    }
    spin_unlock(&readdir_index_lock);

    bufmap_init = 1;
    up_write(&bufmap_init_sem);

    gossip_debug(GOSSIP_BUFMAP_DEBUG, "pvfs_bufmap_initialize: exiting normally\n");
    return 0;

init_failure:
    finalize_bufmap_descriptors();
    up_write(&bufmap_init_sem);
    return ret;
}
Exemple #28
0
extern THETA init_map(
  MAP_TYPE type,		/* type of mapping:
					Uni	- add n prior
					Pam	- pam matrix
				*/
  double scale,			/* degree of crispness, depends on type,
					Uni	- pseudo count n to add
					Pam	- pam distance
				*/
  int alength,			/* length of alphabet */
  double *back,			/* background frequencies for 'X' */
  BOOLEAN lo			/* setup a logodds mapping if true */
)
{
  int i, j, p;
  THETA map;			/* the map */

  /* dayhoff PAM 1 matrix; order of alphabet: ACDEFGHIKLMNPQRSTVWY */
  /* dayhoff_ij = Pr(amino acid j --> amino acid i | time=1) */
  double dayhoff[20][20] = {
    { 9867, 3, 10, 17, 2, 21, 2, 6, 2, 4, 6, 9, 22, 8, 2, 35, 32, 18, 0, 2},
    { 1, 9973, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 5, 1, 2, 0, 3},
    { 6, 0, 9859, 53, 0, 6, 4, 1, 3, 0, 0, 42, 1, 6, 0, 5, 3, 1, 0, 0},
    { 10, 0, 56, 9865, 0, 4, 2, 3, 4, 1, 1, 7, 3, 35, 0, 4, 2, 2, 0, 1},
    { 1, 0, 0, 0, 9946, 1, 2, 8, 0, 6, 4, 1, 0, 0, 1, 2, 1, 0, 3, 28},
    { 21, 1, 11, 7, 1, 9935, 1, 0, 2, 1, 1, 12, 3, 3, 1, 21, 3, 5, 0, 0},
    { 1, 1, 3, 1, 2, 0, 9912, 0, 1, 1, 0, 18, 3, 20, 8, 1, 1, 1, 1, 4},
    { 2, 2, 1, 2, 7, 0, 0, 9872, 2, 9, 12, 3, 0, 1, 2, 1, 7, 33, 0, 1},
    { 2, 0, 6, 7, 0, 2, 2, 4, 9926, 1, 20, 25, 3, 12, 37, 8, 11, 1, 0, 1},
    { 3, 0, 0, 1, 13, 1, 4, 22, 2, 9947, 45, 3, 3, 6, 1, 1, 3, 15, 4, 2},
    { 1, 0, 0, 0, 1, 0, 0, 5, 4, 8, 9874, 0, 0, 2, 1, 1, 2, 4, 0, 0},
    { 4, 0, 36, 6, 1, 6, 21, 3, 13, 1, 0, 9822, 2, 4, 1, 20, 9, 1, 1, 4},
    { 13, 1, 1, 3, 1, 2, 5, 1, 2, 2, 1, 2, 9926, 8, 5, 12, 4, 2, 0, 0},
    { 3, 0, 5, 27, 0, 1, 23, 1, 6, 3, 4, 4, 6, 9876, 9, 2, 2, 1, 0, 0},
    { 1, 1, 0, 0, 1, 0, 10, 3, 19, 1, 4, 1, 4, 10, 9913, 6, 1, 1, 8, 0},
    { 28, 11, 7, 6, 3, 16, 2, 2, 7, 1, 4, 34, 17, 4, 11, 9840, 38, 2, 5, 2},
    { 22, 1, 4, 2, 1, 2, 1, 11, 8, 2, 6, 13, 5, 3, 2, 32, 9871, 9, 0, 2},
    { 13, 3, 1, 2, 1, 3, 3, 57, 1, 11, 17, 1, 3, 2, 2, 2, 10, 9901, 0, 2},
    { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 9976, 1},
    { 1, 3, 0, 1, 21, 0, 4, 1, 0, 1, 0, 3, 0, 0, 0, 1, 1, 1, 2, 9945}
  };

  /* transition/transversion PAM 1 matrix; alphabet order "ACGT" */
  double trans[4][4] = {
    { 9900, 20, 60, 20}, 
    { 20, 9900, 20, 60},
    { 60, 20, 9900, 20},
    { 20, 60, 20, 9900}
  };

  /* special PAM mutation frequencies for proteins */
  double pam_dna_freq[] = { 
      0.25 /* A */,
      0.25 /* C */,
      0.25 /* G */,
      0.25 /* T */
  };

  /* special PAM mutation frequencies for proteins */
  double pam_prot_freq[] = { 
      0.096 /* A */,
      0.025 /* C */,
      0.053 /* D */,
      0.053 /* E */,
      0.045 /* F */,
      0.090 /* G */,
      0.034 /* H */,
      0.035 /* I */,
      0.085 /* K */,
      0.085 /* L */,
      0.012 /* M */,
      0.042 /* N */,
      0.041 /* P */,
      0.032 /* Q */,
      0.034 /* R */,
      0.057 /* S */,
      0.062 /* T */,
      0.078 /* V */,
      0.012 /* W */,
      0.030 /* Y */,
      0.0   /* X */
  };

  /* create the array for the sequence to theta map */
  create_2array(map, double, alength+1, alength+1);

  switch (type) {
    case Uni: {
      double main_letter;	/* probability of main letter */
      double other;		/* probability of each other letter */

      main_letter = (1.0 + scale)/(1.0 + alength * scale);
      other = scale/(1.0 + alength * scale);
      if (VERBOSE) {printf("main= %g\n\n", main_letter);}
      /* create a matrix of columns; each column gives mapping for a letter */
      for (i=0; i<alength; i++) 
	for (j=0; j<alength; j++)  
	  map[i][j] = (i == j) ? main_letter : other;
    } break;
    case Pam: {
      double mul[20][20]; 

      /* convert initial matrix to probabilities */ 
      for (i=0; i<alength; i++)
	for (j=0; j<alength; j++)
          map[i][j] = ((alength == 4) ? trans[i][j] : dayhoff[i][j]) / 10000;

      /* take pam matrix to desired power */ 

      /* copy: */
      for (i = 0; i < alength; i++)
	for (j = 0; j < alength; j++)
	  mul[i][j] = map[i][j];

      /* multiply: */
      while (--scale) {
        double result[20][20], sum;
	for (i = 0; i < alength; i++) {
	  for (j = 0; j < alength; j++) {
            for (sum = p = 0; p < alength; p++) {
              sum += mul[i][p] * map[p][j];
            }
            result[i][j] = sum;
          }
        }

        for (j = 0; j < alength; j++) {
          for (i = 0; i < alength; i++) {
            /*map[i][j] = result[i][j];*/
            RND(result[i][j], 8, map[i][j]);
          }
        }
      }
    }
  }

  /* add last row and column for mapping from the wildcard 'X' */
  for (i=0; i<alength; i++) map[alength][i] = map[i][alength] = back[i];

  /* convert to logodds matrix if requested */
  if (lo) {
    double *pfreq = alength==4 ? pam_dna_freq : pam_prot_freq;
    double avg, x_avg;

    for (i=0; i<alength; i++) {
      for (j=0; j<=i; j++) {
        map[i][j] = map[j][i] = NINT(2*LOG2(map[i][j]/pfreq[i]));
      }
    }

    /* do the last row and column for "X" matches: average of match to all chars */
    x_avg = 0;						/* average for X row */
    for (i=0; i<alength; i++) {
      avg = 0;						/* average for row */
      for (j=0; j<alength; j++) {
        avg += map[i][j];
      }
      x_avg += avg/alength;
      map[i][alength] = map[alength][i] = NINT(avg/alength);
    }
    map[alength][alength] = NINT(x_avg/alength);
#ifdef DEBUG
    for (i=0; i<=alength; i++) {
      for (j=0; j<=alength; j++) {
        printf("%3g ", map[i][j]);
      }
      printf("\n");
    }
#endif
  } /* lo */

  return map;
} /* init_map */
int CameraDump::dumpImage2File(camera_delay_dumpImage_T *aDumpImage, const char *name)
{
    LOG1("@%s", __FUNCTION__);
    void *data = aDumpImage->buffer_raw;
    unsigned int size = aDumpImage->buffer_size;
    unsigned int width = aDumpImage->width;
    unsigned int height = aDumpImage->height;
    unsigned int bpl = aDumpImage->bpl;
    char filename[80];
    static unsigned int count = 0;
    size_t bytes;
    FILE *fp;
    ia_binary_data *uMknData = NULL;
    char rawdpp[100];
    int ret;

    if ((NULL == data) || (0 == size) || (0 == width) || (0 == height) || (NULL == name)
            || (NULL == m3AControls))
        return -ERR_D2F_EVALUE;

    LOG2("%s filename is %s", __func__, name);
    /* media server may not have the access to SD card */
    showMediaServerGroup();

    ret = getRawDataPath(rawdpp);
    LOG2("RawDataPath is %s", rawdpp);
    if(-ERR_D2F_NOPATH == ret) {
        ALOGE("%s No valid mem for rawdata", __func__);
        return ret;
    }
    if ((strcmp(name, "raw.bayer") == 0) && (m3AControls != NULL))
    {
        /* Only RAW image will have same file name as JPEG */
        char filesuffix[20];
        time_t rawtime;
        struct tm *timeinfo;
        time(&rawtime);
        timeinfo = localtime(&rawtime);

        if (timeinfo) {
            strftime((char *)filename, sizeof(filename) - sizeof(filesuffix), "IMG_%Y%m%d_%H%M%S", timeinfo);
        } else {
            snprintf((char *)filename, sizeof(filename) - sizeof(filesuffix), "IMG_%s", "notime");
        }

        snprintf(filesuffix, sizeof(filesuffix), "%03u.i3av4", count);
        strncat(filename, filesuffix, sizeof(filename) - strlen(filename) - 1);
        strncat(rawdpp, filename, strlen(filename));

        ia_aiq_raw_image_full_info raw_info;
        raw_info.raw_image.data_format = ia_aiq_data_format_rawplain16;
        raw_info.raw_image.bayer_order = ia_aiq_bayer_order_grbg;
        raw_info.raw_image.data_format_bpp = 16;
        raw_info.raw_image.data_bpp = 10;
        raw_info.raw_image.width_cols = bytesToPixels(V4L2_PIX_FMT_SBGGR10, bpl);
        raw_info.raw_image.height_lines = height;
        raw_info.header_size_bytes = 0;
        raw_info.footer_size_bytes = 0;
        raw_info.extra_bytes_left = 0;
        raw_info.extra_bytes_right = 0;
        raw_info.extra_lines_top = 0;
        raw_info.extra_cols_left = 0;
        raw_info.extra_cols_right = 0;
        raw_info.extra_lines_bottom = 0;
        raw_info.byte_order_xor = 0;
        raw_info.spatial_sampling = 0;

        // Add raw image info to the maker note.
        m3AControls->add3aMakerNoteRecord(ia_mkn_dfid_unsigned_char, ia_mkn_dnid_hal_records, &raw_info, sizeof(ia_aiq_raw_image_full_info));

        // Get detailed maker note data
        uMknData = m3AControls->get3aMakerNote(ia_mkn_trg_section_2);
        if (uMknData) {
            ALOGD("RAW, mknSize: %d", uMknData->size);
        } else {
            ALOGW("RAW, no makernote");
        }
    }
    else
    {
        snprintf(filename, sizeof(filename), "dump_%d_%d_%03u_%s", width,
                 height, count, name);
        strncat(rawdpp, filename, strlen(filename));
    }

    fp = fopen (rawdpp, "w+");
    if (fp == NULL) {
        ALOGE("open file %s failed %s", rawdpp, strerror(errno));
        if (uMknData) {
            // Delete Maker note data
            m3AControls->put3aMakerNote(uMknData);
        }
        return -ERR_D2F_EOPEN;
    }

    LOG1("Begin write image %s", filename);

    if (uMknData && uMknData->size > 0)
    {
        if ((bytes = fwrite(uMknData->data, uMknData->size, 1, fp)) < (size_t)uMknData->size)
            ALOGW("Write less mkn bytes to %s: %d, %d", filename, uMknData->size, bytes);
    }

    if ((bytes = fwrite(data, size, 1, fp)) < (size_t)size)
        ALOGW("Write less raw bytes to %s: %d, %d", filename, size, bytes);

    count++;

    if (uMknData)
    {
        // Delete Maker note data
        m3AControls->put3aMakerNote(uMknData);
    }

    fclose (fp);

    return ERR_D2F_SUCESS;
}
Exemple #30
0
int PacketHandler::change_sign(User* user)
{
  if (!user->buffer.haveData(16))
  {
    return PACKET_NEED_MORE_DATA;
  }
  int32_t x, z;
  int16_t y;
  std::string strings1, strings2, strings3, strings4;

  user->buffer >> x >> y >> z;

  if (!user->buffer.haveData(8))
  {
    return PACKET_NEED_MORE_DATA;
  }
  user->buffer >> strings1;
  if (!user->buffer.haveData(6))
  {
    return PACKET_NEED_MORE_DATA;
  }
  user->buffer >> strings2;
  if (!user->buffer.haveData(4))
  {
    return PACKET_NEED_MORE_DATA;
  }
  user->buffer >> strings3;
  if (!user->buffer.haveData(2))
  {
    return PACKET_NEED_MORE_DATA;
  }
  user->buffer >> strings4;

  //ToDo: Save signs!
  signDataPtr newSign(new signData);
  newSign->x = x;
  newSign->y = y;
  newSign->z = z;
  newSign->text1 = strings1;
  newSign->text2 = strings2;
  newSign->text3 = strings3;
  newSign->text4 = strings4;

  sChunk* chunk = ServerInstance->map(user->pos.map)->getChunk(blockToChunk(x), blockToChunk(z));

  if (chunk != NULL)
  {
    //Check if this sign data already exists and remove
    chunk->signs.erase(std::remove_if(chunk->signs.begin(), chunk->signs.end(), DataFinder<signData>(x,y,z)), chunk->signs.end());

    // Insert new sign
    chunk->signs.push_back(newSign);

    //Send sign packet to everyone
    Packet pkt;
    pkt << (int8_t)PACKET_SIGN << x << y << z;
    pkt << strings1 << strings2 << strings3 << strings4;
    user->sendAll(pkt);
  }

  LOG2(INFO, "Sign: " + strings1 + strings2 + strings3 + strings4);

  //No need to do anything
  user->buffer.removePacket();
  return PACKET_OK;
}