Ejemplo n.º 1
0
void 
MTfile::Create (const char *filename)
{
	if (IsOpen()) {
		return;
	}
	fileHandle = open (filename, O_RDWR|O_BINARY);
	if (fileHandle >= 0) {
		close (fileHandle);
		return;
	}
	fileHandle = open (filename, O_BINARY|O_RDWR|O_CREAT|O_TRUNC, S_IREAD|S_IWRITE);
	if (fileHandle < 0) {
		return;
	}
	SetOpen (1);

	/* Reserve page 0 */
	char *page = new char[PageSize()];
	memset (page, 0, PageSize());
	memcpy (page, magic, sizeof(magic));
	write (fileHandle, page, PageSize());
	delete []page;
}
Ejemplo n.º 2
0
BOOL CSqlite3Recordset::GetField(short iIndex, CString& Data)
{
   _ASSERTE(IsOpen());
   _ASSERTE(iIndex>=0 && iIndex<m_nCols);
   if( IsEOF() ) return FALSE;
   if( iIndex < 0 || iIndex >= m_nCols ) return FALSE;
   if( m_lType == DB_OPEN_TYPE_FORWARD_ONLY ) {
#if !defined(UNICODE)
      Data = (char*) ::sqlite3_column_text(m_pVm, iIndex);
#else  // UNICODE
      Data = ::sqlite3_column_text16(m_pVm, iIndex);
#endif // UNICODE
   }
   else {
      LPSTR pstr = m_ppSnapshot[ ((m_iPos + 1) * m_nCols) + iIndex ];
      if( pstr == NULL ) {
         Data = _T("");
      }
      else {
         Data = pstr;
      }
   }
   return TRUE;
}
Ejemplo n.º 3
0
bool Ctrl::SetFocus0(bool activate)
{
	GuiLock __;
	USRLOG("      SETFOCUS " << Desc(this));
	LLOG("Ctrl::SetFocus " << Desc(this));
	LLOG("focusCtrlWnd " << UPP::Name(focusCtrlWnd));
	LLOG("Ctrl::SetFocus0 -> deferredSetFocus = NULL; was: " << UPP::Name(defferedSetFocus));
	defferedSetFocus = NULL;
	if(focusCtrl == this) return true;
	if(!IsOpen() || !IsEnabled() || !IsVisible()) return false;
	Ptr<Ctrl> pfocusCtrl = focusCtrl;
	Ptr<Ctrl> topwindow = GetTopWindow();
	Ptr<Ctrl> topctrl = GetTopCtrl();
	Ptr<Ctrl> _this = this;
	if(!topwindow) topwindow = topctrl;
	LLOG("SetFocus -> SetWndFocus: topwindow = " << UPP::Name(topwindow) << ", focusCtrlWnd = " << UPP::Name(focusCtrlWnd));
	if(!topwindow->HasWndFocus() && !topwindow->SetWndFocus()) return false;// cxl 31.1.2004
#ifdef PLATFORM_OSX11 // ugly temporary hack - popups not behaving right in MacOS
	// before 2012-9-2 was #ifdef GUI_X11, but that caused issues in most linux distros (cxl)
	// as parent window of popup always manages focus/keyboard for popup in X11
	if(activate) // Dolik/fudadmin 2011-5-1
		topctrl->SetWndForeground();
#else
	topwindow->SetWndForeground();  // cxl 2007-4-27
#endif
	LLOG("SetFocus -> focusCtrl = this: " << FormatIntHex(this) << ", _this = " << FormatIntHex(~_this) << ", " << UPP::Name(_this));
	focusCtrl = _this;
	focusCtrlWnd = topwindow;
	DoKillFocus(pfocusCtrl, _this);
	LLOG("SetFocus 2");
	DoDeactivate(pfocusCtrl, _this);
	DoSetFocus(pfocusCtrl, _this, activate);
	if(topwindow)
		lastActiveWnd = topwindow;
	return true;
}
Ejemplo n.º 4
0
void 
SPFS::LoadFileAsString(LPCSTR spfsFileName,string& sResultStr)
	{
	if( !IsOpen() )
		throw new SPFSException(_T("pack file isn't opened !"),SPFS_FILE_IS_NOT_OPENED);
	
	DWORD offset  = 0; // offset of file.
	DWORD size    = 0; // size of file.
	DWORD written = 0; // size of written bytes.

	// find file in pack file.
	if( !FindFile(spfsFileName,offset,size) ) 
		throw new SPFSException(_T("not found file in pack !"),SPFS_FILE_IS_NOT_OPENED);

	char* lpBuff   = (char*)malloc(size+1);
	if( ReadFileData(offset,size,lpBuff,size,written) && written == size )
		{
		lpBuff[size] = 0x00;    
		sResultStr     = lpBuff;
		}
	else
		throw new SPFSException(_T("can't read file data !"),SPFS_FILE_CANT_READ);
	free(lpBuff);
	}
Ejemplo n.º 5
0
void 
GiSTfile::Open(const char *filename)
{
  char *page;

  if (IsOpen())
    return;

  fileHandle = open(filename, O_RDWR | O_BINARY);

  if (fileHandle < 0)
    return;

  // Verify that the magic words are there
  page = new char[PageSize()];
  read(fileHandle, page, PageSize());
  if (memcmp(page, magic, sizeof(magic))) {
    close(fileHandle);
	delete page;
    return;
  }
  delete page;
  SetOpen(1);
}
Ejemplo n.º 6
0
   bool
   File::Open(const String &sFilename, OpenType ot)
   {
      if (IsOpen())
      {
         // The file should be closed, before we
         // try to open it again...
         throw std::logic_error(Formatter::FormatAsAnsi("The file {0} is already open.", sFilename));
      }

      std::wstring open_mode;

      switch (ot)
      {
      case OTReadOnly:
         open_mode = _T("rb");
         break;
      case OTCreate:
         open_mode = _T("wb");
         break;
      case OTAppend:
         open_mode = _T("ab");
         break;
      }

      file_ = _wfsopen(sFilename.c_str(), open_mode.c_str(), _SH_DENYNO);

      if (file_ == nullptr)
      {
         return false;
      }

      name_ = sFilename;

      return true;
   }
