Ejemplo n.º 1
0
void
xtr_tta_c::finish_file() {
  m_out.reset();

  mm_io_cptr in;
  try {
    in = mm_file_io_c::open(m_temp_file_name);
  } catch (mtx::mm_io::exception &ex) {
    mxerror(boost::format(Y("The temporary file '%1%' could not be opened for reading: %2%.\n")) % m_temp_file_name % ex);
  }

  try {
    m_out = mm_write_buffer_io_c::open(m_file_name, 5 * 1024 * 1024);
  } catch (mtx::mm_io::exception &ex) {
    mxerror(boost::format(Y("The file '%1%' could not be opened for writing: %2%.\n")) % m_file_name % ex);
  }

  tta_file_header_t tta_header;
  memcpy(tta_header.signature, "TTA1", 4);
  if (3 != m_bps)
    put_uint16_le(&tta_header.audio_format, 1);
  else
    put_uint16_le(&tta_header.audio_format, 3);
  put_uint16_le(&tta_header.channels, m_channels);
  put_uint16_le(&tta_header.bits_per_sample, m_bps);
  put_uint32_le(&tta_header.sample_rate, m_sfreq);

  if (0 >= m_previous_duration)
    m_previous_duration = (int64_t)(TTA_FRAME_TIME * m_sfreq) * 1000000000ll;
  put_uint32_le(&tta_header.data_length, (uint32_t)(m_sfreq * (TTA_FRAME_TIME * (m_frame_sizes.size() - 1) + (double)m_previous_duration / 1000000000.0l)));
  put_uint32_le(&tta_header.crc, 0xffffffff ^ crc_calc(crc_get_table(CRC_32_IEEE_LE), 0xffffffff, (unsigned char *)&tta_header, sizeof(tta_file_header_t) - 4));

  m_out->write(&tta_header, sizeof(tta_file_header_t));

  unsigned char *buffer = (unsigned char *)safemalloc(m_frame_sizes.size() * 4);
  size_t k;
  for (k = 0; m_frame_sizes.size() > k; ++k)
    put_uint32_le(buffer + 4 * k, m_frame_sizes[k]);

  m_out->write(buffer, m_frame_sizes.size() * 4);

  m_out->write_uint32_le(0xffffffff ^ crc_calc(crc_get_table(CRC_32_IEEE_LE), 0xffffffff, buffer, m_frame_sizes.size() * 4));

  safefree(buffer);

  mxinfo(boost::format(Y("\nThe temporary TTA file for track ID %1% is being copied into the final TTA file. This may take some time.\n")) % m_tid);

  buffer = (unsigned char *)safemalloc(128000);
  int nread;
  do {
    nread = in->read(buffer, 128000);
    m_out->write(buffer, nread);
  } while (nread == 128000);

  m_out.reset();
  unlink(m_temp_file_name.c_str());
}
Ejemplo n.º 2
0
/* 0: it is not a legal image
 * 1: it is legal image
 */
int check_imageheader(char *buf, long *filelen)
{
	uint32_t checksum;
	image_header_t header2;
	image_header_t *hdr, *hdr2;

	hdr = (image_header_t *) buf;
	hdr2 = &header2;

	/* check header magic */
	if (ntohl(hdr->ih_magic) != IH_MAGIC) {
		_dprintf("Bad Magic Number\n");
		return 0;
	}

	/* check header crc */
	memcpy(hdr2, hdr, sizeof(image_header_t));
	hdr2->ih_hcrc = 0;
	checksum = crc_calc(0, (const char *)hdr2, sizeof(image_header_t));
	_dprintf("header crc: %X\n", checksum);
	_dprintf("org header crc: %X\n", ntohl(hdr->ih_hcrc));
	if (checksum != ntohl(hdr->ih_hcrc)) {
		_dprintf("Bad Header Checksum\n");
		return 0;
	}

	if (!strcmp(buf + 36, nvram_safe_get("productid"))) {
		*filelen = ntohl(hdr->ih_size);
		*filelen += sizeof(image_header_t);
		_dprintf("image len: %x\n", *filelen);
		return 1;
	}
	return 0;
}
Ejemplo n.º 3
0
static void crcer(const FlashIO* io, void* obj, uint16_t block, uint16_t offset, uint16_t bytes, uint8_t*) {
    uint8_t buff[bytes];

    i2c_load(io->i2c, block, offset, buff, bytes);

    uint16_t* crc = (uint16_t*) obj;
    for (uint16_t i = 0; i < bytes; ++i) {
        *crc = crc_calc(*crc, buff[i]);
    }
}
Ejemplo n.º 4
0
/*
 * write .nvm and .pib to flash
 */
