Exemple #1
0
int getHeight(char *src){
	FILE * pFile;
	if((pFile = fopen(src, "rb")) == NULL){
		puts("Error: wrong source.\n");
		return 0;
	}

	BITMAPFILEHEADER header __attribute__((unused));
 
    header.bfType      = read_u16(pFile);
    header.bfSize      = read_u32(pFile);
    header.bfReserved1 = read_u16(pFile);
    header.bfReserved2 = read_u16(pFile);
    header.bfOffBits   = read_u32(pFile);

    // считываем заголовок изображения
    BITMAPINFOHEADER bmiHeader;

    bmiHeader.biSize          = read_u32(pFile);
    bmiHeader.biWidth         = read_s32(pFile);
    bmiHeader.biHeight        = read_s32(pFile);

    fclose(pFile);
    return bmiHeader.biHeight;
}
Exemple #2
0
unsigned int* read_bmp(char* src){
	FILE * pFile;
	if((pFile = fopen(src, "rb")) == NULL){
		puts("Error: wrong source.\n");
		return 0;
	}

puts("read_bmp 1");

    // считываем заголовок файла
    BITMAPFILEHEADER header __attribute__((unused));
 
    header.bfType      = read_u16(pFile);
    header.bfSize      = read_u32(pFile);
    header.bfReserved1 = read_u16(pFile);
    header.bfReserved2 = read_u16(pFile);
    header.bfOffBits   = read_u32(pFile);

    // считываем заголовок изображения
    BITMAPINFOHEADER bmiHeader;

    bmiHeader.biSize          = read_u32(pFile);
    bmiHeader.biWidth         = read_s32(pFile);
    bmiHeader.biHeight        = read_s32(pFile);
    bmiHeader.biPlanes        = read_u16(pFile);
    bmiHeader.biBitCount      = read_u16(pFile);
    bmiHeader.biCompression   = read_u32(pFile);
    bmiHeader.biSizeImage     = read_u32(pFile);
    bmiHeader.biXPelsPerMeter = read_s32(pFile);
    bmiHeader.biYPelsPerMeter = read_s32(pFile);
    bmiHeader.biClrUsed       = read_u32(pFile);
    bmiHeader.biClrImportant  = read_u32(pFile);

	// unsigned int *img = new unsigned int[bmiHeader.biWidth*bmiHeader.biHeight];
	unsigned int *img = malloc(sizeof(unsigned int)*bmiHeader.biWidth*bmiHeader.biHeight);

puts("read_bmp 2");

    int i, j, k;

	for (i = 0; i < bmiHeader.biHeight; ++i)
	{
		for (j = 0; j < bmiHeader.biWidth; ++j)
		{
			for (k = 0; k < 3; ++k)
			{
				img[i*bmiHeader.biWidth + j] |= !getc(pFile) << (8*k);
			}
		}
		for (j = 0; j < bmiHeader.biWidth%4; ++j)
		{
			getc(pFile);
		}
	}
puts("read_bmp 3");
	fclose(pFile);
	return img;
}
Exemple #3
0
    void btstack_libusb_device_base::handle_event( std::uint8_t ec, std::uint8_t param_size, const std::uint8_t* params )
    {
        std::uint16_t event_code = ec;

        if ( hic_event_code::le_meta_event == static_cast< hic_event_code >( event_code ) && param_size > 0 )
        {
            event_code = ( event_code << 8 ) | *params;
            --param_size;
            ++params;
        }

        switch ( static_cast< hic_event_code >( event_code ) )
        {
            case hic_event_code::le_connection_complete:
                if ( param_size == 18 )
                {
                    const int  status = params[ 0 ];

                    if ( status == 0 )
                    {
                        connection_handle_ = read_u16( &params[ 1 ] );
                        log_info( "connection_handle_: %i", connection_handle_ );
                    }

                    log_info( "le_connection_complete: %i", status );
                }
                break;
            default:
                break;
        }
    }
Exemple #4
0
static void do_test_libeprom24x(void)
{  
  int value;

  do {
    print_menu();
    
    printf("Enter choice : ");
    scanf("%d",&value);
    
    switch(value) {
    case 1:
      get_prod_info();
      break;
    case 2:
      get_last_error();
      break;
    case 3:
      initialize();
      break;
    case 4:
      finalize();
      break;
    case 5:
      read_u8();
      break;
    case 6:
      read_u16();
      break;
    case 7:
      read_u32();
      break;
    case 8:
      read_to_buffer();
      break;
    case 9:
      write_u8();
      break;
    case 10:
      write_u16();
      break;
    case 11:
      write_u32();
      break;
    case 12:
      write_from_buffer();
      break;
    case 13:
      erase_chip();
      break;
    case 100: /* Exit */
      break;
    default:
      printf("Illegal choice!\n");
    }
  } while (value != 100);

  return;
}
void MetroHash128::Finalize(uint8_t * const hash)
{
    // finalize bulk loop, if used
    if (bytes >= 32)
    {
        state.v[2] ^= rotate_right(((state.v[0] + state.v[3]) * k0) + state.v[1], 21) * k1;
        state.v[3] ^= rotate_right(((state.v[1] + state.v[2]) * k1) + state.v[0], 21) * k0;
        state.v[0] ^= rotate_right(((state.v[0] + state.v[2]) * k0) + state.v[3], 21) * k1;
        state.v[1] ^= rotate_right(((state.v[1] + state.v[3]) * k1) + state.v[2], 21) * k0;
    }
    
    // process any bytes remaining in the input buffer
    const uint8_t * ptr = reinterpret_cast<const uint8_t*>(input.b);
    const uint8_t * const end = ptr + (bytes % 32);
    
    if ((end - ptr) >= 16)
    {
        state.v[0] += read_u64(ptr) * k2; ptr += 8; state.v[0] = rotate_right(state.v[0],33) * k3;
        state.v[1] += read_u64(ptr) * k2; ptr += 8; state.v[1] = rotate_right(state.v[1],33) * k3;
        state.v[0] ^= rotate_right((state.v[0] * k2) + state.v[1], 45) * k1;
        state.v[1] ^= rotate_right((state.v[1] * k3) + state.v[0], 45) * k0;
    }

    if ((end - ptr) >= 8)
    {
        state.v[0] += read_u64(ptr) * k2; ptr += 8; state.v[0] = rotate_right(state.v[0],33) * k3;
        state.v[0] ^= rotate_right((state.v[0] * k2) + state.v[1], 27) * k1;
    }

    if ((end - ptr) >= 4)
    {
        state.v[1] += read_u32(ptr) * k2; ptr += 4; state.v[1] = rotate_right(state.v[1],33) * k3;
        state.v[1] ^= rotate_right((state.v[1] * k3) + state.v[0], 46) * k0;
    }

    if ((end - ptr) >= 2)
    {
        state.v[0] += read_u16(ptr) * k2; ptr += 2; state.v[0] = rotate_right(state.v[0],33) * k3;
        state.v[0] ^= rotate_right((state.v[0] * k2) + state.v[1], 22) * k1;
    }

    if ((end - ptr) >= 1)
    {
        state.v[1] += read_u8 (ptr) * k2; state.v[1] = rotate_right(state.v[1],33) * k3;
        state.v[1] ^= rotate_right((state.v[1] * k3) + state.v[0], 58) * k0;
    }
    
    state.v[0] += rotate_right((state.v[0] * k0) + state.v[1], 13);
    state.v[1] += rotate_right((state.v[1] * k1) + state.v[0], 37);
    state.v[0] += rotate_right((state.v[0] * k2) + state.v[1], 13);
    state.v[1] += rotate_right((state.v[1] * k3) + state.v[0], 37);

    bytes = 0;

    // do any endian conversion here

    memcpy(hash, state.v, 16);
}
Exemple #6
0
static void read_u16_func(void** state) {
	uint16_t comp_buf = 0;
	uint32_t idx = 0;

	for(uint32_t i = 0; i < CHAR_SIZE; i += 2) {
		comp_buf = (('a' + i) << 8) | ('b' + i);
		assert_int_equal(read_u16(buffer, &idx), comp_buf);
	}
}
Exemple #7
0
void test16(){
	int fd = open_file();
	u16 * myu16 = malloc(sizeof(u16));

	read_u16(fd,myu16);

	assertTrue_hexa("U16 Reader",*myu16,0x4944);
	
	close(fd);
}
Exemple #8
0
	u32					xbinary_reader::read(u16 & b)
	{
		if (_can_read(len_, cursor_, sizeof(b)))
		{
			xbyte const* ptr = buffer_ + cursor_;
			cursor_ += sizeof(b);
			b = read_u16(ptr);
			return sizeof(b);
		}
		return 0;
	}