Ejemplo n.º 7
0
bool FileInputSource::Close(CFErrorRef *error)
{
	if(!IsOpen()) {
		LOGGER_WARNING("org.sbooth.AudioEngine.InputSource.File", "Close() called on an InputSource that hasn't been opened");
		return true;
	}

	memset(&mFilestats, 0, sizeof(mFilestats));

	if(nullptr != mFile) {
		int result = fclose(mFile);

		mFile = nullptr;

		if(-1 == result) {
			if(error)
				*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, errno, nullptr);
			return false;
		}
	}

	mIsOpen = false;
	return true;
}
Ejemplo n.º 8
0
void CNamedPipe::SetMode(BOOL bByteMode, BOOL bBlockingMode)
{
  //Validate our parameters
  ASSERT(IsOpen()); //Pipe must be open

  DWORD dwMode;
  if (bByteMode)
  {
    if (bBlockingMode)
      dwMode = PIPE_READMODE_BYTE | PIPE_WAIT;
    else
      dwMode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
  }
  else
  {
    if (bBlockingMode)
      dwMode = PIPE_READMODE_MESSAGE | PIPE_WAIT;
    else
      dwMode = PIPE_READMODE_MESSAGE | PIPE_NOWAIT;
  }

  if (!::SetNamedPipeHandleState(m_hPipe, &dwMode, NULL, NULL))
    ThrowNamedPipeException();
}
Ejemplo n.º 9
0
/* MX_OVERRIDDEN */ mx::Size mx::FileStream::PrintfV(
        const Char * const sFormat, va_list pArguments)
{
    mxAssert(IsOpen());
    mxAssert(sFormat != NULL);

    int iCharsWritten;
    if ((iCharsWritten =
#ifndef MXCPP_UNICODE
                     ::vfprintf
#else
                     ::vfwprintf
#endif
                 (m_hFileDescriptor, sFormat, pArguments))
        < 0)
    {
        // We cannot reach eof during write (check it).
        mxAssert(!feof(m_hFileDescriptor));
        // File I/O error other than EOF.
        mxThrow(GenericIOException(ferror(m_hFileDescriptor)));
    }

    return iCharsWritten;
}
Ejemplo n.º 10
0
int CoreIOWriter::WriteU32(uint32_t _data)
{
    CoreAssert(this != NULL);
    if (!IsOpen()) return 0;

#ifndef __GNUC__
    MutexHolder mh(&m_ioMutex);
#endif
    switch (m_endianness)
    {
    case CC_ENDIAN_LITTLE:
        _data = CC_SwapBE32(_data);
        break;
    case CC_ENDIAN_BIG:
        _data = CC_SwapLE32(_data);
        break;
    case CC_ENDIAN_NATIVE:
        /* Do nothing */
        break;
    }
    size_t ret = fwrite(&_data, sizeof(uint32_t), 1, m_fileOutputPointer);

    return ret;
}
Ejemplo n.º 11
0
////////////////////////////////////////////////////////////////////////////////
/// Lecture dans le fichier
///
/// Parametres : 
/// \param buffer     [out]buffer dans lequel a ete ecrit le contenu du fichier
/// \param count      [in]nombre max d'octets a lire
///
/// \return taille du fichier ou -1 si probleme de lecture
////////////////////////////////////////////////////////////////////////////////
int CAdeReadOnlyBinaryFileWithCRC::Read(void* buffer, unsigned int count)
{
    if (IsOpen() == false)
    {
        // fichier non ouvert
        return -1;
    }
    if (m_currPos >= m_lengthWithoutCRC)
    {
        // fin de fichier
        return 0;
    }
    // On limite eventuellement si ce qui reste a lire dans le fichier est inferieur a ce qui est demande
    if (count > static_cast<unsigned int>(m_lengthWithoutCRC - m_currPos))
    {
        count = m_lengthWithoutCRC - m_currPos;
    }
    // On copie les donnees
    memcpy(buffer, &m_fileContent[m_currPos], count);
    // On "avance" dans le fichier
    m_currPos += count;
    // On renvoie le nombre d'octets effectivement lus
    return count;
}
Ejemplo n.º 12
0
GiSTpage 
MTfile::Allocate()
{
	GiSTpage page;
	char *buf;

	if(!IsOpen()) return (0);
	// See if there's a deleted page
	buf=new char[PageSize()];
	Read(0, buf);
	memcpy(&page, buf+sizeof(magic), sizeof(GiSTpage));
	if(page) {
		// Reclaim this page
		Read(page, buf);
		Write(0, buf);
	}
	else {
		page=lseek(fileHandle, 0, SEEK_END)/PageSize();
		memset(buf, 0, PageSize());
		write(fileHandle, buf, PageSize());
	}
	delete buf;
	return page;
}
Ejemplo n.º 13
0
ALERROR CDataFile::AddEntry (const CString &sData, int *retiEntry)

//	AddEntry
//
//	Does some stuff

	{
	ALERROR error;
	int i, iEntry;
	DWORD dwStartingBlock;
	DWORD dwBlockCount;

	ASSERT(IsOpen());
	ASSERT(!m_fReadOnly);

	//	Look for a free entry

	for (i = 0; i < m_iEntryTableCount; i++)
		if (m_pEntryTable[i].dwBlock == FREE_ENTRY)
			break;

	//	If we could not find a free entry, grow the entry table

	if (i == m_iEntryTableCount)
		{
		if ((error = GrowEntryTable(&iEntry)))
			goto Fail;
		}
	else
		iEntry = i;

	//	Figure out how many blocks we need

	dwBlockCount = (sData.GetLength() / m_iBlockSize) + 1;

	//	Allocate a block chain large enough to contain the entry

	if ((error = AllocBlockChain(dwBlockCount, &dwStartingBlock)))
		goto Fail;

	//	Write the block chain

	if ((error = WriteBlockChain(dwStartingBlock, sData.GetPointer(), sData.GetLength())))
		{
		FreeBlockChain(dwStartingBlock, dwBlockCount);
		goto Fail;
		}

	//	Set the entry

	m_pEntryTable[iEntry].dwBlock = dwStartingBlock;
	m_pEntryTable[iEntry].dwBlockCount = dwBlockCount;
	m_pEntryTable[iEntry].dwSize = (DWORD)sData.GetLength();
	m_pEntryTable[iEntry].dwFlags = 0;
	m_fEntryTableModified = TRUE;

	//	Flush

	if ((error = Flush()))
		goto Fail;

	//	Done

	*retiEntry = iEntry;

	return NOERROR;

Fail:

	return error;
	}