static int plc_write_to_flash(char *nvm_path, char *pib_path)
{
	int fd, fl;
	plc_image_header *hdr = &header;
	char cmd[128];

	memset(hdr, 0, sizeof(plc_image_header));
	hdr->magic = PLC_MAGIC;

	// get length and crc of .nvm
	if (get_crc(nvm_path, &hdr->nvm_size, &hdr->nvm_crc)) {
		fprintf(stderr, "%s: Can't check crc of %s\n", __func__, nvm_path);
		return -1;
	}

	// get length and crc of .pib
	if (get_crc(pib_path, &hdr->pib_size, &hdr->pib_crc)) {
		fprintf(stderr, "%s: Can't check crc of %s\n", __func__, pib_path);
		return -1;
	}

	// create header
	hdr->hdr_crc = crc_calc(0, (const char *)hdr, sizeof(plc_image_header));
	if ((fd = open(HDR_PATH, O_RDWR|O_CREAT, 0666)) < 0) {
		fprintf(stderr, "%s: Can't open %s\n", __func__, HDR_PATH);
		return -1;
	}
	write(fd, hdr, sizeof(plc_image_header));
	close(fd);

	// write to plc partition
	while (1) {
		if ((fl = open(PLC_LOCK_FILE, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600)) >= 0) {
			sprintf(cmd, "cat %s %s %s > %s", HDR_PATH, nvm_path, pib_path, IMAGE_PATH);
			system(cmd);
			sprintf(cmd, "mtd-write -i %s -d %s", IMAGE_PATH, PLC_MTD_NAME);
			system(cmd);
			close(PLC_LOCK_FILE);
			unlink(PLC_LOCK_FILE);
			break;
		}
		else {
			dbg("%s: PLC file lock! Try again after waiting 1 sec\n", __func__);
			sleep(1);
		}
	}

	unlink(HDR_PATH);
	unlink(IMAGE_PATH);

	return 0;
}
Ejemplo n.º 5
0
main(int argc,char ** argv)
{
	unsigned char crc;
	
	if(argc>2)
	{
		crc=crc_calc(argv[1],strlen(argv[1]));
		printf("%02X\n",crc);
	}
	else
	{
		printf("erreur parametre\n");
	}
}
Ejemplo n.º 6
0
/*
 * check crc of header
 *
 * : input,  file name
 *
 * return
 * 1: match
 * 0: mismatch or fail
 */
static int hdr_match_crc(plc_image_header *hdr)
{
	unsigned int checksum, checksum_org;

	checksum_org = hdr->hdr_crc;
	hdr->hdr_crc = 0;
	checksum = crc_calc(0, (const char *)hdr, sizeof(plc_image_header));
	fprintf(stderr, "%s: crc %x/%x of header\n", __func__, checksum_org, checksum);

	if (checksum != checksum_org) {
		fprintf(stderr, "%s: header crc mismatch!\n", __func__);
		return 0;
	}

	return 1;
}
Ejemplo n.º 7
0
WORD erdet_db(THREAD *pstThd,char *ppacket)
  {
  int  i;
  DTPARM *pDT = &pstThd->stDTparms;

  switch(pDT->error_detection)
    {
    case 0:                         /* Check sum.                   */
      break;
    case 1:                         /* CRC/16                       */
      accum=0x0000;
      for(i=0;i < pDT->wPacketSize;i++)
        crc_calc(*ppacket++);
      return(accum);
      break;
    default:
      break;
    }
  return(0);
  }
Ejemplo n.º 8
0
/* 0: it is not a legal image
 * 1: it is legal image
 */
int check_imageheader(char *buf, long *filelen)
{
	uint32_t checksum;
	image_header_t header2;
	image_header_t *hdr, *hdr2;

	hdr  = (image_header_t *) buf;
	hdr2 = &header2;

	/* check header magic */
	if (SWAP_LONG(hdr->ih_magic) != IH_MAGIC) {
		_dprintf ("Bad Magic Number\n");
		return 0;
	}

	/* check header crc */
	memcpy (hdr2, hdr, sizeof(image_header_t));
	hdr2->ih_hcrc = 0;
	checksum = crc_calc(0, (const char *)hdr2, sizeof(image_header_t));
	_dprintf("header crc: %X\n", checksum);
	_dprintf("org header crc: %X\n", SWAP_LONG(hdr->ih_hcrc));
	if (checksum != SWAP_LONG(hdr->ih_hcrc))
	{
		_dprintf("Bad Header Checksum\n");
		return 0;
	}

	{
		if(strcmp(buf+36, nvram_safe_get("productid"))==0) {
			*filelen  = SWAP_LONG(hdr->ih_size);
			*filelen += sizeof(image_header_t);
#ifdef RTCONFIG_DSL
			// DSL product may have modem firmware
			*filelen+=(512*1024);			
#endif		
			_dprintf("image len: %x\n", *filelen);	
			return 1;
		}
	}
	return 0;
}
Ejemplo n.º 9
0
/*
 * get file length and crc
 *
 * fname: input,  file name
 * len:   output, file length
 * crc:   output, file crc
 */
