Exemplo n.º 1
0
void DataFlash_Block::ReadBlock(void *pBuffer, uint16_t size)
{
    while (size > 0) {
        uint16_t n = df_PageSize - df_Read_BufferIdx;
        if (n > size) {
            n = size;
        }

        WaitReady();

        BlockRead(df_Read_BufferNum, df_Read_BufferIdx, pBuffer, n);
        size -= n;
        pBuffer = (void *)(n + (uintptr_t)pBuffer);
        
        df_Read_BufferIdx += n;

        if (df_Read_BufferIdx == df_PageSize) {
            df_Read_PageAdr++;
            if (df_Read_PageAdr > df_NumPages) {
                df_Read_PageAdr = 1;
            }
            PageToBuffer(df_Read_BufferNum, df_Read_PageAdr);

            // We are starting a new page - read FileNumber and FilePage
            struct PageHeader ph;
            BlockRead(df_Read_BufferNum, 0, &ph, sizeof(ph));
            df_FileNumber = ph.FileNumber;
            df_FilePage   = ph.FilePage;

            df_Read_BufferIdx = sizeof(ph);
        }
    }
}
Exemplo n.º 2
0
Arquivo: fat.c Projeto: d33tah/whitix
DWORD FatAccess(struct VfsSuperBlock* sBlock,DWORD clusterNum,int newVal)
{
	struct FatSbInfo* fatInfo=FatGetSbPriv(sBlock);
	DWORD first=0,last=0,retVal=0;
	BYTE *pFirst=NULL,*pLast=NULL;
	struct Buffer* buff,*buff2,*copyBuff,*copyBuff2;
	DWORD i;
	int block;

	if (clusterNum > fatInfo->totalDataSectors)
	{
		KePrint("PANIC: FatAccess : cluster number (%#X) > totalDataSectors from %#X\n",clusterNum,__builtin_return_address(0));
		KernelPanic("FatAccess: cluster number > total data sectors");
		cli(); hlt();
	}

	/* Due to the lovely FAT12 format, where entries can strech over blocks, 
	 * 2 blocks have to be read in in the worst case scenario */

	/* Get the index number into the FAT */
	if (fatInfo->fatType == 12)
	{
		first=clusterNum*3/2;
		last=first+1;
	}else if (fatInfo->fatType == 16)
		last=first=clusterNum*2; /* Never goes over a sector boundary */
	else
		/* FAT32 */
		last = first = clusterNum * 4;

	/* Read in the FAT sector(s) concerned */
	buff=BlockRead(sBlock->sDevice,fatInfo->fatStart+(first/BYTES_PER_SECTOR(sBlock)));
	if (!buff)
	{
		KePrint("Failed to read buffer in FatAccess\n");
		return 0;
	}

	/* Is the entry on the same sector? */
	if ((first/BYTES_PER_SECTOR(sBlock)) == (last/BYTES_PER_SECTOR(sBlock)))
		buff2=buff;
	else{
		buff2=BlockRead(sBlock->sDevice,(fatInfo->fatStart+(first/BYTES_PER_SECTOR(sBlock)))+1);
		if (!buff2)
		{
			BlockFree(buff);
			KePrint("Failed to read buffer 2 in FatAccess\n");
			return 0;
		}
	}

	if (fatInfo->fatType == 12)
	{
		/* Slightly confusing */
		pFirst=&((BYTE*)buff->data)[first % BYTES_PER_SECTOR(sBlock)];
		pLast=&((BYTE*)buff2->data)[(first+1) % BYTES_PER_SECTOR(sBlock)];
		if (clusterNum & 1)
			retVal=((*pFirst >> 4) | (*pLast << 4)) & 0xFFF;
		else
Exemplo n.º 3
0
Arquivo: demux.c Projeto: CSRedRat/vlc
static int Demux( demux_t *demux )
{
    demux_sys_t *sys = demux->p_sys;
    struct pollfd ufd;

    ufd.fd = sys->i_fd;
    ufd.events = POLLIN|POLLPRI;
    /* Wait for data */
    /* FIXME: remove timeout */
    while( poll( &ufd, 1, 500 ) == -1 )
        if( errno != EINTR )
        {
            msg_Err( demux, "poll error: %m" );
            return -1;
        }

    if( ufd.revents == 0 )
        return 1;

    block_t *block;

    if( sys->io == IO_METHOD_READ )
        block = BlockRead( VLC_OBJECT(demux), ufd.fd, sys->blocksize );
    else
        block = GrabVideo( VLC_OBJECT(demux), sys );
    if( block == NULL )
        return 1;

    block->i_pts = block->i_dts = mdate();
    block->i_flags |= sys->i_block_flags;
    es_out_Control( demux->out, ES_OUT_SET_PCR, block->i_pts );
    es_out_Send( demux->out, sys->p_es, block );
    return 1;
}
Exemplo n.º 4
0
int GptBlockRead(HGPT hGPT, QWORD qwSector, WORD wNum, void FAR *pBuf)
    {
    QWORD qw = qwSector;
    qw *= hGPT->iSectPerSect;

    return BlockRead(hGPT->hBlockDev, qw, (WORD)(wNum*hGPT->iSectPerSect), pBuf);
    }
Exemplo n.º 5
0
//****************************************************************************
//
//! Get the raw accelerometer data register readings
//!
//! \param psAccX pointer to the raw AccX store
//! \param psAccY pointer to the raw AccY store
//! \param psAccZ pointer to the raw AccZ store
//! 
//! This function  
//!    1. Reads the data registers over I2C.
//!    2. Returns the accelerometer readings
//!
//! \return 0: Success, < 0: Failure.
//
//****************************************************************************
int
BMA222ReadNew(signed char *pcAccX, signed char *pcAccY, signed char *pcAccZ)
{
    char cAccX[6];
   
    //
    // Read the acclerometer output registers LSB and MSB
    //
    RET_IF_ERR(BlockRead(BMA222_ACC_DATA_X_NEW, (unsigned char *)cAccX,6));

     //
    // Check whether new Sensor Data is available
    //
    if((cAccX[0] & 0x1) && (cAccX[2] & 0x1) && (cAccX[4] & 0x1))
    {
        *pcAccX = cAccX[1];
        *pcAccY = cAccX[3];
        *pcAccZ = cAccX[5];
        return SUCCESS;
    }

    //New Sensor Data Not Available
    return FAILURE;

}
Exemplo n.º 6
0
/* Update the freeClusters in the FsInfo sector on FAT32 */
int FatWriteSuper(struct VfsSuperBlock* superBlock)
{
	struct FatSbInfo* sbInfo;
	struct FatFsInfo* info;
	struct Buffer* buff;
	DWORD prevSize = superBlock->sDevice->softBlockSize;
	
	sbInfo = FatGetSbPriv(superBlock);

	if (sbInfo->fatType != 32)
		return 0;
	
	/* Need this to write the correct FsInfo sector. It will throw all blocks
	 * out of cache, but if we're calling this, we're either syncing or
	 * freeing the super typically.
	 */
	 
	BlockSetSize(superBlock->sDevice, superBlock->sDevice->blockSize);
	
	buff = BlockRead(superBlock->sDevice, sbInfo->fsInfoSector);
	
	info = (struct FatFsInfo*)(buff->data + 0x1E0);
	info->freeClusters = sbInfo->freeClusters;
	
	BlockWrite(buff->device, buff);
	
	BlockSetSize(superBlock->sDevice, prevSize);
	
	return 0;
}
Exemplo n.º 7
0
void DataFlash_Block::StartRead(uint16_t PageAdr)
{
    df_Read_PageAdr   = PageAdr;

    // We are starting a new page - read FileNumber and FilePage
    struct PageHeader ph;
    BlockRead(df_Read_PageAdr << 8, &ph, sizeof(ph));
    df_FileNumber = ph.FileNumber;
    df_FilePage   = ph.FilePage;
    df_Read_BufferIdx = sizeof(ph);
}
Exemplo n.º 8
0
//****************************************************************************
//
//! Get the accelerometer data readings
//!
//! \param pfAccX pointer to the AccX store
//! \param pfAccY pointer to the AccY store
//! \param pfAccZ pointer to the AccZ store
//! 
//! This function  
//!    1. Reads the data registers over I2C.
//!    2. Applies the range conversion to the raw values
//!
//! \return 0: Success, < 0: Failure.
//
//****************************************************************************
int
BMA222Read(signed char *pcAccX, signed char *pcAccY, signed char *pcAccZ)
{
    char cAccX = 0;
    char cAccY = 0;
    char cAccZ = 0;
    //
    // Read the acclerometer output registers LSB and MSB
    //
    RET_IF_ERR(BlockRead(BMA222_ACC_DATA_X, (unsigned char *)&cAccX,
                     sizeof(cAccX)));

    RET_IF_ERR(BlockRead(BMA222_ACC_DATA_Y, (unsigned char *)&cAccY,
             sizeof(cAccY)));

    RET_IF_ERR(BlockRead(BMA222_ACC_DATA_Z, (unsigned char *)&cAccZ,
             sizeof(cAccZ)));

    *pcAccX = cAccX;
    *pcAccY = cAccY;
    *pcAccZ = cAccZ;

    return SUCCESS;
}
Exemplo n.º 9
0
// *** DATAFLASH PUBLIC FUNCTIONS ***
void DataFlash_Block::StartWrite(uint16_t PageAdr)
{
    df_BufferIdx  = 0;
    df_BufferNum  = 0;
    df_PageAdr    = PageAdr;

    if (df_PageAdr >= DF_LAST_PAGE){
	df_PageAdr = 1;
	Flash_Jedec_EraseSector(0); // Erase Sector
    }

    uint16_t data = 0;
    BlockRead((df_PageAdr << 8), &data, sizeof(data));
    if (data != 0xFFFF)
       Flash_Jedec_EraseSector(df_PageAdr << 8); // Erase Sector
}
Exemplo n.º 10
0
void DataFlash_Block::StartRead(uint16_t PageAdr)
{
    df_Read_BufferNum = 0;
    df_Read_PageAdr   = PageAdr;

    WaitReady();

    // copy flash page to buffer
    PageToBuffer(df_Read_BufferNum, df_Read_PageAdr);

    // We are starting a new page - read FileNumber and FilePage
    struct PageHeader ph;
    BlockRead(df_Read_BufferNum, 0, &ph, sizeof(ph));
    df_FileNumber = ph.FileNumber;
    df_FilePage   = ph.FilePage;
    df_Read_BufferIdx = sizeof(ph);
}
Exemplo n.º 11
0
int Ext3ReadSuperBlock(struct VfsSuperBlock* superBlock, struct Ext3SbInfo* sbInfo)
{
	int sector, offset;
	
	sector=1*1024/BYTES_PER_SECTOR(superBlock);
	offset=(1*1024) % BYTES_PER_SECTOR(superBlock);
	
	sbInfo->sbBuffer=BlockRead(superBlock->sDevice, sector);

	if (!sbInfo->sbBuffer)
		return -EIO;

	sbInfo->super=(struct Ext3SuperBlock*)((sbInfo->sbBuffer->data)+offset);
	sbInfo->sbSector=sector;

	return 0;	
}
Exemplo n.º 12
0
int FatReadFsInfo(struct VfsSuperBlock* superBlock, unsigned long fsInfoSector)
{
	struct Buffer* buff;
	struct FatFsInfo* info;
	struct FatSbInfo* sbInfo;
	BYTE* data;
	int ret = 0;
		
	buff = BlockRead(superBlock->sDevice, fsInfoSector);
	
	if (!buff)
		return -EIO;

	data = (BYTE*)(buff->data);
	info = (struct FatFsInfo*)(data + 0x1E0);
		
	/* Four byte signature at start of fsInfo sector. */
	if (data[0] != 0x52 || data[1] != 0x52 || data[2] != 0x61 || data[3] != 0x41)
	{
		ret = -EINVAL;
		goto out;
	}
	
	/* TODO: Check info->signature? */
	
	/* Boot record signature at end of fsInfo sector. */
	if (data[510] != 0x55 || data[511] != 0xAA)
	{
		ret = -EINVAL;
		goto out;
	}
	
	/* Store the number of free clusters, and update it again in WriteSuper. */
	sbInfo = FatGetSbPriv(superBlock);
	
	sbInfo->freeClusters = info->freeClusters;
	sbInfo->fsInfoSector = fsInfoSector;
		
out:
	if (ret)
		KePrint(KERN_DEBUG "FAT: Invalid FAT32 filesystem.\n");
		
	BlockFree(buff);
	return ret;
}
Exemplo n.º 13
0
void DataFlash_Block::FinishWrite(void)
{
    WaitReady();

    BufferToPage (df_PageAdr << 8); // Save 256 bytes from buffer to Page

    df_PageAdr++;

    if (df_PageAdr > df_NumPages){
	Flash_Jedec_EraseSector(0); // Erase Sector 0
    	df_PageAdr = 1;
    }
    // check if new sector is erased
    if (df_PageAdr % 256 == 0){
	uint16_t data = 0;
	BlockRead((df_PageAdr << 8), &data, sizeof(data));
    	if (data != 0xFFFF){
    	   Flash_Jedec_EraseSector(df_PageAdr << 8); // Erase Sector
        }
    }

    df_BufferIdx = 0;
}
int main(void)
{

/*  Initialise hardware timers and ports. All start off as inputs */
/*  PD0 is RxD
    PD1 is TxD */
/** PORTB is set as outputs on bits 0,3,4 to set controls.
    The SPI output ports SCK and MOSI stay as inputs until ready to program.
    Set the Ports PB0-2 as outputs and set high to turn off all LEDs
    PB0 = programming mode LED
    PB3 = programming completed LED (and serial comms switch over)
    PB4 = programming active LED (and reset out)
    PB5 = MOSI
    PB6 = MISO
    PB7 = SCK */

    sbi(ACSR,7);                                        // Turn off Analogue Comparator
    initbootuart();           	                        // Initialize UART.
    uint8_t sigByte1=0;                                 // Target Definition defaults
    uint8_t sigByte2=0;
    uint8_t sigByte3=0;
    uint8_t fuseBits=0;
    uint8_t highFuseBits=0;
    uint8_t extendedFuseBits=0;
    uint8_t lockBits=0;

/*---------------------------------------------------------------------------*/
/* Main loop. We exit this only with an "E" command. */
    {
        for(;;)
        {
            command=recchar();                          // Loop and wait for command character.

/** 'a' Check autoincrement status.
This allows a block of data to be uploaded to consecutive addresses without
specifying the address each time */
            if (command=='a')
            {
                sendchar('Y');                          // Yes, we will autoincrement.
            }

/** 'A' Set address.
This is stored and incremented for each upload/download.
NOTE: Flash addresses are given as word addresses, not byte addresses. */
            else if (command=='A')                       // Set address
            {
                address = (recchar()<<8);               // Set address high byte first.
                address |= recchar();                   // Then low byte.
                sendchar('\r');                         // Send OK back.
            }

/** 'b' Check block load support. This returns the allowed block size.
We will not buffer anything so we will use the FLASH page size to limit
the programmer's blocks to those that will fit the target's page. This then avoids
the long delay when the page is committed, that may cause incoming data to be lost.
This should not be called before the P command is executed, and the target device
characteristics obtained. The fPageSize characteristic should be non zero.*/
           else if (command=='b')
            {
                uint16_t blockLength = ((uint16_t)fPageSize<<1);
                if (fPageSize > 0) sendchar('Y');       // Report block load supported.
                else sendchar('N');
                sendchar(high(blockLength));            // MSB first.
                sendchar(low(blockLength));             // Report FLASH pagesize (bytes).
            }

/** 'p' Get programmer type. This returns just 'S' for serial. */
            else if (command=='p')
            {
                sendchar('S');                          // Answer 'SERIAL'.
            }

/** 'S' Return programmer identifier. Always 7 digits. We call it AVRSPRG */
            else if (command=='S')
            {
                sendchar('A');
                sendchar('V');                          // ID always 7 characters.
                sendchar('R');
                sendchar('S');
                sendchar('P');
                sendchar('R');
                sendchar('G');
            }

/** 'V' Return software version. */
            else if (command=='V')
            {
                sendchar('0');
                sendchar('0');
            }

/** 't' Return supported device codes. This returns a list of devices that can be programmed.
This is only used by AVRPROG so we will not use it - we work with signature bytes instead. */
            else if(command=='t')
            {
                sendchar( 0 );                          // Send list terminator.
            }

/** 'x' Set LED. */
            else if ((command=='x') || (command=='y') || (command=='T'))
            {
//                if (command=='x') sbi(PORTB,LED);
//                else if (command=='y') cbi(PORTB,LED);
                recchar();                              // Discard sent value
                sendchar('\r');                         // Send OK back.
            }

/** 'P' Enter programming mode.
This starts the programming of the device. Pulse the reset line high while SCK is low.
Send the command and ensure that the echoed second byte is correct, otherwise redo.
With this we get the device signature and search the table for its characteristics.
A timeout is provided in case the device doesn't respond. This will allow fall through
to an ultimate error response.
The reset line is held low until programming mode is exited. */
            else if (command=='P')
            {
                outb(DDRB,(inb(DDRB) | 0xB9));          // Setup SPI output ports
                outb(PORTB,(inb(PORTB) | 0xB9));        // SCK and MOSI high, and LEDs off
                uint8_t retry = 10;
                uint8_t result = 0;
                while ((result != 0x53) && (retry-- > 0))
                {
                    cbi(PORTB,SCK);                     // Set serial clock low
                    sbi(PORTB,RESET);                   // Pulse reset line off
                    _delay_us(100);                     // Delay to let CPU know that programming will occur
                    cbi(PORTB,RESET);                   // Pulse reset line on
                    _delay_us(25000);                   // 25ms delay
                    writeCommand(0xAC,0x53,0x00,0x00);  // "Start programming" command
                    result=buffer[2];
                }
/** Once we are in programming mode, grab the signature bytes and extract all information
about the target device such as its memory sizes, page sizes and capabilities. */
                writeCommand(0x30,0x00,0x00,0x00);
                sigByte1 = buffer[3];
                writeCommand(0x30,0x00,0x01,0x00);
                sigByte2 = buffer[3];
                writeCommand(0x30,0x00,0x02,0x00);      // Signature Bytes
                sigByte3 = buffer[3];
/* Check for device support. If the first signature byte is not 1E, then the device is
either not an Atmel device, is locked, or is not responding.*/
                uint8_t found=FALSE;                    // Indicates if the target device is supported
                uint8_t partNo = 0;
                if (sigByte1 == 0x1E)
                {
                    while ((partNo < NUMPARTS) && (! found))
                    {
                        found = ((part[partNo][0] == sigByte2) && (part[partNo][1] == sigByte3));
                        partNo++;
                    }
                }
                if (found)
                {
                    partNo--;
                    sendchar('\r');
                    fPageSize = part[partNo][2];
                    ePageSize = part[partNo][3];
                    canCheckBusy = part[partNo][4];
                    lfCapability = part[partNo][5];
                    buffer[3] = 0;                      // In case we cannot read these
                    if (lfCapability & 0x08) writeCommand(0x50,0x08,0x00,0x00);  // Read Extended Fuse Bits
                    extendedFuseBits = buffer[3];
                    if (lfCapability & 0x04) writeCommand(0x58,0x08,0x00,0x00);  // Read High Fuse Bits
                    highFuseBits = buffer[3];
                    if (lfCapability & 0x02) writeCommand(0x50,0x00,0x00,0x00);  // Read Fuse Bits
                    fuseBits = buffer[3];
                    if (lfCapability & 0x01) writeCommand(0x58,0x00,0x00,0x00);  // Read Lock Bits
                    lockBits = buffer[3];
                }
                else                                    // Not found?
                {
                    sbi(PORTB,RESET);                   // Lift reset line
                    sendchar('?');                      // Device cannot be programmed
                    outb(DDRB,(inb(DDRB) & ~0xA0));     // Set SPI ports to inputs
                }
            }

/** 'L' Leave programming mode. */
            else if(command=='L')
            {
                sbi(PORTB,RESET);                       // Turn reset line off
                sendchar('\r');                         // Answer OK.
                outb(DDRB,(inb(DDRB) & ~0xA0));         // Set SPI ports to inputs
            }

/** 'e' Chip erase.
This requires several ms. Ensure that the command has finished before acknowledging. */
            else if (command=='e')
            {
                writeCommand(0xAC,0x80,0x00,0x00);      // Erase command
                pollDelay(FALSE);
                sendchar('\r');                         // Send OK back.
            }

/** 'R' Read program memory */
            else if (command=='R')
            {
/** Send high byte, then low byte of flash word.
Send each byte from the address specified (note address variable is modified).*/
                lsbAddress = low(address);
                msbAddress = high(address);
                writeCommand(0x28,msbAddress,lsbAddress,0x00);  // Read high byte
                sendchar(buffer[3]);
                writeCommand(0x20,msbAddress,lsbAddress,0x00);  // Read low byte
                sendchar(buffer[3]);
                address++;                              // Auto-advance to next Flash word.
            }

/** 'c' Write to program memory page buffer, low byte.
NOTE: Always use this command before sending the high byte. It is written to the
page but the address is not incremented.*/
            else if (command=='c')
            {
                received = recchar();
                writeCommand(0x40,0x00,address & 0x7F,received);    // Low byte
                sendchar('\r');                         // Send OK back.
            }

/** 'C' Write to program memory page buffer, high byte.
This will cause the word to be written to the page and the address incremented. It is
the responsibility of the user to issue a page write command.*/
            else if (command=='C')
            {
                received = recchar();
                writeCommand(0x48,0x00,address & 0x7F,received);    // High Byte
                address++;                              // Auto-advance to next Flash word.
                sendchar('\r');                         // Send OK back.
            }

/** 'm' Issue Page Write. This writes the target device page buffer to the Flash.
The address is that of the page, with the lower bits masked out.
This requires several ms. Ensure that the command has finished before acknowledging.
We could check for end of memory here but that would require storing the Flash capacity
for each device. The calling program will know in any case if it has overstepped.*/
            else if (command== 'm')
            {
                writeCommand(0x4C,(address>>8) & 0x7F,address & 0xE0,0x00);  // Write Page
                pollDelay(TRUE);                        // Short delay
                sendchar('\r');                         // Send OK back.
            }
/** 'D' Write EEPROM memory
This writes the byte directly to the EEPROM at the specified address.
This requires several ms. Ensure that the command has finished before acknowledging.*/
            else if (command == 'D')
            {
                lsbAddress = low(address);
                msbAddress = high(address);
                writeCommand(0xC0,msbAddress,lsbAddress,recchar());     // EEPROM byte
                address++;                              // Auto-advance to next EEPROM byte.
                pollDelay(FALSE);                       // Long delay
                sendchar('\r');                         // Send OK back.
            }

/** 'd' Read EEPROM memory */
            else if (command == 'd')
            {
                lsbAddress = low(address);
                msbAddress = high(address);
                writeCommand(0xA0,msbAddress,lsbAddress, 0x00);
                sendchar(buffer[3]);
                address++;                              // Auto-advance to next EEPROM byte.
            }

/** 'B' Start block load.
 The address must have already been set otherwise it will be undefined. */
            else if (command=='B')
            {
                tempInt = (recchar()<<8);               // Get block size high byte first.
                tempInt |= recchar();                   // Low Byte.
                sendchar(BlockLoad(tempInt,recchar(),&address));  // Block load.
            }

/** 'g' Start block read.
 The address must have already been set otherwise it will be undefined.*/
            else if (command=='g')
            {
                tempInt = (recchar()<<8);               // Get block size high byte first.
                tempInt |= recchar();                   // Low Byte.
                command = recchar();                    // Get memory type
                BlockRead(tempInt,command,&address);    // Block read
            }
/** 'r' Read lock bits. */
            else if (command=='r')
            {
                sendchar(lockBits);
            }

/** 'l' Write lockbits. */
            else if (command=='l')
            {
                if (lfCapability & 0x10) writeCommand(0xAC,0xE0,0x00,recchar());
                sendchar('\r');                         // Send OK back.
            }

/** 'F' Read fuse bits. */
            else if (command=='F')
            {
                sendchar(fuseBits);
            }

/** 'f' Write fuse bits. */
            else if (command=='f')
            {
                if (lfCapability & 0x20) writeCommand(0xAC,0xA0,0x00,recchar()); // Fuse byte
                sendchar('\r');                         // Send OK back.
            }

/** 'N' Read high fuse bits. */
            else if (command=='N')
            {
                sendchar(highFuseBits);
            }

/** 'n' Write high fuse bits. */
            else if (command=='n')
            {
                if (lfCapability & 0x40) writeCommand(0xAC,0xA8,0x00,recchar()); // High Fuse byte
                sendchar('\r');                         // Send OK back.
            }

/** 'Q' Read extended fuse bits. */
            else if (command=='Q')
            {
                sendchar(extendedFuseBits);
            }

/** 'q' Write extended fuse bits. */
            else if (command=='q')
            {
                if (lfCapability & 0x80) writeCommand(0xAC,0xA4,0x00,recchar()); // Extended Fuse byte
                sendchar('\r');                         // Send OK back.
            }

/** 's' Return signature bytes. Sent Most Significant Byte first. */
            else if (command=='s')
            {
                sendchar(sigByte3);
                sendchar(sigByte2);
                sendchar(sigByte1);
            }

/** 'E' Exit bootloader.
At this command we enter serial passthrough and don't return from it until a
hardware reset occurs.
At the same time we should lift the reset from the target. Spin endlessly so we
don't interpret serial data, and wait for our own hard reset.*/
            else if (command=='E')
            {
                sendchar('\r');
                sbi(PORTB,RESET);                       // Pulse reset line off
                cbi(PORTB,PASSTHROUGH);                 // Change to serial passthrough
                outb(DDRB,(inb(DDRB) & ~0xA0));         // Set SPI ports to inputs
                for (;;);                    // Spin endlessly
            }

/** The last command to accept is ESC (synchronization).
This is used to abort any command by filling in remaining parameters, after which
it is simply ignored.
Otherwise, the command is not recognized and a "?" is returned.*/
            else if (command!=0x1b) sendchar('?');       // If not ESC, then it is unrecognized
        }
Exemplo n.º 15
0
struct VfsSuperBlock* FatReadSuper(struct StorageDevice* dev,int flags,char* data)
{
	struct FatBootSector* bootSec;
	struct Buffer* buff;
	struct VfsSuperBlock* retVal;
	struct FatSbInfo* fatSbInfo;
	DWORD clusterCount,totalSectors;

	if (!dev)
		return NULL;

	/* This fixes issue #110. The soft block size at the start should be the
	 * device's sector size as we may read the second sector of the disk in 
	 * FatReadFsInfo. */
	 
	if (BlockSetSize(dev, dev->blockSize))
		return NULL;

	buff = BlockRead(dev, 0);
	
	if (!buff)
	{
		KePrint("FAT: Failed to read superblock\n");
		return NULL;
	}

	bootSec=(struct FatBootSector*)(buff->data);

	if (bootSec->bytesPerSec != 512 && bootSec->bytesPerSec != 1024 && bootSec->bytesPerSec != 2048 && bootSec->bytesPerSec != 4096)
	{
		BlockFree(buff);
		return NULL;
	}

	retVal=VfsAllocSuper(dev,flags);
	if (!retVal)
		goto end;

	retVal->sbOps=&fatSbOps;

	/* Allocate the FAT-specific superblock structure */
	fatSbInfo=(struct FatSbInfo*)MemAlloc(sizeof(struct FatSbInfo));
	if (!fatSbInfo)
		goto fail;

	retVal->privData=(void*)fatSbInfo;

	/* Fill the structure with info */
	fatSbInfo->fatStart=bootSec->reservedSectorCnt;

	if (bootSec->secsPerFat == 0 && bootSec->secsPerFat32 > 0)
	{
		/* Must be FAT32 then */
		fatSbInfo->rootDirStart = bootSec->rootClus;
		fatSbInfo->fatLength = bootSec->secsPerFat32;
	}else{
		fatSbInfo->rootDirStart = bootSec->reservedSectorCnt+(bootSec->numFats*bootSec->secsPerFat);
		fatSbInfo->fatLength = bootSec->secsPerFat;
	}

	totalSectors=(bootSec->totalSecSmall) ? bootSec->totalSecSmall : bootSec->totalSectorsLarge;
	fatSbInfo->rootDirEnts = bootSec->numRootDirEnts;
	fatSbInfo->rootDirLength=(bootSec->numRootDirEnts*sizeof(struct FatDirEntry))/bootSec->bytesPerSec; /* FAT32 doesn't use this */
 	fatSbInfo->firstDataSector=bootSec->reservedSectorCnt+
 		(bootSec->numFats*fatSbInfo->fatLength)+fatSbInfo->rootDirLength;
	fatSbInfo->clusterLength=bootSec->bytesPerSec*bootSec->sectorsPerClus;
	fatSbInfo->secsPerClus=bootSec->sectorsPerClus;
	fatSbInfo->totalDataSectors=totalSectors-fatSbInfo->firstDataSector;
	fatSbInfo->numFats=bootSec->numFats;

	clusterCount=fatSbInfo->totalDataSectors/bootSec->sectorsPerClus;

	/* Set the FAT type and end of cluster marker, depending on the number of clusters */
	if (clusterCount < 4085)
	{
		fatSbInfo->fatType=12;
		fatSbInfo->invalidCluster=0xFF8;
	}else if (clusterCount < 65525)
	{
		fatSbInfo->fatType=16;
		fatSbInfo->invalidCluster=0xFFF8;
	}else{
		fatSbInfo->fatType = 32;
		fatSbInfo->invalidCluster=0x0FFFFFF8;
	}
	
	/* Read the FsInfo structure if this is a FAT32 filesystem, so we can keep
	 * track of the free clusters and update it when necessary. */
	if (fatSbInfo->fatType == 32)
	{
		if (FatReadFsInfo(retVal, bootSec->fsInfo))
			goto fail;
	}
	
	KePrint(KERN_DEBUG "FAT: drive is a FAT%u volume\n",(DWORD)fatSbInfo->fatType);

	if (BlockSetSize(dev,bootSec->bytesPerSec))
		goto fail;

	retVal->mount = VNodeGet(retVal, FAT_ROOT_ID);

	if (!retVal->mount)
		goto fail;

end:
	if (buff->refs)
		BlockFree(buff);
	return retVal;

fail:
	/* privData is freed in VfsFreeSuper */
	VfsFreeSuper(retVal);
	retVal=NULL;
	goto end;
}
Exemplo n.º 16
0
int main(int argc, char *argv[]){

    FILE *infile, *outfile;
    char infilename[260], outfilename[260];
    char WaveId[4];
    wHeader infileHeader;
    fmtChunk infileChunk;
    unsigned long Count, DataSize, tmpDataSize, FilePos;
	unsigned int tmpRIFFSize;

    float LPCutoff, HPCutoff, Invert, VocalPan, Gain;
    float ChMix[4];
    double a1[3],b1[3],a2[3],b2[3];
    double LP_L_In[3], LP_L_Out[3], HP_L_In[3], HP_L_Out[3];
    double LP_R_In[3], LP_R_Out[3], HP_R_In[3], HP_R_Out[3];    
    double Left, Right, NewLeft, NewRight;
    unsigned long i, j, k;
    short percentage = 0;
    
    /* Display version and usage */
    printf("VoiX Version %s\n(http://vocaleliminator.sourceforge.net)\n", VERSION);

    if (argc==1) {printf("\nUsage: %s <infile> [outfile] [options]\n", argv[0]);
                  printf("\nOptions: <lowpass> <highpass> <invert> <pan> <gain>\n");
                  printf("\n<lowpass>: Cutoff frequency (in Hz) for low-pass filter\n");
                  printf("<highpass>: Cutoff frequency (in Hz) for high-pass filter\n");
                  printf("<invert>: Invert right channel to make it mono, 0=off 1=on\n");                  
                  printf("<pan>: Pan for Vocal Track: 0=center -100=left 100=right\n");
                  printf("<gain>: Gain (in dB) for output file\n");                  
                  printf("\nExample: %s input.wav output.wav 200 8000\n", argv[0]);
                  return(0);}
    strcpy(infilename,argv[1]); /* Copy input filename from first parameter */
    
    /* For Windows Drag & Drop*/
    char *FileExt = ".voix.wav";
    if (argc==2) {
                 strcpy(outfilename, infilename); strcat(outfilename,FileExt); 
                 } else strcpy(outfilename,argv[2]);
    /* Windows Drag & Drop End*/
    
    printf("Input: %s ", infilename);
    if (argc>=4) LPCutoff = atof(argv[3]); else LPCutoff = 200.0;
    if (argc>=5) HPCutoff = atof(argv[4]); else HPCutoff = 8000.0;
    if (argc>=6) Invert = atof(argv[5]); else Invert = 0.0;
    if (argc>=7) VocalPan = atof(argv[6]); else VocalPan = 0.0;
    if ((VocalPan<=-100.0)||(VocalPan>=100.0)) VocalPan = 0.0;
    if (argc>=8) Gain = atof(argv[7]); else Gain = 0.0;
    if ((Gain<-20.0)||(Gain>20.0)) Gain = 0.0;

    /* Read Header from Input Wave File*/
    if ((infile = fopen(infilename,"rb+")) == NULL) {
        printf("\n\nError(1): Could not open input file \"%s\".\n",infilename); return(1);}
    
    fread(&infileHeader, sizeof(infileHeader), 1, infile);
    if ((infileHeader.ID[0]!='R')||(infileHeader.ID[1]!='I')
       ||(infileHeader.ID[2]!='F')||(infileHeader.ID[3]!='F')) {
         printf("\n\nError(3): \"%s\" is not a standrad RIFF file.\n",infilename);
           fclose(infile); return(3);}

    fread(&WaveId, sizeof(WaveId), 1, infile);
    if ((WaveId[0]!='W')||(WaveId[1]!='A')||(WaveId[2]!='V')||(WaveId[3]!='E')) {
        printf("\n\nError(4): Could not find correct WAVE header form \"%s\".\n", infilename);
           fclose(infile); return(4);}

    fread(&infileHeader, sizeof(infileHeader), 1, infile);
    if ((infileHeader.ID[0]!='f')||(infileHeader.ID[1]!='m')
      ||(infileHeader.ID[2]!='t')||(infileHeader.ID[3]!=' ')) {
        printf("\n\nError(5): Could not find correct chunk header form \"%s\".\n", infilename);
           fclose(infile); return(5);}
    
    fread(&infileChunk, sizeof(infileChunk), 1, infile);
    fseek(infile, ftell(infile) + infileHeader.Length - 16, 0);
    /* Display the input file format*/
    if (infileChunk.FormatTag == 1) printf("(Windows PCM");
    if (infileChunk.FormatTag == 3) printf("(IEEE float");
    printf(", %d Hz, %d bit, ", infileChunk.SampleRate, infileChunk.Bits);
    if (infileChunk.Channels == 1) printf("mono)\n"); else
    if (infileChunk.Channels == 2) printf("stereo)\n"); else
    printf("%d channels)\n", infileChunk.Channels);
    /* end */
    if ((infileChunk.FormatTag!=0x0001)&&(infileChunk.FormatTag!=0x0003)) {
        printf("\nError(6): \"%s\" is not a PCM or IEEE float wave file.\n",infilename);
          fclose(infile); return(6);}
    if (infileChunk.Channels!=2) {
        printf("\nError(7): \"%s\" is not stereo.\n",infilename);
          fclose(infile); return(7);}
    if ((infileChunk.Bits!=8)&&(infileChunk.Bits!=16)&&(infileChunk.Bits!=24)&&(infileChunk.Bits!=32))
        { printf("\nError(8): VoiX could not process %d bit wave files.\n", infileChunk.Bits);
          fclose(infile); return(8);}
    if (infileChunk.Bits/8*infileChunk.Channels!=infileChunk.BlockAlign)
        { printf("\nError(9): VoiX could not process non-standrad wave files.\n");
          fclose(infile); return(9);}
    fread(&infileHeader, sizeof(infileHeader), 1, infile);
    while (((infileHeader.ID[0]!='d')||(infileHeader.ID[1]!='a')||
          (infileHeader.ID[2]!='t')||(infileHeader.ID[3]!='a'))
    &&(!feof(infile))) {
    fseek(infile, ftell(infile) + infileHeader.Length, 0); 
    fread(&infileHeader, sizeof(infileHeader), 1, infile);
    }
    if (feof(infile)) {
       printf("\nError(10): Could not find correct data header form \"%s\".\n", infilename);
         fclose(infile); return(10);}
    printf("Output: %s\n", outfilename);
    if ((outfile = fopen(outfilename,"wb+")) == NULL) {
        printf("\nError(2): Could not open output file \"%s\".\n",outfilename);
          fclose(infile); return(2);}
    
    /* Write Header to Output Wave File*/
    DataSize = infileHeader.Length;
    tmpDataSize = 0;
    strcpy(infileHeader.ID,"RIFF"); infileHeader.Length = tmpDataSize+36;
    fwrite(&infileHeader,sizeof(infileHeader),1,outfile);
    strcpy(WaveId,"WAVE"); fwrite(WaveId,sizeof(WaveId),1,outfile);
    strcpy(infileHeader.ID,"fmt "); infileHeader.Length = 16;
    fwrite(&infileHeader,sizeof(infileHeader),1,outfile);
    fwrite(&infileChunk,sizeof(infileChunk),1,outfile);
    strcpy(infileHeader.ID,"data"); infileHeader.Length = tmpDataSize;
    fwrite(&infileHeader,sizeof(infileHeader),1,outfile);    
    
    if ((LPCutoff < 1.00) || (LPCutoff > infileChunk.SampleRate/2 - 1)) LPCutoff = 1.00;
    if ((HPCutoff < 1.00) || (HPCutoff > infileChunk.SampleRate/2 - 1)) HPCutoff = infileChunk.SampleRate/2 - 1;
    if (HPCutoff < LPCutoff) HPCutoff = LPCutoff;
    printf("(i)Lowpass: %.1f Hz, Highpass: %.1f Hz\n", LPCutoff, HPCutoff);
    SetLP(infileChunk.SampleRate,LPCutoff,a1,b1);
    SetHP(infileChunk.SampleRate,HPCutoff,a2,b2);
    for (i=0;i<=2;i++) {
      LP_L_In[i]=0; LP_L_Out[i]=0;
      HP_L_In[i]=0; HP_L_Out[i]=0;
      LP_R_In[i]=0; LP_R_Out[i]=0;
      HP_R_In[i]=0; HP_R_Out[i]=0;
    }
    printf("(i)Invert: ");
    if (Invert == 1.00) printf("On"); else printf("Off");
    printf(" Vocal Pan: "); printf("%.1f", VocalPan);
    VocalPan = (VocalPan+100.00)/2.00;
    printf(" Gain: %.1f dB\n", Gain);
    Gain = pow(10.0,Gain/20.0);
    
    if (VocalPan <= 50.0) {
    ChMix[0] = 1.0;
    ChMix[1] = -(VocalPan/(100.0-VocalPan));
    ChMix[2] = 1.0;
    ChMix[3] = -(VocalPan/(100.0-VocalPan));
    }
    if (VocalPan > 50.0) {
    ChMix[0] = -((100.0-VocalPan)/VocalPan);
    ChMix[1] = 1.0;
    ChMix[2] = -((100.0-VocalPan)/VocalPan);
    ChMix[3] = 1.0;
    }
    if (Invert == 0.00) {
      if (VocalPan<=50.00) {
         ChMix[2] = -ChMix[2]; ChMix[3] = -ChMix[3];
      }else {
         ChMix[0] = -ChMix[0]; ChMix[1] = -ChMix[1];         
      }         
    }

    printf("(!)Press [Ctrl+C] to exit\n(i)Process: ");
    Count = 0;
    for (i = 1; i <= DataSize/infileChunk.BlockAlign; i++) {
        
        if (feof(infile)) {
                        printf("\nError(11): EOF(End of file) of input file detected.\n");
                        fclose(infile); fclose(outfile); return(11);
                        }
        BlockRead(&Left, infileChunk.Bits, infileChunk.FormatTag, infile);
        BlockRead(&Right, infileChunk.Bits, infileChunk.FormatTag, infile);      
      
        
        if (percentage<i*20/(DataSize/infileChunk.BlockAlign)) {
          tmpDataSize = Count*infileChunk.BlockAlign;
          FilePos = ftell(outfile);
          tmpRIFFSize = tmpDataSize + 36;
          fseek(outfile,4,0); fwrite(&tmpRIFFSize,sizeof(tmpRIFFSize),1,outfile);
          fseek(outfile,40,0); fwrite(&tmpDataSize,sizeof(tmpDataSize),1,outfile);        
          fseek(outfile,FilePos,0);
          percentage= i*20/(DataSize/infileChunk.BlockAlign);
          printf("."); if (percentage%5==0) printf("%d%c",percentage*5,'%');

        }
        
        Count++;
        LP_L_In[2]=Left; LP_R_In[2]=Right;
        LP_L_Out[2]=(b1[0]/a1[0])*LP_L_In[2]+(b1[1]/a1[0])*LP_L_In[1]+(b1[2]/a1[0])*LP_L_In[0]-(a1[1]/a1[0])*LP_L_Out[1]-(a1[2]/a1[0])*LP_L_Out[0];
        LP_R_Out[2]=(b1[0]/a1[0])*LP_R_In[2]+(b1[1]/a1[0])*LP_R_In[1]+(b1[2]/a1[0])*LP_R_In[0]-(a1[1]/a1[0])*LP_R_Out[1]-(a1[2]/a1[0])*LP_R_Out[0];

        HP_L_In[2]=Left; HP_R_In[2]=Right;
        HP_L_Out[2]=(b2[0]/a2[0])*HP_L_In[2]+(b2[1]/a2[0])*HP_L_In[1]+(b2[2]/a2[0])*HP_L_In[0]-(a2[1]/a2[0])*HP_L_Out[1]-(a2[2]/a2[0])*HP_L_Out[0];
        HP_R_Out[2]=(b2[0]/a2[0])*HP_R_In[2]+(b2[1]/a2[0])*HP_R_In[1]+(b2[2]/a2[0])*HP_R_In[0]-(a2[1]/a2[0])*HP_R_Out[1]-(a2[2]/a2[0])*HP_R_Out[0];
           
        NewLeft=(ChMix[0]*(Left-LP_L_Out[2]-HP_L_Out[2])+ChMix[1]*(Right-LP_R_Out[2]-HP_R_Out[2]))*Gain+LP_L_Out[2]+HP_L_Out[2];
        NewRight=(ChMix[2]*(Left-LP_L_Out[2]-HP_L_Out[2])+ChMix[3]*(Right-LP_R_Out[2]-HP_R_Out[2]))*Gain+LP_R_Out[2]+HP_R_Out[2];
      
        LP_L_In[0]=LP_L_In[1]; LP_L_In[1]=LP_L_In[2];
        LP_R_In[0]=LP_R_In[1]; LP_R_In[1]=LP_R_In[2];
        LP_L_Out[0]=LP_L_Out[1]; LP_L_Out[1]=LP_L_Out[2];
        LP_R_Out[0]=LP_R_Out[1]; LP_R_Out[1]=LP_R_Out[2]; 
      
        HP_L_In[0]=HP_L_In[1]; HP_L_In[1]=HP_L_In[2];
        HP_R_In[0]=HP_R_In[1]; HP_R_In[1]=HP_R_In[2];
        HP_L_Out[0]=HP_L_Out[1]; HP_L_Out[1]=HP_L_Out[2];
        HP_R_Out[0]=HP_R_Out[1]; HP_R_Out[1]=HP_R_Out[2];  
      
        BlockWrite(NewLeft, infileChunk.Bits, infileChunk.FormatTag, outfile);
        BlockWrite(NewRight,infileChunk.Bits, infileChunk.FormatTag, outfile);       
    }
    tmpDataSize = DataSize;
    FilePos = ftell(outfile);
    tmpRIFFSize = tmpDataSize + 36;
    fseek(outfile,4,0); fwrite(&tmpRIFFSize,sizeof(tmpRIFFSize),1,outfile);
    fseek(outfile,40,0); fwrite(&tmpDataSize,sizeof(tmpDataSize),1,outfile);        
    fseek(outfile,FilePos,0);    
    printf("\n(i)Done processing file!\n");
    fclose(infile); fclose(outfile); return(0);
}
Exemplo n.º 17
0
struct VfsSuperBlock* Ext3ReadSuper(struct StorageDevice* dev,int flags,char* data)
{
	struct VfsSuperBlock* retVal;
	struct Buffer* buff;
	struct Ext3SuperBlock sb;
	struct Ext3SbInfo* sbInfo;
	int descCount,i;

	/* Must have a storage device */
	if (!dev || BlockSetSize(dev,1024))
		return NULL;

	/* The Ext3 superblock is located after the first block, which is reserved for boot-
	 * related data. */
	buff=BlockRead(dev, 1);
	if (!buff)
		goto error;

	/* The buffer will be freed if we set the block size to something other than
	 * 1024, so save the data off now.
	 */

	memcpy(&sb, buff->data, sizeof(struct Ext3SuperBlock));

	/* Sanity check. */
	if (sb.magic != EXT3_SB_MAGIC)
		goto blockReadError;

	retVal=VfsAllocSuper(dev,flags);
	if (!retVal)
		goto blockReadError;

	/* Ext3 block sizes are a multiple of 1024. */
	BlockSetSize(dev,1024 << sb.logBlockSize);

	/* Copy some useful information over into the private superblock structure. */
	sbInfo=(struct Ext3SbInfo*)MemAlloc(sizeof(struct Ext3SbInfo));
	if (!sbInfo)
		goto superFreeError;

	sbInfo->iNodesCount=sb.iNodesCount;
	sbInfo->blocksPerGrp=sb.blocksPerGrp;
	sbInfo->groupCount=(sb.blocksCount-sb.firstDataBlock+sb.blocksPerGrp-1)/sb.blocksPerGrp;
	sbInfo->iNodesPerGrp=sb.iNodesPerGrp;

	sbInfo->firstDataBlock=sb.firstDataBlock;
	
	/* Read in the superblock again. */
	Ext3ReadSuperBlock(retVal, sbInfo);

	/* And set the Ext3-specific parts of the superblock structure. */
	retVal->privData=sbInfo;
	retVal->sbOps=&ext3SbOps;

	/* Read in the block descriptors as pointers to buffers. */
	descCount=(sbInfo->groupCount+DESCS_PER_BLOCK(retVal)-1)/DESCS_PER_BLOCK(retVal);
	sbInfo->descs=(struct Buffer**)MemAlloc(descCount*sizeof(struct Buffer*));

	if (!descCount)
		goto superFreeError;

	for (i=0; i<descCount; i++)
		sbInfo->descs[i]=BlockRead(dev, Ext3GetDescriptorLoc(retVal, i));

	/* If we have a journal, read it in. We read the journal in before the root
	 * node, because it may have been modified in the journal. */

	if (EXT3_FEATURE_COMPAT(&sb, EXT3_FEATURE_COMPAT_JOURNAL))
	{
		if (Ext3JournalInit(retVal, &sb))
			goto descsFree;
		
		/* Write journal superblock. */
	}

	retVal->mount=VNodeGet(retVal, EXT3_ROOT_VNO);
	if (!retVal->mount)
		goto descsFree;

	BlockFree(buff);
	return retVal;

descsFree:
	for (i=0; i<descCount; i++)
		BlockFree(sbInfo->descs[i]);

	MemFree(sbInfo->descs);
	/* sbInfo is freed in VfsFreeSuper */
superFreeError:
	VfsFreeSuper(retVal);
blockReadError:
	BlockFree(buff);
error:
	return NULL;
}