Ejemplo n.º 14
0
BOOL PNDASPhysicalDrive::GetDriveLayout( LPBYTE lpbMemory, DWORD dwSize )
{
	if(!IsOpen())
		return FALSE;

	BOOL bResults = NdasCommGetUnitDeviceDynInfo(&m_ConnectionInfo, &m_UnitDynInfo);
	if(!bResults)
		return FALSE;

	PCHAR lpszDesc = (PCHAR)lpbMemory;
	CHAR bufferModel[100];
	CHAR bufferFwRev[100];
	CHAR bufferSerialNo[100];

	memcpy(bufferModel, (const char *)m_UnitInfo.Model, sizeof(m_UnitInfo.Model)); bufferModel[sizeof(m_UnitInfo.Model)] = '\0';
	memcpy(bufferFwRev, (const char *)m_UnitInfo.FwRev, sizeof(m_UnitInfo.FwRev)); bufferFwRev[sizeof(m_UnitInfo.FwRev)] = '\0';
	memcpy(bufferSerialNo, (const char *)m_UnitInfo.SerialNo, sizeof(m_UnitInfo.SerialNo)); bufferSerialNo[sizeof(m_UnitInfo.SerialNo)] = '\0';

	sprintf(
		lpszDesc,
		"Hardware Type : %d\n"
		"Hardware Version : %d\n"
		"Hardware Protocol Type : %d\n"
		"Hardware Protocol Version : %d\n"
		"Number of slot : %d\n"
		"Maximum transfer blocks : %d\n"
		"Maximum targets : %d\n"
		"Maximum LUs : %d\n"
		"Header Encryption : %s\n"
		"Data Encryption : %s\n"
		"\n"
		"Sector count : %I64d\n"
		"Supports LBA : %s\n"
		"Supports LBA48 : %s\n"
		"Supports PIO : %s\n"
		"Supports DMA : %s\n"
		"Supports UDMA : %s\n"
		"Model : %s\n"
		"Firmware Rev : %s\n"
		"Serial number : %s\n"
		"Media type : %s\n"
		"\n"
		"Present : %s\n"
		"Number of hosts with RW priviliage : %d\n"
		"Number of hosts with RO priviliage : %d\n",
		m_Info.HWType,
		m_Info.HWVersion,
		m_Info.HWProtoType,
		m_Info.HWProtoVersion,
		m_Info.iNumberofSlot,
		m_Info.iMaxBlocks,
		m_Info.iMaxTargets,
		m_Info.iMaxLUs,
		(m_Info.iHeaderEncryptAlgo) ? "YES" : "NO",
		(m_Info.iDataEncryptAlgo) ? "YES" : "NO",
		m_UnitInfo.SectorCount,
		(m_UnitInfo.bLBA) ? "YES" : "NO",
		(m_UnitInfo.bLBA48) ? "YES" : "NO",
		(m_UnitInfo.bPIO) ? "YES" : "NO",
		(m_UnitInfo.bDma) ? "YES" : "NO",
		(m_UnitInfo.bUDma) ? "YES" : "NO",
		bufferModel,
		bufferFwRev,
		bufferSerialNo,
		(m_UnitInfo.MediaType == MEDIA_TYPE_UNKNOWN_DEVICE) ? "Unknown device" :
		(m_UnitInfo.MediaType == MEDIA_TYPE_BLOCK_DEVICE) ? "Non-packet mass-storage device (HDD)" :
		(m_UnitInfo.MediaType == MEDIA_TYPE_COMPACT_BLOCK_DEVICE) ? "Non-packet compact storage device (Flash card)" :
		(m_UnitInfo.MediaType == MEDIA_TYPE_CDROM_DEVICE) ? "CD-ROM device (CD/DVD)" :
		(m_UnitInfo.MediaType == MEDIA_TYPE_OPMEM_DEVICE) ? "Optical memory device (MO)" :
		"Unknown device",
		(m_UnitDynInfo.bPresent) ? "YES" : "NO",
		m_UnitDynInfo.NRRWHost,
		m_UnitDynInfo.NRROHost);


	return TRUE;
} // GetDriveLayout()
Ejemplo n.º 15
0
bool OggSpeexDecoder::Open(CFErrorRef *error)
{
	if(IsOpen()) {
		LOGGER_WARNING("org.sbooth.AudioEngine.AudioDecoder.OggSpeex", "Open() called on an AudioDecoder that is already open");		
		return true;
	}

	// Ensure the input source is open
	if(!mInputSource->IsOpen() && !mInputSource->Open(error))
		return false;

	// Initialize Ogg data struct
	ogg_sync_init(&mOggSyncState);

	// Get the ogg buffer for writing
	char *data = ogg_sync_buffer(&mOggSyncState, READ_SIZE_BYTES);
	
	// Read bitstream from input file
	ssize_t bytesRead = GetInputSource()->Read(data, READ_SIZE_BYTES);
	if(-1 == bytesRead) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   0,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);
			
			CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL());
			CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, 
															   NULL, 
															   CFCopyLocalizedString(CFSTR("The file “%@” could not be read."), ""), 
															   displayName);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 errorString);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedFailureReasonKey, 
								 CFCopyLocalizedString(CFSTR("Read error"), ""));
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedRecoverySuggestionKey, 
								 CFCopyLocalizedString(CFSTR("Unable to read from the input file."), ""));
			
			CFRelease(errorString), errorString = NULL;
			CFRelease(displayName), displayName = NULL;
			
			*error = CFErrorCreate(kCFAllocatorDefault, 
								   AudioDecoderErrorDomain, 
								   AudioDecoderInputOutputError, 
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}
		
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}
	
	// Tell the sync layer how many bytes were written to its internal buffer
	int result = ogg_sync_wrote(&mOggSyncState, bytesRead);
	if(-1 == result) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   0,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);
			
			CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL());
			CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, 
															   NULL, 
															   CFCopyLocalizedString(CFSTR("The file “%@” does not appear to be an Ogg file."), ""), 
															   displayName);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 errorString);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedFailureReasonKey, 
								 CFCopyLocalizedString(CFSTR("Not an Ogg file"), ""));
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedRecoverySuggestionKey, 
								 CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
			
			CFRelease(errorString), errorString = NULL;
			CFRelease(displayName), displayName = NULL;
			
			*error = CFErrorCreate(kCFAllocatorDefault, 
								   AudioDecoderErrorDomain, 
								   AudioDecoderFileFormatNotRecognizedError, 
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}
		
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}
	
	// Turn the data we wrote into an ogg page
	result = ogg_sync_pageout(&mOggSyncState, &mOggPage);
	if(1 != result) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   0,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);
			
			CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL());
			CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, 
															   NULL, 
															   CFCopyLocalizedString(CFSTR("The file “%@” does not appear to be an Ogg file."), ""), 
															   displayName);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 errorString);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedFailureReasonKey, 
								 CFCopyLocalizedString(CFSTR("Not an Ogg file"), ""));
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedRecoverySuggestionKey, 
								 CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
			
			CFRelease(errorString), errorString = NULL;
			CFRelease(displayName), displayName = NULL;
			
			*error = CFErrorCreate(kCFAllocatorDefault, 
								   AudioDecoderErrorDomain, 
								   AudioDecoderFileFormatNotRecognizedError, 
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}
		
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	// Initialize the stream and grab the serial number
	ogg_stream_init(&mOggStreamState, ogg_page_serialno(&mOggPage));
	
	// Get the first Ogg page
	result = ogg_stream_pagein(&mOggStreamState, &mOggPage);
	if(0 != result) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   0,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);
			
			CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL());
			CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, 
															   NULL, 
															   CFCopyLocalizedString(CFSTR("The file “%@” does not appear to be an Ogg file."), ""), 
															   displayName);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 errorString);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedFailureReasonKey, 
								 CFCopyLocalizedString(CFSTR("Not an Ogg file"), ""));
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedRecoverySuggestionKey, 
								 CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
			
			CFRelease(errorString), errorString = NULL;
			CFRelease(displayName), displayName = NULL;
			
			*error = CFErrorCreate(kCFAllocatorDefault, 
								   AudioDecoderErrorDomain, 
								   AudioDecoderFileFormatNotRecognizedError, 
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}
	
	// Get the first packet (should be the header) from the page
	ogg_packet op;
	result = ogg_stream_packetout(&mOggStreamState, &op);
	if(1 != result) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   0,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);
			
			CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL());
			CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, 
															   NULL, 
															   CFCopyLocalizedString(CFSTR("The file “%@” does not appear to be an Ogg file."), ""), 
															   displayName);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 errorString);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedFailureReasonKey, 
								 CFCopyLocalizedString(CFSTR("Not an Ogg file"), ""));
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedRecoverySuggestionKey, 
								 CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
			
			CFRelease(errorString), errorString = NULL;
			CFRelease(displayName), displayName = NULL;
			
			*error = CFErrorCreate(kCFAllocatorDefault, 
								   AudioDecoderErrorDomain, 
								   AudioDecoderFileFormatNotRecognizedError, 
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}
		
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}

	if(op.bytes >= 5 && !memcmp(op.packet, "Speex", 5))
		mSpeexSerialNumber = mOggStreamState.serialno;

	++mOggPacketCount;
	
	// Convert the packet to the Speex header
	SpeexHeader *header = speex_packet_to_header((char *)op.packet, static_cast<int>(op.bytes));
	if(NULL == header) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   0,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);
			
			CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL());
			CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, 
															   NULL, 
															   CFCopyLocalizedString(CFSTR("The file “%@” does not appear to be an Ogg Speex file."), ""), 
															   displayName);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 errorString);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedFailureReasonKey, 
								 CFCopyLocalizedString(CFSTR("Not an Ogg Speex file"), ""));
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedRecoverySuggestionKey, 
								 CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), ""));
			
			CFRelease(errorString), errorString = NULL;
			CFRelease(displayName), displayName = NULL;
			
			*error = CFErrorCreate(kCFAllocatorDefault, 
								   AudioDecoderErrorDomain, 
								   AudioDecoderFileFormatNotRecognizedError, 
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}
	else if(SPEEX_NB_MODES <= header->mode) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   0,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);
			
			CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL());
			CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, 
															   NULL, 
															   CFCopyLocalizedString(CFSTR("The Speex mode in the file “%@” is not supported."), ""), 
															   displayName);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 errorString);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedFailureReasonKey, 
								 CFCopyLocalizedString(CFSTR("Unsupported Ogg Speex file mode"), ""));
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedRecoverySuggestionKey, 
								 CFCopyLocalizedString(CFSTR("This file may have been encoded with a newer version of Speex."), ""));
			
			CFRelease(errorString), errorString = NULL;
			CFRelease(displayName), displayName = NULL;
			
			*error = CFErrorCreate(kCFAllocatorDefault, 
								   AudioDecoderErrorDomain, 
								   AudioDecoderFileFormatNotSupportedError, 
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}
		
		speex_header_free(header), header = NULL;
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}
	
	const SpeexMode *mode = speex_lib_get_mode(header->mode);
	if(mode->bitstream_version != header->mode_bitstream_version) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   0,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);
			
			CFStringRef displayName = CreateDisplayNameForURL(mInputSource->GetURL());
			CFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, 
															   NULL, 
															   CFCopyLocalizedString(CFSTR("The Speex version in the file “%@” is not supported."), ""), 
															   displayName);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 errorString);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedFailureReasonKey, 
								 CFCopyLocalizedString(CFSTR("Unsupported Ogg Speex file version"), ""));
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedRecoverySuggestionKey, 
								 CFCopyLocalizedString(CFSTR("This file was encoded with a different version of Speex."), ""));
			
			CFRelease(errorString), errorString = NULL;
			CFRelease(displayName), displayName = NULL;
			
			*error = CFErrorCreate(kCFAllocatorDefault, 
								   AudioDecoderErrorDomain, 
								   AudioDecoderFileFormatNotSupportedError, 
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}
		
		speex_header_free(header), header = NULL;
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}
	
	// Initialize the decoder
	mSpeexDecoder = speex_decoder_init(mode);
	if(NULL== mSpeexDecoder) {
		if(error) {
			CFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 
																			   0,
																			   &kCFTypeDictionaryKeyCallBacks,
																			   &kCFTypeDictionaryValueCallBacks);
			
			CFDictionarySetValue(errorDictionary, 
								 kCFErrorLocalizedDescriptionKey, 
								 CFCopyLocalizedString(CFSTR("Unable to initialize the Speex decoder."), ""));
			
//			CFDictionarySetValue(errorDictionary, 
//								 kCFErrorLocalizedFailureReasonKey, 
//								 CFCopyLocalizedString(CFSTR("Unsupported Ogg Speex file version"), ""));
			
//			CFDictionarySetValue(errorDictionary, 
//								 kCFErrorLocalizedRecoverySuggestionKey, 
//								 CFCopyLocalizedString(CFSTR("This file was encoded with a different version of Speex."), ""));
			
			*error = CFErrorCreate(kCFAllocatorDefault, 
								   AudioDecoderErrorDomain, 
								   AudioDecoderInputOutputError, 
								   errorDictionary);
			
			CFRelease(errorDictionary), errorDictionary = NULL;				
		}
		
		speex_header_free(header), header = NULL;
		ogg_sync_destroy(&mOggSyncState);
		return false;
	}
	
	speex_decoder_ctl(mSpeexDecoder, SPEEX_SET_SAMPLING_RATE, &header->rate);
	
	mSpeexFramesPerOggPacket = (0 == header->frames_per_packet ? 1 : header->frames_per_packet);
	mExtraSpeexHeaderCount = header->extra_headers;

	// Initialize the speex bit-packing data structure
	speex_bits_init(&mSpeexBits);
	
	// Initialize the stereo mode
	mSpeexStereoState = speex_stereo_state_init();
	
	if(2 == header->nb_channels) {
		SpeexCallback callback;
		callback.callback_id = SPEEX_INBAND_STEREO;
		callback.func = speex_std_stereo_request_handler;
		callback.data = mSpeexStereoState;
		speex_decoder_ctl(mSpeexDecoder, SPEEX_SET_HANDLER, &callback);
	}
	
	// Canonical Core Audio format
	mFormat.mFormatID			= kAudioFormatLinearPCM;
	mFormat.mFormatFlags		= kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
	
	mFormat.mBitsPerChannel		= 8 * sizeof(float);
	mFormat.mSampleRate			= header->rate;
	mFormat.mChannelsPerFrame	= header->nb_channels;
	
	mFormat.mBytesPerPacket		= (mFormat.mBitsPerChannel / 8);
	mFormat.mFramesPerPacket	= 1;
	mFormat.mBytesPerFrame		= mFormat.mBytesPerPacket * mFormat.mFramesPerPacket;
	
	mFormat.mReserved			= 0;
	
	// Set up the source format
	mSourceFormat.mFormatID				= 'SPEE';
	
	mSourceFormat.mSampleRate			= header->rate;
	mSourceFormat.mChannelsPerFrame		= header->nb_channels;
	
	switch(header->nb_channels) {
		case 1:		mChannelLayout = CreateChannelLayoutWithTag(kAudioChannelLayoutTag_Mono);			break;
		case 2:		mChannelLayout = CreateChannelLayoutWithTag(kAudioChannelLayoutTag_Stereo);			break;
	}
	
	speex_header_free(header), header = NULL;

	// Allocate the buffer list
	spx_int32_t speexFrameSize = 0;
	speex_decoder_ctl(mSpeexDecoder, SPEEX_GET_FRAME_SIZE, &speexFrameSize);
	
	mBufferList = AllocateABL(mFormat, speexFrameSize);
	if(NULL == mBufferList) {
		if(error)
			*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, ENOMEM, NULL);

		speex_header_free(header), header = NULL;
		speex_stereo_state_destroy(mSpeexStereoState), mSpeexStereoState = NULL;
		speex_decoder_destroy(mSpeexDecoder), mSpeexDecoder = NULL;
		speex_bits_destroy(&mSpeexBits);

		ogg_sync_destroy(&mOggSyncState);
		return false;
	}
	
	for(UInt32 i = 0; i < mBufferList->mNumberBuffers; ++i)
		mBufferList->mBuffers[i].mDataByteSize = 0;

	mIsOpen = true;
	return true;
}
Ejemplo n.º 16
0
OggSpeexDecoder::~OggSpeexDecoder()
{
	if(IsOpen())
		Close();
}
Ejemplo n.º 17
0
UInt32 OggSpeexDecoder::ReadAudio(AudioBufferList *bufferList, UInt32 frameCount)
{
	if(!IsOpen() || NULL == bufferList || bufferList->mNumberBuffers != mFormat.mChannelsPerFrame || 0 == frameCount)
		return 0;

	UInt32 framesRead = 0;
	
	// Reset output buffer data size
	for(UInt32 i = 0; i < bufferList->mNumberBuffers; ++i)
		bufferList->mBuffers[i].mDataByteSize = 0;

	for(;;) {
		
		UInt32	framesRemaining	= frameCount - framesRead;
		UInt32	framesToSkip	= static_cast<UInt32>(bufferList->mBuffers[0].mDataByteSize / sizeof(float));
		UInt32	framesInBuffer	= static_cast<UInt32>(mBufferList->mBuffers[0].mDataByteSize / sizeof(float));
		UInt32	framesToCopy	= std::min(framesInBuffer, framesRemaining);
		
		// Copy data from the buffer to output
		for(UInt32 i = 0; i < mBufferList->mNumberBuffers; ++i) {
			float *floatBuffer = static_cast<float *>(bufferList->mBuffers[i].mData);
			memcpy(floatBuffer + framesToSkip, mBufferList->mBuffers[i].mData, framesToCopy * sizeof(float));
			bufferList->mBuffers[i].mDataByteSize += static_cast<UInt32>(framesToCopy * sizeof(float));
			
			// Move remaining data in buffer to beginning
			if(framesToCopy != framesInBuffer) {
				floatBuffer = static_cast<float *>(mBufferList->mBuffers[i].mData);
				memmove(floatBuffer, floatBuffer + framesToCopy, (framesInBuffer - framesToCopy) * sizeof(float));
			}
			
			mBufferList->mBuffers[i].mDataByteSize -= static_cast<UInt32>(framesToCopy * sizeof(float));
		}
		
		framesRead += framesToCopy;
		
		// All requested frames were read
		if(framesRead == frameCount)
			break;
		
		// EOS reached
		if(mSpeexEOSReached)
			break;

		// Attempt to process the desired number of packets
		unsigned packetsDesired = 1;
		while(0 < packetsDesired && !mSpeexEOSReached) {

			// Process any packets in the current page
			while(0 < packetsDesired && !mSpeexEOSReached) {

				// Grab a packet from the streaming layer
				ogg_packet oggPacket;
				int result = ogg_stream_packetout(&mOggStreamState, &oggPacket);
				if(-1 == result) {
					LOGGER_ERR("org.sbooth.AudioEngine.AudioDecoder.OggSpeex", "Ogg Speex decoding error: Ogg loss of streaming");
					break;
				}
				
				// If result is 0, there is insufficient data to assemble a packet
				if(0 == result)
					break;

				// Otherwise, we got a valid packet for processing
				if(1 == result) {
					if(5 <= oggPacket.bytes && !memcmp(oggPacket.packet, "Speex", 5))
						mSpeexSerialNumber = mOggStreamState.serialno;
					
					if(-1 == mSpeexSerialNumber || mOggStreamState.serialno != mSpeexSerialNumber)
						break;
					
					// Ignore the following:
					//  - Speex comments in packet #2
					//  - Extra headers (optionally) in packets 3+
					if(1 != mOggPacketCount && 1 + mExtraSpeexHeaderCount <= mOggPacketCount) {
						// Detect Speex EOS
						if(oggPacket.e_o_s && mOggStreamState.serialno == mSpeexSerialNumber)
							mSpeexEOSReached = true;

						// SPEEX_GET_FRAME_SIZE is in samples
						spx_int32_t speexFrameSize;
						speex_decoder_ctl(mSpeexDecoder, SPEEX_GET_FRAME_SIZE, &speexFrameSize);
						float buffer [(2 == mFormat.mChannelsPerFrame) ? 2 * speexFrameSize : speexFrameSize];
						
						// Copy the Ogg packet to the Speex bitstream
						speex_bits_read_from(&mSpeexBits, (char *)oggPacket.packet, static_cast<int>(oggPacket.bytes));
						
						// Decode each frame in the Speex packet
						for(spx_int32_t i = 0; i < mSpeexFramesPerOggPacket; ++i) {
							
							result = speex_decode(mSpeexDecoder, &mSpeexBits, buffer);

							// -1 indicates EOS
							if(-1 == result)
								break;
							else if(-2 == result) {
								LOGGER_ERR("org.sbooth.AudioEngine.AudioDecoder.OggSpeex", "Ogg Speex decoding error: possible corrupted stream");
								break;
							}
							
							if(0 > speex_bits_remaining(&mSpeexBits)) {
								LOGGER_ERR("org.sbooth.AudioEngine.AudioDecoder.OggSpeex", "Ogg Speex decoding overflow: possible corrupted stream");
								break;
							}
							
							// Normalize the values
							float maxSampleValue = 1u << 15;
							vDSP_vsdiv(buffer, 1, &maxSampleValue, buffer, 1, speexFrameSize);

							// Copy the frames from the decoding buffer to the output buffer, skipping over any frames already decoded
							framesInBuffer = static_cast<UInt32>(mBufferList->mBuffers[0].mDataByteSize / sizeof(float));
							memcpy(static_cast<float *>(mBufferList->mBuffers[0].mData) + framesInBuffer, buffer, speexFrameSize * sizeof(float));
							mBufferList->mBuffers[0].mDataByteSize += static_cast<UInt32>(speexFrameSize * sizeof(float));
							
							// Process stereo channel, if present
							if(2 == mFormat.mChannelsPerFrame) {
								speex_decode_stereo(buffer, speexFrameSize, mSpeexStereoState);
								vDSP_vsdiv(buffer + speexFrameSize, 1, &maxSampleValue, buffer + speexFrameSize, 1, speexFrameSize);

								memcpy(static_cast<float *>(mBufferList->mBuffers[1].mData) + framesInBuffer, buffer + speexFrameSize, speexFrameSize * sizeof(float));
								mBufferList->mBuffers[1].mDataByteSize += static_cast<UInt32>(speexFrameSize * sizeof(float));
							}
							
							// Packet processing finished
							--packetsDesired;
						}
					}

					++mOggPacketCount;
				}
			}
			
			// Grab a new Ogg page for processing, if necessary
			if(!mSpeexEOSReached && 0 < packetsDesired) {
				while(1 != ogg_sync_pageout(&mOggSyncState, &mOggPage)) {
					// Get the ogg buffer for writing
					char *data = ogg_sync_buffer(&mOggSyncState, READ_SIZE_BYTES);
					
					// Read bitstream from input file
					ssize_t bytesRead = GetInputSource()->Read(data, READ_SIZE_BYTES);
					if(-1 == bytesRead) {
						LOGGER_ERR("org.sbooth.AudioEngine.AudioDecoder.OggSpeex", "Unable to read from the input file");
						break;
					}
					
					ogg_sync_wrote(&mOggSyncState, bytesRead);

					// No more data available from input file
					if(0 == bytesRead)
						break;
				}
				
				// Ensure all Ogg streams are read
				if(ogg_page_serialno(&mOggPage) != mOggStreamState.serialno)
					ogg_stream_reset_serialno(&mOggStreamState, ogg_page_serialno(&mOggPage));

				// Get the resultant Ogg page
				int result = ogg_stream_pagein(&mOggStreamState, &mOggPage);
				if(0 != result) {
					LOGGER_ERR("org.sbooth.AudioEngine.AudioDecoder.OggSpeex", "Error reading Ogg page");
					break;
				}
			}
		}
	}
	
	mCurrentFrame += framesRead;

	if(0 == framesRead && mSpeexEOSReached)
		mTotalFrames = mCurrentFrame;

	return framesRead;
}
bool MemoryMappedFileInputSource::Open(CFErrorRef *error)
{
	if(IsOpen()) {
		log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("org.sbooth.AudioEngine.InputSource.MemoryMappedFile");
		LOG4CXX_WARN(logger, "Open() called on an InputSource that is already open");
		return true;
	}
	
	UInt8 buf [PATH_MAX];
	Boolean success = CFURLGetFileSystemRepresentation(mURL, FALSE, buf, PATH_MAX);
	if(!success) {
		if(error)
			*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, EIO, NULL);
		return false;
	}
	
	int fd = open(reinterpret_cast<const char *>(buf), O_RDONLY);
	
	if(-1 == fd) {
		if(error)
			*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, errno, NULL);
		return false;
	}
	
	if(-1 == fstat(fd, &mFilestats)) {
		if(error)
			*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, errno, NULL);

		if(-1 == close(fd)) {
			log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("org.sbooth.AudioEngine.InputSource.MemoryMappedFile");
			LOG4CXX_WARN(logger, "Unable to close the file: " << strerror(errno));
		}

		return false;
	}
	
	// Only regular files can be mapped
	if(!S_ISREG(mFilestats.st_mode)) {
		if(error)
			*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, EBADF, NULL);
		
		if(-1 == close(fd)) {
			log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("org.sbooth.AudioEngine.InputSource.MemoryMappedFile");
			LOG4CXX_WARN(logger, "Unable to close the file: " << strerror(errno));
		}
		
		memset(&mFilestats, 0, sizeof(mFilestats));

		return false;
	}
	
	mMemory = static_cast<int8_t *>(mmap(0, mFilestats.st_size, PROT_READ, MAP_FILE | MAP_SHARED, fd, 0));
	
	if(MAP_FAILED == mMemory) {
		if(error)
			*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, errno, NULL);
		
		if(-1 == close(fd)) {
			log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("org.sbooth.AudioEngine.InputSource.MemoryMappedFile");
			LOG4CXX_WARN(logger, "Unable to close the file: " << strerror(errno));
		}
		
		memset(&mFilestats, 0, sizeof(mFilestats));

		return false;
	}
	
	if(-1 == close(fd)) {
		if(error)
			*error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainPOSIX, errno, NULL);

		memset(&mFilestats, 0, sizeof(mFilestats));

		return false;
	}

	mCurrentPosition = mMemory;

	mIsOpen = true;
	return true;
}
Ejemplo n.º 19
0
dbiplus::Dataset* BXDatabase::Exec(const char *query, ...)
{
  if (!IsOpen()) {
    return NULL;
  }
  
  std::string strQuery = query;
  BXUtils::StringReplace(strQuery, "%s", "%q");
  BXUtils::StringReplace(strQuery, "%I64", "%ll");

  va_list args;
  va_start(args, query);
  char *szSql = sqlite3_vmprintf(strQuery.c_str(), args);
  va_end(args);

  std::string strResult;
  if (szSql) {
    strResult = szSql;
    sqlite3_free(szSql);
  }

  Dataset* pDataset = m_pDatabase->CreateDataset();
  if (pDataset == NULL)
  {
    LOG(LOG_LEVEL_ERROR, "Could not create dataset, query %s not executed", strResult.c_str());
    return NULL;
  }

  int iRetries = MEDIA_DATABSE_LOCK_RETRIES;

  while (iRetries > 0)
  {
    try 
    {
      pDataset->exec(strResult.c_str());
      return pDataset;
    }
    catch(dbiplus::DbErrors& e) {
      if (GetLastErrorCode() == SQLITE_LOCKED || GetLastErrorCode() == SQLITE_BUSY || GetLastErrorCode() == SQLITE_CANTOPEN)
      {
        LOG(LOG_LEVEL_DEBUG, "Database was locked, retry. Error = %s, msg= %s", GetLastErrorMessage(), e.getMsg());

        SDL_Delay(BXUtils::GetRandInt(10) + 10);
        iRetries--;
        
        // log the last attempt as error
        if (iRetries == 0)
          LOG(LOG_LEVEL_ERROR, "Exception caught, could not execute query. Error = %s, msg= %s", GetLastErrorMessage(), e.getMsg());

        continue;
      }
      else
      {
        // Some other error
        LOG(LOG_LEVEL_ERROR, "Exception caught, could not execute query. Error = %s, msg= %s", GetLastErrorMessage(), e.getMsg());
        iRetries = 0;
      }
    }
  }

  delete pDataset;
  return NULL;
}
Ejemplo n.º 20
0
CFirmaSet :: ~CFirmaSet ()
{
	if (IsOpen ())
		Close ();
}
Ejemplo n.º 21
0
bool BaseTCPServer::Open( uint16 port, char* errbuf )
{
    if( errbuf != NULL )
        errbuf[0] = 0;

    // mutex lock
    MutexLock lock( mMSock );

    if( IsOpen() )
    {
        if( errbuf != NULL )
            snprintf( errbuf, TCPSRV_ERRBUF_SIZE, "Listening socket already open" );
        return false;
    }
    else
    {
        mMSock.Unlock();

        // Wait for thread to terminate
        WaitLoop();

        mMSock.Lock();
    }

    // Setting up TCP port for new TCP connections
    mSock = new Socket( AF_INET, SOCK_STREAM, 0 );

    // Quag: don't think following is good stuff for TCP, good for UDP
    // Mis: SO_REUSEADDR shouldn't be a problem for tcp - allows you to restart
    //      without waiting for conn's in TIME_WAIT to die
    unsigned int reuse_addr = 1;
    mSock->setopt( SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof( reuse_addr ) );

    // Setup internet address information.
    // This is used with the bind() call
    sockaddr_in address;
    memset( &address, 0, sizeof( address ) );

    address.sin_family = AF_INET;
    address.sin_port = htons( port );
    address.sin_addr.s_addr = htonl( INADDR_ANY );

    if( mSock->bind( (sockaddr*)&address, sizeof( address ) ) < 0 )
    {
        if( errbuf != NULL )
            snprintf( errbuf, TCPSRV_ERRBUF_SIZE, "bind(): < 0" );

        SafeDelete( mSock );
        return false;
    }

    unsigned int bufsize = 64 * 1024; // 64kbyte receive buffer, up from default of 8k
    mSock->setopt( SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof( bufsize ) );

#ifdef WIN32
    unsigned long nonblocking = 1;
    mSock->ioctl( FIONBIO, &nonblocking );
#else
    mSock->fcntl( F_SETFL, O_NONBLOCK );
#endif

    if( mSock->listen() == SOCKET_ERROR )
    {
        if( errbuf != NULL )
#ifdef WIN32
            snprintf( errbuf, TCPSRV_ERRBUF_SIZE, "listen() failed, Error: %u", WSAGetLastError() );
#else
            snprintf( errbuf, TCPSRV_ERRBUF_SIZE, "listen() failed, Error: %s", strerror( errno ) );
#endif

        SafeDelete( mSock );
        return false;
    }

    mPort = port;

    // Start processing thread
    StartLoop();

    return true;
}
Ejemplo n.º 22
0
ALERROR CDataFile::ReadEntryPartial (int iEntry, int iPos, int iLength, CString *retsData)