static int get_crc(char* fname, unsigned int *len, unsigned int *crc)
{
	int fd, ret = -1;
	struct stat fs;
	unsigned char *ptr = NULL;

	if ((fd = open(fname, O_RDONLY)) < 0) {
		fprintf(stderr, "%s: Can't open %s\n", __func__, fname);
		goto open_fail;
	}

	if (fstat(fd, &fs) < 0) {
		fprintf(stderr, "%s: Can't stat %s\n", __func__, fname);
		goto checkcrc_fail;
	}
	*len = fs.st_size;

	ptr = (unsigned char *)mmap(0, fs.st_size, PROT_READ, MAP_SHARED, fd, 0);
	if (ptr == (unsigned char *)MAP_FAILED) {
		fprintf(stderr, "%s: Can't map %s\n", __func__, fname);
		goto checkcrc_fail;
	}
	*crc = crc_calc(0, (const char *)ptr, fs.st_size);

	ret = 0;

checkcrc_fail:
	if (ptr != NULL)
		munmap(ptr, fs.st_size);
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void)fdatasync(fd);
#else
	(void)fsync(fd);
#endif
	close(fd);

open_fail:
	return ret;
}
Ejemplo n.º 10
0
int erdet_dt(THREAD *pstThd,char *ppacket,char *pcode)
  {
  int  i;
  DTPARM *pDT = &pstThd->stDTparms;

  switch(pDT->error_detection)
    {
    case 0:            /* Check sum.           */
      *pcode = NUL;
      for (i = 0; i < pDT->wPacketSize; i++)
        *pcode += *ppacket++;
      return(1);
    case 1:                         /* CRC/16                       */
      accum = 0x0000;
      for(i=0;i<pDT->wPacketSize;i++)
        crc_calc(*ppacket++);
      return(2);
      break;
    default:
      break;
    }
  return(0);
  }
