Beispiel #1
1
void ServerLink::Send(Game::Property::Stream properties) {
	Packet::Packet packet
      { Packet::Type::kProperties, uint8_t(server_slot_), properties.Packed() };
  data_.Push(packet.Packed());
}
Beispiel #2
1
Entry* probe(const Position& pos) {

  Key key = pos.material_key();
  Entry* e = pos.this_thread()->materialTable[key];

  if (e->key == key)
      return e;

  std::memset(e, 0, sizeof(Entry));
  e->key = key;
  e->factor[WHITE] = e->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL;
  e->gamePhase = pos.game_phase();

  // Let's look if we have a specialized evaluation function for this particular
  // material configuration. Firstly we look for a fixed configuration one, then
  // for a generic one if the previous search failed.
  if ((e->evaluationFunction = pos.this_thread()->endgames.probe<Value>(key)) != nullptr)
      return e;

  for (Color c = WHITE; c <= BLACK; ++c)
      if (is_KXK(pos, c))
      {
          e->evaluationFunction = &EvaluateKXK[c];
          return e;
      }

  // OK, we didn't find any special evaluation function for the current material
  // configuration. Is there a suitable specialized scaling function?
  EndgameBase<ScaleFactor>* sf;

  if ((sf = pos.this_thread()->endgames.probe<ScaleFactor>(key)) != nullptr)
  {
      e->scalingFunction[sf->strong_side()] = sf; // Only strong color assigned
      return e;
  }

  // We didn't find any specialized scaling function, so fall back on generic
  // ones that refer to more than one material distribution. Note that in this
  // case we don't return after setting the function.
  for (Color c = WHITE; c <= BLACK; ++c)
  {
    if (is_KBPsKs(pos, c))
        e->scalingFunction[c] = &ScaleKBPsK[c];

    else if (is_KQKRPs(pos, c))
        e->scalingFunction[c] = &ScaleKQKRPs[c];
  }

  Value npm_w = pos.non_pawn_material(WHITE);
  Value npm_b = pos.non_pawn_material(BLACK);

  if (npm_w + npm_b == VALUE_ZERO && pos.pieces(PAWN)) // Only pawns on the board
  {
      if (!pos.count<PAWN>(BLACK))
      {
          assert(pos.count<PAWN>(WHITE) >= 2);

          e->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
      }
      else if (!pos.count<PAWN>(WHITE))
      {
          assert(pos.count<PAWN>(BLACK) >= 2);

          e->scalingFunction[BLACK] = &ScaleKPsK[BLACK];
      }
      else if (pos.count<PAWN>(WHITE) == 1 && pos.count<PAWN>(BLACK) == 1)
      {
          // This is a special case because we set scaling functions
          // for both colors instead of only one.
          e->scalingFunction[WHITE] = &ScaleKPKP[WHITE];
          e->scalingFunction[BLACK] = &ScaleKPKP[BLACK];
      }
  }

  // Zero or just one pawn makes it difficult to win, even with a small material
  // advantage. This catches some trivial draws like KK, KBK and KNK and gives a
  // drawish scale factor for cases such as KRKBP and KmmKm (except for KBBKN).
  if (!pos.count<PAWN>(WHITE) && npm_w - npm_b <= BishopValueMg)
      e->factor[WHITE] = uint8_t(npm_w <  RookValueMg   ? SCALE_FACTOR_DRAW :
                                 npm_b <= BishopValueMg ? 4 : 14);

  if (!pos.count<PAWN>(BLACK) && npm_b - npm_w <= BishopValueMg)
      e->factor[BLACK] = uint8_t(npm_b <  RookValueMg   ? SCALE_FACTOR_DRAW :
                                 npm_w <= BishopValueMg ? 4 : 14);

  if (pos.count<PAWN>(WHITE) == 1 && npm_w - npm_b <= BishopValueMg)
      e->factor[WHITE] = (uint8_t) SCALE_FACTOR_ONEPAWN;

  if (pos.count<PAWN>(BLACK) == 1 && npm_b - npm_w <= BishopValueMg)
      e->factor[BLACK] = (uint8_t) SCALE_FACTOR_ONEPAWN;

  // Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
  // for the bishop pair "extended piece", which allows us to be more flexible
  // in defining bishop pair bonuses.
  const int PieceCount[COLOR_NB][PIECE_TYPE_NB] = {
  { pos.count<BISHOP>(WHITE) > 1, pos.count<PAWN>(WHITE), pos.count<KNIGHT>(WHITE),
    pos.count<BISHOP>(WHITE)    , pos.count<ROOK>(WHITE), pos.count<QUEEN >(WHITE) },
  { pos.count<BISHOP>(BLACK) > 1, pos.count<PAWN>(BLACK), pos.count<KNIGHT>(BLACK),
    pos.count<BISHOP>(BLACK)    , pos.count<ROOK>(BLACK), pos.count<QUEEN >(BLACK) } };

  e->value = int16_t((imbalance<WHITE>(PieceCount) - imbalance<BLACK>(PieceCount)) / 16);
  return e;
}
Beispiel #3
1
 void DevicePool_c::calcChecksumAdd( const char* str ) {
   const size_t l = CNAMESPACE::strlen( str );
   calcChecksumAdd( uint8_t( l ) );
   calcChecksumAdd( ( const uint8_t* )str, l );
 }
std::string term_clear() 
{
    std::ostringstream oss;
    oss << uint8_t(0x1b) << "[2J";
    return oss.str();
}
Beispiel #5
0
Entry* probe(const Position& pos, Table& entries, Endgames& endgames) {

  Key key = pos.material_key();
  Entry* e = entries[key];

  // If e->key matches the position's material hash key, it means that we
  // have analysed this material configuration before, and we can simply
  // return the information we found the last time instead of recomputing it.
  if (e->key == key)
      return e;

  std::memset(e, 0, sizeof(Entry));
  e->key = key;
  e->factor[WHITE] = e->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL;
  e->gamePhase = game_phase(pos);

  // Let's look if we have a specialized evaluation function for this particular
  // material configuration. Firstly we look for a fixed configuration one, then
  // for a generic one if the previous search failed.
  if (endgames.probe(key, e->evaluationFunction))
      return e;

  if (is_KXK<WHITE>(pos))
  {
      e->evaluationFunction = &EvaluateKXK[WHITE];
      return e;
  }

  if (is_KXK<BLACK>(pos))
  {
      e->evaluationFunction = &EvaluateKXK[BLACK];
      return e;
  }

  // OK, we didn't find any special evaluation function for the current
  // material configuration. Is there a suitable scaling function?
  //
  // We face problems when there are several conflicting applicable
  // scaling functions and we need to decide which one to use.
  EndgameBase<ScaleFactor>* sf;

  if (endgames.probe(key, sf))
  {
      e->scalingFunction[sf->color()] = sf;
      return e;
  }

  // Generic scaling functions that refer to more than one material
  // distribution. They should be probed after the specialized ones.
  // Note that these ones don't return after setting the function.
  if (is_KBPsKs<WHITE>(pos))
      e->scalingFunction[WHITE] = &ScaleKBPsK[WHITE];

  if (is_KBPsKs<BLACK>(pos))
      e->scalingFunction[BLACK] = &ScaleKBPsK[BLACK];

  if (is_KQKRPs<WHITE>(pos))
      e->scalingFunction[WHITE] = &ScaleKQKRPs[WHITE];

  else if (is_KQKRPs<BLACK>(pos))
      e->scalingFunction[BLACK] = &ScaleKQKRPs[BLACK];

  Value npm_w = pos.non_pawn_material(WHITE);
  Value npm_b = pos.non_pawn_material(BLACK);

  if (npm_w + npm_b == VALUE_ZERO && pos.pieces(PAWN))
  {
      if (!pos.count<PAWN>(BLACK))
      {
          assert(pos.count<PAWN>(WHITE) >= 2);
          e->scalingFunction[WHITE] = &ScaleKPsK[WHITE];
      }
      else if (!pos.count<PAWN>(WHITE))
      {
          assert(pos.count<PAWN>(BLACK) >= 2);
          e->scalingFunction[BLACK] = &ScaleKPsK[BLACK];
      }
      else if (pos.count<PAWN>(WHITE) == 1 && pos.count<PAWN>(BLACK) == 1)
      {
          // This is a special case because we set scaling functions
          // for both colors instead of only one.
          e->scalingFunction[WHITE] = &ScaleKPKP[WHITE];
          e->scalingFunction[BLACK] = &ScaleKPKP[BLACK];
      }
  }

  // No pawns makes it difficult to win, even with a material advantage. This
  // catches some trivial draws like KK, KBK and KNK and gives a very drawish
  // scale factor for cases such as KRKBP and KmmKm (except for KBBKN).
  if (!pos.count<PAWN>(WHITE) && npm_w - npm_b <= BishopValueMg)
      e->factor[WHITE] = uint8_t(npm_w < RookValueMg ? SCALE_FACTOR_DRAW : npm_b <= BishopValueMg ? 4 : 12);

  if (!pos.count<PAWN>(BLACK) && npm_b - npm_w <= BishopValueMg)
      e->factor[BLACK] = uint8_t(npm_b < RookValueMg ? SCALE_FACTOR_DRAW : npm_w <= BishopValueMg ? 4 : 12);

  if (pos.count<PAWN>(WHITE) == 1 && npm_w - npm_b <= BishopValueMg)
      e->factor[WHITE] = (uint8_t) SCALE_FACTOR_ONEPAWN;

  if (pos.count<PAWN>(BLACK) == 1 && npm_b - npm_w <= BishopValueMg)
      e->factor[BLACK] = (uint8_t) SCALE_FACTOR_ONEPAWN;

  // Compute the space weight
  if (npm_w + npm_b >= 2 * QueenValueMg + 4 * RookValueMg + 2 * KnightValueMg)
  {
      int minorPieceCount =  pos.count<KNIGHT>(WHITE) + pos.count<BISHOP>(WHITE)
                           + pos.count<KNIGHT>(BLACK) + pos.count<BISHOP>(BLACK);

      e->spaceWeight = make_score(minorPieceCount * minorPieceCount, 0);
  }

  // Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
  // for the bishop pair "extended piece", which allows us to be more flexible
  // in defining bishop pair bonuses.
  const int pieceCount[COLOR_NB][PIECE_TYPE_NB] = {
  { pos.count<BISHOP>(WHITE) > 1, pos.count<PAWN>(WHITE), pos.count<KNIGHT>(WHITE),
    pos.count<BISHOP>(WHITE)    , pos.count<ROOK>(WHITE), pos.count<QUEEN >(WHITE) },
  { pos.count<BISHOP>(BLACK) > 1, pos.count<PAWN>(BLACK), pos.count<KNIGHT>(BLACK),
    pos.count<BISHOP>(BLACK)    , pos.count<ROOK>(BLACK), pos.count<QUEEN >(BLACK) } };

  e->value = (int16_t)((imbalance<WHITE>(pieceCount) - imbalance<BLACK>(pieceCount)) / 16);
  return e;
}
void RageSurfaceUtils::ErrorDiffusionDither( const RageSurface *src, RageSurface *dst )
{
	// We can't dither to paletted surfaces.
	ASSERT( dst->format->BytesPerPixel > 1 );

	uint32_t src_cbits[4], dst_cbits[4];
	RageSurfaceUtils::GetBitsPerChannel( src->format, src_cbits );
	RageSurfaceUtils::GetBitsPerChannel( dst->format, dst_cbits );

	// Calculate the ratio from the old bit depth to the new for each color channel.
	int conv[4];
	for( int i = 0; i < 4; ++i )
	{
		int MaxInputIntensity = (1 << src_cbits[i])-1;
		int MaxOutputIntensity = (1 << dst_cbits[i])-1;
		// If the source is missing the channel, avoid div/0.
		if( MaxInputIntensity == 0 )
			conv[i] = 0;
		else
			conv[i] = MaxOutputIntensity * 65536 / MaxInputIntensity;
	}

	// Max alpha value; used when there's no alpha source.
	const uint8_t alpha_max = uint8_t((1 << dst_cbits[3]) - 1);

	// For each row:
	for(int row = 0; row < src->h; ++row) 
	{
		int32_t accumError[4] = { 0, 0, 0, 0 }; // accum error values are reset every row

		const uint8_t *srcp = src->pixels + row * src->pitch;
		uint8_t *dstp = dst->pixels + row * dst->pitch;

		// For each pixel in row:
		for( int col = 0; col < src->w; ++col )
		{
			uint8_t colors[4];
			RageSurfaceUtils::GetRawRGBAV( srcp, src->fmt, colors );

			for( int c = 0; c < 3; ++c )
			{
				colors[c] = EDDitherPixel( col, row, colors[c], conv[c], accumError[c] );
			}

			/* If the source has no alpha, the conversion formula will end up
			 * with 0; that's fine for color channels, but for alpha we need to
			 * be opaque. */
			if( src_cbits[3] == 0 )
			{
				colors[3] = alpha_max;
			} else {
				/* Same as DitherPixel, except it doesn't actually dither;
				 * dithering looks bad on the alpha channel. */
				int out_intensity = colors[3] * conv[3];

				// Round:
				colors[3] = uint8_t((out_intensity + 32767) >> 16);
			}

			RageSurfaceUtils::SetRawRGBAV( dstp, dst, colors );

			srcp += src->format->BytesPerPixel;
			dstp += dst->format->BytesPerPixel;
		}
	}
}
/**
 *  Write to the I2C device.
 *
 *  Returns: An error code.
 */