//	ReadEntryPartial
//
//	Reads a portion of the given entry.
//	If iLength is -1, we read until the end of the buffer.

	{
	DWORD dwPos;
	char *pDest;
	DWORD dwRead;
	bool bOverrun = false;

	ASSERT(IsOpen());

	//	Make sure we're in bounds

	if (iEntry < 0 || iEntry >= m_iEntryTableCount)
		return ERR_FAIL;

	if (m_pEntryTable[iEntry].dwBlock == FREE_ENTRY)
		return ERR_FAIL;

	//	If we're off the end, then we're done. If we ask to read more than
	//	we have left, then it is an error.

	int iEntrySize = (int)m_pEntryTable[iEntry].dwSize;
	if (iPos > iEntrySize)
		{
		*retsData = NULL_STR;
		return ERR_FAIL;
		}

	//	Figure out how large the return buffer will be

	int iReadSize;
	if (iLength == -1)
		iReadSize = iEntrySize - iPos;
	else if (iPos + iLength > iEntrySize)
		{
		iReadSize = iEntrySize - iPos;
		bOverrun = true;
		}
	else
		iReadSize = iLength;

	if (iReadSize == 0)
		{
		*retsData = NULL_STR;
		return (bOverrun ? ERR_FAIL : NOERROR);
		}

	//	Allocate space in the string

	pDest = retsData->GetWritePointer(iReadSize);
	if (pDest == NULL)
		return ERR_MEMORY;

	//	Calculate the position

	dwPos = sizeof(HEADERSTRUCT) + (m_pEntryTable[iEntry].dwBlock * m_iBlockSize) + (DWORD)iPos;

	//	Position the file

	if (SDL_RWseek(m_hFile, dwPos, SEEK_SET) != dwPos)
		return ERR_FAIL;

	//	Read the file data

	dwRead = SDL_RWread(m_hFile, pDest, 1, iReadSize);
	if (dwRead != iReadSize)
		return ERR_FAIL;

	return NOERROR;
	}