Ejemplo n.º 11
0
static vsf_err_t nuc400swj_init_iap(void)
{
	uint32_t reg;
	uint8_t verify_buff[sizeof(iap_code)];
	uint32_t fuse_data[4];
	
	if (cm_dp_halt())
	{
		LOG_ERROR(ERRMSG_FAILURE_OPERATION, "halt nuc400");
		return ERRCODE_FAILURE_OPERATION;
	}
	
	if (nuc400swj_unlock())
	{
		LOG_ERROR(ERRMSG_FAILURE_OPERATION, "unlock NUC chip");
		return ERRCODE_FAILURE_OPERATION;
	}
	
	if (nuc400swj_fmc_enable())
	{
		LOG_ERROR(ERRMSG_FAILURE_OPERATION, "enable FMC");
		return ERRCODE_FAILURE_OPERATION;
	}
	
	chip_protected = false;
	if (nuc400swj_isp_run(NUC400_REG_ISPCMD_READ,
							NUC400_REG_CFG_BA, (uint32_t *)fuse_data, 4, true))
	{
		return ERRCODE_FAILURE_OPERATION;
	}
	if ((fuse_data[0] != 0xFFFFFFFF) || (fuse_data[1] != 0xFFFFFFFF) ||
		(fuse_data[2] != 0xFFFFFFFF))
	{
		uint32_t crc32 = 0;
		struct crc_t crc8 = {CRC_BITLEN_8, 0xFF, 0x07};
		uint8_t *fuse_byte = (uint8_t *)fuse_data;
		uint8_t i;
		
		for (i = 0; i < 4; i++)
		{
			crc8.result = 0xFF;
			crc_calc(&crc8, &fuse_byte[i + 0], 1);
			crc_calc(&crc8, &fuse_byte[i + 4], 1);
				crc_calc(&crc8, &fuse_byte[i + 8], 1);
			crc32 |= crc8.result << (i * 8);
		}
		if (crc32 == fuse_data[3])
		{
			// checksum ok, option bytes valid
			// check if read protected
			if (!(fuse_data[0] & 0x00000002))
			{
				// read protected
				chip_protected = true;
				LOG_INFO("chip protected");
				return VSFERR_NONE;
			}
		}
	}
	
	// write iap_code
	if (adi_memap_write_buf32(NUC400_IAP_BASE, (uint8_t*)iap_code,
											sizeof(iap_code)))
	{
		LOG_ERROR(ERRMSG_FAILURE_OPERATION, "load iap_code to SRAM");
		return ERRCODE_FAILURE_OPERATION;
	}
	// verify iap_code
	memset(verify_buff, 0, sizeof(iap_code));
	if (adi_memap_read_buf32(NUC400_IAP_BASE, verify_buff,
										sizeof(iap_code)))
	{
		LOG_ERROR(ERRMSG_FAILURE_OPERATION, "read flash_loader");
		return ERRCODE_FAILURE_OPERATION;
	}
	if (memcmp(verify_buff, iap_code, sizeof(iap_code)))
	{
		LOG_ERROR(ERRMSG_FAILURE_OPERATION, "verify flash_loader");
		return ERRCODE_FAILURE_OPERATION;
	}
	
	// write pc
	reg = NUC400_IAP_BASE + 1;
	if (cm_write_core_register(CM_COREREG_PC, &reg))
	{
		LOG_ERROR(ERRMSG_FAILURE_OPERATION, "write PC");
		return ERRCODE_FAILURE_OPERATION;
	}
	
	if (cm_dp_resume())
	{
		LOG_ERROR(ERRMSG_FAILURE_OPERATION, "run iap");
		return ERRCODE_FAILURE_OPERATION;
	}
	return VSFERR_NONE;
}
Ejemplo n.º 12
0
void Dialog::ProgramThread_run()
{
    int i;
    int j;
    int ret = 0;
    err_code_t err_code = OK;
    long t, dt;
    float calc_time;
    uint32_t fw_size = 256*1024*3;
    uint8_t  board_str[16];
    uint8_t  board_str_len;
    uint32_t board_version;
    uint32_t board_revision;
    uint32_t crc;
    uint32_t crc_ret = 0;
    uint8_t  *p_buf_crc;
    char *portname;
    char *filename;
    uint32_t baud;
    uint8_t  block_buf[FLASH_TX_BLOCK_LENGTH];
    uint32_t addr;
    uint32_t len;

    baud     = (uint32_t)port->baudRate();
    //QString --> QByteArray --> const char*

    QString strportName = port->portName();
    QByteArray ba = strportName.toLatin1();
    portname = ba.data();

    // Open port
    if (!port->isOpen())
    {
        onTextBoxLogPrint("serial port is not opened\r\n");
        return;
    }

    QString selectedFile;
    for(int nIndex=0; nIndex < fileNames.size(); nIndex++)
    {
        selectedFile.append(fileNames.at(nIndex).toLocal8Bit().constData());
    }
    QByteArray bafilename = selectedFile.toLatin1();
    filename = bafilename.data();

    QString textPrint;
    if( ( opencr_fp = fopen(filename, "rb" ) ) == NULL )
    {
        onTextBoxLogPrint(textPrint.sprintf("Failed to open file : %s\r\n",filename));
        return;
        //exit( 1 );
    }
    else
    {
        fseek( opencr_fp, 0, SEEK_END );
        opencr_fpsize = ftell( opencr_fp );
        fseek( opencr_fp, 0, SEEK_SET );
        onTextBoxLogPrint(">>\r\n");
        onTextBoxLogPrint(textPrint.sprintf("file name :\r\n %s \r\n", filename));
        onTextBoxLogPrint(textPrint.sprintf("file size : %d KB\r\n", opencr_fpsize/1024));
    }

    fw_size = opencr_fpsize;

    t = iclock();
    ret = opencr_ld_flash_erase(fw_size);
    dt = iclock() - t;

    onTextBoxLogPrint(textPrint.sprintf("flash_erase : %d : %f sec\r\n", ret, GET_CALC_TIME(dt)));
    if( ret < 0 )
    {
        //port->close();
        fclose( opencr_fp );
        onTextBoxLogPrint("erase flash failed...\r\n");
        return;//exit(1);
    }
    else
    {
        onTextBoxLogPrint("erase flash completed...\r\n");
    }

    t = iclock();
    crc  = 0;
    addr = 0;
    while(1)
    {
        // ui->progressBar_Status->setValue(100*addr/fw_size);
        len = opencr_ld_file_read_data( block_buf, FLASH_TX_BLOCK_LENGTH);
        if( len == 0 ) break;

        for( i=0; i<len; i++ )
        {
            crc = crc_calc( crc,  block_buf[i] );
        }

        ret = opencr_ld_flash_write( addr, block_buf, len );
        if( ret < 0 ) break;
        addr += len;

        ui->textEdit_Log->insertPlainText(".");
    }
    ui->textEdit_Log->insertPlainText("\r\n");
    dt = iclock() - t;

    onTextBoxLogPrint(textPrint.sprintf("flash_write : %d : %f sec \r\n", ret,  GET_CALC_TIME(dt)));
    if( ret < 0 )
    {
        port->close();
        fclose( opencr_fp );
        return;
    }

    t = iclock();
    err_code = cmd_flash_fw_verify( fw_size, crc, &crc_ret );
    dt = iclock() - t;
    if( err_code == OK )
    {
        onTextBoxLogPrint(textPrint.sprintf("CRC OK %X %X %f sec\r\n", crc, crc_ret, GET_CALC_TIME(dt)));
    }
    else
    {
        onTextBoxLogPrint(textPrint.sprintf("CRC Fail : 0x%X : %X, %X %f sec\r\n", err_code, crc, crc_ret, GET_CALC_TIME(dt)));
    }

    onTextBoxLogPrint(textPrint.sprintf("jump_to_fw \r\n"));
    cmd_jump_to_fw();

    port->close();
    fclose( opencr_fp );
}
Ejemplo n.º 13
0
/*
	Encode a single frame of audio from 1152 samples
	Audio samples are taken from glopts->buffer
	Encoded bit stream is placed in to parameter bs
	(not intended for use outside the library)
	
	Returns the size of the frame
	or -1 if there is an error
*/
static int encode_frame(twolame_options *glopts, bit_stream *bs)
{
	int nch = glopts->frame.nch;
	int sb, ch, adb, i;
	unsigned long frameBits, initial_bits;
	short sam[2][1056];
// MEANX
        int head1,head2;
        

// /MEANX
	if (!glopts->twolame_init) {
		fprintf (stderr, "Please call twolame_init_params() before starting encoding.\n");
		return -1;
	}
	
	// Scale and mix the input buffer
	scale_and_mix_samples( glopts );
	
	
    // Clear the saved audio buffer
    memset ((char *) sam, 0, sizeof (sam));

	/* Store the number of bits initially in the bit buffer */
	initial_bits = buffer_sstell(bs);

	adb = available_bits ( glopts );

    /* allow the user to reserve some space at the end of the frame
       This will however leave fewer bits for the audio.
       Need to do a sanity check here to see that there are *some* 
       bits left. */
	if (glopts->num_ancillary_bits > 0.6*adb) {
		/* Trying to reserve more than 60% of the frame.
		   0.6 is arbitrary. but since most applications
		   probably only want to reserve a few bytes, this seems fine.
		   Typical frame size is about 800bytes */
		fprintf(stderr,"You're trying to reserve more than 60%% of the mpeg frame for ancillary data\n");
		fprintf(stderr,"This is probably an error. But I'll keep going anyway...\n");
    } 

	adb -= glopts->num_ancillary_bits;


    /* MFC 26 July 2003
       Doing DAB became a bit harder in the reorganisation of the code.
       Now there is no guarantee that there is more than one frame in the bitbuffer.
       But DAB requires that the CRC for the *current* frame be written at the end 
       of the *previous* frame.
       Workaround: Users (Nicholas?) wanting to implement DAB will have to do some work
       in the frontend.
            First: Reserve some bits for yourself (options->num_ancillary_bits)
	    Second: Put the encoder into "single frame mode" i.e. only read 1152 samples
	            per channel. (frontendoptions->singleFrameMode)
	    Third: When you receive each mp2 frame back from the library, you'll have to insert
	           the options->dabCrc[i] values into the end of the frame yourself. (DAB crc calc is 
		   done below)
       The frontend will have to keep the previous frame in memory. 
       As of 26July all that needs to be done is for the frontend to buffer one frame in memory, such that
       the CRC for the next frame can be written in at the end of it.
    */

    {
		int gr, bl, ch;
		/* New polyphase filter
		 Combines windowing and filtering. Ricardo Feb'03 */
		for( gr = 0; gr < 3; gr++ )
		for ( bl = 0; bl < 12; bl++ )
		for ( ch = 0; ch < nch; ch++ )
			window_filter_subband( &glopts->smem, &glopts->buffer[ch][gr * 12 * 32 + 32 * bl], ch,
				 &(*glopts->sb_sample)[ch][gr][bl][0] );
    }

    scalefactor_calc(*glopts->sb_sample, glopts->scalar, nch, glopts->frame.sblimit);
    find_sf_max (glopts, glopts->scalar, glopts->max_sc);
    if (glopts->frame.actual_mode == TWOLAME_JOINT_STEREO) {
		/* this way we calculate more mono than we need */
		/* but it is cheap */
		combine_lr (*glopts->sb_sample, *glopts->j_sample, glopts->frame.sblimit);
		scalefactor_calc (glopts->j_sample, &glopts->j_scale, 1, glopts->frame.sblimit);
    }

    if ((glopts->quickmode == TRUE) && (++glopts->psycount % glopts->quickcount != 0)) {
		/* We're using quick mode, so we're only calculating the model every
		 'quickcount' frames. Otherwise, just copy the old ones across */
		for (ch = 0; ch < nch; ch++) {
			for (sb = 0; sb < SBLIMIT; sb++) {
				glopts->smr[ch][sb] = glopts->smrdef[ch][sb];
			}
		}
	} else {
		/* calculate the psymodel */
		switch (glopts->psymodel) {
			case -1:
				psycho_n1 (glopts, glopts->smr, nch);
			break;
			case 0:	/* Psy Model A */
				psycho_0 (glopts, glopts->smr, glopts->scalar);	
			break;
			case 1:
				psycho_1 (glopts, glopts->buffer, glopts->max_sc, glopts->smr);
			break;
			case 2:
				psycho_2 (glopts, glopts->buffer, sam, glopts->smr );	
			break;
			case 3:
				/* Modified psy model 1 */
				psycho_3 (glopts, glopts->buffer, glopts->max_sc, glopts->smr);
			break;
			case 4:
				psycho_4 (glopts, glopts->buffer, sam, glopts->smr );
			break;	
			default:
				fprintf (stderr, "Invalid psy model specification: %i\n", glopts->psymodel);
				return -1;
			break;
		}

		if (glopts->quickmode == TRUE) {
			/* copy the smr values and reuse them later */
			for (ch = 0; ch < nch; ch++) {
				for (sb = 0; sb < SBLIMIT; sb++) glopts->smrdef[ch][sb] = glopts->smr[ch][sb];
			}
		}
	}


    sf_transmission_pattern (glopts, glopts->scalar, glopts->scfsi);
    main_bit_allocation (glopts, glopts->smr, glopts->scfsi, glopts->bit_alloc, &adb);
#if 0 //MEANX
    if (glopts->error_protection)
      crc_calc (glopts, glopts->bit_alloc, glopts->scfsi, &glopts->crc);
#endif
    write_header (glopts, bs);
	if (glopts->error_protection)
		buffer_putbits (bs, glopts->crc, 16);
    
    head1=write_bit_alloc (glopts, glopts->bit_alloc, bs);

    head2=write_scalefactors(glopts, glopts->bit_alloc, glopts->scfsi, glopts->scalar, bs);


    
   //MEANX  printf("Bits: %d + %d = %d\n",head1,head2,head1+head2);
    subband_quantization (glopts, glopts->scalar, *glopts->sb_sample, glopts->j_scale, *glopts->j_sample, glopts->bit_alloc,
    			  *glopts->subband);
    write_samples(glopts, *glopts->subband, glopts->bit_alloc, bs);

    /* If not all the bits were used, write out a stack of zeros */
    for (i = 0; i < adb; i++)	buffer_put1bit (bs, 0);


    /* MFC July 03 
       Write an extra byte for 16/24/32/48 input when padding is on.
       Something must be going astray with the frame size calcs.
       This fudge works fine for the moment */
    if ((glopts->header.samplerate_idx != 0) && (glopts->padding)) // i.e. not a 44.1 or 22kHz input file
		buffer_putbits (bs, 0, 8);

    if (glopts->do_dab) {
		// Do the CRC calc for DAB stuff if required.
		// It will be up to the frontend to insert it into the end of the 
		// previous frame.
		for (i=glopts->dab_crc_len-1; i>=0; i--) {
			dab_crc_calc (glopts, glopts->bit_alloc, glopts->scfsi, glopts->scalar, &glopts->dab_crc[i], i);
		}
    }


	// Allocate space for the reserved ancillary bits
	for (i=0; i<glopts->num_ancillary_bits;i++) 
		buffer_put1bit(bs, 0);


	// Calulate the number of bits in this frame
    frameBits = buffer_sstell(bs) - initial_bits;
    if (frameBits % 8) {	/* a program failure */
		fprintf (stderr, "Sent %ld bits = %ld slots plus %ld\n", frameBits, frameBits/8, frameBits%8);
		fprintf (stderr, "If you are reading this, the program is broken\n");
		fprintf (stderr, "email %s with the command line arguments and other info\n", PACKAGE_BUGREPORT);
		return -1;
    }

    //fprintf(stdout,"Frame size: %li\n\n",frameBits/8);

	// *** FIXME currently broken njh Sept 04
    if (glopts->do_energy_levels)
    	do_energy_levels(glopts, bs);

  // MEANX: Recompute checksum
  if (glopts->error_protection)
  {
      unsigned char *begin=(initial_bits>>3)+bs->buf;
      int protectedBits=head1+head2;

           CRC_writeheader(protectedBits, begin);
  }
Ejemplo n.º 14
0
int
checkcrc(char *fname)
{
	int ifd;
	uint32_t checksum;
	struct stat sbuf;
	unsigned char *ptr;
	image_header_t header2;
	image_header_t *hdr, *hdr2=&header2;
	char *imagefile;
	int ret=0;

	imagefile = fname;
//	fprintf(stderr, "img file: %s\n", imagefile);

	ifd = open(imagefile, O_RDONLY|O_BINARY);

	if (ifd < 0) {
		fprintf (stderr, "Can't open %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
		goto checkcrc_end;
	}

	memset (hdr2, 0, sizeof(image_header_t));

	/* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (fstat(ifd, &sbuf) < 0) {
		fprintf (stderr, "Can't stat %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
		goto checkcrc_fail;
	}

	ptr = (unsigned char *)mmap(0, sbuf.st_size,
				    PROT_READ, MAP_SHARED, ifd, 0);
	if (ptr == (unsigned char *)MAP_FAILED) {
		fprintf (stderr, "Can't map %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
		goto checkcrc_fail;
	}
	hdr = (image_header_t *)ptr;
/*
	checksum = crc32_sp (0,
			  (const char *)(ptr + sizeof(image_header_t)),
			  sbuf.st_size - sizeof(image_header_t)
			 );
	fprintf(stderr,"data crc: %X\n", checksum);
	fprintf(stderr,"org data crc: %X\n", SWAP_LONG(hdr->ih_dcrc));
//	if (checksum!=SWAP_LONG(hdr->ih_dcrc))
//		return -1;
*/
	memcpy (hdr2, hdr, sizeof(image_header_t));
	memset(&hdr2->ih_hcrc, 0, sizeof(uint32_t));
	
	checksum = crc_calc(0,(const char *)hdr2,sizeof(image_header_t));

	fprintf(stderr, "header crc: %X\n", checksum);
	fprintf(stderr, "org header crc: %X\n", SWAP_LONG(hdr->ih_hcrc));

	if (checksum!=SWAP_LONG(hdr->ih_hcrc))
	{
		ret=-1;
		goto checkcrc_fail;
	}

	(void) munmap((void *)ptr, sbuf.st_size);

	/* We're a bit of paranoid */
checkcrc_fail:
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (close(ifd)) {
		fprintf (stderr, "Read error on %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
	}
checkcrc_end:
	return ret;
}
Ejemplo n.º 15
0
int
checkcrc(char *fname)
{
	int ifd = -1;
	uint32_t checksum;
	struct stat sbuf;
	unsigned char *ptr = NULL;
	image_header_t *hdr;
	char *imagefile;
	int ret = -1;
	int len;

	imagefile = fname;
//	fprintf(stderr, "img file: %s\n", imagefile);

	ifd = open(imagefile, O_RDONLY|O_BINARY);

	if (ifd < 0) {
		_dprintf("Can't open %s: %s\n",
			imagefile, strerror(errno));
		goto checkcrc_end;
	}

	/* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (fstat(ifd, &sbuf) < 0) {
		_dprintf("Can't stat %s: %s\n",
			imagefile, strerror(errno));
		goto checkcrc_fail;
	}

	ptr = (unsigned char *)mmap(0, sbuf.st_size,
				    PROT_READ, MAP_SHARED, ifd, 0);
	if (ptr == (unsigned char *)MAP_FAILED) {
		_dprintf("Can't map %s: %s\n",
			imagefile, strerror(errno));
		goto checkcrc_fail;
	}
	hdr = (image_header_t *)ptr;

	/* check image header */
	if(check_imageheader((char*)hdr, (long*)&len) == 0)
	{
		_dprintf("Check image heaer fail !!!\n");
		goto checkcrc_fail;
	}

	len = SWAP_LONG(hdr->ih_size);
	if (sbuf.st_size < (len + sizeof(image_header_t))) {
		_dprintf("Size mismatch %lx/%lx !!!\n", sbuf.st_size, (len + sizeof(image_header_t)));
		goto checkcrc_fail;
	}

	/* check body crc */
	_dprintf("Verifying Checksum ... ");
	checksum = crc_calc(0, (const char *)ptr + sizeof(image_header_t), len);
	if(checksum != SWAP_LONG(hdr->ih_dcrc))
	{
		_dprintf("Bad Data CRC\n");
		goto checkcrc_fail;
	}
	_dprintf("OK\n");

	ret = 0;

	/* We're a bit of paranoid */
checkcrc_fail:
	if(ptr != NULL)
		munmap(ptr, sbuf.st_size);
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (close(ifd)) {
		_dprintf("Read error on %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
	}
checkcrc_end:
	return ret;
}
Ejemplo n.º 16
0
bool extract_files(FILE *exefp)
{
uint8_t *buffer;
uint8_t *file;
uint32_t length;
uint32_t crc;
bool check_crc = true;
bool first_crc_failure = true;

	buffer = (uint8_t *)malloc(MAX_FILE_SIZE);
	crc_init();
	
	for(int i=0;;i++)
	{
		if (!files[i].filename) break;
		char outfilename[1024];
		retro_create_path_string(outfilename, sizeof(outfilename), g_dir, files[i].filename);
		
		NX_LOG("[ %s ]\n", outfilename);
		
		// initialize header if any
		file = buffer;
		length = files[i].length;
		
		if (files[i].header)
		{
			memcpy(buffer, files[i].header, HEADER_LEN);
			file += HEADER_LEN;
			length += HEADER_LEN;
		}
		
		// read data from exe
		fseek(exefp, files[i].offset, SEEK_SET);
		fread(file, files[i].length, 1, exefp);
		
		if (check_crc)
		{
			crc = crc_calc(file, files[i].length);
			if (crc != files[i].crc)
			{
				NX_ERR("File '%s' failed CRC check.\n", outfilename);
				NX_ERR("\n");
				
					NX_ERR("[I]gnore\n");
					NX_ERR("Ignore [A]ll\n");
					NX_ERR("[S]top\n");
					#define IGNORE_BTN		SDLK_i
					#define IGNORE_ALL_BTN	SDLK_a
					#define STOP_BTN		SDLK_s
				
				first_crc_failure = false;
			}
		}
		
		// write out the file
		createdir(outfilename);
		
		FILE *fp = fopen(outfilename, "wb");
		if (!fp)
		{
			NX_ERR("Failed to open '%s' for writing.\n", outfilename);
			free(buffer);
			return 1;
		}
		
		fwrite(buffer, length, 1, fp);
		fclose(fp);
	}
	
	free(buffer);
	return 0;
}
Ejemplo n.º 17
0
static int
test_crc_calc(void)
{
	uint32_t i;
	enum rte_net_crc_type type;
	uint8_t *test_data;
	uint32_t result;
	int error;

	/* 32-bit ethernet CRC: Test 1 */
	type = RTE_NET_CRC32_ETH;

	result = crc_calc(crc_vec, CRC_VEC_LEN, type);
	if (result != crc32_vec_res)
		return -1;

	/* 32-bit ethernet CRC: Test 2 */
	test_data = rte_zmalloc(NULL, CRC32_VEC_LEN1, 0);

	for (i = 0; i < CRC32_VEC_LEN1; i += 12)
		rte_memcpy(&test_data[i], crc32_vec1, 12);

	result = crc_calc(test_data, CRC32_VEC_LEN1, type);
	if (result != crc32_vec1_res) {
		error = -2;
		goto fail;
	}

	/* 32-bit ethernet CRC: Test 3 */
	for (i = 0; i < CRC32_VEC_LEN2; i += 12)
		rte_memcpy(&test_data[i], crc32_vec1, 12);

	result = crc_calc(test_data, CRC32_VEC_LEN2, type);
	if (result != crc32_vec2_res) {
		error = -3;
		goto fail;
	}

	/* 16-bit CCITT CRC:  Test 4 */
	type = RTE_NET_CRC16_CCITT;
	result = crc_calc(crc_vec, CRC_VEC_LEN, type);
	if (result != crc16_vec_res) {
		error = -4;
		goto fail;
	}
	/* 16-bit CCITT CRC:  Test 5 */
	result = crc_calc(crc16_vec1, CRC16_VEC_LEN1, type);
	if (result != crc16_vec1_res) {
		error = -5;
		goto fail;
	}
	/* 16-bit CCITT CRC:  Test 6 */
	result = crc_calc(crc16_vec2, CRC16_VEC_LEN2, type);
	if (result != crc16_vec2_res) {
		error = -6;
		goto fail;
	}

	rte_free(test_data);
	return 0;

fail:
	rte_free(test_data);
	return error;
}