uint8_t Max6651ClosedLoop::write(Register command, uint8_t data) const {
  return i2c_->write(address_, uint8_t(command), data);
}
Beispiel #8
0
void DS2433::duty(OneWireHub * const hub)
{
    constexpr uint8_t ALTERNATE_01 { 0b10101010 };

    static uint16_t reg_TA { 0 }; // contains TA1, TA2 (Target Address)
    static uint8_t  reg_ES { 31 };  // E/S register

    uint8_t  data, cmd;
    uint16_t crc { 0 };

    if (hub->recv(&cmd,1,crc))  return;

    switch (cmd)
    {
        case 0x0F:      // WRITE SCRATCHPAD COMMAND

            if (hub->recv(reinterpret_cast<uint8_t *>(&reg_TA),2,crc)) return;
            reg_TA &= MEM_MASK; // make sure to stay in boundary
            reg_ES = uint8_t(reg_TA) & PAGE_MASK; // register-offset

            // receive up to 8 bytes of data
            for (; reg_ES < PAGE_SIZE; ++reg_ES)
            {
                if (hub->recv(&scratchpad[reg_ES], 1, crc))
                {
                    if (hub->getError() == Error::AWAIT_TIMESLOT_TIMEOUT_HIGH) reg_ES |= REG_ES_PF_MASK;
                    break;
                }
            }
            reg_ES--;
            reg_ES &= PAGE_MASK;

            if (hub->getError() == Error::NO_ERROR)  // try to send crc if wanted
            {
                crc = ~crc; // normally crc16 is sent ~inverted
                hub->send(reinterpret_cast<uint8_t *>(&crc), 2);
            }
            break;

        case 0x55:      // COPY SCRATCHPAD

            if (hub->recv(&data)) return; // TA1
            if (data != reinterpret_cast<uint8_t *>(&reg_TA)[0]) return;
            if (hub->recv(&data)) return;  // TA2
            if (data != reinterpret_cast<uint8_t *>(&reg_TA)[1]) return;
            if (hub->recv(&data)) return;  // ES
            if (data != reg_ES) return;

            if ((reg_ES & REG_ES_PF_MASK) != 0)                  break; // stop if error occured earlier

            reg_ES |= REG_ES_AA_MASK; // compare was successful

            {    // Write Scratchpad to memory, writing takes about 5ms
                const uint8_t start  = uint8_t(reg_TA) & PAGE_MASK;
                const uint8_t length = (reg_ES & PAGE_MASK)+ uint8_t(1) - start;
                writeMemory(&scratchpad[start], length, reg_TA);
            }

            noInterrupts();

            do
            {
                hub->clearError();
                hub->sendBit(true); // send passive 1s
            }
            while   (hub->getError() == Error::AWAIT_TIMESLOT_TIMEOUT_HIGH); // wait for timeslots

            interrupts();

            while (!hub->send(&ALTERNATE_01)); // send alternating 1 & 0 after copy is complete
            break;

        case 0xAA:      // READ SCRATCHPAD COMMAND

            if (hub->send(reinterpret_cast<uint8_t *>(&reg_TA),2))  return;
            if (hub->send(&reg_ES,1)) return;

            {   // send Scratchpad content
                const uint8_t start  = uint8_t(reg_TA) & PAGE_MASK;
                const uint8_t length = PAGE_SIZE - start;
                if (hub->send(&scratchpad[start],length))   return;
            }
            return; // datasheed says we should send all 1s, till reset (1s are passive... so nothing to do here)

        case 0xF0:      // READ MEMORY

            if (hub->recv(reinterpret_cast<uint8_t *>(&reg_TA),2)) return;

            for (uint16_t i = reg_TA; i < MEM_SIZE; i+=PAGE_SIZE) // model of the 32byte scratchpad
            {
                if (hub->send(&memory[i],PAGE_SIZE)) return;
            }
            return; // datasheed says we should send all 1s, till reset (1s are passive... so nothing to do here)

        default:

            hub->raiseSlaveError(cmd);
    }
}
Beispiel #9
0
 inline void pack( Stream& s, const variant& v )
 {
    pack( s, uint8_t(v.get_type()) );
    v.visit( variant_packer<Stream>(s) );
 }