Ejemplo n.º 23
0
void Ctrl::Refresh(const Rect& area) {
	GuiLock __;
	if(fullrefresh || !IsVisible() || !IsOpen()) return;
	LLOG("Refresh " << Name() << ' ' <<  area);
	RefreshFrame((area + GetView().TopLeft()) & GetView().Inflated(OverPaint()));
}
Ejemplo n.º 24
0
/**
 * Open or close the popup
 *
 * @param InIsOpen  If true, open the popup. Otherwise close it.
 */
void SMenuAnchor::SetIsOpen( bool InIsOpen, const bool bFocusMenu )
{
	// Prevent redundant opens/closes
	if ( IsOpen() != InIsOpen )
	{
		if ( InIsOpen )
		{
			TSharedPtr< SWidget > MenuContentPtr = OnGetMenuContent.IsBound() ? OnGetMenuContent.Execute() : MenuContent;

			if ( MenuContentPtr.IsValid() )
			{
				// OPEN POPUP
				if ( OnMenuOpenChanged.IsBound() )
				{
					OnMenuOpenChanged.Execute(true);
				}

				// This can be called at any time so we use the push menu override that explicitly allows us to specify our parent

				// Figure out where the menu anchor is on the screen, so we can set the initial position of our pop-up window
				SlatePrepass();

				// NOTE: Careful, GeneratePathToWidget can be reentrant in that it can call visibility delegates and such
				FWidgetPath MyWidgetPath;
				FSlateApplication::Get().GeneratePathToWidgetChecked(AsShared(), MyWidgetPath);
				const FGeometry& MyGeometry = MyWidgetPath.Widgets.Last().Geometry;

				// @todo Slate: This code does not properly propagate the layout scale of the widget we are creating the popup for.
				// The popup instead has a scale of one, but a computed size as if the contents were scaled. This code should ideally
				// wrap the contents with an SFxWidget that applies the necessary layout scale. This is a very rare case right now.

				// Figure out how big the content widget is so we can set the window's initial size properly
				TSharedRef< SWidget > MenuContentRef = MenuContentPtr.ToSharedRef();
				MenuContentRef->SlatePrepass();

				// Combo-boxes never size down smaller than the widget that spawned them, but all
				// other pop-up menus are currently auto-sized
				const FVector2D DesiredContentSize = MenuContentRef->GetDesiredSize();  // @todo: This is ignoring any window border size!
				const EMenuPlacement PlacementMode = Placement.Get();

				const FVector2D NewPosition = MyGeometry.AbsolutePosition;
				FVector2D NewWindowSize = DesiredContentSize;
				const FVector2D SummonLocationSize = MyGeometry.Size;

				FPopupTransitionEffect TransitionEffect(FPopupTransitionEffect::None);
				if ( PlacementMode == MenuPlacement_ComboBox || PlacementMode == MenuPlacement_ComboBoxRight )
				{
					TransitionEffect = FPopupTransitionEffect(FPopupTransitionEffect::ComboButton);
					NewWindowSize = FVector2D(FMath::Max(MyGeometry.Size.X, DesiredContentSize.X), DesiredContentSize.Y);
				}
				else if ( PlacementMode == MenuPlacement_BelowAnchor )
				{
					TransitionEffect = FPopupTransitionEffect(FPopupTransitionEffect::TopMenu);
				}
				else if ( PlacementMode == MenuPlacement_MenuRight )
				{
					TransitionEffect = FPopupTransitionEffect(FPopupTransitionEffect::SubMenu);
				}

				if ( Method == CreateNewWindow )
				{
					// Open the pop-up
					TSharedRef<SWindow> PopupWindow = FSlateApplication::Get().PushMenu(AsShared(), MenuContentRef, NewPosition, TransitionEffect, bFocusMenu, false, NewWindowSize, SummonLocationSize);
					PopupWindow->SetRequestDestroyWindowOverride(FRequestDestroyWindowOverride::CreateSP(this, &SMenuAnchor::RequestClosePopupWindow));
					PopupWindowPtr = PopupWindow;
				}
				else
				{
					// We are re-using the current window instead of creating a new one.
					// The popup will be presented via an overlay service.
					ensure(Method == UseCurrentWindow);
					Children[1]
						[
							MenuContentRef
						];

					// We want to support dismissing the popup widget when the user clicks outside it.
					FSlateApplication::Get().GetPopupSupport().RegisterClickNotification(MenuContentRef, FOnClickedOutside::CreateSP(this, &SMenuAnchor::OnClickedOutsidePopup));
				}

				if ( bFocusMenu )
				{
					FSlateApplication::Get().SetKeyboardFocus(MenuContentRef, EKeyboardFocusCause::SetDirectly);
				}
			}
		}
		else
		{
			// CLOSE POPUP

			if (Method == CreateNewWindow)
			{
				// Close the Popup window.
				TSharedPtr<SWindow> PopupWindow = PopupWindowPtr.Pin();
				if ( PopupWindow.IsValid() )
				{
					// Request that the popup be closed.
					PopupWindow->RequestDestroyWindow();
				}
			}
			else
			{
				// Close the popup overlay
				ensure(Method==UseCurrentWindow);
				Children[1].DetachWidget();
			}

			if (OnMenuOpenChanged.IsBound())
			{
				OnMenuOpenChanged.Execute(false);
			}
		}
	}
}
Ejemplo n.º 25
0
//
// File::Open
//
// Open a file using a path
//
Bool File::Open(const char *path, U32 modeIn)
{
    ASSERT(!IsOpen())

    // Save the mode
    mode = modeIn;

    U32 access = 0;
    U32 share = 0;
    U32 create = 0;
    U32 attrib = 0;

    // Translate mode into attributes

    access |= mode & MODE_READ ? GENERIC_READ : 0;
    access |= mode & MODE_WRITE ? GENERIC_WRITE : 0;

    share |= mode & MODE_SHARE_READ ? FILE_SHARE_READ : 0;
    share |= mode & MODE_SHARE_WRITE ? FILE_SHARE_WRITE : 0;

    switch (mode & MODE_CREATE_MASK)
    {
    case MODE_CREATE_NEW:
        create = CREATE_NEW;
        break;

    case MODE_CREATE_ALWAYS:
        create = CREATE_ALWAYS;
        break;

    case MODE_OPEN_EXISTING:
        create = OPEN_EXISTING;
        break;

    case MODE_OPEN_ALWAYS:
        create = OPEN_ALWAYS;
        break;

    case MODE_TRUNCATE_EXISTING:
        create = TRUNCATE_EXISTING;
        break;

    default:
        LERR("Unknown create/open mode")
    }

    attrib = FILE_ATTRIBUTE_NORMAL;
    attrib |= mode & MODE_ATTRIB_ARCHIVE ? FILE_ATTRIBUTE_ARCHIVE : 0;
    attrib |= mode & MODE_ATTRIB_HIDDEN ? FILE_ATTRIBUTE_HIDDEN : 0;
    attrib |= mode & MODE_ATTRIB_READONLY ? FILE_ATTRIBUTE_READONLY : 0;
    attrib |= mode & MODE_ATTRIB_SYSTEM ? FILE_ATTRIBUTE_SYSTEM : 0;

    handle = CreateFile(path, access, share, NULL, create, attrib, NULL);

    // Did an error occur
    if (handle == INVALID_HANDLE_VALUE)
    {
        Error("Could not open file");
        return (FALSE);
    }
    else
    {
        return (TRUE);
    }
}
Ejemplo n.º 26
0
bool SMenuAnchor::ShouldOpenDueToClick() const
{
	return !IsOpen() && !bDismissedThisTick;
}
Ejemplo n.º 27
0
int BXDatabase::Insert(const char* query, ...)
{
  if (!IsOpen())
  {
    return MEDIA_DATABASE_ERROR;
  }
  
  //LOG(LOG_LEVEL_DEBUG, "Inserting query for database %d in thread %d", m_pDatabase, pthread_self());

  std::string strQuery = query;
  BXUtils::StringReplace(strQuery, "%s", "%q");
  BXUtils::StringReplace(strQuery, "%I64", "%ll");

  va_list args;
  va_start(args, query);
  char *szSql = sqlite3_vmprintf(strQuery.c_str(), args);
  va_end(args);

  std::string strResult;
  if (szSql)
  {
    strResult = szSql;
    sqlite3_free(szSql);
  }

  //LOG(LOG_LEVEL_DEBUG, "Inserting query: %s for database %d in thread %d", strResult.c_str(), m_pDatabase, pthread_self());

  Dataset* pDataset = m_pDatabase->CreateDataset();
  if (pDataset == NULL)
  {
    LOG(LOG_LEVEL_ERROR, "Could not create dataset, query %s not executed", strResult.c_str());
    return MEDIA_DATABASE_ERROR;
  }

  int iID = MEDIA_DATABASE_ERROR;

  int iRetries = MEDIA_DATABSE_LOCK_RETRIES;

  while (iRetries > 0)
  {
    try
    {
      // In case of the error, exception will be thrown
      pDataset->exec(strResult.c_str());

      iID = (int)sqlite3_last_insert_rowid(m_pDatabase->getHandle());
      iRetries = 0;
    }
    catch(dbiplus::DbErrors& e)
    {
      if (GetLastErrorCode() == SQLITE_LOCKED || GetLastErrorCode() == SQLITE_BUSY || GetLastErrorCode() == SQLITE_CANTOPEN)
      {
        LOG(LOG_LEVEL_DEBUG, "Database was locked, retry. Error = %s, msg= %s", GetLastErrorMessage(), e.getMsg());

        // Sleep random amount of time 
        SDL_Delay(BXUtils::GetRandInt(10) + 10);
        iRetries--;

        // log the last attempt as error
        if (iRetries == 0)
          LOG(LOG_LEVEL_ERROR, "Exception caught, could not execute query. Error = %s, msg= %s", GetLastErrorMessage(), e.getMsg());

        continue;
      }
      else
      {
        // Some other error
        LOG(LOG_LEVEL_ERROR, "Exception caught, could not execute query. Error = %s, msg= %s", GetLastErrorMessage(), e.getMsg());
        iRetries = 0;
      }
    }
  }

  delete pDataset;

  return iID;
}
Ejemplo n.º 28
0
//初始化交易容器
void Dataprocess::Init()
{
    if(mapTran.empty())
    {
        S_TYPEFUNC sTF;
        if(IsOpen(6))
        {
            sTF.tradeType=POS_PREAUTH;
            sTF.func=CTradeTemplate<TranPreauth>::DoTrade;
            mapTran["01000310"]=sTF;//预授权
        }

        if(IsOpen(7))
        {
            sTF.tradeType=POS_PREAUTHREVE;
            sTF.func=CTradeTemplate<TranPreauthreve>::DoTrade;
            mapTran["01002011"]=sTF;//预授权撤销
        }

        if(IsOpen(8))
        {
            sTF.tradeType=POS_PREAUTHCPLREQ;
            sTF.func=CTradeTemplate<TranPreauthreq>::DoTrade;
            mapTran["02000020"]=sTF;//预授权完成(请求)
        }

        sTF.tradeType=POS_CONSUME;
        sTF.func=CTradeTemplate<TranConsume>::DoTrade;
        mapTran["02000022"]=sTF;//消费

        if(IsOpen(9))
        {
            sTF.tradeType=POS_PREAUTHCPLREVE;
            sTF.func=CTradeTemplate<TranPreauthcplreve>::DoTrade;
            mapTran["02002021"]=sTF;//预授权完成撤销
        }

        if(IsOpen(3))
        {
            sTF.tradeType=POS_REPEAL;
            sTF.func=CTradeTemplate<TranRepeal>::DoTrade;
            mapTran["02002023"]=sTF;//消费撤销
        }

        if(IsOpen(2))
        {
            sTF.tradeType=POS_QUERY;
            sTF.func=CTradeTemplate<TranQuery>::DoTrade;
            mapTran["02003101"]=sTF;//余额查询
        }

        if(IsOpen(14))
        {
            sTF.tradeType=POS_PREAUTHCPLNOTIFY;
            sTF.func=CTradeTemplate<TranPreauthnotify>::DoTrade;
            mapTran["02200024"]=sTF;//预授权完成(通知)
        }

         /**< 生产环境屏蔽退货 */
        if(IsOpen(1))
        {
            sTF.tradeType=POS_PAYBACK;
            sTF.func=CTradeTemplate<TranPayback>::DoTrade;
            mapTran["02202025"]=sTF; //退货
        }

        sTF.tradeType=POS_BATCHUPLOAD;
        sTF.func=CTradeTemplate<TranBatchupload>::DoTrade;
        mapTran["032000"]=sTF;//批上送金融交易/批上送结束、批上送通知交易、借/贷批上送通知交易、电子钱包/存折圈存批上送通知

        if(IsOpen(12))
        {
            sTF.tradeType=POS_UNPREAUTHCPLREQ;
            sTF.func=CTradeTemplate<TranUnpreauthreq>::DoTrade;
            mapTran["04000020"]=sTF;//预授权完成(请求)冲正
        }

        if(IsOpen(4))
        {
            sTF.tradeType=POS_UNCONSUME;
            sTF.func=CTradeTemplate<TranUnconsume>::DoTrade;
            mapTran["04000022"]=sTF;//消费冲正
        }

        if(IsOpen(10))
        {
            sTF.tradeType=POS_UNPREAUTH;
            sTF.func=CTradeTemplate<TranUnpreauth>::DoTrade;
            mapTran["04000310"]=sTF;//预授权冲正
        }

        if(IsOpen(5))
        {
            sTF.tradeType=POS_UNREPEAL;
            sTF.func=CTradeTemplate<TranUnrepeal>::DoTrade;
            mapTran["04002023"]=sTF;//消费撤销冲正
        }

        if(IsOpen(11))
        {
            sTF.tradeType=POS_UNPREAUTHREVE;
            sTF.func=CTradeTemplate<TranUnpreauthreve>::DoTrade;
            mapTran["04002011"]=sTF;//预授权撤销冲正
        }

        if(IsOpen(13))
        {
            sTF.tradeType=POS_UNPREAUTHCPLREVE;
            sTF.func=CTradeTemplate<TranUnpreauthcplreve>::DoTrade;
            mapTran["04002021"]=sTF;//预授权完成撤销冲正
        }

        sTF.tradeType=POS_BATCHFOOT;
        sTF.func=CTradeTemplate<TranBatchfoot>::DoTrade;
        mapTran["050000"]=sTF;//批结算

        sTF.tradeType=POS_SIGN;
        sTF.func=CTradeTemplate<TranSign>::DoTrade;
        mapTran["080000"]=sTF ;//签到

        sTF.tradeType=POS_DOWN_PARA;
        sTF.func=CTradeTemplate<TranDownpara>::DoTrade;
        mapTran["08000800"]=sTF ;//参数下载

		sTF.tradeType=POS_CHECKAMOUNT;
		sTF.func=CTradeTemplate<TranCheckamount>::DoTrade;
		mapTran["02003180"]=sTF;//余额查询

		sTF.tradeType=POS_WITHDRAW;
		sTF.func=CTradeTemplate<TranWithdraw>::DoTrade;
		mapTran["02003190"]=sTF;//提现

		sTF.tradeType=SCRIPTNOTIFY;
		sTF.func=CTradeTemplate<TranScriptNotify>::DoTrade;
		mapTran["06200000"]=sTF;//(消费)脚本结果通知

		sTF.tradeType=SCRIPTNOTIFY;
		sTF.func=CTradeTemplate<TranScriptNotify>::DoTrade;
		mapTran["06200300"]=sTF;//(预授权)脚本结果通知

		sTF.tradeType=IC_PARAMSQRY;
		sTF.func=CTradeTemplate<TranQueryPK>::DoTrade;
		mapTran["082000"]=sTF;//

		sTF.tradeType=IC_PARAMSDWNLD;
		sTF.func=CTradeTemplate<TranDownPK>::DoTrade;
		mapTran["080090"]=sTF;//
		
    }
}
Ejemplo n.º 29
0
/*
================
rvTramGate::Event_IsOpen
================
*/
void rvTramGate::Event_IsOpen( void ) {
	idThread::ReturnInt( IsOpen() );
}
MemoryMappedFileInputSource::~MemoryMappedFileInputSource()
{
	if(IsOpen())
		Close();
}