Exemple #9
0
void main(){
	//ouverture 
	int fd ;
	fd = open("/home/marms/Documents/ASR/C/TP5/x.mp3", O_CREAT |  O_RDONLY, 0666 );
    if( fd == -1 ){
    	printf("erreur ouverture\n");
    	exit(15);
    }	
	
  	printf("\n====ESSAIS PERMUTE======\n");
	  
	  	u16 *x= (u16*)malloc(sizeof(u16)); 
	  	*x=0x4244;//BD
	 	affiche_u16(x);
		permut2(x); //DB 
		affiche_u16(x);
		printf("x, %0x\n",*x);

		u32* g= (u32*)malloc(sizeof(u32));
		*g=0x10203040;
		permut4(g);			
	 	printf("g, %0x\n",*g);
	printf("\n======FIN PERMUTE=======\n");
  
	u8* a = (u8*) malloc(sizeof(u8));
	if(! read_u8(fd,a)){ printf("echec3\n");}
	affiche_u8(a);


	u16* e = (u16*) malloc(sizeof(u16));
	if(! read_u16(fd,e)){ printf("echec3\n");}
	affiche_u16(e);
	
	u32* f = (u32*) malloc(sizeof(u32));
	if(! read_u32(fd,f)){ printf("echec4\n");}
	affiche_u32(f);	



		*h = 0x6d776e6e ; 
		affiche_u32(h);
		aff_bin((u8*)h);	 printf("\n"); 
	    *h=	convert_size(*h);
		aff_bin((u8*)h); printf("\n"); 
	//fermeture
    close(fd);
}
Exemple #10
0
StartOfFileRecord::StartOfFileRecord(const Source &source, const unsigned char *payload, int payload_len) {
  try {
    const unsigned char *ptr=payload;
    protocol_version = read_u16(ptr);
    time = TimeRecord(source, ptr);
    tick_period = read_u48(ptr);
    if (verbose) log_f("parse_bt_file: Parsing SOFR:  tick_period is %llu", tick_period);
    char *cptr = (char*) ptr, *end= (char*) payload+payload_len;
    if (end[-1] != 0) throw ParseError("At byte %d: DEVICE_PARAMS don't end with NUL", source.pos(end-1));
    while (cptr < end-1) {
      char *keyptr = cptr;
      cptr = strchr(cptr, '\t');
      if (!cptr) throw ParseError("At byte %d: DEVICE_PARAMS missing tab", source.pos(keyptr));
      std::string key(keyptr, cptr);
      cptr++; // skip tab
      char *valueptr = cptr;
      cptr = strchr(cptr, '\n');
      if (!cptr) throw ParseError("At byte %d: DEVICE_PARAMS missing newline", source.pos(valueptr));
      std::string value(valueptr, cptr);
      cptr++; // skip
      if (verbose) log_f("parse_bt_file:   '%s'='%s'", key.c_str(), value.c_str());
      device_params[key] = value;
    }
    
    if (!device_params.count("channel_specs")) {
      throw ParseError("No channel_specs field in DEVICE_PARAMS in START_OF_FILE record");
    }
    Json::Reader reader;
    if (!reader.parse(device_params["channel_specs"], channel_specs)) {
      throw ParseError("Failed to parse channel_specs JSON");
    }
    Json::Value::Members channel_names = channel_specs.getMemberNames();
    for (unsigned i = 0; i < channel_names.size(); i++) {
      std::string units = get_channel_units(channel_names[i]);
      double scale = get_channel_scale(channel_names[i]);
      if (verbose)
        log_f("parse_bt_file:   channel %d: '%s', units '%s', scale %g",
                i, channel_names[i].c_str(), units.c_str(), scale);
    }
  }
  catch (ParseError &e) {
    throw ParseError("In RTYPE_START_OF_FILE payload starting at byte %d: %s", source.pos(payload), e.what());
  }
}
Exemple #11
0
static const uint8_t *
mdns_read_header(const uint8_t *ptr, size_t n, struct mdns_hdr *hdr)
{
        if (n <= sizeof(struct mdns_hdr)) {
                errno = ENOSPC;
                return NULL;
        }
        ptr = read_u16(ptr, &n, &hdr->id);
        ptr = read_u16(ptr, &n, &hdr->flags);
        ptr = read_u16(ptr, &n, &hdr->num_qn);
        ptr = read_u16(ptr, &n, &hdr->num_ans_rr);
        ptr = read_u16(ptr, &n, &hdr->num_auth_rr);
        ptr = read_u16(ptr, &n, &hdr->num_add_rr);
        return ptr;
}
Exemple #12
0
int tag_read_id3_header(int fd, id3v2_header_t *header)
{
	if(strcmp("ID3", read_string(fd, header->ID3, 3, 0)))
		return -1;

	if(!read_u16(fd, &(header->version)))
		return -1;

	// version valide
	if(header->version > 0x0300)
		return -1;

	if(!read_u8(fd, &(header->flags)))
		return -1;

	if(!read_u32(fd, &(header->size)))
		return -1;

	header->size = convert_size(header->size);
	return 0;
}
Exemple #13
0
/**
 * Reads a frame, stores data into the structure
 *
 * @param fd file descriptor
 * @param frame structure pointer
 *
 * @return -1 on error, 0 otherwise
 */