static void
IncrementMutationCount(uint8_t* aCount)
{
    *aCount = uint8_t(std::min(0xFF, *aCount + 1));
}
Beispiel #11
0
///
/// @brief Configure the ARR0 of the CCS instruction for mrs05, data object as input
/// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] i_data an mrs05_data object, filled in
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs05(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                        const mrs05_data& i_data,
                        ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
                        const uint64_t i_rank)
{
    constexpr uint64_t CA_PARITY_LATENCY_LENGTH = 3;
    constexpr uint64_t CA_PARITY_LATENCY_START = 7;
    constexpr uint64_t RTT_PARK_LENGTH = 3;
    constexpr uint64_t RTT_PARK_START = 7;

    constexpr uint64_t CA_PARITY_COUNT = 9;
    //                                                             0                4      5      6         8
    constexpr uint8_t ca_parity_latency_map[CA_PARITY_COUNT] = { 0b000, 0, 0, 0, 0b001, 0b010, 0b011, 0, 0b100 };

    fapi2::buffer<uint8_t> l_ca_parity_latency_buffer;

    fapi2::buffer<uint8_t> l_rtt_park_buffer = i_data.iv_rtt_park[mss::index(i_rank)];

    //check here to make sure the rank indexes correctly into the attribute array
    FAPI_ASSERT( (mss::index(i_rank) < MAX_RANK_PER_DIMM),
                 fapi2::MSS_BAD_MR_PARAMETER()
                 .set_MR_NUMBER(5)
                 .set_PARAMETER(RANK)
                 .set_PARAMETER_VALUE(i_rank)
                 .set_DIMM_IN_ERROR(i_target),
                 "Bad value for RTT park: %d (%s)", i_rank, mss::c_str(i_target));

    FAPI_ASSERT( (i_data.iv_ca_parity_latency < CA_PARITY_COUNT),
                 fapi2::MSS_BAD_MR_PARAMETER()
                 .set_MR_NUMBER(5)
                 .set_PARAMETER(CA_PARITY_LATENCY)
                 .set_PARAMETER_VALUE(i_data.iv_ca_parity_latency)
                 .set_DIMM_IN_ERROR(i_target),
                 "Bad value for CA parity latency: %d (%s)", i_data.iv_ca_parity_latency, mss::c_str(i_target));

    l_ca_parity_latency_buffer = ca_parity_latency_map[i_data.iv_ca_parity_latency];

    FAPI_INF("%s MR5 rank %d attributes: CAPL: 0x%x(0x%x), CRC_EC: 0x%x, CA_PES: 0x%x, ODT_IB: 0x%x "
             "RTT_PARK: 0x%x, CAP: 0x%x, DM: 0x%x, WDBI: 0x%x, RDBI: 0x%x",
             mss::c_str(i_target), i_rank, i_data.iv_ca_parity_latency, uint8_t(l_ca_parity_latency_buffer),
             i_data.iv_crc_error_clear, i_data.iv_ca_parity_error_status, i_data.iv_odt_input_buffer,
             uint8_t(l_rtt_park_buffer), i_data.iv_ca_parity,
             i_data.iv_data_mask, i_data.iv_write_dbi, i_data.iv_read_dbi);

    mss::swizzle<A0, CA_PARITY_LATENCY_LENGTH, CA_PARITY_LATENCY_START>(l_ca_parity_latency_buffer, io_inst.arr0);
    io_inst.arr0.writeBit<A3>(i_data.iv_crc_error_clear);
    io_inst.arr0.writeBit<A4>(i_data.iv_ca_parity_error_status);
    io_inst.arr0.writeBit<A5>(i_data.iv_odt_input_buffer);
    mss::swizzle<A6, RTT_PARK_LENGTH, RTT_PARK_START>(l_rtt_park_buffer, io_inst.arr0);
    io_inst.arr0.writeBit<A9>(i_data.iv_ca_parity);
    io_inst.arr0.writeBit<A10>(i_data.iv_data_mask);
    io_inst.arr0.writeBit<A11>(i_data.iv_write_dbi);
    io_inst.arr0.writeBit<A12>(i_data.iv_read_dbi);

    FAPI_INF("%s MR5: 0x%016llx", mss::c_str(i_target), uint64_t(io_inst.arr0));

    return fapi2::FAPI2_RC_SUCCESS;

fapi_try_exit:
    return fapi2::current_err;
}
Beispiel #12
0
ArgType immType(const Op opcode, int idx) {
  assert(isValidOpcode(opcode));
  assert(idx >= 0 && idx < numImmediates(opcode));
  always_assert(idx < 4); // No opcodes have more than four immediates
  static const int8_t arg0Types[] = {
#define NA -1,
#define ONE(a) a,
#define TWO(a, b) a,
#define THREE(a, b, c) a,
#define FOUR(a, b, c, d) a,
#define O(name, imm, unusedPop, unusedPush, unusedFlags) imm
    OPCODES
// re-using definition of O below.
#undef NA
#undef ONE
#undef TWO
#undef THREE
#undef FOUR
  };
  static const int8_t arg1Types[] = {
#define NA -1,
#define ONE(a) -1,
#define TWO(a, b) b,
#define THREE(a, b, c) b,
#define FOUR(a, b, c, d) b,
    OPCODES
// re-using definition of O below.
#undef NA
#undef ONE
#undef TWO
#undef THREE
#undef FOUR
  };
  static const int8_t arg2Types[] = {
#define NA -1,
#define ONE(a) -1,
#define TWO(a, b) -1,
#define THREE(a, b, c) c,
#define FOUR(a, b, c, d) c,
    OPCODES
#undef NA
#undef ONE
#undef TWO
#undef THREE
#undef FOUR
  };
  static const int8_t arg3Types[] = {
#define NA -1,
#define ONE(a) -1,
#define TWO(a, b) -1,
#define THREE(a, b, c) -1,
#define FOUR(a, b, c, d) d,
    OPCODES
#undef O
#undef NA
#undef ONE
#undef TWO
#undef THREE
#undef FOUR
  };
  auto opInt = uint8_t(opcode);
  switch (idx) {
    case 0: return (ArgType)arg0Types[opInt];
    case 1: return (ArgType)arg1Types[opInt];
    case 2: return (ArgType)arg2Types[opInt];
    case 3: return (ArgType)arg3Types[opInt];
    default: assert(false); return (ArgType)-1;
  }
}
Beispiel #13
0
Offset* instrJumpOffset(Op* instr) {
  static const int8_t jumpMask[] = {
#define NA 0
#define MA 0
#define IVA 0
#define I64A 0
#define DA 0
#define SA 0
#define AA 0
#define BA 1
#define LA 0
#define IA 0
#define OA 0
#define ONE(a) a
#define TWO(a, b) (a + 2 * b)
#define THREE(a, b, c) (a + 2 * b + 4 * c)
#define FOUR(a, b, c, d) (a + 2 * b + 4 * c + 8 * d)
#define O(name, imm, pop, push, flags) imm,
    OPCODES
#undef NA
#undef MA
#undef IVA
#undef I64A
#undef DA
#undef SA
#undef AA
#undef LA
#undef IA
#undef BA
#undef OA
#undef ONE
#undef TWO
#undef THREE
#undef FOUR
#undef O
  };

  assert(!isSwitch(*instr));

  if (Op(*instr) == OpIterBreak) {
    uint32_t veclen = *(uint32_t *)(instr + 1);
    assert(veclen > 0);
    Offset* target  = (Offset *)((uint32_t *)(instr + 1) + 2 * veclen + 1);
    return target;
  }

  int mask = jumpMask[uint8_t(*instr)];
  if (mask == 0) {
    return nullptr;
  }
  int immNum;
  switch (mask) {
    case 0: return nullptr;
    case 1: immNum = 0; break;
    case 2: immNum = 1; break;
    case 4: immNum = 2; break;
    case 8: immNum = 3; break;
    default: assert(false); return nullptr;
  }

  return &getImmPtr(instr, immNum)->u_BA;
}
Beispiel #14
0
void ServerLink::SendDataRequest() {
	Packet::Packet packet 
      { Packet::Type::kDataRequest, uint8_t(server_slot_), {'0'} };
  SendReliable(packet);
}
Beispiel #15
0
static int generate_joint_tables(HYuvContext *s)
{
    uint16_t symbols[1 << VLC_BITS];
    uint16_t bits[1 << VLC_BITS];
    uint8_t len[1 << VLC_BITS];
    int ret;

    if (s->bitstream_bpp < 24) {
        int p, i, y, u;
        for (p = 0; p < 3; p++) {
            for (i = y = 0; y < 256; y++) {
                int len0 = s->len[0][y];
                int limit = VLC_BITS - len0;
                if(limit <= 0 || !len0)
                    continue;
                for (u = 0; u < 256; u++) {
                    int len1 = s->len[p][u];
                    if (len1 > limit || !len1)
                        continue;
                    av_assert0(i < (1 << VLC_BITS));
                    len[i] = len0 + len1;
                    bits[i] = (s->bits[0][y] << len1) + s->bits[p][u];
                    symbols[i] = (y << 8) + u;
                    if(symbols[i] != 0xffff) // reserved to mean "invalid"
                        i++;
                }
            }
            ff_free_vlc(&s->vlc[3 + p]);
            if ((ret = ff_init_vlc_sparse(&s->vlc[3 + p], VLC_BITS, i, len, 1, 1,
                                          bits, 2, 2, symbols, 2, 2, 0)) < 0)
                return ret;
        }
    } else {
        uint8_t (*map)[4] = (uint8_t(*)[4])s->pix_bgr_map;
        int i, b, g, r, code;
        int p0 = s->decorrelate;
        int p1 = !s->decorrelate;
        // restrict the range to +/-16 because that's pretty much guaranteed to
        // cover all the combinations that fit in 11 bits total, and it doesn't
        // matter if we miss a few rare codes.
        for (i = 0, g = -16; g < 16; g++) {
            int len0 = s->len[p0][g & 255];
            int limit0 = VLC_BITS - len0;
            if (limit0 < 2 || !len0)
                continue;
            for (b = -16; b < 16; b++) {
                int len1 = s->len[p1][b & 255];
                int limit1 = limit0 - len1;
                if (limit1 < 1 || !len1)
                    continue;
                code = (s->bits[p0][g & 255] << len1) + s->bits[p1][b & 255];
                for (r = -16; r < 16; r++) {
                    int len2 = s->len[2][r & 255];
                    if (len2 > limit1 || !len2)
                        continue;
                    av_assert0(i < (1 << VLC_BITS));
                    len[i] = len0 + len1 + len2;
                    bits[i] = (code << len2) + s->bits[2][r & 255];
                    if (s->decorrelate) {
                        map[i][G] = g;
                        map[i][B] = g + b;
                        map[i][R] = g + r;
                    } else {
                        map[i][B] = g;
                        map[i][G] = b;
                        map[i][R] = r;
                    }
                    i++;
                }
            }
        }
        ff_free_vlc(&s->vlc[3]);
        if ((ret = init_vlc(&s->vlc[3], VLC_BITS, i, len, 1, 1, bits, 2, 2, 0)) < 0)
            return ret;
    }
    return 0;
}
surfel_mem_array reduction_spatially_subdivided_random::
create_lod(real& reduction_error,
          const std::vector<surfel_mem_array*>& input,
          const uint32_t surfels_per_node,
          const bvh& tree,
          const size_t start_node_id) const
{
    surfel_mem_array mem_array(std::make_shared<surfel_vector>(surfel_vector()), 0, 0);

    std::vector<surfel> already_picked_surfel;
    std::vector<surfel> original_surfels;


    auto const& tree_nodes = tree.nodes();
    auto combined_bounding_box = tree_nodes[start_node_id].get_bounding_box();

    for( uint8_t non_first_child_ids = 1; 
         non_first_child_ids < tree.fan_factor(); 
         ++non_first_child_ids) {

        auto const& sibling_bb = tree_nodes[start_node_id + non_first_child_ids].get_bounding_box();
        combined_bounding_box.expand( sibling_bb.max() );
        combined_bounding_box.expand( sibling_bb.min() );
    }


    uint32_t const num_divisions_for_shortest_axis = 8;

    vec3r step_length(-1.0, -1.0, -1.0);

    uint8_t shortest_axis = -1;
    real min_length = std::numeric_limits<real>::max();

    vec3r axis_lengths = combined_bounding_box.max() - combined_bounding_box.min();

    for( uint8_t axis_idx = 0; axis_idx < 3; ++axis_idx ) {
        if( axis_lengths[axis_idx] < min_length ) {
            min_length = axis_lengths[axis_idx];
            shortest_axis = axis_idx;
        }
    }

    step_length[shortest_axis] = axis_lengths[shortest_axis] / num_divisions_for_shortest_axis;

    vec3b steps_per_axis(-1,-1,-1);

    steps_per_axis[shortest_axis] = num_divisions_for_shortest_axis;

    for( uint8_t axis_idx = 0; axis_idx < 3; ++axis_idx ) {
        if (axis_idx != shortest_axis) {
            uint32_t num_axis_steps = std::max(1, int(std::ceil(  axis_lengths[axis_idx] / step_length[shortest_axis] ) ) );
            step_length[axis_idx] = axis_lengths[axis_idx] / num_axis_steps;

            steps_per_axis[axis_idx] = num_axis_steps;
        }
    }


    std::vector< std::vector<surfel> > spatially_divided_surfels;
    
    spatially_divided_surfels.resize( steps_per_axis[0]*steps_per_axis[1]*steps_per_axis[2] );


    for (size_t node_id = 0; node_id < input.size(); ++node_id) {
        for (size_t surfel_id = input[node_id]->offset();
                    surfel_id < input[node_id]->offset() + input[node_id]->length();
                    ++surfel_id){
            
            //this surfel will be referenced in the entropy surfel
            auto current_surfel = input[node_id]->mem_data()->at(input[node_id]->offset() + surfel_id);
            
            // ignore outlier radii of any kind
            if (current_surfel.radius() == 0.0) {
                continue;
            } 


            uint32_t x_summand = std::max(uint8_t(0), std::min( uint8_t( steps_per_axis[0] - 1), uint8_t( ( current_surfel.pos()[0] - combined_bounding_box.min()[0] ) /
                                 ( combined_bounding_box.max()[0] - combined_bounding_box.min()[0] ) *
                                 steps_per_axis[0]) ) ) * steps_per_axis[1] * steps_per_axis[2];

            uint32_t y_summand = std::max(uint8_t(0), std::min( uint8_t(steps_per_axis[1] - 1), uint8_t( ( current_surfel.pos()[1] - combined_bounding_box.min()[1] ) /
                                 ( combined_bounding_box.max()[1] - combined_bounding_box.min()[1] ) *
                                 steps_per_axis[1]) ) ) * steps_per_axis[2];

            uint32_t z_summand = std::max(uint8_t(0), std::min( uint8_t(steps_per_axis[2] - 1), uint8_t( ( current_surfel.pos()[2] - combined_bounding_box.min()[2] ) /
                                 ( combined_bounding_box.max()[2] - combined_bounding_box.min()[2] ) *
                                 steps_per_axis[2]) ) );

            uint32_t box_id = x_summand + y_summand + z_summand;


            spatially_divided_surfels[box_id].push_back(current_surfel);
            original_surfels.push_back(current_surfel);
       }
    }

    std::sort(std::begin(spatially_divided_surfels), std::end(spatially_divided_surfels), [](std::vector<surfel> const& lhs, std::vector<surfel> const& rhs) { return lhs.size() > rhs.size();});    

    while( spatially_divided_surfels.back().empty() ){
        spatially_divided_surfels.pop_back();
    } 

    std::set<size_t> picked_box_ids;

    while( already_picked_surfel.size () < surfels_per_node ) {

        size_t box_id;

        do {
            box_id = rand() % spatially_divided_surfels.size();
        } while(picked_box_ids.find(box_id) != picked_box_ids.end());

        picked_box_ids.insert(box_id);
 
        if( picked_box_ids.size() == spatially_divided_surfels.size() ) {
            picked_box_ids.clear();
        }


        auto& current_surfel_box = spatially_divided_surfels[box_id];

        int32_t surf_id;

        surf_id = rand() % current_surfel_box.size();

        surfel picked_surfel = current_surfel_box[surf_id];

        already_picked_surfel.push_back(picked_surfel);

        current_surfel_box.erase(current_surfel_box.begin() + surf_id);
        
        if(current_surfel_box.empty()) {
            spatially_divided_surfels.erase( spatially_divided_surfels.begin() + box_id);

            if(picked_box_ids.find(box_id) != picked_box_ids.end())
                picked_box_ids.erase(box_id);
        }

    }

    for (auto& final_candidate : already_picked_surfel) {

        interpolate_approx_natural_neighbours(final_candidate, original_surfels, tree);

        mem_array.mem_data()->push_back(final_candidate);
    }

    mem_array.set_length(mem_array.mem_data()->size());

    reduction_error = 0.0;

    return mem_array;
}
Beispiel #17
0
}

void RageSurfaceUtils::encodepixel( uint8_t *p, int bpp, uint32_t pixel )
{
	switch(bpp)
	{
	case 1: *p = uint8_t(pixel); break;
	case 2: *(uint16_t *)p = uint16_t(pixel); break;
	case 3:
		if( BYTE_ORDER == BIG_ENDIAN )
		{
			p[0] = uint8_t((pixel >> 16) & 0xff);
			p[1] = uint8_t((pixel >> 8) & 0xff);
			p[2] = uint8_t(pixel & 0xff);
		} else {
			p[0] = uint8_t(pixel & 0xff);
			p[1] = uint8_t((pixel >> 8) & 0xff);
			p[2] = uint8_t((pixel >> 16) & 0xff);
		}
		break;
	case 4: *(uint32_t *)p = pixel; break;
	}
}

// Get and set colors without scaling to 0..255.
void RageSurfaceUtils::GetRawRGBAV( uint32_t pixel, const RageSurfaceFormat &fmt, uint8_t *v )
{
	if( fmt.BytesPerPixel == 1 )
	{
		v[0] = fmt.palette->colors[pixel].r;
		v[1] = fmt.palette->colors[pixel].g;
Beispiel #18
0
 void TED7360::initRegisters()
 {
   cycle_count = 0;
   videoColumn = 100;
   // initialize memory paging
   memoryReadMap = 0x06F8U;
   memoryWriteMap = 0x0678U;
   cpuMemoryReadMap = 0x06F8U;
   tedDMAReadMap = 0x07F8U;
   tedBitmapReadMap = 0x07F8U;
   // clear memory used by TED registers
   ioRegister_0000 = uint8_t(0x0F);
   ioRegister_0001 = uint8_t(0xC8);
   if (tedRegisters[0x07] & uint8_t(0x40)) {
     tedRegisters[0x07] = uint8_t(0x00);
     ntscModeChangeCallback(false);
   }
   for (uint8_t i = 0x00; i <= 0x1F; i++)
     tedRegisters[i] = tedRegisterInit[i];
   // set internal TED registers
   render_func = &render_char_std;
   current_render_func = &render_border;
   videoLine = 224;
   characterLine = 0;
   characterPosition = 0x0000;
   savedCharacterPosition = 0x0000;
   characterPositionReload = 0x0000;
   characterColumn = 0;
   dmaPosition = 0x03FF;
   dmaPositionReload = 0x03FF;
   dmaBaseAddr = 0x0000;
   bitmap_base_addr = 0x0000;
   charset_base_addr = 0x0000;
   cursor_position = 0x03FF;
   ted_disabled = false;
   flashState = 0x00;
   renderWindow = false;
   incrementingCharacterLine = false;
   bitmapAddressDisableFlags = 0x03;
   displayWindow = false;
   displayActive = false;
   videoOutputFlags = 0x30;
   vsyncFlags = 0x00;
   timer1_run = true;                          // timers
   timer2_run = true;
   timer3_run = true;
   timer1_state = 0;
   timer1_reload_value = 0;
   timer2_state = 0;
   timer3_state = 0;
   soundChannel1Cnt = 0x03FF;                  // sound generators
   soundChannel1Reload = 0x03FF;
   soundChannel2Cnt = 0x03FF;
   soundChannel2Reload = 0x03FF;
   prvSoundChannel1Overflow = false;
   prvSoundChannel2Overflow = false;
   soundChannel1Decay = 131072U;
   soundChannel2Decay = 131072U;
   soundChannel1State = uint8_t(1);
   soundChannel2State = uint8_t(1);
   soundChannel2NoiseState = uint8_t(0xFF);
   soundChannel2NoiseOutput = uint8_t(1);
   soundVolume = 0x00;
   soundChannel1Output = 0x00;
   soundChannel2Output = 0x00;
   prvSoundOutput = 0x00;
   for (int i = 0; i < 64; i++) {              // video buffers
     attr_buf[i] = uint8_t(0);
     attr_buf_tmp[i] = uint8_t(0);
     char_buf[i] = uint8_t(0);
   }
   for (int i = 0; i < 464; i++)
     video_buf[i] = uint8_t(0x00);
   prv_video_buf_pos = 0;
   video_buf_pos = 0;
   videoShiftRegisterEnabled = false;
   videoMode = 0x00;
   characterMask = uint8_t(0x7F);
   for (int i = 0; i < 5; i++)
     colorRegisters[i] = uint8_t(0x80);
   horizontalScroll = 0;
   verticalScroll = 3;
   dmaEnabled = false;
   savedVideoLineDelay1 = 223;
   singleClockModeFlags = 0x00;
   externalFetchSingleClockFlag = true;
   dmaFlags = 0x00;
   dmaActive = false;
   incrementingDMAPosition = false;
   incrementingCharacterPosition = false;
   cpuHaltedFlag = false;
   delayedEvents0 = 0U;
   delayedEvents1 = 0U;
   savedVideoLine = 224;
   videoInterruptLine = 0;
   prvVideoInterruptState = false;
   prvCharacterLine = 0;
   dataBusState = uint8_t(0xFF);
   dramRefreshAddrL = 0x00;
   keyboard_row_select_mask = 0xFFFF;
   tape_motor_state = false;
   tape_write_state = false;
   hannesRegister = uint8_t(0xFF);
 }
void RageSurfaceUtils::OrderedDither( const RageSurface *src, RageSurface *dst )
{
	static bool DitherMatCalc_initted = false;
	if( !DitherMatCalc_initted )
	{
		for( int i = 0; i < DitherMatDim; ++i )
		{
			for( int j = 0; j < DitherMatDim; ++j )
			{
				/* Each value is 0..15.  They represent 0/16 through 15/16.
				 * Set DitherMatCalc to that value * 65536, so we can do it
				 * with integer calcs. */
				DitherMatCalc[i][j] = DitherMat[i][j] * 65536 / 16;
			}
		}
			
		DitherMatCalc_initted = true;
	}

	// We can't dither to paletted surfaces.
	ASSERT( dst->format->BytesPerPixel > 1 );

	uint32_t src_cbits[4], dst_cbits[4];
	RageSurfaceUtils::GetBitsPerChannel( src->format, src_cbits );
	RageSurfaceUtils::GetBitsPerChannel( dst->format, dst_cbits );

	// Calculate the ratio from the old bit depth to the new for each color channel.
	int conv[4];
	for( int i = 0; i < 4; ++i )
	{
		int MaxInputIntensity = (1 << src_cbits[i])-1;
		int MaxOutputIntensity = (1 << dst_cbits[i])-1;
		// If the source is missing the channel, avoid div/0.
		if( MaxInputIntensity == 0 )
			conv[i] = 0;
		else
			conv[i] = MaxOutputIntensity * 65536 / MaxInputIntensity;
	}

	// Max alpha value; used when there's no alpha source.
	const uint8_t alpha_max = uint8_t((1 << dst_cbits[3]) - 1);

	// For each row:
	for( int row = 0; row < src->h; ++row )
	{
		const uint8_t *srcp = src->pixels + row * src->pitch;
		uint8_t *dstp = dst->pixels + row * dst->pitch;

		// For each pixel:
		for( int col = 0; col < src->w; ++col )
		{
			uint8_t colors[4];
			RageSurfaceUtils::GetRawRGBAV( srcp, src->fmt, colors );

			// Note that we don't dither the alpha channel.
			for( int c = 0; c < 3; ++c )
			{
				// If the destination has less bits, dither:
				colors[c] = DitherPixel( col, row, colors[c], conv[c] );
			}

			/* If the source has no alpha, the conversion formula will end up
			 * with 0; that's fine for color channels, but for alpha we need to
			 * be opaque. */
			if( src_cbits[3] == 0 )
			{
				colors[3] = alpha_max;
			} else {
				/* Same as DitherPixel, except it doesn't actually dither;
				 * dithering looks bad on the alpha channel. */
				int out_intensity = colors[3] * conv[3];
	
				// Round:
				colors[3] = uint8_t((out_intensity + 32767) >> 16);
			}

			// Raw value -> int -> pixel
			RageSurfaceUtils::SetRawRGBAV(dstp, dst, colors);

			srcp += src->format->BytesPerPixel;
			dstp += dst->format->BytesPerPixel;
		}
	}
}
Beispiel #20
0
 TED7360::TED7360() : M7501()
 {
   tedRegisters[0x07] = uint8_t(0x00);         // default to PAL mode
   for (int i = 0; i < int(sizeof(callbacks) / sizeof(TEDCallback)); i++) {
     callbacks[i].func = (void (*)(void *)) 0;
     callbacks[i].userData = (void *) 0;
     callbacks[i].nxt0 = (TEDCallback *) 0;
     callbacks[i].nxt1 = (TEDCallback *) 0;
   }
   firstCallback0 = (TEDCallback *) 0;
   firstCallback1 = (TEDCallback *) 0;
   // create initial memory map
   ramSegments = 0;
   ramPatternCode = 0UL;
   randomSeed = Plus4Emu::Timer::getRandomSeedFromTime() & 0x7FFFFFFFU;
   for (int i = 0; i < 256; i++)
     segmentTable[i] = (uint8_t *) 0;
   try {
     setRAMSize(64);
   }
   catch (...) {
     for (int i = 0; i < 256; i++) {
       if (segmentTable[i] != (uint8_t *) 0) {
         delete[] segmentTable[i];
         segmentTable[i] = (uint8_t *) 0;
       }
     }
     throw;
   }
   setMemoryCallbackUserData(this);
   for (uint16_t i = 0x0000; i <= 0x0FFF; i++) {
     setMemoryReadCallback(i, &read_memory_0000_to_0FFF);
     setMemoryWriteCallback(i, &write_memory_0000_to_0FFF);
   }
   for (uint16_t i = 0x1000; i <= 0x3FFF; i++) {
     setMemoryReadCallback(i, &read_memory_1000_to_3FFF);
     setMemoryWriteCallback(i, &write_memory_1000_to_3FFF);
   }
   for (uint16_t i = 0x4000; i <= 0x7FFF; i++) {
     setMemoryReadCallback(i, &read_memory_4000_to_7FFF);
     setMemoryWriteCallback(i, &write_memory_4000_to_7FFF);
   }
   for (uint16_t i = 0x8000; i <= 0xBFFF; i++) {
     setMemoryReadCallback(i, &read_memory_8000_to_BFFF);
     setMemoryWriteCallback(i, &write_memory_8000_to_BFFF);
   }
   for (uint16_t i = 0xC000; i <= 0xFBFF; i++) {
     setMemoryReadCallback(i, &read_memory_C000_to_FBFF);
     setMemoryWriteCallback(i, &write_memory_C000_to_FBFF);
   }
   for (uint16_t i = 0xFC00; i <= 0xFCFF; i++) {
     setMemoryReadCallback(i, &read_memory_FC00_to_FCFF);
     setMemoryWriteCallback(i, &write_memory_FC00_to_FCFF);
   }
   for (uint16_t i = 0xFD00; i <= 0xFEFF; i++) {
     setMemoryReadCallback(i, &read_memory_FD00_to_FEFF);
     setMemoryWriteCallback(i, &write_memory_FD00_to_FEFF);
   }
   for (uint16_t i = 0xFF00; i <= 0xFF1F; i++) {
     setMemoryReadCallback(i, &read_register_FFxx);
     setMemoryWriteCallback(i, &write_register_FFxx);
   }
   for (uint32_t i = 0xFF20; i <= 0xFFFF; i++) {
     setMemoryReadCallback(uint16_t(i), &read_memory_FF00_to_FFFF);
     setMemoryWriteCallback(uint16_t(i), &write_memory_FF00_to_FFFF);
   }
   // TED register read
   setMemoryReadCallback(0x0000, &read_register_0000);
   setMemoryReadCallback(0x0001, &read_register_0001);
   for (uint16_t i = 0xFD00; i <= 0xFD0F; i++)
     setMemoryReadCallback(i, &read_register_FD0x);
   for (uint16_t i = 0xFD10; i <= 0xFD1F; i++)
     setMemoryReadCallback(i, &read_register_FD1x);
   setMemoryReadCallback(0xFD16, &read_register_FD16);
   for (uint16_t i = 0xFD30; i <= 0xFD3F; i++)
     setMemoryReadCallback(i, &read_register_FD3x);
   setMemoryReadCallback(0xFF00, &read_register_FF00);
   setMemoryReadCallback(0xFF01, &read_register_FF01);
   setMemoryReadCallback(0xFF02, &read_register_FF02);
   setMemoryReadCallback(0xFF03, &read_register_FF03);
   setMemoryReadCallback(0xFF04, &read_register_FF04);
   setMemoryReadCallback(0xFF05, &read_register_FF05);
   setMemoryReadCallback(0xFF06, &read_register_FF06);
   setMemoryReadCallback(0xFF09, &read_register_FF09);
   setMemoryReadCallback(0xFF0A, &read_register_FF0A);
   setMemoryReadCallback(0xFF0C, &read_register_FF0C);
   setMemoryReadCallback(0xFF10, &read_register_FF10);
   setMemoryReadCallback(0xFF12, &read_register_FF12);
   setMemoryReadCallback(0xFF13, &read_register_FF13);
   setMemoryReadCallback(0xFF14, &read_register_FF14);
   setMemoryReadCallback(0xFF1A, &read_register_FF1A);
   setMemoryReadCallback(0xFF1B, &read_register_FF1B);
   setMemoryReadCallback(0xFF1C, &read_register_FF1C);
   setMemoryReadCallback(0xFF1E, &read_register_FF1E);
   setMemoryReadCallback(0xFF1F, &read_register_FF1F);
   setMemoryReadCallback(0xFF3E, &read_register_FF3E_FF3F);
   setMemoryReadCallback(0xFF3F, &read_register_FF3E_FF3F);
   // TED register write
   setMemoryWriteCallback(0x0000, &write_register_0000);
   setMemoryWriteCallback(0x0001, &write_register_0001);
   for (uint16_t i = 0xFD10; i <= 0xFD1F; i++)
     setMemoryWriteCallback(i, &write_register_FD1x);
   setMemoryWriteCallback(0xFD16, &write_register_FD16);
   for (uint16_t i = 0xFD30; i <= 0xFD3F; i++)
     setMemoryWriteCallback(i, &write_register_FD3x);
   for (uint16_t i = 0xFDD0; i <= 0xFDDF; i++)
     setMemoryWriteCallback(i, &write_register_FDDx);
   setMemoryWriteCallback(0xFF00, &write_register_FF00);
   setMemoryWriteCallback(0xFF01, &write_register_FF01);
   setMemoryWriteCallback(0xFF02, &write_register_FF02);
   setMemoryWriteCallback(0xFF03, &write_register_FF03);
   setMemoryWriteCallback(0xFF04, &write_register_FF04);
   setMemoryWriteCallback(0xFF05, &write_register_FF05);
   setMemoryWriteCallback(0xFF06, &write_register_FF06);
   setMemoryWriteCallback(0xFF07, &write_register_FF07);
   setMemoryWriteCallback(0xFF08, &write_register_FF08);
   setMemoryWriteCallback(0xFF09, &write_register_FF09);
   setMemoryWriteCallback(0xFF0A, &write_register_FF0A);
   setMemoryWriteCallback(0xFF0B, &write_register_FF0B);
   setMemoryWriteCallback(0xFF0C, &write_register_FF0C);
   setMemoryWriteCallback(0xFF0D, &write_register_FF0D);
   setMemoryWriteCallback(0xFF0E, &write_register_FF0E);
   setMemoryWriteCallback(0xFF0F, &write_register_FF0F);
   setMemoryWriteCallback(0xFF10, &write_register_FF10);
   setMemoryWriteCallback(0xFF11, &write_register_FF11);
   setMemoryWriteCallback(0xFF12, &write_register_FF12);
   setMemoryWriteCallback(0xFF13, &write_register_FF13);
   setMemoryWriteCallback(0xFF14, &write_register_FF14);
   setMemoryWriteCallback(0xFF15, &write_register_FF15_to_FF19);
   setMemoryWriteCallback(0xFF16, &write_register_FF15_to_FF19);
   setMemoryWriteCallback(0xFF17, &write_register_FF15_to_FF19);
   setMemoryWriteCallback(0xFF18, &write_register_FF15_to_FF19);
   setMemoryWriteCallback(0xFF19, &write_register_FF15_to_FF19);
   setMemoryWriteCallback(0xFF1A, &write_register_FF1A);
   setMemoryWriteCallback(0xFF1B, &write_register_FF1B);
   setMemoryWriteCallback(0xFF1C, &write_register_FF1C);
   setMemoryWriteCallback(0xFF1D, &write_register_FF1D);
   setMemoryWriteCallback(0xFF1E, &write_register_FF1E);
   setMemoryWriteCallback(0xFF1F, &write_register_FF1F);
   setMemoryWriteCallback(0xFF3E, &write_register_FF3E);
   setMemoryWriteCallback(0xFF3F, &write_register_FF3F);
   // initialize external ports
   user_port_state = uint8_t(0xFF);
   tape_read_state = false;
   tape_button_state = false;
   // set internal TED registers
   this->initRegisters();
   cpu_clock_multiplier = 1;
   for (int i = 0; i < 16; i++)                // keyboard matrix
     keyboard_matrix[i] = uint8_t(0xFF);
 }
/**
 *  Read the specified register. If an error
 *  occurs, return error.
 *
 *  Returns a error code.
 */
uint8_t Max6651ClosedLoop::read(Register command, uint8_t & result) const {
  return i2c_->read(address_, uint8_t(command), result);
}
Beispiel #22
0
void PtexMainWriter::writeMetaData(FILE* fp)
{
    std::vector<MetaEntry*> lmdEntries; // large meta data items

    // write small meta data items in a single zip block
    for (int i = 0, n = _metadata.size(); i < n; i++) {
	MetaEntry& e = _metadata[i];
#ifndef PTEX_NO_LARGE_METADATA_BLOCKS
	if (int(e.data.size()) > MetaDataThreshold) {
	    // skip large items, but record for later
	    lmdEntries.push_back(&e);
	}
	else 
#endif
    {
	    // add small item to zip block
	    _header.metadatamemsize += writeMetaDataBlock(fp, e);
	}
    }
    if (_header.metadatamemsize) {
	// finish zip block
	_header.metadatazipsize = writeZipBlock(fp, 0, 0, /*finish*/ true);
    }

    // write compatibility barrier
    writeBlank(fp, sizeof(uint64_t));

    // write large items as separate blocks
    int nLmd = lmdEntries.size();
    if (nLmd > 0) {
	// write data records to tmp file and accumulate zip sizes for lmd header
	std::vector<FilePos> lmdoffset(nLmd);
	std::vector<uint32_t> lmdzipsize(nLmd);
	for (int i = 0; i < nLmd; i++) {
	    MetaEntry* e= lmdEntries[i];
	    lmdoffset[i] = ftello(_tmpfp);
	    lmdzipsize[i] = writeZipBlock(_tmpfp, &e->data[0], e->data.size());
	}

	// write lmd header records as single zip block
	for (int i = 0; i < nLmd; i++) {
	    MetaEntry* e = lmdEntries[i];
	    uint8_t keysize = uint8_t(e->key.size()+1);
	    uint8_t datatype = e->datatype;
	    uint32_t datasize = e->data.size();
	    uint32_t zipsize = lmdzipsize[i];

	    writeZipBlock(fp, &keysize, sizeof(keysize), false);
	    writeZipBlock(fp, e->key.c_str(), keysize, false);
	    writeZipBlock(fp, &datatype, sizeof(datatype), false);
	    writeZipBlock(fp, &datasize, sizeof(datasize), false);
	    writeZipBlock(fp, &zipsize, sizeof(zipsize), false);
	    _extheader.lmdheadermemsize +=
		sizeof(keysize) + keysize + sizeof(datatype) + sizeof(datasize) + sizeof(zipsize);
	}
	_extheader.lmdheaderzipsize = writeZipBlock(fp, 0, 0, /*finish*/ true);

	// copy data records
	for (int i = 0; i < nLmd; i++) {
	    _extheader.lmddatasize +=
		copyBlock(fp, _tmpfp, lmdoffset[i], lmdzipsize[i]);
	}
    }
}
Beispiel #23
0
void SequenceParser::sendPlaybookInformation(const std::string& name) {
    std::string fullName = std::string(PlaybookIdentifierName) + "_" + name;
    _messageIdentifier = OsEng.networkEngine().identifier(fullName);

    std::vector<char> buffer(1024);
    size_t currentWriteLocation = 0;

    // Protocol:
    // 4 bytes: Total number of bytes sent
    // 1 byte : Number of Targets (i)
    // i times: 1 byte (id), 1 byte (length j of name), j bytes (name)
    // 1 byte : Number of Instruments (i)
    // i times: 1 byte (id), 1 byte (length j of name), j bytes (name)
    // 4 byte: Number (n) of images
    // n times: 8 byte (beginning time), 8 byte (ending time), 1 byte (target id), 2 byte (instrument id)

    std::map<std::string, uint8_t> targetMap;
    uint8_t currentTargetId = 0;
    for (auto target : _subsetMap) {
        if (targetMap.find(target.first) == targetMap.end())
            targetMap[target.first] = currentTargetId++;
    }

    std::map<std::string, uint16_t> instrumentMap;
    uint16_t currentInstrumentId = 1;
    for (auto target : _subsetMap) {
        for (auto image : target.second._subset) {
            for (auto instrument : image.activeInstruments) {
                if (instrumentMap.find(instrument) == instrumentMap.end()) {
                    instrumentMap[instrument] = currentInstrumentId;
                    currentInstrumentId = currentInstrumentId << 1;
                }
            }
        }
    }

    writeToBuffer(buffer, currentWriteLocation, uint8_t(targetMap.size()));
    for (const std::pair<std::string, uint8_t>& p : targetMap) {
        writeToBuffer(buffer, currentWriteLocation, p.second);
        writeToBuffer(buffer, currentWriteLocation, p.first);
    }

    writeToBuffer(buffer, currentWriteLocation, uint8_t(instrumentMap.size()));
    for (const std::pair<std::string, uint16_t>& p : instrumentMap) {
        writeToBuffer(buffer, currentWriteLocation, p.second);
        writeToBuffer(buffer, currentWriteLocation, p.first);
    }

    uint32_t allImages = 0;
    for (auto target : _subsetMap)
        allImages += static_cast<uint32_t>(target.second._subset.size());
    writeToBuffer(buffer, currentWriteLocation, allImages);

    for (auto target : _subsetMap){
        for (auto image : target.second._subset){
            writeToBuffer(buffer, currentWriteLocation, image.timeRange.start);
            writeToBuffer(buffer, currentWriteLocation, image.timeRange.end);

            std::string timeBegin = SpiceManager::ref().dateFromEphemerisTime(image.timeRange.start);
            std::string timeEnd = SpiceManager::ref().dateFromEphemerisTime(image.timeRange.end);

            writeToBuffer(buffer, currentWriteLocation, timeBegin);
            writeToBuffer(buffer, currentWriteLocation, timeEnd);

            uint8_t targetId = targetMap[target.first];
            writeToBuffer(buffer, currentWriteLocation, targetId);
            uint16_t totalInstrumentId = 0;
            if (image.activeInstruments.empty()) {
                LERROR("Image had no active instruments");
            }

            for (auto instrument : image.activeInstruments) {
                uint16_t thisInstrumentId = instrumentMap[instrument];
                totalInstrumentId |= thisInstrumentId;
            }
            writeToBuffer(buffer, currentWriteLocation, totalInstrumentId);
        }
    }

    union {
        uint32_t value;
        std::array<char, sizeof(uint32_t)> data;
    } sizeBuffer;
    sizeBuffer.value = static_cast<uint32_t>(currentWriteLocation);
    buffer.insert(buffer.begin(), sizeBuffer.data.begin(), sizeBuffer.data.end());
    currentWriteLocation += sizeof(uint32_t);

    buffer.resize(currentWriteLocation);

    //OsEng.networkEngine()->publishMessage(PlaybookIdentifier, buffer);
    OsEng.networkEngine().setInitialConnectionMessage(_messageIdentifier, buffer);
}
Beispiel #24
0
void PtexMainWriter::finish()
{
    // do nothing if there's no new data to write
    if (!_hasNewData) return;

    // copy missing faces from _reader
    if (_reader) {
	for (int i = 0, nfaces = _header.nfaces; i < nfaces; i++) {
	    if (_faceinfo[i].flags == uint8_t(-1)) {
		// copy face data
                const Ptex::FaceInfo& info = _reader->getFaceInfo(i);
                int size = _pixelSize * info.res.size();
                if (info.isConstant()) {
                    PtexPtr<PtexFaceData> data ( _reader->getData(i) );
                    if (data) {
                        writeConstantFace(i, info, data->getData());
                    }
                } else {
                    void* data = malloc(size);
                    _reader->getData(i, data, 0);
                    writeFace(i, info, data, 0);
                    free(data);
                }
	    }
	}
    }
    else {
	// just flag missing faces as constant (black)
	for (int i = 0, nfaces = _header.nfaces; i < nfaces; i++) {
	    if (_faceinfo[i].flags == uint8_t(-1))
		_faceinfo[i].flags = FaceInfo::flag_constant;
	}
    }

    // write reductions to tmp file
    if (_genmipmaps)
	generateReductions();

    // flag faces w/ constant neighborhoods
    flagConstantNeighorhoods();

    // update header
    _header.nlevels = uint16_t(_levels.size());
    _header.nfaces = uint32_t(_faceinfo.size());

    // create new file
    FILE* newfp = fopen(_newpath.c_str(), "wb+");
    if (!newfp) {
	setError(fileError("Can't write to ptex file: ", _newpath.c_str()));
	return;
    }

    // write blank header (to fill in later)
    writeBlank(newfp, HeaderSize);
    writeBlank(newfp, ExtHeaderSize);

    // write compressed face info block
    _header.faceinfosize = writeZipBlock(newfp, &_faceinfo[0],
					 sizeof(FaceInfo)*_header.nfaces);

    // write compressed const data block
    _header.constdatasize = writeZipBlock(newfp, &_constdata[0], int(_constdata.size()));

    // write blank level info block (to fill in later)
    FilePos levelInfoPos = ftello(newfp);
    writeBlank(newfp, LevelInfoSize * _header.nlevels);

    // write level data blocks (and record level info)
    std::vector<LevelInfo> levelinfo(_header.nlevels);
    for (int li = 0; li < _header.nlevels; li++)
    {
	LevelInfo& info = levelinfo[li];
	LevelRec& level = _levels[li];
	int nfaces = int(level.fdh.size());
	info.nfaces = nfaces;
	// output compressed level data header
	info.levelheadersize = writeZipBlock(newfp, &level.fdh[0],
					     sizeof(FaceDataHeader)*nfaces);
	info.leveldatasize = info.levelheadersize;
	// copy level data from tmp file
	for (int fi = 0; fi < nfaces; fi++)
	    info.leveldatasize += copyBlock(newfp, _tmpfp, level.pos[fi],
					    level.fdh[fi].blocksize());
	_header.leveldatasize += info.leveldatasize;
    }
    rewind(_tmpfp);

    // write meta data (if any)
    if (!_metadata.empty())
	writeMetaData(newfp);

    // update extheader for edit data position
    _extheader.editdatapos = ftello(newfp);

    // rewrite level info block
    fseeko(newfp, levelInfoPos, SEEK_SET);
    _header.levelinfosize = writeBlock(newfp, &levelinfo[0], LevelInfoSize*_header.nlevels);

    // rewrite header
    fseeko(newfp, 0, SEEK_SET);
    writeBlock(newfp, &_header, HeaderSize);
    writeBlock(newfp, &_extheader, ExtHeaderSize);
    fclose(newfp);
}
Beispiel #25
0
	void vertexPack(const float _input[4], bool _inputNormalized, Attrib::Enum _attr, const VertexDecl& _decl, void* _data, uint32_t _index)
	{
		if (!_decl.has(_attr) )
		{
			return;
		}

		uint32_t stride = _decl.getStride();
		uint8_t* data = (uint8_t*)_data + _index*stride + _decl.getOffset(_attr);

		uint8_t num;
		AttribType::Enum type;
		bool normalized;
		bool asInt;
		_decl.decode(_attr, num, type, normalized, asInt);

		switch (type)
		{
		default:
		case AttribType::Uint8:
			{
				uint8_t* packed = (uint8_t*)data;
				if (_inputNormalized)
				{
					if (asInt)
					{
						switch (num)
						{
						default: *packed++ = uint8_t(*_input++ * 127.0f + 128.0f);
						case 3:  *packed++ = uint8_t(*_input++ * 127.0f + 128.0f);
						case 2:  *packed++ = uint8_t(*_input++ * 127.0f + 128.0f);
						case 1:  *packed++ = uint8_t(*_input++ * 127.0f + 128.0f);
						}
					}
					else
					{
						switch (num)
						{
						default: *packed++ = uint8_t(*_input++ * 255.0f);
						case 3:  *packed++ = uint8_t(*_input++ * 255.0f);
						case 2:  *packed++ = uint8_t(*_input++ * 255.0f);
						case 1:  *packed++ = uint8_t(*_input++ * 255.0f);
						}
					}
				}
				else
				{
					switch (num)
					{
					default: *packed++ = uint8_t(*_input++);
					case 3:  *packed++ = uint8_t(*_input++);
					case 2:  *packed++ = uint8_t(*_input++);
					case 1:  *packed++ = uint8_t(*_input++);
					}
				}
			}
			break;

		case AttribType::Uint10:
			{
				uint32_t packed = 0;
				if (_inputNormalized)
				{
					if (asInt)
					{
						switch (num)
						{
						default:
						case 3:                packed |= uint32_t(*_input++ * 511.0f + 512.0f);
						case 2: packed <<= 10; packed |= uint32_t(*_input++ * 511.0f + 512.0f);
						case 1: packed <<= 10; packed |= uint32_t(*_input++ * 511.0f + 512.0f);
						}
					}
					else
					{
						switch (num)
						{
						default:
						case 3:                packed |= uint32_t(*_input++ * 1023.0f);
						case 2: packed <<= 10; packed |= uint32_t(*_input++ * 1023.0f);
						case 1: packed <<= 10; packed |= uint32_t(*_input++ * 1023.0f);
						}
					}
				}
				else
				{
					switch (num)
					{
					default:
					case 3:                packed |= uint32_t(*_input++);
					case 2: packed <<= 10; packed |= uint32_t(*_input++);
					case 1: packed <<= 10; packed |= uint32_t(*_input++);
					}
				}
				*(uint32_t*)data = packed;
			}
			break;

		case AttribType::Int16:
			{
				int16_t* packed = (int16_t*)data;
				if (_inputNormalized)
				{
					if (asInt)
					{
						switch (num)
						{
						default: *packed++ = int16_t(*_input++ * 32767.0f);
						case 3:  *packed++ = int16_t(*_input++ * 32767.0f);
						case 2:  *packed++ = int16_t(*_input++ * 32767.0f);
						case 1:  *packed++ = int16_t(*_input++ * 32767.0f);
						}
					}
					else
					{
						switch (num)
						{
						default: *packed++ = int16_t(*_input++ * 65535.0f - 32768.0f);
						case 3:  *packed++ = int16_t(*_input++ * 65535.0f - 32768.0f);
						case 2:  *packed++ = int16_t(*_input++ * 65535.0f - 32768.0f);
						case 1:  *packed++ = int16_t(*_input++ * 65535.0f - 32768.0f);
						}
					}
				}
				else
				{
					switch (num)
					{
					default: *packed++ = int16_t(*_input++);
					case 3:  *packed++ = int16_t(*_input++);
					case 2:  *packed++ = int16_t(*_input++);
					case 1:  *packed++ = int16_t(*_input++);
					}
				}
			}
			break;

		case AttribType::Half:
			{
				uint16_t* packed = (uint16_t*)data;
				switch (num)
				{
				default: *packed++ = bx::halfFromFloat(*_input++);
				case 3:  *packed++ = bx::halfFromFloat(*_input++);
				case 2:  *packed++ = bx::halfFromFloat(*_input++);
				case 1:  *packed++ = bx::halfFromFloat(*_input++);
				}
			}
			break;

		case AttribType::Float:
			memcpy(data, _input, num*sizeof(float) );
			break;
		}
	}
static void *worker(void *blks) {
	// State variables
	uint64_t lowesthash[8];
	pthread_mutex_lock(&mutex);
	memcpy(lowesthash, global_lowest_hash, sizeof(lowesthash));
	pthread_mutex_unlock(&mutex);
	uint8_t (*blocks)[NUM_CH][8] = (uint8_t (*)[NUM_CH][8])blks;
	
	for (long i = 0; ; i++) {
		// Accumulate status
		if (i >= iters_per_accumulate) {
			pthread_mutex_lock(&mutex);
			total_iterations += i;
			pthread_mutex_unlock(&mutex);
			i = 0;
		}
		
		// Do hashing
		uint64_t hashes[8][NUM_CH];
		memcpy(hashes, INITIAL_STATES, sizeof(hashes));
		sha512_compress_dual(hashes, blocks);
		
		// Compare with lowest hash
		if (hashes[0][0] <= lowesthash[0] || hashes[0][1] <= lowesthash[0]) {  // Assumes NUM_CH = 2
			pthread_mutex_lock(&mutex);
			for (int ch = 0; ch < NUM_CH; ch++) {
				if (compare_hashes(hashes, ch, global_lowest_hash) < 0) {
					char message[MSG_LEN + 1];
					get_message(blocks, ch, message);
					fprintf(stdout, "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 " %s\n",
						hashes[0][ch], hashes[1][ch], hashes[2][ch], hashes[3][ch], hashes[4][ch], hashes[5][ch], hashes[6][ch], hashes[7][ch], message);
					if (prev_print_type == 1)
						fprintf(stderr, "    ");
					fprintf(stderr, "%016" PRIx64 "%016" PRIx64 "... %s\n", hashes[0][ch], hashes[1][ch], message);
					fflush(stdout);
					fflush(stderr);
					for (int j = 0; j < 8; j++)
						global_lowest_hash[j] = hashes[j][ch];
					prev_print_type = 0;
				}
			}
			for (int j = 0; j < 8; j++)
				lowesthash[j] = global_lowest_hash[j];
			pthread_mutex_unlock(&mutex);
		}
		
		// Increment messages
		int j;
		for (j = MSG_LEN - 1; j >= 0 && get_byte(blocks, j, 0) >= 'z'; j--) {
			for (int ch = 0; ch < NUM_CH; ch++)
				set_byte(blocks, j, ch, 'a');
		}
		if (j < 0)
			break;
		for (int ch = 0; ch < NUM_CH; ch++)
			set_byte(blocks, j, ch, get_byte(blocks, j, ch) + 1);
	}
	pthread_mutex_lock(&mutex);
	finished_threads++;
	pthread_mutex_unlock(&mutex);
	return NULL;
}
Beispiel #27
0
// do the whole hash in one call
void SpookyHashV1::Hash128(
    const void *message,
    size_t length,
    uint64_t *hash1,
    uint64_t *hash2)
{
    if (length < sc_bufSize)
    {
        Short(message, length, hash1, hash2);
        return;
    }

    uint64_t h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11;
    uint64_t buf[sc_numVars];
    uint64_t *end;
    union
    {
        const uint8_t *p8;
        uint64_t *p64;
        size_t i;
    } u;
    size_t remainder;

    h0=h3=h6=h9  = *hash1;
    h1=h4=h7=h10 = *hash2;
    h2=h5=h8=h11 = sc_const;

    u.p8 = (const uint8_t *)message;
    end = u.p64 + (length/sc_blockSize)*sc_numVars;

    // handle all whole sc_blockSize blocks of bytes
    if (ALLOW_UNALIGNED_READS || ((u.i & 0x7) == 0))
    {
        while (u.p64 < end)
        {
            Mix(u.p64, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11);
            u.p64 += sc_numVars;
        }
    }
    else
    {
        while (u.p64 < end)
        {
            memcpy(buf, u.p64, sc_blockSize);
            Mix(buf, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11);
            u.p64 += sc_numVars;
        }
    }

    // handle the last partial block of sc_blockSize bytes
    remainder = (length - ((const uint8_t *)end-(const uint8_t *)message));
    memcpy(buf, end, remainder);
    memset(((uint8_t *)buf)+remainder, 0, sc_blockSize-remainder);
    ((uint8_t*)buf)[sc_blockSize - 1] = uint8_t(remainder);
    Mix(buf, h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11);

    // do some final mixing
    End(h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11);
    *hash1 = h0;
    *hash2 = h1;
}
int main(void) {
	// Sanity test
	if (!self_check()) {
		fprintf(stderr, "Self-check failed\n");
		return EXIT_FAILURE;
	}
	benchmark();
	
	// Set up the SHA-512 processed blocks: Message (28 bytes), terminator and padding (96 bytes), length (16 bytes)
	uint8_t (*blocks)[16][NUM_CH][8] = calloc(num_threads * 16 * NUM_CH * 8, sizeof(uint8_t));
	if (blocks == NULL) {
		perror("calloc");
		return EXIT_FAILURE;
	}
	{
		struct timespec ts;
		clock_gettime(CLOCK_REALTIME, &ts);
		uint64_t time = ts.tv_sec * UINT64_C(1000000000) + ts.tv_nsec;
		
		for (int i = 0; i < num_threads; i++) {
			for (int ch = 0; ch < NUM_CH; ch++) {
				uint8_t (*blks)[NUM_CH][8] = blocks[i];
				uint64_t temp = time + i * NUM_CH + ch;
				for (int j = 0; j < MSG_LEN / 2; j++, temp /= 26)
					set_byte(blks, j, ch, 'a' + temp % 26);
				for (int j = 0; j < MSG_LEN / 2; j++)
					set_byte(blks, j + MSG_LEN / 2, ch, 'a');
				set_byte(blks, MSG_LEN, ch, 0x80);
				set_byte(blks, 126, ch, MSG_LEN >> 5);
				set_byte(blks, 127, ch, MSG_LEN << 3);
			}
		}
	}
	
	// Initialize initial lowest hash
	memset(global_lowest_hash, 0xFF, sizeof(global_lowest_hash));
	global_lowest_hash[0] >>= 24;  // Exclude trivial matches
	
	// Launch threads
	pthread_t *threads = calloc(num_threads, sizeof(pthread_t));
	if (threads == NULL) {
		perror("calloc");
		return EXIT_FAILURE;
	}
	for (int i = 0; i < num_threads; i++)
		pthread_create(&threads[i], NULL, worker, blocks[i]);
	
	// Print status until threads finish
	while (true) {
		pthread_mutex_lock(&mutex);
		if (finished_threads >= num_threads) {
			pthread_mutex_unlock(&mutex);
			break;
		}
		
		char message[MSG_LEN + 1];
		get_message(blocks[0], 0, message);  // Only print thread 0, channel 0
		fprintf(stderr, "\rHash trials: %.3f billion (%s)", total_iterations * NUM_CH / 1.0e9, message);
		fflush(stderr);
		prev_print_type = 1;
		
		pthread_mutex_unlock(&mutex);
		sleep(10);
	}
	fprintf(stderr, "\nSearch space exhausted\n");
	
	// Clean up
	for (int i = 0; i < num_threads; i++)
		pthread_join(threads[i], NULL);
	free(blocks);
	free(threads);
	return EXIT_SUCCESS;
}
Beispiel #29
0
    AACEncode::AACEncode(int frequencyInHz, int channelCount, int bitRate)
    : m_sentConfig(false)
    {
        
        OSStatus result = 0;
        char err[5];
        
        AudioStreamBasicDescription in = {0}, out = {0};
        
        
        // passing anything except 48000, 44100, and 22050 for mSampleRate results in "!dat"
        // OSStatus when querying for kAudioConverterPropertyMaximumOutputPacketSize property
        // below
        in.mSampleRate = frequencyInHz;
        // passing anything except 2 for mChannelsPerFrame results in "!dat" OSStatus when
        // querying for kAudioConverterPropertyMaximumOutputPacketSize property below
        in.mChannelsPerFrame = channelCount;
        in.mBitsPerChannel = 16;
        in.mFormatFlags =  kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;
        in.mFormatID = kAudioFormatLinearPCM;
        in.mFramesPerPacket = 1;
        in.mBytesPerFrame = in.mBitsPerChannel * in.mChannelsPerFrame / 8;
        in.mBytesPerPacket = in.mFramesPerPacket*in.mBytesPerFrame;
        
        out.mFormatID = kAudioFormatMPEG4AAC;
        out.mFormatFlags = 0;
        out.mFramesPerPacket = kSamplesPerFrame;
        out.mSampleRate = frequencyInHz;
        out.mChannelsPerFrame = channelCount;
        
        UInt32 outputBitrate = bitRate; // 128 kbps
        UInt32 propSize = sizeof(outputBitrate);
        UInt32 outputPacketSize = 0;

        AudioClassDescription requestedCodecs[2] = {
            {
                kAudioEncoderComponentType,
                kAudioFormatMPEG4AAC,
                kAppleSoftwareAudioCodecManufacturer
            },
            {
                kAudioEncoderComponentType,
                kAudioFormatMPEG4AAC,
                kAppleHardwareAudioCodecManufacturer
            }
        };
        
        result = AudioConverterNewSpecific(&in, &out, 2, requestedCodecs, &m_audioConverter);

        if(result == noErr) {
        
            result = AudioConverterSetProperty(m_audioConverter, kAudioConverterEncodeBitRate, propSize, &outputBitrate);

        }
        if(result == noErr) {
            result = AudioConverterGetProperty(m_audioConverter, kAudioConverterPropertyMaximumOutputPacketSize, &propSize, &outputPacketSize);
        }
        
        if(result == noErr) {
            m_outputPacketMaxSize = outputPacketSize;
            
            m_bytesPerSample = 2 * channelCount;
            
            uint8_t sampleRateIndex = 0;
            switch(frequencyInHz) {
                case 48000:
                    sampleRateIndex = 3;
                    break;
                case 44100:
                    sampleRateIndex = 4;
                    break;
                case 22050:
                    sampleRateIndex = 7;
                    break;
                case 11025:
                    sampleRateIndex = 10;
                    break;
                case 8000:
                    sampleRateIndex = 11;
                    break;
                default:
                    sampleRateIndex = 15;
            }
            makeAsc(sampleRateIndex, uint8_t(channelCount));
        } else {
            std::cerr << "Error setting up audio encoder " << result << std::endl ;
        }
    }
Beispiel #30
0
void ServerLink::SendReliable(Game::Property::Stream properties) {
	Packet::Packet packet 
      { Packet::Type::kProperties, uint8_t(server_slot_), properties.Packed() };
  SendReliable(packet);
}