int tag_read_one_frame(int fd, id3v2_frame_t *frame)
{
    u8 encoding;
	int i = 0;

    if(read_string(fd, frame->id, ID3V2_FRAME_ID_LENGTH, 0) == NULL)
		return -1;

    if(!read_u32(fd, &(frame->size)))
		return -1;
    if(!read_u16(fd, &(frame->flags)))
		return -1;

	if(frame->id[0] != 'T' || !strcmp(frame->id, "TXXX"))
	{
		lseek(fd, frame->size, SEEK_CUR);
		frame->text = NULL;
		return -1;
	}

	for(i = 0 ; i < ID3V2_FRAME_ID_LENGTH ; i++)
	{
		if(!isupper(frame->id[i]) && !isdigit(frame->id[i])) {
			lseek(fd, frame->size, SEEK_CUR);
			frame->text = NULL;
			return -1;
		}
	}


    if(!read_u8(fd, &(encoding)))
		return -1;

    frame->text = read_string(fd, NULL, frame->size - 1, (int) encoding);
	if(frame->text == NULL)
		return -1;


    return 0;
}
Exemple #14
0
int tag_read_id3_header(int fd, id3v2_header_t *header)
{
	if(strcmp("ID3", read_string(fd, header->ID3, 3, 0)) != 0)
	{
		printf("titi1");
		return -1;
	}


	if(!read_u16(fd, &(header->version)))
	{
		printf("titi2");
		return -1;
	}

	// version valide
	if(header->version > 0x0300)
	{
		printf("titi3");
		return -1;
	}

	if(!read_u8(fd, &(header->flags)))
	{
		printf("titi4");
		return -1;
	}

	if(!read_u32(fd, &(header->size)))
	{
		printf("titi5");
		return -1;
	}

	header->size = convert_size(header->size);
	return 0;
}
Exemple #15
0
int blob_decode_t::output(int &n,char ** &s_arr,int *&len_arr)
{

	int parser_pos=0;

	if(parser_pos+(int)sizeof(u32_t)>current_len) {mylog(log_info,"failed 0\n");return -1;}

	n=(int)read_u32(input_buf+parser_pos);
	if(n>max_blob_packet_num) {mylog(log_info,"failed 1\n");return -1;}
	s_arr=output_buf;
	len_arr=output_len;

	parser_pos+=sizeof(u32_t);
	for(int i=0;i<n;i++)
	{
		if(parser_pos+(int)sizeof(u16_t)>current_len) {mylog(log_info,"failed2 \n");return -1;}
		len_arr[i]=(int)read_u16(input_buf+parser_pos);
		parser_pos+=(int)sizeof(u16_t);
		if(parser_pos+len_arr[i]>current_len) {mylog(log_info,"failed 3 %d  %d %d\n",parser_pos,len_arr[i],current_len);return -1;}
		s_arr[i]=input_buf+parser_pos;
		parser_pos+=len_arr[i];
	}
	return 0;
}
void metrohash128crc_2(const uint8_t * key, uint64_t len, uint32_t seed, uint8_t * out)
{
    static const uint64_t k0 = 0xEE783E2F;
    static const uint64_t k1 = 0xAD07C493;
    static const uint64_t k2 = 0x797A90BB;
    static const uint64_t k3 = 0x2E4B2E1B;

    const uint8_t * ptr = reinterpret_cast<const uint8_t*>(key);
    const uint8_t * const end = ptr + len;
    
    uint64_t v[4];
    
    v[0] = ((static_cast<uint64_t>(seed) - k0) * k3) + len;
    v[1] = ((static_cast<uint64_t>(seed) + k1) * k2) + len;
    
    if (len >= 32)
    {        
        v[2] = ((static_cast<uint64_t>(seed) + k0) * k2) + len;
        v[3] = ((static_cast<uint64_t>(seed) - k1) * k3) + len;

        do
        {
            v[0] ^= _mm_crc32_u64(v[0], read_u64(ptr)); ptr += 8;
            v[1] ^= _mm_crc32_u64(v[1], read_u64(ptr)); ptr += 8;
            v[2] ^= _mm_crc32_u64(v[2], read_u64(ptr)); ptr += 8;
            v[3] ^= _mm_crc32_u64(v[3], read_u64(ptr)); ptr += 8;
        }
        while (ptr <= (end - 32));

        v[2] ^= rotate_right(((v[0] + v[3]) * k0) + v[1], 12) * k1;
        v[3] ^= rotate_right(((v[1] + v[2]) * k1) + v[0], 19) * k0;
        v[0] ^= rotate_right(((v[0] + v[2]) * k0) + v[3], 12) * k1;
        v[1] ^= rotate_right(((v[1] + v[3]) * k1) + v[2], 19) * k0;
    }
    
    if ((end - ptr) >= 16)
    {
        v[0] += read_u64(ptr) * k2; ptr += 8; v[0] = rotate_right(v[0],41) * k3;
        v[1] += read_u64(ptr) * k2; ptr += 8; v[1] = rotate_right(v[1],41) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 10) * k1;
        v[1] ^= rotate_right((v[1] * k3) + v[0], 10) * k0;
    }
    
    if ((end - ptr) >= 8)
    {
        v[0] += read_u64(ptr) * k2; ptr += 8; v[0] = rotate_right(v[0],34) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 22) * k1;
    }
    
    if ((end - ptr) >= 4)
    {
        v[1] ^= _mm_crc32_u64(v[0], read_u32(ptr)); ptr += 4;
        v[1] ^= rotate_right((v[1] * k3) + v[0], 14) * k0;
    }
    
    if ((end - ptr) >= 2)
    {
        v[0] ^= _mm_crc32_u64(v[1], read_u16(ptr)); ptr += 2;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 15) * k1;
    }
    
    if ((end - ptr) >= 1)
    {
        v[1] ^= _mm_crc32_u64(v[0], read_u8 (ptr));
        v[1] ^= rotate_right((v[1] * k3) + v[0],  18) * k0;
    }
    
    v[0] += rotate_right((v[0] * k0) + v[1], 15);
    v[1] += rotate_right((v[1] * k1) + v[0], 27);
    v[0] += rotate_right((v[0] * k0) + v[1], 15);
    v[1] += rotate_right((v[1] * k1) + v[0], 27);

    memcpy(out, v, 16);
}
Exemple #17
0
bool
db_dwarf_line_at_pc(const char *linetab, size_t linetabsize, uintptr_t pc,
    const char **outdirname, const char **outbasename, int *outline)
{
	struct dwbuf table = { .buf = linetab, .len = linetabsize };

	/*
	 * For simplicity, we simply brute force search through the entire
	 * line table each time.
	 */
	uint32_t unitsize;
	struct dwbuf unit;
next:
	/* Line tables are a sequence of compilation unit entries. */
	if (!read_u32(&table, &unitsize) || unitsize >= 0xfffffff0 ||
	    !read_buf(&table, &unit, unitsize))
		return (false);

	uint16_t version;
	uint32_t header_size;
	if (!read_u16(&unit, &version) || version > 2 ||
	    !read_u32(&unit, &header_size))
		goto next;

	struct dwbuf headerstart = unit;
	uint8_t min_insn_length, default_is_stmt, line_range, opcode_base;
	int8_t line_base;
	if (!read_u8(&unit, &min_insn_length) ||
	    !read_u8(&unit, &default_is_stmt) ||
	    !read_s8(&unit, &line_base) ||
	    !read_u8(&unit, &line_range) ||
	    !read_u8(&unit, &opcode_base))
		goto next;

	/*
	 * Directory and file names are next in the header, but for now we
	 * skip directly to the line number program.
	 */
	struct dwbuf names = unit;
	unit = headerstart;
	if (!skip_bytes(&unit, header_size))
		return (false);

	/* VM registers. */
	uint64_t address = 0, file = 1, line = 1, column = 0;
	uint8_t is_stmt = default_is_stmt;
	bool basic_block = false, end_sequence = false;
	bool prologue_end = false, epilogue_begin = false;

	/* Last line table entry emitted, if any. */
	bool have_last = false;
	uint64_t last_line = 0, last_file = 0;

	/* Time to run the line program. */
	uint8_t opcode;
	while (read_u8(&unit, &opcode)) {
		bool emit = false, reset_basic_block = false;

		if (opcode >= opcode_base) {
			/* "Special" opcodes. */
			uint8_t diff = opcode - opcode_base;
			address += diff / line_range;
			line += line_base + diff % line_range;
			emit = true;
		} else if (opcode == 0) {
			/* "Extended" opcodes. */
			uint64_t extsize;
			struct dwbuf extra;
			if (!read_uleb128(&unit, &extsize) ||
			    !read_buf(&unit, &extra, extsize) ||
			    !read_u8(&extra, &opcode))
				goto next;
			switch (opcode) {
			case DW_LNE_end_sequence:
				emit = true;
				end_sequence = true;
				break;
			case DW_LNE_set_address:
				switch (extra.len) {
				case 4: {
					uint32_t address32;
					if (!read_u32(&extra, &address32))
						goto next;
					address = address32;
					break;
				}
				case 8:
					if (!read_u64(&extra, &address))
						goto next;
					break;
				default:
					DWARN("unexpected address length: %zu",
					    extra.len);
					goto next;
				}
				break;
			case DW_LNE_define_file:
				/* XXX: hope this isn't needed */
			default:
				DWARN("unknown extended opcode: %d", opcode);
				goto next;
			}
		} else {
			/* "Standard" opcodes. */
			switch (opcode) {
			case DW_LNS_copy:
				emit = true;
				reset_basic_block = true;
				break;
			case DW_LNS_advance_pc: {
				uint64_t delta;
				if (!read_uleb128(&unit, &delta))
					goto next;
				address += delta * min_insn_length;
				break;
			}
			case DW_LNS_advance_line: {
				int64_t delta;
				if (!read_sleb128(&unit, &delta))
					goto next;
				line += delta;
				break;
			}
			case DW_LNS_set_file:
				if (!read_uleb128(&unit, &file))
					goto next;
				break;
			case DW_LNS_set_column:
				if (!read_uleb128(&unit, &column))
					goto next;
				break;
			case DW_LNS_negate_stmt:
				is_stmt = !is_stmt;
				break;
			case DW_LNS_set_basic_block:
				basic_block = true;
				break;
			case DW_LNS_const_add_pc:
				address += (255 - opcode_base) / line_range;
				break;
			case DW_LNS_set_prologue_end:
				prologue_end = true;
				break;
			case DW_LNS_set_epilogue_begin:
				epilogue_begin = true;
				break;
			default:
				DWARN("unknown standard opcode: %d", opcode);
				goto next;
			}
		}

		if (emit) {
			if (address > pc) {
				/* Found an entry after our target PC. */
				if (!have_last) {
					/* Give up on this program. */
					break;
				}
				/* Return the last entry. */
				*outline = last_line;
				return (read_filename(&names, outdirname,
				    outbasename, opcode_base, file));
			}

			last_file = file;
			last_line = line;
			have_last = true;
		}

		if (reset_basic_block)
			basic_block = false;
	}

	goto next;
}
Exemple #18
0
void parse_bt_file(const std::string &infile,
                   std::map<std::string, simple_shared_ptr<std::vector<DataSample<double> > > > &data,
                   std::vector<ParseError> &errors,
		   ParseInfo &info)
{
  info.good_records = 0;
  info.bad_records = 0;
  double begintime = doubletime();
  // Memory-map file
  FILE *in = fopen(infile.c_str(), "rb");
  if (!in) throw std::runtime_error("fopen");
  struct stat statbuf;
  if (-1 == fstat(fileno(in), &statbuf)) throw std::runtime_error("fopen");
  long long len = statbuf.st_size;
  const unsigned char *in_mem = (unsigned char*) mmap(NULL, len, PROT_READ, MAP_SHARED/*|MAP_POPULATE*/, fileno(in), 0);
  const unsigned char *end = in_mem + len;
  if (in_mem == (unsigned char*)-1) throw std::runtime_error("mmap");
  if (verbose) log_f("parse_bt_file: Mapped %s (%lld KB)", infile.c_str(), len/1024);
  Source source(in_mem);
  const unsigned char *ptr = in_mem;

  int nrecords[256];
  memset(nrecords, 0, sizeof(nrecords));
  long long nvalues=0;
  
  StartOfFileRecord sofr;
  TickToTime ttt;

  std::map<std::string, unsigned long long> last_tick;
  bool out_of_order = false;
  
  while (ptr < end) {
    const unsigned char *beginning_of_record = ptr;
    try {
      unsigned int magic = read_u32(ptr);
      if (magic != 0xb0de744c) throw ParseError("Incorrect magic # at byte %d", source.pos(ptr - 4));
      unsigned int record_size = read_u32(ptr);
      if (verbose) {
        log_f("parse_bt_file:  At location %d, magic=0x%x, record size %d",
              (int)(beginning_of_record - in_mem), magic, record_size);
      }
      if (record_size + beginning_of_record > end) throw ParseError("Record size too long at byte %d (size=%d, but only %d bytes left in file)", source.pos(ptr - 4), record_size, end-beginning_of_record);
      int record_type = read_u16(ptr);
      if (record_type != RTYPE_START_OF_FILE && record_type != RTYPE_RTC && record_type != RTYPE_PERIODIC_DATA) {
        throw ParseError("Unknown record type 0x%x at byte %d", record_type, source.pos(ptr - 2));
      }
      const unsigned char *payload = ptr;
      unsigned int payload_len = record_size-14;
      ptr += payload_len;
      if (verbose) log_f("parse_bt_file: Got record type %d, payload len %d", record_type, payload_len);
      unsigned int crc = read_u32(ptr);
      unsigned int calculated_crc = crc32(beginning_of_record, record_size - 4, 0);
      if (crc != calculated_crc) {
        // Recoverable error;  add to errors and try to continue
        errors.push_back(ParseError("Incorrect CRC32 byte %d.  read 0x%x != calculated 0x%x",
                                    source.pos(ptr - 4), crc, calculated_crc));
	if (record_type == RTYPE_PERIODIC_DATA) info.bad_records++;
        continue;
      }

      switch (record_type) {
      case RTYPE_START_OF_FILE:
        sofr = StartOfFileRecord(source, payload, payload_len);
        ttt.receive_binrec(sofr);
	info.channel_specs = sofr.channel_specs;
        break;
      case RTYPE_RTC:
      {
        RtcRecord rtcr(source, payload, payload_len);
        ttt.receive_binrec(rtcr);
        if (verbose) log_f("parse_bt_file: %s", rtcr.to_string().c_str());
      }
      break;
      case RTYPE_PERIODIC_DATA:
      {
        PeriodicDataRecord pdr(source, payload, payload_len, &sofr);
        ttt.receive_binrec(pdr);
        pdr.set_time(ttt);
        for (unsigned i = 0; i < pdr.n_channels(); i++) {
          std::string channel_name = pdr.channel_name(i);
          nvalues += pdr.number_of_samples;
          log_f("parse_pt_file: %d samples, start tick 0x%x (%u)",
                pdr.number_of_samples, pdr.first_sample_short_tick, pdr.first_sample_short_tick);
          std::vector<DataSample<double> > data_samples;
          pdr.get_data_samples(i, data_samples);

          if (data_samples.size()) {
            if (data.find(channel_name) == data.end()) {
              data[channel_name].reset(new std::vector<DataSample<double> >());
            } else {
              if (data[channel_name]->back().time > data_samples.front().time) {
                if (verbose) log_f("Warning: sample times in channel %s are out-of-order (%f > %f)",
                                   channel_name.c_str(),
                                   data[channel_name]->back().time, data_samples.front().time);
                out_of_order = true;
              }
            }
            
            data[channel_name]->insert(data[channel_name]->end(), data_samples.begin(), data_samples.end());
	    info.good_records++;
          }
          last_tick[channel_name] = pdr.first_sample_long_tick;
          
          
        }
      }
      break;
      default:
        assert(0);
      }
      nrecords[record_type]++;
    }
    catch (ParseError &e) {
      errors.push_back(ParseError("In record starting at byte %d in file %s: %s",
                                  source.pos(beginning_of_record), infile.c_str(), e.what()));
      info.bad_records++;
    }
  }
  
  if (-1 == munmap((void*)in_mem, len)) { perror("munmap"); exit(1); }
  fclose(in);
  
  if (out_of_order) {
    for (std::map<std::string, simple_shared_ptr<std::vector<DataSample<double> > > >::iterator i =
           data.begin(); i != data.end(); ++i) {
      
      simple_shared_ptr<std::vector<DataSample<double > > > samples = i->second;
      std::sort(samples->begin(), samples->end(), DataSample<double>::time_lessthan);
    }
  }

  // Check samples are in order
  for (std::map<std::string, simple_shared_ptr<std::vector<DataSample<double> > > >::iterator i =
         data.begin(); i != data.end(); ++i) {
    
    simple_shared_ptr<std::vector<DataSample<double > > > samples = i->second;
    for (unsigned i = 0; i < samples->size()-1; i++) {
      assert((*samples)[i].time <= ((*samples)[i+1].time));
    }
  }

  double duration = doubletime() - begintime;
  log_f("parse_bt_file: Parsed %lld bytes in %g seconds (%dK/sec)", len, duration, (int)(len / duration / 1024));
  if (verbose) {
    log_f("parse_bt_file: %d RTYPE_START_OF_FILE records", nrecords[RTYPE_START_OF_FILE]);
    log_f("parse_bt_file: %d RTYPE_RTC records", nrecords[RTYPE_RTC]);
    log_f("parse_bt_file: %d RTYPE_PERIODIC_DATA records", nrecords[RTYPE_PERIODIC_DATA]);
    log_f("parse_bt_file:    %lld values", nvalues);
  }
}
void metrohash64crc_1(const uint8_t * key, uint64_t len, uint32_t seed, uint8_t * out)
{
    static const uint64_t k0 = 0xC83A91E1;
    static const uint64_t k1 = 0x8648DBDB;
    static const uint64_t k2 = 0x7BDEC03B;
    static const uint64_t k3 = 0x2F5870A5;

    const uint8_t * ptr = reinterpret_cast<const uint8_t*>(key);
    const uint8_t * const end = ptr + len;
    
    uint64_t hash = ((static_cast<uint64_t>(seed) + k2) * k0) + len;
    
    if (len >= 32)
    {
        uint64_t v[4];
        v[0] = hash;
        v[1] = hash;
        v[2] = hash;
        v[3] = hash;
        
        do
        {
            v[0] ^= _mm_crc32_u64(v[0], read_u64(ptr)); ptr += 8;
            v[1] ^= _mm_crc32_u64(v[1], read_u64(ptr)); ptr += 8;
            v[2] ^= _mm_crc32_u64(v[2], read_u64(ptr)); ptr += 8;
            v[3] ^= _mm_crc32_u64(v[3], read_u64(ptr)); ptr += 8;
        }
        while (ptr <= (end - 32));

        v[2] ^= rotate_right(((v[0] + v[3]) * k0) + v[1], 33) * k1;
        v[3] ^= rotate_right(((v[1] + v[2]) * k1) + v[0], 33) * k0;
        v[0] ^= rotate_right(((v[0] + v[2]) * k0) + v[3], 33) * k1;
        v[1] ^= rotate_right(((v[1] + v[3]) * k1) + v[2], 33) * k0;
        hash += v[0] ^ v[1];
    }
    
    if ((end - ptr) >= 16)
    {
        uint64_t v0 = hash + (read_u64(ptr) * k0); ptr += 8; v0 = rotate_right(v0,33) * k1;
        uint64_t v1 = hash + (read_u64(ptr) * k1); ptr += 8; v1 = rotate_right(v1,33) * k2;
        v0 ^= rotate_right(v0 * k0, 35) + v1;
        v1 ^= rotate_right(v1 * k3, 35) + v0;
        hash += v1;
    }
    
    if ((end - ptr) >= 8)
    {
        hash += read_u64(ptr) * k3; ptr += 8;
        hash ^= rotate_right(hash, 33) * k1;
        
    }
    
    if ((end - ptr) >= 4)
    {
        hash ^= _mm_crc32_u64(hash, read_u32(ptr)); ptr += 4;
        hash ^= rotate_right(hash, 15) * k1;
    }
    
    if ((end - ptr) >= 2)
    {
        hash ^= _mm_crc32_u64(hash, read_u16(ptr)); ptr += 2;
        hash ^= rotate_right(hash, 13) * k1;
    }
    
    if ((end - ptr) >= 1)
    {
        hash ^= _mm_crc32_u64(hash, read_u8(ptr));
        hash ^= rotate_right(hash, 25) * k1;
    }
    
    hash ^= rotate_right(hash, 33);
    hash *= k0;
    hash ^= rotate_right(hash, 33);

    memcpy(out, &hash, 8);
}
Exemple #20
0
static int read_header(void *ss, uchar *head)
{
	*head = read_u8(ss, 0);
	return read_u16(ss, 0);
}
Exemple #21
0
int16_t read_s16(const unsigned char *p)
{
	return (int16_t) read_u16(p);
}
Exemple #22
0
void cmd_chlist(int socket)
{
	char line[80];
	FILE *fp;
	int n,i,svc_name_len, rf_name_len;
	unsigned char *names;
	u16 svcid;
	u16 name_offset;
	u16 rf_offset;
	u32 svc_offset;
	RFInfo *rf, *rf_ptr;
	u16 rf_count;
	
	fp = fopen(SVC_PATH, "r");
	if(fp == NULL)
		return;

	fseek(fp, 0x30, SEEK_SET);
	//read number of channels
	n = read_u16(fp);
	fseek(fp, 0x4, SEEK_CUR);
	svc_name_len = read_u32(fp);
	rf_name_len = read_u32(fp);

	names = (unsigned char *)malloc(svc_name_len);
	
	fseek(fp, 0x3e, SEEK_SET);
	
	//read in name data
	fread(names,svc_name_len, 1, fp);
	
	//move to start of svcid segment
	fseek(fp, rf_name_len + 0x58, SEEK_CUR);
	
	//save the offset for later
	svc_offset = ftell(fp);
	
	//skip the svcid segment
	fseek(fp, 0x24 * n, SEEK_CUR);

	fseek(fp, 0x6, SEEK_CUR); //move to rf_count
	rf_count = read_u16(fp);
	
	rf = malloc(sizeof(RFInfo) * rf_count);
	
	rf_ptr = rf;
	
	//move to first rf entry
	fseek(fp, 0x20, SEEK_CUR);
	
	for(i=0;i < rf_count && !feof(fp);i++)
	{
		fseek(fp, 0x8, SEEK_CUR); //skip rf data + Mhz
		rf_ptr->onid = read_u16(fp);
		rf_ptr->tsid = read_u16(fp);
		
		rf_ptr++;
	}

	fseek(fp, svc_offset, SEEK_SET);
	
	//send the number of channels
	sprintf(line, "%d\n", n);
	printf("%s",line);
	write(socket,line,strlen(line));
	
	for(i=0;i<n;i++)
	{
		fseek(fp, 0x4, SEEK_CUR);
		rf_offset = read_u16(fp); //rf offset
		fseek(fp, 0x2, SEEK_CUR); //skip unknown
		svcid = read_u16(fp); //svcid
		fseek(fp, 0xa, SEEK_CUR); //skip to name offset data
		
		name_offset = read_u16(fp);
		
		sprintf(line, "%d,%d,%d:%s\n",rf[rf_offset].onid, rf[rf_offset].tsid, svcid, &names[name_offset]);
		printf("%s",line);
		write(socket,line,strlen(line));
		
		fseek(fp, 0xe, SEEK_CUR); //skip to end of this record.

	}

	free(rf);
	free(names);
	fclose(fp);

	return;
}
void metrohash128crc_1(const uint8_t * key, uint64_t len, uint32_t seed, uint8_t * out)
{
    static const uint64_t k0 = 0xC83A91E1;
    static const uint64_t k1 = 0x8648DBDB;
    static const uint64_t k2 = 0x7BDEC03B;
    static const uint64_t k3 = 0x2F5870A5;

    const uint8_t * ptr = reinterpret_cast<const uint8_t*>(key);
    const uint8_t * const end = ptr + len;
    
    uint64_t v[4];
    
    v[0] = ((static_cast<uint64_t>(seed) - k0) * k3) + len;
    v[1] = ((static_cast<uint64_t>(seed) + k1) * k2) + len;
    
    if (len >= 32)
    {        
        v[2] = ((static_cast<uint64_t>(seed) + k0) * k2) + len;
        v[3] = ((static_cast<uint64_t>(seed) - k1) * k3) + len;

        do
        {
            v[0] ^= _mm_crc32_u64(v[0], read_u64(ptr)); ptr += 8;
            v[1] ^= _mm_crc32_u64(v[1], read_u64(ptr)); ptr += 8;
            v[2] ^= _mm_crc32_u64(v[2], read_u64(ptr)); ptr += 8;
            v[3] ^= _mm_crc32_u64(v[3], read_u64(ptr)); ptr += 8;
        }
        while (ptr <= (end - 32));

        v[2] ^= rotate_right(((v[0] + v[3]) * k0) + v[1], 34) * k1;
        v[3] ^= rotate_right(((v[1] + v[2]) * k1) + v[0], 37) * k0;
        v[0] ^= rotate_right(((v[0] + v[2]) * k0) + v[3], 34) * k1;
        v[1] ^= rotate_right(((v[1] + v[3]) * k1) + v[2], 37) * k0;
    }
    
    if ((end - ptr) >= 16)
    {
        v[0] += read_u64(ptr) * k2; ptr += 8; v[0] = rotate_right(v[0],34) * k3;
        v[1] += read_u64(ptr) * k2; ptr += 8; v[1] = rotate_right(v[1],34) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 30) * k1;
        v[1] ^= rotate_right((v[1] * k3) + v[0], 30) * k0;
    }
    
    if ((end - ptr) >= 8)
    {
        v[0] += read_u64(ptr) * k2; ptr += 8; v[0] = rotate_right(v[0],36) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 23) * k1;
    }
    
    if ((end - ptr) >= 4)
    {
        v[1] ^= _mm_crc32_u64(v[0], read_u32(ptr)); ptr += 4;
        v[1] ^= rotate_right((v[1] * k3) + v[0], 19) * k0;
    }
    
    if ((end - ptr) >= 2)
    {
        v[0] ^= _mm_crc32_u64(v[1], read_u16(ptr)); ptr += 2;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 13) * k1;
    }
    
    if ((end - ptr) >= 1)
    {
        v[1] ^= _mm_crc32_u64(v[0], read_u8 (ptr));
        v[1] ^= rotate_right((v[1] * k3) + v[0], 17) * k0;
    }
    
    v[0] += rotate_right((v[0] * k0) + v[1], 11);
    v[1] += rotate_right((v[1] * k1) + v[0], 26);
    v[0] += rotate_right((v[0] * k0) + v[1], 11);
    v[1] += rotate_right((v[1] * k1) + v[0], 26);

    memcpy(out, v, 16);
}
Exemple #24
0
void metrohash128_2(const uint8_t * key, uint64_t len, uint32_t seed, uint8_t * out)
{
    static const uint64_t k0 = 0xD6D018F5;
    static const uint64_t k1 = 0xA2AA033B;
    static const uint64_t k2 = 0x62992FC1;
    static const uint64_t k3 = 0x30BC5B29; 

    const uint8_t * ptr = reinterpret_cast<const uint8_t*>(key);
    const uint8_t * const end = ptr + len;
    
    uint64_t v[4];
    
    v[0] = ((static_cast<uint64_t>(seed) - k0) * k3) + len;
    v[1] = ((static_cast<uint64_t>(seed) + k1) * k2) + len;
    
    if (len >= 32)
    {        
        v[2] = ((static_cast<uint64_t>(seed) + k0) * k2) + len;
        v[3] = ((static_cast<uint64_t>(seed) - k1) * k3) + len;

        do
        {
            v[0] += read_u64(ptr) * k0; ptr += 8; v[0] = rotate_right(v[0],29) + v[2];
            v[1] += read_u64(ptr) * k1; ptr += 8; v[1] = rotate_right(v[1],29) + v[3];
            v[2] += read_u64(ptr) * k2; ptr += 8; v[2] = rotate_right(v[2],29) + v[0];
            v[3] += read_u64(ptr) * k3; ptr += 8; v[3] = rotate_right(v[3],29) + v[1];
        }
        while (ptr <= (end - 32));

        v[2] ^= rotate_right(((v[0] + v[3]) * k0) + v[1], 33) * k1;
        v[3] ^= rotate_right(((v[1] + v[2]) * k1) + v[0], 33) * k0;
        v[0] ^= rotate_right(((v[0] + v[2]) * k0) + v[3], 33) * k1;
        v[1] ^= rotate_right(((v[1] + v[3]) * k1) + v[2], 33) * k0;
    }
    
    if ((end - ptr) >= 16)
    {
        v[0] += read_u64(ptr) * k2; ptr += 8; v[0] = rotate_right(v[0],29) * k3;
        v[1] += read_u64(ptr) * k2; ptr += 8; v[1] = rotate_right(v[1],29) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 29) * k1;
        v[1] ^= rotate_right((v[1] * k3) + v[0], 29) * k0;
    }
    
    if ((end - ptr) >= 8)
    {
        v[0] += read_u64(ptr) * k2; ptr += 8; v[0] = rotate_right(v[0],29) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 29) * k1;
    }
    
    if ((end - ptr) >= 4)
    {
        v[1] += read_u32(ptr) * k2; ptr += 4; v[1] = rotate_right(v[1],29) * k3;
        v[1] ^= rotate_right((v[1] * k3) + v[0], 25) * k0;
    }
    
    if ((end - ptr) >= 2)
    {
        v[0] += read_u16(ptr) * k2; ptr += 2; v[0] = rotate_right(v[0],29) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 30) * k1;
    }
    
    if ((end - ptr) >= 1)
    {
          v[1] += read_u8 (ptr) * k2; v[1] = rotate_right(v[1],29) * k3;
          v[1] ^= rotate_right((v[1] * k3) + v[0], 18) * k0;
    }
    
    v[0] += rotate_right((v[0] * k0) + v[1], 33);
    v[1] += rotate_right((v[1] * k1) + v[0], 33);
    v[0] += rotate_right((v[0] * k2) + v[1], 33);
    v[1] += rotate_right((v[1] * k3) + v[0], 33);

    // do any endian conversion here

    memcpy(out, v, 16);
}
Exemple #25
0
void process(NIC* ni) {
	static uint32_t myip = 0xc0a86402;	// 192.168.100.2
	
	Packet* packet = nic_input(ni);
	if(!packet)
		return;
	
	Ether* ether = (Ether*)(packet->buffer + packet->start);
	if(endian16(ether->type) == ETHER_TYPE_ARP) {
		// ARP response
		ARP* arp = (ARP*)ether->payload;
		if(endian16(arp->operation) == 1 && endian32(arp->tpa) == myip) {
			ether->dmac = ether->smac;
			ether->smac = endian48(ni->mac);
			arp->operation = endian16(2);
			arp->tha = arp->sha;
			arp->tpa = arp->spa;
			arp->sha = ether->smac;
			arp->spa = endian32(myip);
			
			nic_output(ni, packet);
			packet = NULL;
		}
	} else if(endian16(ether->type) == ETHER_TYPE_IPv4) {
		IP* ip = (IP*)ether->payload;
		
		if(ip->protocol == IP_PROTOCOL_ICMP && endian32(ip->destination) == myip) {
			// Echo reply
			ICMP* icmp = (ICMP*)ip->body;
			
			icmp->type = 0;
			icmp->checksum = 0;
			icmp->checksum = endian16(checksum(icmp, packet->end - packet->start - ETHER_LEN - IP_LEN));
			
			ip->destination = ip->source;
			ip->source = endian32(myip);
			ip->ttl = endian8(64);
			ip->checksum = 0;
			ip->checksum = endian16(checksum(ip, ip->ihl * 4));
			
			ether->dmac = ether->smac;
			ether->smac = endian48(ni->mac);
			
			nic_output(ni, packet);
			packet = NULL;
		} else if(ip->protocol == IP_PROTOCOL_UDP) {
			UDP* udp = (UDP*)ip->body;
			
			if(endian16(udp->destination) == 9000) {
				reply_count = 2;
				
				// Control packet
				uint32_t idx = 0;
				seq = read_u16(udp->body, &idx);
				user_mac = endian48(ether->smac);
				user_ip = endian32(ip->source);
				user_port = endian16(udp->source);
				uint8_t msg = read_u8(udp->body, &idx);
				switch(msg) {
					case 1: // MSG_CREATE
					{
						idx++;	// read ctype
						uint32_t clen = read_u32(udp->body, &idx);
						char collection[clen + 1];
						collection[clen] = '\0';
						memcpy(collection, udp->body + idx, clen);
						idx += clen;
						
						uint64_t id = newID(collection);
						memmove(udp->body + idx + 9, udp->body + idx, endian16(udp->length) - 8 - idx);
						packet->end += 9;
						
						udp->length = endian16(endian16(udp->length) + 9);
						ip->length = endian16(endian16(ip->length) + 9);
						
						write_u8(udp->body, 4, &idx);
						write_u64(udp->body, id, &idx);
					}
						break;
					case 2: // MSG_READ
						reply_count = 1;
						break;
					case 3: // MSG_RETRIEVE
						break;
					case 4: // MSG_UPDATE
						break;
					case 5: // MSG_DELETE
						break;
					case 6: // MSG_HELLO
						reply_count = 1;
						break;
				}
				
				udp->source = endian16(9999);
				udp->destination = endian16(9001);
				udp->checksum = 0;
				
				ip->destination = ip->source;
				ip->source = endian32(myip);
				ip->ttl = endian8(ip->ttl) - 1;
				ip->checksum = 0;
				ip->checksum = endian16(checksum(ip, ip->ihl * 4));
				
				ether->dmac = ether->smac;
				ether->smac = endian48(ni->mac);
				
				nic_output_dup(ni, packet);
				
				udp->destination = endian16(9002);
				ip->checksum = 0;
				ip->checksum = endian16(checksum(ip, ip->ihl * 4));
				nic_output_dup(ni, packet);
				
				udp->destination = endian16(9003);
				ip->checksum = 0;
				ip->checksum = endian16(checksum(ip, ip->ihl * 4));
				nic_output(ni, packet);
				packet = NULL;
			} else if(endian16(udp->destination) == 9999) {
				uint32_t idx = 0;
				uint16_t seq2 = read_u16(udp->body, &idx);
				if(seq == seq2 && --reply_count == 0) {
					udp->checksum = 0;
					udp->destination = endian16(user_port);
					udp->source = endian16(9000);
					
					ip->destination = endian32(user_ip);
					ip->source = endian32(myip);
					ip->ttl = endian8(64);
					ip->checksum = 0;
					ip->checksum = endian16(checksum(ip, ip->ihl * 4));
					
					ether->dmac = endian48(user_mac);
					ether->smac = endian48(ni->mac);
					
					nic_output(ni, packet);
					packet = NULL;
				}
			}
		}
	}
	
	if(packet)
		nic_free(packet);
}
Exemple #26
0
// Parse the user data for captions. The udtype variable denotes
// to which type of data it belongs:
// 0 .. sequence header
// 1 .. GOP header
// 2 .. picture header
// Return TRUE if the data parsing finished, FALSE otherwise.
// estream->pos is advanced. Data is only processed if ustream->error
// is FALSE, parsing can set ustream->error to TRUE.
int user_data(struct lib_cc_decode *ctx, struct bitstream *ustream, int udtype, struct cc_subtitle *sub)
{
	dbg_print(CCX_DMT_VERBOSE, "user_data(%d)\n", udtype);

	// Shall not happen
	if (ustream->error || ustream->bitsleft <= 0)
	{
		// ustream->error=1;
		return 0; // Actually discarded on call.
		// CFS: Seen in a Wobble edited file.
		// fatal(CCX_COMMON_EXIT_BUG_BUG, "user_data: Impossible!");
	}

	// Do something
	ctx->stat_numuserheaders++;
	//header+=4;

	unsigned char *ud_header = next_bytes(ustream, 4);
	if (ustream->error || ustream->bitsleft <= 0)
	{
		return 0;  // Actually discarded on call.
		// CFS: Seen in Stick_VHS.mpg.
		// fatal(CCX_COMMON_EXIT_BUG_BUG, "user_data: Impossible!");
	}

	// DVD CC header, see
	// <http://www.theneitherworld.com/mcpoodle/SCC_TOOLS/DOCS/SCC_FORMAT.HTML>
	if ( !memcmp(ud_header,"\x43\x43", 2 ) )
	{
		ctx->stat_dvdccheaders++;

		// Probably unneeded, but keep looking for extra caption blocks
		int maybeextracb = 1;

		read_bytes(ustream, 4); // "43 43 01 F8"

		unsigned char pattern_flag = (unsigned char) read_bits(ustream,1);
		read_bits(ustream,1);
		int capcount=(int) read_bits(ustream,5);
		int truncate_flag = (int) read_bits(ustream,1); // truncate_flag - one CB extra

		int field1packet = 0; // expect Field 1 first
		if (pattern_flag == 0x00)
			field1packet=1; // expect Field 1 second

		dbg_print(CCX_DMT_VERBOSE, "Reading %d%s DVD CC segments\n",
				capcount, (truncate_flag?"+1":""));

		capcount += truncate_flag;

		// This data comes before the first frame header, so
		// in order to get the correct timing we need to set the
		// current time to one frame after the maximum time of the
		// last GOP.  Only useful when there are frames before
		// the GOP.
		if (ctx->timing->fts_max > 0)
			ctx->timing->fts_now = ctx->timing->fts_max + (LLONG) (1000.0/current_fps);

		int rcbcount = 0;
		for (int i=0; i<capcount; i++)
		{
			for (int j=0;j<2;j++)
			{
				unsigned char data[3];
				data[0]=read_u8(ustream);
				data[1]=read_u8(ustream);
				data[2]=read_u8(ustream);

				// Obey the truncate flag.
				if ( truncate_flag && i == capcount-1 && j == 1 )
				{
					maybeextracb = 0;
					break;
				}
				/* Field 1 and 2 data can be in either order,
				   with marker bytes of \xff and \xfe
				   Since markers can be repeated, use pattern as well */
				if ((data[0]&0xFE) == 0xFE) // Check if valid
				{
					if (data[0]==0xff && j==field1packet)
						data[0]=0x04; // Field 1
					else
						data[0]=0x05; // Field 2
					do_cb(ctx, data, sub);
					rcbcount++;
				}
				else
				{
					dbg_print(CCX_DMT_VERBOSE, "Illegal caption segment - stop here.\n");
					maybeextracb = 0;
					break;
				}
			}
		}
		// Theoretically this should not happen, oh well ...
		// Deal with extra closed captions some DVD have.
		int ecbcount = 0;
		while ( maybeextracb && (next_u8(ustream)&0xFE) == 0xFE )
		{
			for (int j=0;j<2;j++)
			{
				unsigned char data[3];
				data[0]=read_u8(ustream);
				data[1]=read_u8(ustream);
				data[2]=read_u8(ustream);
				/* Field 1 and 2 data can be in either order,
				   with marker bytes of \xff and \xfe
				   Since markers can be repeated, use pattern as well */
				if ((data[0]&0xFE) == 0xFE) // Check if valid
				{
					if (data[0]==0xff && j==field1packet)
						data[0]=0x04; // Field 1
					else
						data[0]=0x05; // Field 2
					do_cb(ctx, data, sub);
					ecbcount++;
				}
				else
				{
					dbg_print(CCX_DMT_VERBOSE, "Illegal (extra) caption segment - stop here.\n");
					maybeextracb = 0;
					break;
				}
			}
		}

		dbg_print(CCX_DMT_VERBOSE, "Read %d/%d DVD CC blocks\n", rcbcount, ecbcount);
	}
	// SCTE 20 user data
	else if (!ctx->noscte20 && ud_header[0] == 0x03)
	{
		if ((ud_header[1]&0x7F) == 0x01)
		{
			unsigned char cc_data[3*31+1]; // Maximum cc_count is 31

			ctx->stat_scte20ccheaders++;
			read_bytes(ustream, 2); // "03 01"

			unsigned cc_count = (unsigned int) read_bits(ustream,5);
			dbg_print(CCX_DMT_VERBOSE, "Reading %d SCTE 20 CC blocks\n", cc_count);

			unsigned field_number;
			unsigned cc_data1;
			unsigned cc_data2;

			for (unsigned j=0;j<cc_count;j++)
			{
				skip_bits(ustream,2); // priority - unused
				field_number = (unsigned int) read_bits(ustream,2);
				skip_bits(ustream,5); // line_offset - unused
				cc_data1 = (unsigned int) read_bits(ustream,8);
				cc_data2 = (unsigned int) read_bits(ustream,8);
				read_bits(ustream,1); // TODO: Add syntax check */

				if (ustream->bitsleft < 0)
					fatal(CCX_COMMON_EXIT_BUG_BUG, "In user_data: ustream->bitsleft < 0. Cannot continue.");

				// Field_number is either
				//  0 .. forbidden
				//  1 .. field 1 (odd)
				//  2 .. field 2 (even)
				//  3 .. repeated, from repeat_first_field, effectively field 1
				if (field_number < 1)
				{
					// 0 is invalid
					cc_data[j*3]=0x00; // Set to invalid
					cc_data[j*3+1]=0x00;
					cc_data[j*3+2]=0x00;
				}
				else
				{
					// Treat field_number 3 as 1
					field_number = (field_number - 1) & 0x01;
					// top_field_first also affects to which field the caption
					// belongs.
					if(!ctx->top_field_first)
						field_number ^= 0x01;
					cc_data[j*3]=0x04|(field_number);
					cc_data[j*3+1]=reverse8(cc_data1);
					cc_data[j*3+2]=reverse8(cc_data2);
				}
			}
			cc_data[cc_count*3]=0xFF;
			store_hdcc(ctx, cc_data, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

			dbg_print(CCX_DMT_VERBOSE, "Reading SCTE 20 CC blocks - done\n");
		}
		// reserved - unspecified
	}
	// ReplayTV 4000/5000 caption header - parsing information
	// derived from CCExtract.bdl
	else if ( (ud_header[0] == 0xbb     //ReplayTV 4000
				|| ud_header[0] == 0x99) //ReplayTV 5000
			&& ud_header[1] == 0x02 )
	{
		unsigned char data[3];

		if (ud_header[0]==0xbb)
			ctx->stat_replay4000headers++;
		else
			ctx->stat_replay5000headers++;


		read_bytes(ustream, 2); // "BB 02" or "99 02"
		data[0]=0x05; // Field 2
		data[1]=read_u8(ustream);
		data[2]=read_u8(ustream);
		do_cb(ctx, data, sub);
		read_bytes(ustream, 2); // Skip "CC 02" for R4000 or "AA 02" for R5000
		data[0]=0x04; // Field 1
		data[1]=read_u8(ustream);
		data[2]=read_u8(ustream);
		do_cb(ctx, data, sub);
	}
	// HDTV - see A/53 Part 4 (Video)
	else if ( !memcmp(ud_header,"\x47\x41\x39\x34", 4 ) )
	{
		ctx->stat_hdtv++;

		read_bytes(ustream, 4); // "47 41 39 34"

		unsigned char type_code = read_u8(ustream);
		if (type_code==0x03) // CC data.
		{
			skip_bits(ustream,1); // reserved
			unsigned char process_cc_data = (unsigned char) read_bits(ustream,1);
			skip_bits(ustream,1); // additional_data - unused
			unsigned char cc_count = (unsigned char) read_bits(ustream,5);
			read_bytes(ustream, 1); // "FF"
			if (process_cc_data)
			{
				dbg_print(CCX_DMT_VERBOSE, "Reading %d HDTV CC blocks\n", cc_count);

				int proceed = 1;
				unsigned char *cc_data = read_bytes(ustream, cc_count*3);
				if (ustream->bitsleft < 0)
					fatal(CCX_COMMON_EXIT_BUG_BUG, "In user_data: ustream->bitsleft < 0. Cannot continue.\n");

				// Check for proper marker - This read makes sure that
				// cc_count*3+1 bytes are read and available in cc_data.
				if (read_u8(ustream)!=0xFF)
					proceed=0;

				if (!proceed)
				{
					dbg_print(CCX_DMT_VERBOSE, "\rThe following payload is not properly terminated.\n");
					dump (CCX_DMT_VERBOSE, cc_data, cc_count*3+1, 0, 0);
				}
				dbg_print(CCX_DMT_VERBOSE, "Reading %d HD CC blocks\n", cc_count);

				// B-frames might be (temporal) before or after the anchor
				// frame they belong to. Store the buffer until the next anchor
				// frame occurs.  The buffer will be flushed (sorted) in the
				// picture header (or GOP) section when the next anchor occurs.
				// Please note we store the current value of the global
				// fts_now variable (and not get_fts()) as we are going to
				// re-create the timeline in process_hdcc() (Slightly ugly).
				store_hdcc(ctx, cc_data, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

				dbg_print(CCX_DMT_VERBOSE, "Reading HDTV blocks - done\n");
			}
		}
		// reserved - additional_cc_data
	}
	// DVB closed caption header for Dish Network (Field 1 only) */
	else if ( !memcmp(ud_header,"\x05\x02", 2 ) )
	{
		// Like HDTV (above) Dish Network captions can be stored at each
		// frame, but maximal two caption blocks per frame and only one
		// field is stored.
		// To process this with the HDTV framework we create a "HDTV" caption
		// format compatible array. Two times 3 bytes plus one for the 0xFF
		// marker at the end. Pre-init to field 1 and set the 0xFF marker.
		static unsigned char dishdata[7] = {0x04, 0, 0, 0x04, 0, 0, 0xFF};
		int cc_count;

		dbg_print(CCX_DMT_VERBOSE, "Reading Dish Network user data\n");

		ctx->stat_dishheaders++;

		read_bytes(ustream, 2); // "05 02"

		// The next bytes are like this:
		// header[2] : ID: 0x04 (MPEG?), 0x03 (H264?)
		// header[3-4]: Two byte counter (counting (sub-)GOPs?)
		// header[5-6]: Two bytes, maybe checksum?
		// header[7]: Pattern type
		//            on B-frame: 0x02, 0x04
		//            on I-/P-frame: 0x05
		unsigned char id = read_u8(ustream);
		unsigned dishcount = read_u16(ustream);
		unsigned something = read_u16(ustream);
		unsigned char type = read_u8(ustream);
		dbg_print(CCX_DMT_PARSE, "DN  ID: %02X  Count: %5u  Unknown: %04X  Pattern: %X",
				id, dishcount, something, type);

		unsigned char hi;

		// The following block needs 4 to 6 bytes starting from the
		// current position
		unsigned char *dcd = ustream->pos; // dish caption data
		switch (type)
		{
			case 0x02:
				// Two byte caption - always on B-frame
				// The following 4 bytes are:
				// 0  :  0x09
				// 1-2: caption block
				// 3  : REPEAT - 02: two bytes
				//             - 04: four bytes (repeat first two)
				dbg_print(CCX_DMT_PARSE, "\n02 %02X  %02X:%02X - R:%02X :",
						dcd[0], dcd[1], dcd[2], dcd[3]);

				cc_count = 1;
				dishdata[1]=dcd[1];
				dishdata[2]=dcd[2];

				dbg_print(CCX_DMT_PARSE, "%s", debug_608_to_ASC( dishdata, 0) );

				type=dcd[3];  // repeater (0x02 or 0x04)
				hi = dishdata[1] & 0x7f; // Get only the 7 low bits
				if (type==0x04 && hi<32) // repeat (only for non-character pairs)
				{
					cc_count = 2;
					dishdata[3]=0x04; // Field 1
					dishdata[4]=dishdata[1];
					dishdata[5]=dishdata[2];

					dbg_print(CCX_DMT_PARSE, "%s:\n", debug_608_to_ASC( dishdata+3, 0) );
				}
				else
				{
					dbg_print(CCX_DMT_PARSE, ":\n");
				}

				dishdata[cc_count*3] = 0xFF; // Set end marker

				store_hdcc(ctx, dishdata, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

				// Ignore 3 (0x0A, followed by two unknown) bytes.
				break;
			case 0x04:
				// Four byte caption - always on B-frame
				// The following 5 bytes are:
				// 0  :  0x09
				// 1-2: caption block
				// 3-4: caption block
				dbg_print(CCX_DMT_PARSE, "\n04 %02X  %02X:%02X:%02X:%02X  :",
						dcd[0], dcd[1], dcd[2], dcd[3], dcd[4]);

				cc_count = 2;
				dishdata[1]=dcd[1];
				dishdata[2]=dcd[2];

				dishdata[3]=0x04; // Field 1
				dishdata[4]=dcd[3];
				dishdata[5]=dcd[4];
				dishdata[6] = 0xFF; // Set end marker

				dbg_print(CCX_DMT_PARSE, "%s", debug_608_to_ASC( dishdata, 0) );
				dbg_print(CCX_DMT_PARSE, "%s:\n", debug_608_to_ASC( dishdata+3, 0) );

				store_hdcc(ctx, dishdata, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

				// Ignore 4 (0x020A, followed by two unknown) bytes.
				break;
			case 0x05:
				// Buffered caption - always on I-/P-frame
				// The following six bytes are:
				// 0  :  0x04
				// - the following are from previous 0x05 caption header -
				// 1  : prev dcd[2]
				// 2-3: prev dcd[3-4]
				// 4-5: prev dcd[5-6]
				dbg_print(CCX_DMT_PARSE, " - %02X  pch: %02X %5u %02X:%02X\n",
						dcd[0], dcd[1],
						(unsigned)dcd[2]*256+dcd[3],
						dcd[4], dcd[5]);
				dcd+=6; // Skip these 6 bytes

				// Now one of the "regular" 0x02 or 0x04 captions follows
				dbg_print(CCX_DMT_PARSE, "%02X %02X  %02X:%02X",
						dcd[0], dcd[1], dcd[2], dcd[3]);

				type=dcd[0]; // Number of caption bytes (0x02 or 0x04)

				cc_count = 1;
				dishdata[1]=dcd[2];
				dishdata[2]=dcd[3];

				dcd+=4; // Skip the first 4 bytes.
				if (type==0x02)
				{
					type=dcd[0]; // repeater (0x02 or 0x04)
					dcd++; // Skip the repeater byte.

					dbg_print(CCX_DMT_PARSE, " - R:%02X :%s", type, debug_608_to_ASC( dishdata, 0) );

					hi = dishdata[1] & 0x7f; // Get only the 7 low bits
					if (type==0x04 && hi<32)
					{
						cc_count = 2;
						dishdata[3]=0x04; // Field 1
						dishdata[4]=dishdata[1];
						dishdata[5]=dishdata[2];
						dbg_print(CCX_DMT_PARSE, "%s:\n", debug_608_to_ASC( dishdata+3, 0) );
					}
					else
					{
						dbg_print(CCX_DMT_PARSE, ":\n");
					}
					dishdata[cc_count*3] = 0xFF; // Set end marker
				}
				else
				{
					dbg_print(CCX_DMT_PARSE, ":%02X:%02X  ",
							dcd[0], dcd[1]);
					cc_count = 2;
					dishdata[3]=0x04; // Field 1
					dishdata[4]=dcd[0];
					dishdata[5]=dcd[1];
					dishdata[6] = 0xFF; // Set end marker

					dbg_print(CCX_DMT_PARSE, ":%s", debug_608_to_ASC( dishdata, 0) );
					dbg_print(CCX_DMT_PARSE, "%s:\n", debug_608_to_ASC( dishdata+3, 0) );
				}

				store_hdcc(ctx, dishdata, cc_count, ctx->timing->current_tref, ctx->timing->fts_now, sub);

				// Ignore 3 (0x0A, followed by 2 unknown) bytes.
				break;
			default:
				// printf ("Unknown?\n");
				break;
		} // switch

		dbg_print(CCX_DMT_VERBOSE, "Reading Dish Network user data - done\n");
	}
	// CEA 608 / aka "Divicom standard", see:
	// http://www.pixeltools.com/tech_tip_closed_captioning.html
	else if ( !memcmp(ud_header,"\x02\x09", 2 ) )
	{
		// Either a documentation or more examples are needed.
		ctx->stat_divicom++;

		unsigned char data[3];

		read_bytes(ustream, 2); // "02 09"
		read_bytes(ustream, 2); // "80 80" ???
		read_bytes(ustream, 2); // "02 0A" ???
		data[0]=0x04; // Field 1
		data[1]=read_u8(ustream);
		data[2]=read_u8(ustream);
		do_cb(ctx, data, sub);
		// This is probably incomplete!
	}
	// GXF vbi OEM code
	else if ( !memcmp(ud_header,"\x73\x52\x21\x06", 4 ) )
	{
		int udatalen = ustream->end - ustream->pos;
		uint16_t line_nb;
		uint8_t line_type;
		uint8_t field = 1;
		read_bytes(ustream, 4); //skip header code
		read_bytes(ustream, 2); //skip data length
		line_nb = read_bits(ustream, 16);
		line_type = read_u8(ustream);
		field = (line_type & 0x03);
		if(field == 0)
			mprint("MPEG:VBI: Invalid field\n");

		line_type = line_type >> 2;
		if(line_type != 1)
			mprint("MPEG:VBI: only support Luma line\n");

		if (udatalen < 720)
			mprint("MPEG:VBI: Minimum 720 bytes in luma line required\n");

		decode_vbi(ctx, field, ustream->pos, 720, sub);
		dbg_print(CCX_DMT_VERBOSE, "GXF (vbi line %d) user data:\n", line_nb);
	}
Exemple #27
0
//Noise::
unsigned int delete_noise(char* src){
	FILE * pFile;
	if((pFile = fopen(src, "rb")) == NULL){
		puts("Error: wrong source.\n");
		return 0;
	}

    // считываем заголовок файла
    BITMAPFILEHEADER header __attribute__((unused));
 
    header.bfType      = read_u16(pFile);
    header.bfSize      = read_u32(pFile);
    header.bfReserved1 = read_u16(pFile);
    header.bfReserved2 = read_u16(pFile);
    header.bfOffBits   = read_u32(pFile);

    // считываем заголовок изображения
    BITMAPINFOHEADER bmiHeader;

    bmiHeader.biSize          = read_u32(pFile);
    bmiHeader.biWidth         = read_s32(pFile);
    bmiHeader.biHeight        = read_s32(pFile);
    bmiHeader.biPlanes        = read_u16(pFile);
    bmiHeader.biBitCount      = read_u16(pFile);
    bmiHeader.biCompression   = read_u32(pFile);
    bmiHeader.biSizeImage     = read_u32(pFile);
    bmiHeader.biXPelsPerMeter = read_s32(pFile);
    bmiHeader.biYPelsPerMeter = read_s32(pFile);
    bmiHeader.biClrUsed       = read_u32(pFile);
    bmiHeader.biClrImportant  = read_u32(pFile);

	// unsigned int *img = new unsigned int[bmiHeader.biWidth*bmiHeader.biHeight];
	unsigned int *img = malloc(sizeof(unsigned int)*bmiHeader.biWidth*bmiHeader.biHeight);

	int i, j, k;

	for (i = 0; i < bmiHeader.biHeight * bmiHeader.biWidth; ++i)
	{
		img[i] = 0;
	}

	for (i = 0; i < bmiHeader.biHeight; ++i)
	{
		for (j = 0; j < bmiHeader.biWidth; ++j)
		{
			for (k = 0; k < 3; ++k)
			{
				img[i*bmiHeader.biWidth + j] |= getc(pFile) << (8*k);
			}
		}
		for (j = 0; j < bmiHeader.biWidth%4; ++j)
		{
			getc(pFile);
		}
	}

	for (i = 0, j = 0; i < bmiHeader.biWidth * bmiHeader.biHeight; ++i)
	{
		img[i] = (img[i] == 0)?0xFFFFFF:0;
	}

	// unsigned int *col = new unsigned int[bmiHeader.biHeight];
	unsigned int *col = malloc(sizeof(unsigned int)*bmiHeader.biHeight);

	// unsigned int *row = new unsigned int[bmiHeader.biWidth];
	unsigned int *row = malloc(sizeof(unsigned int)*bmiHeader.biWidth);

	for (i = 0; i < bmiHeader.biWidth; ++i)
	{
		row[i] = 0;
	}

	for (i = 0; i < bmiHeader.biWidth; ++i)
	{
		for (j = 0; j < bmiHeader.biHeight; ++j)
		{
			row[i] |= img[i + j*bmiHeader.biWidth];
		}
	}

	int n = 0;

	for (i = 0; i < bmiHeader.biWidth - 1; ++i)
	{
		if(row[i + 1] != row[i])
			n++;
	}
	n = n/2;

	int length = 0, start_l = 0, l = 0;
	int vertical = 0, start_v = 0;

	for (k = 0; k < n; ++k)
	{	
		l = length + start_l;
		length = 0;
		for (; l < bmiHeader.biWidth - 1; ++l)
		{
			if(row[0] != 0)
				start_l = 0;
			if(row[l] == 0 && row[l + 1] != row[l])
				start_l = l + 1;
			if(row[l] != 0 && row[l + 1] == row[l])
				++length;
			if(row[l] != 0 && row[l + 1] != row[l]){
				++length;
				break;
			}
		}

//COL
		for (i = 0; i < bmiHeader.biHeight; ++i)
		{
			col[i] = 0;
		}

		for (i = 0; i < bmiHeader.biHeight; ++i)
		{
			for (j = 0; j < length; ++j)
			{
				col[i] |= img[j + start_l + i*bmiHeader.biWidth];
			}
		}

		vertical = 1;

		for (i = 0; i < bmiHeader.biHeight - 1; ++i)
		{
			if(col[i] == 0 && col[i + 1] != 0)
				start_v = i + 1;
			if(col[i] != 0)
				++vertical;
		}

		// unsigned int* p = new unsigned int[length * vertical];
		unsigned int* p = malloc(sizeof(unsigned int)*length * vertical);

		for(i = 0; i < length; ++i)
		{
			for (j = 0; j < vertical; ++j)
			{
				p[i + j*length] = (img[(i + start_l) + (j + start_v)*bmiHeader.biWidth])?0:0xFFFFFF;
			}
		}
		// char *name = new char[5];
		char *name = malloc(sizeof(char)*5);;
		name[0] = k + 0x31;
		name[1] = '.';
		name[2] = 'b';
		name[3] = 'm';
		name[4] = 'p';
		CreateBMP(name, p, length, vertical);
		// delete[] p;
		free(p);
	}



	// CreateBMP((char*)"result.bmp", img, bmiHeader.biWidth, bmiHeader.biHeight);
	fclose(pFile);

	// delete[] col;
	free(col);
	// delete[] row;
	free(row);
	// delete[] img;
	free(img);

	return n;
}
Exemple #28
0
int main()
{
    int rfbargc = 0;
    char **rfbargv = 0;

    int bpp = 4;

    rfbScreenInfoPtr server = rfbGetScreen(&rfbargc, rfbargv, FRAMEBUFFER_WIDTH, FRAMEBUFFER_HEIGHT, 8, 3, bpp);
    fb = new unsigned char[FRAMEBUFFER_WIDTH * FRAMEBUFFER_HEIGHT * bpp];

    server->frameBuffer = (char *)fb;
    server->kbdAddEvent = handleKey;
    server->ptrAddEvent = handlePointer;

    rfbInitServer(server);

    int file;
  
    file = open(devname, O_RDWR);
    if (file < 0) {
        perror("open");
	exit(EXIT_FAILURE);
    }

    int addr = ADXL345_ADDRESS; /* The I2C address */

    if (ioctl(file, I2C_SLAVE, addr) < 0) {
        perror("ioctl");
	exit(EXIT_FAILURE);
    }

    uint16_t id = read_u16(file, 0x00);

    printf("id is 0x%04X\n", id);

    ADXL345_init(file);

    int tilt_was_valid = false; 

    while(1) {
	int16_t xdata = read_u16_le(file, ADXL345_DATAX0);
	int16_t ydata = read_u16_le(file, ADXL345_DATAY0);
	int16_t zdata = read_u16_le(file, ADXL345_DATAZ0);
	float xg = xdata / 256.0;
	float yg = ydata / 256.0;
	float zg = zdata / 256.0;
	float theta_y = -atan2(yg, zg);
	float theta_x = atan2(xg, zg);
	float y_angle_center = 40.0 / 180.0 * M_PI;
	float y_angle_range = 25.0 / 180.0 * M_PI;
	float x_angle_center = 0.0 / 180.0 * M_PI;
	float x_angle_range = 25.0 / 180.0 * M_PI;
	int tilt_is_valid =
	    (theta_y > y_angle_center - y_angle_range) && 
	    (theta_y < y_angle_center + y_angle_range) && 
	    (theta_x > x_angle_center - x_angle_range) && 
	    (theta_x < x_angle_center + x_angle_range);
	if(tilt_is_valid != tilt_was_valid) {
	    if(tilt_is_valid)
		printf("TILT_VALID\n");
	    else
		printf("TILT_INVALID\n");
	    tilt_was_valid = tilt_is_valid;
	}
	if(tilt_is_valid) {
	    float tilt_x_valuator = (theta_x - x_angle_center) / x_angle_range;
	    float tilt_y_valuator = (theta_y - y_angle_center) / y_angle_range;
	    // printf("    %f, %f\n", tilt_x_valuator, tilt_y_valuator);
	    draw_new_circle(server,
		(tilt_x_valuator + 1) * .5 * FRAMEBUFFER_WIDTH,
		(tilt_y_valuator + 1) * .5 * FRAMEBUFFER_HEIGHT,
		1.0);
	}
	// usleep(100000);
	rfbProcessEvents(server, 10000);
    }
}
Exemple #29
0
void MetroHash128::Hash(const uint8_t * buffer, const uint64_t length, uint8_t * const hash, const uint64_t seed)
{
    const uint8_t * ptr = reinterpret_cast<const uint8_t*>(buffer);
    const uint8_t * const end = ptr + length;

    uint64_t v[4];

    v[0] = (static_cast<uint64_t>(seed) - k0) * k3;
    v[1] = (static_cast<uint64_t>(seed) + k1) * k2;

    if (length >= 32)
    {
        v[2] = (static_cast<uint64_t>(seed) + k0) * k2;
        v[3] = (static_cast<uint64_t>(seed) - k1) * k3;

        do
        {
            v[0] += read_u64(ptr) * k0; ptr += 8; v[0] = rotate_right(v[0],29) + v[2];
            v[1] += read_u64(ptr) * k1; ptr += 8; v[1] = rotate_right(v[1],29) + v[3];
            v[2] += read_u64(ptr) * k2; ptr += 8; v[2] = rotate_right(v[2],29) + v[0];
            v[3] += read_u64(ptr) * k3; ptr += 8; v[3] = rotate_right(v[3],29) + v[1];
        }
        while (ptr <= (end - 32));

        v[2] ^= rotate_right(((v[0] + v[3]) * k0) + v[1], 21) * k1;
        v[3] ^= rotate_right(((v[1] + v[2]) * k1) + v[0], 21) * k0;
        v[0] ^= rotate_right(((v[0] + v[2]) * k0) + v[3], 21) * k1;
        v[1] ^= rotate_right(((v[1] + v[3]) * k1) + v[2], 21) * k0;
    }

    if ((end - ptr) >= 16)
    {
        v[0] += read_u64(ptr) * k2; ptr += 8; v[0] = rotate_right(v[0],33) * k3;
        v[1] += read_u64(ptr) * k2; ptr += 8; v[1] = rotate_right(v[1],33) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 45) * k1;
        v[1] ^= rotate_right((v[1] * k3) + v[0], 45) * k0;
    }

    if ((end - ptr) >= 8)
    {
        v[0] += read_u64(ptr) * k2; ptr += 8; v[0] = rotate_right(v[0],33) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 27) * k1;
    }

    if ((end - ptr) >= 4)
    {
        v[1] += read_u32(ptr) * k2; ptr += 4; v[1] = rotate_right(v[1],33) * k3;
        v[1] ^= rotate_right((v[1] * k3) + v[0], 46) * k0;
    }

    if ((end - ptr) >= 2)
    {
        v[0] += read_u16(ptr) * k2; ptr += 2; v[0] = rotate_right(v[0],33) * k3;
        v[0] ^= rotate_right((v[0] * k2) + v[1], 22) * k1;
    }

    if ((end - ptr) >= 1)
    {
        v[1] += read_u8 (ptr) * k2; v[1] = rotate_right(v[1],33) * k3;
        v[1] ^= rotate_right((v[1] * k3) + v[0], 58) * k0;
    }

    v[0] += rotate_right((v[0] * k0) + v[1], 13);
    v[1] += rotate_right((v[1] * k1) + v[0], 37);
    v[0] += rotate_right((v[0] * k2) + v[1], 13);
    v[1] += rotate_right((v[1] * k3) + v[0], 37);

    // do any endian conversion here

    memcpy(hash, v, 16);
}
Exemple #30
0
    void btstack_libusb_device_base::btstack_packet_handler( std::uint8_t packet_type, std::uint8_t *packet, std::uint16_t size)
    {
        bool no_log = false;

        switch (packet_type) {
            case HCI_EVENT_PACKET:
                log_info( "*HCI_EVENT_PACKET: %i; size: %lu", packet_type, size );

                if ( size >= 2 )
                {
                    const std::uint8_t event_code       = packet[ 0 ];
                    const std::uint8_t parameter_length = packet[ 1 ];
                    packet += 2;

                    if ( parameter_length  + 2 == size )
                    {
                        handle_event( event_code, parameter_length, packet );
                    }
                    else
                    {
                        log_error( "!!unresonable HCI_EVENT_parameter_length: %i; size: %lu plength: %lu", packet_type, size, parameter_length );
                    }
                }
                else
                {
                    log_error( "!!unresonable HCI_EVENT_SIZE: %i; size: %lu", packet_type, size);
                }

                break;
            case HCI_ACL_DATA_PACKET:
                log_info( "*HCI_ACL_DATA_PACKET: %i; size: %lu", packet_type, size );

                if ( size > 8 )
                {
                    hexdump( packet, size );
                    const std::uint16_t hci_length       = read_u16( packet + 2 );
                    const std::uint16_t l2cap_length     = read_u16( packet + 4 );
                    const std::uint16_t l2cap_channel_id = read_u16( packet + 6 );

                    if ( l2cap_channel_id == 0x0004 && l2cap_length == size - 8 && hci_length == size - 4 )
                    {
                        size    -= hci_header_size;
                        packet  += hci_header_size;
                        log_info( "*ATT-Command: %i", size );
                        hexdump( packet, size ), no_log = true;

                        hci_reserve_packet_buffer();
                        uint8_t     *acl_buffer      = hci_get_outgoing_packet_buffer();
                        std::size_t out_buffer_size  = mtu_size_;

                        l2cap_input_( packet, size, acl_buffer + hci_header_size, out_buffer_size );

                        send_acl_package( acl_buffer, out_buffer_size + hci_header_size );
                    }
                }
                break;
            default:
                break;
        }

        if ( !no_log )
            hexdump( packet, size );

        static int init_phase = 0;

        if ( hci_can_send_command_packet_now() && init_phase < 100 )
        {
            if ( init_phase == 0 )
            {
                std::uint8_t      adv_data[ 31 ] = { 0 };
                const std::size_t size           = advertising_data_( adv_data, sizeof( adv_data ) );

                hci_send_cmd( &hci_le_set_advertising_data, size, adv_data );
            }
            else if ( init_phase == 1 )
            {
                hci_send_cmd( &hci_le_set_advertise_enable, 1 );
            }

            ++init_phase;
        }
    }