示例#1
0
bool QDirectFBPixmapData::fromDataBufferDescription(const DFBDataBufferDescription &dataBufferDescription)
{
    IDirectFB *dfb = screen->dfb();
    Q_ASSERT(dfb);
    DFBResult result = DFB_OK;
    IDirectFBDataBuffer *dataBufferPtr;
    if ((result = dfb->CreateDataBuffer(dfb, &dataBufferDescription, &dataBufferPtr)) != DFB_OK) {
        DirectFBError("QDirectFBPixmapData::fromDataBufferDescription()", result);
        return false;
    }
    QDirectFBPointer<IDirectFBDataBuffer> dataBuffer(dataBufferPtr);

    IDirectFBImageProvider *providerPtr;
    if ((result = dataBuffer->CreateImageProvider(dataBuffer.data(), &providerPtr)) != DFB_OK)
        return false;

    QDirectFBPointer<IDirectFBImageProvider> provider(providerPtr);

    DFBImageDescription imageDescription;
    result = provider->GetImageDescription(provider.data(), &imageDescription);
    if (result != DFB_OK) {
        DirectFBError("QDirectFBPixmapData::fromSurfaceDescription(): Can't get image description", result);
        return false;
    }

    if (imageDescription.caps & DICAPS_COLORKEY) {
        return false;
    }

    DFBSurfaceDescription surfaceDescription;
    if ((result = provider->GetSurfaceDescription(provider.data(), &surfaceDescription)) != DFB_OK) {
        DirectFBError("QDirectFBPixmapData::fromDataBufferDescription(): Can't get surface description", result);
        return false;
    }

    alpha = imageDescription.caps & DICAPS_ALPHACHANNEL;
    imageFormat = alpha ? screen->alphaPixmapFormat() : screen->pixelFormat();

    dfbSurface = screen->createDFBSurface(QSize(surfaceDescription.width, surfaceDescription.height),
                                          imageFormat, QDirectFBScreen::TrackSurface);

    result = provider->RenderTo(provider.data(), dfbSurface, 0);
    if (result != DFB_OK) {
        DirectFBError("QDirectFBPixmapData::fromSurfaceDescription(): Can't render to surface", result);
        return false;
    }

    w = surfaceDescription.width;
    h = surfaceDescription.height;
    is_null = (w <= 0 || h <= 0);
    d = QDirectFBScreen::depth(imageFormat);
    setSerialNumber(++global_ser_no);

#if defined QT_DIRECTFB_IMAGEPROVIDER_KEEPALIVE
    screen->setDirectFBImageProvider(providerPtr);
    provider.take();
#endif

    return true;
}
QString AbstractByteArrayStreamEncoder::previewData( AbstractModel* model, const AbstractModelSelection* selection )
{
    const ByteArrayView* byteArrayView = qobject_cast<const ByteArrayView*>( model );

    const ByteArrayDocument* byteArrayDocument =
        byteArrayView ? qobject_cast<const ByteArrayDocument*>( byteArrayView->baseModel() ) : 0;
    if( byteArrayDocument == 0 )
        return QString();

    const Okteta::AbstractByteArrayModel* byteArray = byteArrayDocument->content();

    const ByteArraySelection* byteArraySelection =
        selection ? static_cast<const ByteArraySelection*>( selection ) : 0;

    Okteta::AddressRange range = byteArraySelection && byteArraySelection->isValid() ?
        byteArraySelection->range() :
        Okteta::AddressRange::fromWidth( 0, byteArray->size() );
    range.restrictEndByWidth( MaxPreviewSize );

    QByteArray data;
    QBuffer dataBuffer( &data );
    dataBuffer.open( QIODevice::WriteOnly );

    const bool success = encodeDataToStream( &dataBuffer, byteArrayView, byteArray, range );
    dataBuffer.close();

    return success ? QString::fromLatin1(data) : QString();
}
// Lists all recruits for a guild - Misses times
void WorldSession::HandleGuildFinderGetRecruits(WorldPacket& recvPacket)
{
    sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_LF_GUILD_GET_RECRUITS");

    uint32 unkTime = 0;
    //recvPacket >> unkTime;

    Player* player = GetPlayer();
    if (!player->GetGuildId())
        return;

    std::vector<MembershipRequest> recruitsList = sGuildFinderMgr->GetAllMembershipRequestsForGuild(player->GetGuildId());
    uint32 recruitCount = recruitsList.size();

    ByteBuffer dataBuffer(53 * recruitCount);
    WorldPacket data(SMSG_LF_GUILD_RECRUIT_LIST_UPDATED, 7 + 26 * recruitCount + 53 * recruitCount);
    data.WriteBits(recruitCount, 20);

    for (std::vector<MembershipRequest>::const_iterator itr = recruitsList.begin(); itr != recruitsList.end(); ++itr)
    {
        MembershipRequest request = *itr;
        ObjectGuid playerGuid(MAKE_NEW_GUID(request.GetPlayerGUID(), 0, HIGHGUID_PLAYER));
        
        data.WriteBit(playerGuid[1]);
        data.WriteBit(playerGuid[4]);
        data.WriteBit(playerGuid[2]);
        data.WriteBit(playerGuid[6]);
        data.WriteBits(request.GetName().size(), 7);
        data.WriteBit(playerGuid[3]);
        data.WriteBit(playerGuid[7]);
        data.WriteBit(playerGuid[5]);
        data.WriteBits(request.GetComment().size(), 11);
        data.WriteBit(playerGuid[0]);
        
        dataBuffer << int32(request.GetAvailability());
        dataBuffer.WriteByteSeq(playerGuid[1]);
        dataBuffer << int32(time(NULL) <= request.GetExpiryTime());
        dataBuffer << int32(request.GetInterests());
        dataBuffer << int32(request.GetClassRoles());
        dataBuffer << int32(time(NULL) - request.GetSubmitTime()); // Time in seconds since application submitted.
        dataBuffer.WriteString(request.GetName());
        dataBuffer.WriteByteSeq(playerGuid[4]);
        dataBuffer.WriteByteSeq(playerGuid[6]);
        dataBuffer.WriteByteSeq(playerGuid[3]);
        dataBuffer.WriteByteSeq(playerGuid[7]);
        dataBuffer.WriteString(request.GetComment());
        dataBuffer << int32(request.GetLevel());
        dataBuffer << int32(request.GetExpiryTime() - time(NULL)); // TIme in seconds until application expires.
        dataBuffer.WriteByteSeq(playerGuid[2]);
        dataBuffer.WriteByteSeq(playerGuid[0]);
        dataBuffer << int32(request.GetClass());
        dataBuffer.WriteByteSeq(playerGuid[5]);
    }

    data.FlushBits();
    data.append(dataBuffer);
    data << uint32(time(NULL)); // Unk time

    player->SendDirectMessage(&data);
}
// -----------------------------------------------------------------------------
// ReadArrayFromStringL
// Reads the array from the string
// -----------------------------------------------------------------------------
//
LOCAL_C void ReadArrayFromStringL( const TDesC8& aString,
                                   RPointerArray<HBufC8>& aArray )
    {
    RMemReadStream inRead( static_cast<const TAny*>( aString.Ptr() ), aString.Size() );
    TInt size = 0;
    HBufC8* addData = NULL;
    TPtr8 dataBuffer(NULL,0,0);
    CleanupClosePushL( inRead );


    aArray.ResetAndDestroy();


    for( TInt i = 0; i < aString.Size();)
        {
        // If there is not enough data to read the integer
        // it means that it's an old version and the whole thing is the
        // string since in previous versions only one string is stored
        if(( aString.Size() - i) < sizeof(TInt) )
            {
            aArray.ResetAndDestroy();
            addData = aString.AllocLC();
            aArray.AppendL( addData );
            CleanupStack::Pop();
            CleanupStack::PopAndDestroy(); // inRead
            return;
            }

        size = inRead.ReadInt32L();
        i += sizeof(TInt);

        // If the size is negative or the size left is not large enough
        // it means that it's an old version and the whole thing is the
        // string since in previous versions only one string is stored.
        if( size < 0 || size > ( aString.Size() - i ) )
            {
            aArray.ResetAndDestroy();
            addData = aString.AllocLC();
            aArray.AppendL( addData );
            CleanupStack::Pop();
            CleanupStack::PopAndDestroy(); // inRead
            return;
            }
        addData = HBufC8::NewMaxLC( size );

        // Set the read buffer:
        dataBuffer.Set(const_cast<TUint8*>(addData->Ptr()), 0, size);

        // Read the data:
        inRead.ReadL( dataBuffer );

        aArray.AppendL( addData );
        CleanupStack::Pop( addData );

        i += size;
        }
    CleanupStack::PopAndDestroy();
    return;
    }
示例#5
0
bool WaveReader::DecodeAudioData()
{
  MOZ_ASSERT(OnTaskQueue());

  int64_t pos = GetPosition() - mWavePCMOffset;
  int64_t len = GetDataLength();
  int64_t remaining = len - pos;
  NS_ASSERTION(remaining >= 0, "Current wave position is greater than wave file length");

  static const int64_t BLOCK_SIZE = 4096;
  int64_t readSize = std::min(BLOCK_SIZE, remaining);
  int64_t frames = readSize / mFrameSize;

  static_assert(uint64_t(BLOCK_SIZE) < UINT_MAX /
                sizeof(AudioDataValue) / MAX_CHANNELS,
                "bufferSize calculation could overflow.");
  const size_t bufferSize = static_cast<size_t>(frames * mChannels);
  nsAutoArrayPtr<AudioDataValue> sampleBuffer(new AudioDataValue[bufferSize]);

  static_assert(uint64_t(BLOCK_SIZE) < UINT_MAX / sizeof(char),
                "BLOCK_SIZE too large for enumerator.");
  nsAutoArrayPtr<char> dataBuffer(new char[static_cast<size_t>(readSize)]);

  if (!ReadAll(dataBuffer, readSize)) {
    return false;
  }

  // convert data to samples
  const char* d = dataBuffer.get();
  AudioDataValue* s = sampleBuffer.get();
  for (int i = 0; i < frames; ++i) {
    for (unsigned int j = 0; j < mChannels; ++j) {
      if (mSampleFormat == FORMAT_U8) {
        uint8_t v =  ReadUint8(&d);
        *s++ = UnsignedByteToAudioSample<AudioDataValue>(v);
      } else if (mSampleFormat == FORMAT_S16) {
        int16_t v =  ReadInt16LE(&d);
        *s++ = SignedShortToAudioSample<AudioDataValue>(v);
      }
    }
  }

  double posTime = BytesToTime(pos);
  double readSizeTime = BytesToTime(readSize);
  NS_ASSERTION(posTime <= INT64_MAX / USECS_PER_S, "posTime overflow");
  NS_ASSERTION(readSizeTime <= INT64_MAX / USECS_PER_S, "readSizeTime overflow");
  NS_ASSERTION(frames < INT32_MAX, "frames overflow");

  mAudioQueue.Push(new AudioData(pos,
                                 static_cast<int64_t>(posTime * USECS_PER_S),
                                 static_cast<int64_t>(readSizeTime * USECS_PER_S),
                                 static_cast<int32_t>(frames),
                                 sampleBuffer.forget(),
                                 mChannels,
                                 mSampleRate));

  return true;
}
示例#6
0
void
GslVector::mpiBcast(int srcRank, const MpiComm& bcastComm)
{
  // Filter out those nodes that should not participate
  if (bcastComm.MyPID() < 0) return;

  // Check 'srcRank'
  queso_require_msg(!((srcRank < 0) || (srcRank >= bcastComm.NumProc())), "invalud srcRank");

  // Check number of participant nodes
  double localNumNodes = 1.;
  double totalNumNodes = 0.;
  bcastComm.Allreduce((void *) &localNumNodes, (void *) &totalNumNodes, (int) 1, RawValue_MPI_DOUBLE, RawValue_MPI_SUM,
                      "GslVector::mpiBcast()",
                      "failed MPI.Allreduce() for numNodes");
  queso_require_equal_to_msg(((int) totalNumNodes), bcastComm.NumProc(), "inconsistent numNodes");

  // Check that all participant nodes have the same vector size
  double localVectorSize  = this->sizeLocal();
  double sumOfVectorSizes = 0.;
  bcastComm.Allreduce((void *) &localVectorSize, (void *) &sumOfVectorSizes, (int) 1, RawValue_MPI_DOUBLE, RawValue_MPI_SUM,
                      "GslVector::mpiBcast()",
                      "failed MPI.Allreduce() for vectorSize");

  if ( ((unsigned int) sumOfVectorSizes) != ((unsigned int)(totalNumNodes*localVectorSize)) ) {
    std::cerr << "rank "                 << bcastComm.MyPID()
              << ": sumOfVectorSizes = " << sumOfVectorSizes
              << ", totalNumNodes = "    << totalNumNodes
              << ", localVectorSize = "  << localVectorSize
              << std::endl;
  }
  bcastComm.Barrier();
  queso_require_equal_to_msg(((unsigned int) sumOfVectorSizes), ((unsigned int)(totalNumNodes*localVectorSize)), "inconsistent vectorSize");

  // Ok, bcast data
  std::vector<double> dataBuffer((unsigned int) localVectorSize, 0.);
  if (bcastComm.MyPID() == srcRank) {
    for (unsigned int i = 0; i < dataBuffer.size(); ++i) {
      dataBuffer[i] = (*this)[i];
    }
  }

  bcastComm.Bcast((void *) &dataBuffer[0], (int) localVectorSize, RawValue_MPI_DOUBLE, srcRank,
                  "GslVector::mpiBcast()",
                  "failed MPI.Bcast()");

  if (bcastComm.MyPID() != srcRank) {
    for (unsigned int i = 0; i < dataBuffer.size(); ++i) {
      (*this)[i] = dataBuffer[i];
    }
  }

  return;
}
bool loadThemeFromBlob(const QString &themeBlob,
                       QHash<QString, QPicture> &partPictures,
                       QHash<QPair<QString, int>, QColor> &colors)
{
    QFile blob(themeBlob);
    if (!blob.open(QIODevice::ReadOnly)) {
        qWarning() << __FUNCTION__ << ": Could not read blob: " << themeBlob;
        return false;
    }
    QDataStream blobIn(&blob);

    quint32 version;
    blobIn >> version;

    if (version != blobVersion) {
        qWarning() << __FUNCTION__ << ": Invalid blob version: " << version << " ...expected: " << blobVersion;
        return false;
    }

    QByteArray data;
    blobIn >> data;
    data = qUncompress(data);
    QBuffer dataBuffer(&data);
    dataBuffer.open(QIODevice::ReadOnly);
    QDataStream dataIn(&dataBuffer);

    int colorsCount;
    dataIn >> colorsCount;
    for (int i = 0; i < colorsCount; ++i) {
        QPair<QString, int> key;
        dataIn >> key;
        QColor value;
        dataIn >> value;
        colors.insert(key, value);
    }

    int picturesCount;
    dataIn >> picturesCount;
    for (int i = 0; i < picturesCount; ++i) {
        QString key;
        dataIn >> key;
        QPicture value;
        dataIn >> value;
        value.setBoundingRect(QRect(0, 0, pictureSize, pictureSize)); // Bug? The forced bounding rect was not deserialized.
        partPictures.insert(key, value);
    }

    if (dataIn.status() != QDataStream::Ok) {
        qWarning() << __FUNCTION__ << ": Invalid data blob: " << themeBlob;
        return false;
    }
    return true;
}
示例#8
0
// -----------------------------------------------------------------------------
// CDRMXOma::InternalizeL
// -----------------------------------------------------------------------------
// 
void CDRMXOma::InternalizeL( RReadStream& aStream )
    {
    TInt64 timeData = 0;    
    TInt dataLength = 0;
    HBufC8* dataPart = 0;
    TPtr8 dataBuffer(NULL,0,0);
    TPtr16 dataBuffer2(NULL,0,0);
    
    // Read the ContentID
    dataLength = aStream.ReadInt32L();
    
    if( dataLength )
        {
        // Reserve a new buffer:
        dataPart = HBufC8::NewMaxLC( dataLength );
        
        // Set the read buffer:
        dataBuffer.Set(const_cast<TUint8*>(dataPart->Ptr()), 0, dataLength);
        
        // Read the data:
        aStream.ReadL( dataBuffer );
        
        // Pop the buffer 
        CleanupStack::Pop(); // dataPart
                
        // If an old content identifier exists delete it        
        if( iContentID )
            {
            delete iContentID;
            iContentID = NULL;
            }
        
        // assign the new content id
        iContentID = dataPart;    
        }
    else
        {
        // If an old content identifier exists delete it 
        if( iContentID )
            {
            delete iContentID;
            iContentID = NULL;
            }        
        }           
        
    // The Time stamp
    ReadInt64L( timeData, aStream );
    iTimeStamp = timeData;    
                   
    // The time interval                
    iWaitTime =  aStream.ReadInt32L();               
    };   
示例#9
0
bool Downloader::request(const QString& theMethod, const QUrl& url, const QString& theData, bool FireForget) {
    if (Error) return false;

    qDebug() << "Downloader::request: " << url;

    netManager.setProxy(M_PREFS->getProxy(url));
    QNetworkRequest req(url);

    req.setRawHeader(QByteArray("Content-Type"), QByteArray("text/xml"));
    req.setRawHeader(QByteArray("User-Agent"), USER_AGENT.toLatin1());

    QByteArray dataArray(theData.toUtf8());
    QBuffer dataBuffer(&dataArray);
    currentReply = netManager.sendCustomRequest(req, theMethod.toLatin1(), &dataBuffer);

    if (AnimationTimer) {
        AnimationTimer->start(200);
        connect(currentReply,SIGNAL(downloadProgress(qint64, qint64)), this,SLOT(progress(qint64, qint64)));
    }

    if (FireForget)
        return true;

    if (Loop.exec() == QDialog::Rejected)
        return false;

    if (AnimationTimer)
        SAFE_DELETE(AnimationTimer);

    /* Test for redirections */
    QVariant redir = currentReply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if (redir.isValid()) {
        LocationText = redir.toString();
        if (!LocationText.isEmpty()) {
            QUrl newUrl(LocationText);
            return request(theMethod, newUrl, theData, FireForget);
        }
    }

    /* Handler error? */
    if (currentReply->error())
        QMessageBox::information(0,tr("error"), currentReply->errorString());


    /* Read the data */
    Content = currentReply->readAll();
    Result = currentReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    ResultText = currentReply->errorString();
    ErrorText = currentReply->rawHeader("Error");
    return !Error;
}
bool
MapModuleNoticeContainer::oldLoad( int fd,
                                   uint32 totalLength,
                                   uint32 nbrMaps)
{
   mc2dbg << "[MMNC]: Using old type of index.db!" << endl;
   
   

   vector<MapModuleNotice*> notices;

   {
      errno = 0;
      DataBuffer dataBuffer(totalLength);
      if (! Utility::read( fd,
                           dataBuffer.getBufferAddress(), 
                           totalLength) ) {     
         mc2log << error << "[MMNC]::oldLoad - error reading index : "
                << strerror(errno) << ", totalLength = " << totalLength
                << endl;
         return false;
      } else {
         for (uint32 i=0; i<nbrMaps; i++) {
            MapModuleNotice *tmpMN = new MapModuleNotice(&dataBuffer);
            mc2dbg4 << "MapNotice for map with ID=" 
                    << tmpMN->getMapID() << ", country=" 
                    << StringTable::getString(
                       StringTable::getCountryStringCode(
                          tmpMN->getCountryCode()),
                       StringTable::SWEDISH) << endl;
            mc2dbg4 << "MapModuleNotice with mapID = "  
                    << tmpMN->getMapID() << " loaded." << endl;
            notices.push_back(tmpMN);
#if 0
            if ( MapBits::isCountryMap(tmpMN->getMapID()) ) {
               notices.push_back(new MapModuleNotice(
                  MapBits::countryToOverview(tmpMN->getMapID())));
            }
#endif
         }
      }
   }

   // Remove contents of container.
   deleteAllObjs();
   // Fake regions.
   initUsingCC( notices );
   return true;
   
}
bool saveThemeToBlob(const QString &themeBlob,
                     const QHash<QString, QPicture> &partPictures,
                     const QHash<QPair<QString, int>, QColor> &colors)
{
    QFile blob(themeBlob);
    if (!blob.open(QIODevice::WriteOnly)) {
        qWarning() << __FUNCTION__ << ": Could not create blob: " << themeBlob;
        return false;
    }

    QByteArray data;
    QBuffer dataBuffer(&data);
    dataBuffer.open(QIODevice::WriteOnly);
    QDataStream dataOut(&dataBuffer);

    const int colorsCount = colors.count();
    dataOut << colorsCount;
    const QList<QPair<QString, int> > colorKeys = colors.keys();
    for (int i = 0; i < colorsCount; ++i) {
        const QPair<QString, int> &key = colorKeys.at(i);
        dataOut << key;
        const QColor color = colors.value(key);
        dataOut << color;
    }

    dataOut << partPictures.count();
    QHashIterator<QString, QPicture> i(partPictures);
    while (i.hasNext()) {
        i.next();
        dataOut << i.key();
        dataOut << i.value(); // the QPicture
    }

    QDataStream blobOut(&blob);
    blobOut << blobVersion;
    blobOut << qCompress(data);
    return blobOut.status() == QDataStream::Ok;
}
// COM port and baud rate enumeration
int DFURequestsCOM::EnumeratePorts(CStringListX &ports)
{
#if !defined _WINCE && !defined _WIN32_WCE
	// Try to read the COM ports from the registry first
	ports.RemoveAll();
	HKEY handle;
	if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
		             0, KEY_ENUMERATE_SUB_KEYS | KEY_EXECUTE | KEY_QUERY_VALUE | KEY_READ,
					 &handle)
		== ERROR_SUCCESS)
	{
		// Determine the maximum buffer sizes required
		DWORD maxNameLength;
		DWORD maxDataLength;
		if (RegQueryInfoKey(handle, 0, 0, 0, 0, 0, 0, 0,
			                &maxNameLength, &maxDataLength, 0, 0)
			== ERROR_SUCCESS)
		{
			// Allocate buffers to receive the key data
			SmartPtr<TCHAR, true> nameBuffer(new TCHAR[++maxNameLength]);
			SmartPtr<BYTE, true> dataBuffer(new BYTE[maxDataLength]);
			
			// Enumerate the values
			DWORD index = 0;
			DWORD type;
			DWORD nameBufferLength = maxNameLength;
			DWORD dataBufferLength = maxDataLength;
			while (RegEnumValue(handle, index++,
				                nameBuffer, &nameBufferLength, 0, &type,
								(BYTE *) dataBuffer, &dataBufferLength)
				   == ERROR_SUCCESS)
			{
				// Add this port if the type is correct
				if (type == REG_SZ) ports.AddTail((TCHAR *) (BYTE *) dataBuffer);

				// Restore the buffer lengths
				nameBufferLength = maxNameLength;
				dataBufferLength = maxDataLength;
			}
		}

		// Close the registry
		RegCloseKey(handle);
	}

	// If any ports found then check if they can be opened
	if (!ports.IsEmpty())
	{
		// Try to open all of the ports
		for (CStringListX::POSITION port = ports.GetHeadPosition(); port;)
		{
			CStringListX::POSITION portPos = port;
			if (!bool(Device(ports.GetNext(port))))
			{
				ports.RemoveAt(portPos);
			}
		}

		// Sort the list and return the number of ports found
		return Device::Sort(deviceFormat, firstPort, lastPort, ports);
	}
#endif

	// Try opening all possible COM ports
	return Device::Enumerate(deviceFormat, firstPort, lastPort, ports);
}
示例#13
0
// -----------------------------------------------------------------------------
// CDRMConstraint::InternalizeL
// -----------------------------------------------------------------------------
//
EXPORT_C void CDRMConstraint::InternalizeL( RReadStream& aStream )
    {

    TInt64 timeData = 0;
    TInt32 temp = 0;

    // used for the buffers
    TInt dataLength = 0;
    HBufC8* dataPart = NULL;
    TPtr8 dataBuffer(NULL,0,0);

    // Read the (possible) synchronizing marker.
    iSyncMark = aStream.ReadInt32L();

    if ( iSyncMark != KSyncMark )
        {

        // The structure of the externalized Permission object is the old one.
        // The first four bytes constitute half of the eight bytes of Start time.
        // Read another four bytes from the stream (and apply bit modifications)
        // in order to reconstruct the Start time (iStartTime).
        temp = aStream.ReadInt32L();

        timeData = temp;
        timeData <<= 32;

        Mem::Copy( &timeData, &iSyncMark, sizeof(TInt32) );

        iStartTime = timeData;
        timeData = 0;

        // The version is marked as old version for differentiation in
        // InternalizeL.
        iVersion = KVersion3_2_0;

        }
    else
        {
        // The structure of the externalized Permission object is the new one.
        // Read the version and Start time.
        iVersion = aStream.ReadInt32L();

        // Read the start time
        ReadInt64L( timeData, aStream );
        iStartTime = timeData;

        }

    // Read the end time
    ReadInt64L( timeData, aStream );
    iEndTime = timeData;

    // Read the interval start time
    ReadInt64L( timeData, aStream );
    iIntervalStart = timeData;

    // Read the interval
    iInterval = aStream.ReadInt32L();

    // Read the counter
    iCounter = aStream.ReadInt32L();

    // Read the original counter
    iOriginalCounter = aStream.ReadInt32L();

    // Read the timed counter
    iTimedCounter = aStream.ReadInt32L();

    // Read the timed interval
    iTimedInterval = aStream.ReadInt32L();

    // Read the accumulated time
    iAccumulatedTime = aStream.ReadInt32L();

    // Read the individual
    dataLength = aStream.ReadInt32L();

    SanitizeL( dataLength );

    if( dataLength > 0 )
        {
        // Reserve a new buffer:
        dataPart = HBufC8::NewMaxLC( dataLength );

        // Set the read buffer:
        dataBuffer.Set(const_cast<TUint8*>(dataPart->Ptr()), 0, dataLength);

        // Read the data:
        aStream.ReadL( dataBuffer );


        // Fill the array from the string
        ReadArrayFromStringL( dataBuffer, iIndividual);

        // Pop the buffer
        CleanupStack::PopAndDestroy(); // dataPart

        }
    else
        {
        iIndividual.ResetAndDestroy();
        }


    // Read the system
    if ( iVersion == KVersion3_2_0 ) // Constraint has the old structure.
        {

        dataLength = aStream.ReadInt32L();

        SanitizeL( dataLength );

        if( dataLength > 0 )
            {
            // Reserve a new buffer:
            dataPart = HBufC8::NewMaxLC( dataLength );

            // Set the read buffer:
            dataBuffer.Set( const_cast<TUint8*>(dataPart->Ptr()), 0,
                            dataLength );

            // Read the data:
            aStream.ReadL( dataBuffer );

            // Pop the buffer
            CleanupStack::Pop(); // dataPart

            // If an old content identifier exists delete it
            if ( iSystem.Count() )
                {
                iSystem.ResetAndDestroy();
                }

            // assign the new content id
            iSystem.AppendL( dataPart );
            }
        else
            {
            // If an old system exists delete it
            if ( iSystem.Count() )
                {
                iSystem.ResetAndDestroy();
                }
            }
        }

    // Software Vendor Id
    iVendorId.iUid = aStream.ReadInt32L();

    // Secure Id of the allowed application
    iSecureId.iUid = aStream.ReadInt32L();

    // Active constraints
    iActiveConstraints = aStream.ReadUint32L();

#ifdef RD_DRM_METERING

    // Do not read metering information if the version
    // is the old one because Metering is not activated in it.
    if ( iVersion == KVersion3_2_1 )
        {

        // Metering info
        dataLength = aStream.ReadInt32L();

        SanitizeL( dataLength );

        if( dataLength > 0 )
            {

            if( !iDrmMeteringInfo )
                {
                // Reserve a new metering information instance
                iDrmMeteringInfo = new (ELeave)TDrmMeteringInfo;
                }
            else
                {
                iDrmMeteringInfo->iGraceTime = 0;
                iDrmMeteringInfo->iAllowUseWithoutMetering = EFalse;
                }

            // Read grace time
            iDrmMeteringInfo->iGraceTime = aStream.ReadInt32L();

            // Read whether content can be consumed without
            // metering being used
            iDrmMeteringInfo->iAllowUseWithoutMetering =
                aStream.ReadInt8L();

            }
        else
            {

            // If old metering information exists delete it
            if( iDrmMeteringInfo )
                {
                delete iDrmMeteringInfo;
                iDrmMeteringInfo = NULL;
                }
            }
        }

#endif //RD_DRM_METERING

    // Read the system and original timed counter
    // according to the new structure.
    if ( iVersion == KVersion3_2_1 )
        {

        dataLength = aStream.ReadInt32L();

        SanitizeL( dataLength );

        if( dataLength > 0 )
            {
            // Reserve a new buffer:
            dataPart = HBufC8::NewMaxLC( dataLength );

            // Set the read buffer:
            dataBuffer.Set(const_cast<TUint8*>(dataPart->Ptr()), 0, dataLength);

            // Read the data:
            aStream.ReadL( dataBuffer );

            // Fill the array from the string
            ReadArrayFromStringL( dataBuffer, iSystem);

            // Pop the buffer
            CleanupStack::PopAndDestroy(); // dataPart

            }
        else
            {
            iSystem.ResetAndDestroy();
            }

        // Read the original timed counter
        iOriginalTimedCounter = aStream.ReadInt32L();

        // For future use or development, reads the data at the end of the stream
        dataLength = aStream.ReadInt32L();

        SanitizeL( dataLength );

        if ( dataLength > 0 )
            {

            // Reserve a new buffer:
            dataPart = HBufC8::NewMaxLC( dataLength );

            // Set the read buffer:
            dataBuffer.Set(const_cast<TUint8*>(dataPart->Ptr()), 0, dataLength);

            // Read the data:
            aStream.ReadL( dataBuffer );

            // Pop the buffer
            CleanupStack::PopAndDestroy( dataPart );
            }
        }

    // Constraint can be considered to have the new structure from now on.
    if ( iVersion == KVersion3_2_0 )
        {
        iSyncMark = KSyncMark;
        iVersion = KVersion3_2_1;
        }

    };
示例#14
0
	void NewSerialPort::write(const char aData[], size_t aLength)
	{
		std::vector<char> dataBuffer(aData, aData + aLength);
		write(dataBuffer);
	}
bool 
OldCountryOverviewMap::internalSave(int outfile)
{
   // Save the general map data
   bool retVal = OldGenericMap::internalSave(outfile);
   
   mc2dbg1 << "SAVING COUNTRYMAP" << endl;
   if (retVal) {
      // Save the ID of the maps in this country
      DataBuffer dataBuffer((m_mapsInCountry.size()+1)*24);
      dataBuffer.writeNextLong(m_mapsInCountry.size());
      mc2dbg1 << "Nbr maps = " << m_mapsInCountry.size() << endl;
      for (uint32 i=0; i<m_mapsInCountry.size(); i++) {
         mc2dbg4 << "Saving map with ID=" 
                 << m_mapsInCountry[i].mapID << endl;
         dataBuffer.writeNextLong(m_mapsInCountry[i].mapID);
         dataBuffer.writeNextLong(m_mapsInCountry[i].creationTime);
         mc2dbg4 << "creationTime = " 
                 << m_mapsInCountry[i].creationTime << endl;
         dataBuffer.writeNextLong(m_mapsInCountry[i].maxLat);
         dataBuffer.writeNextLong(m_mapsInCountry[i].minLon);
         dataBuffer.writeNextLong(m_mapsInCountry[i].minLat);
         dataBuffer.writeNextLong(m_mapsInCountry[i].maxLon);
      }

      // Save to file
      write(outfile, 
            dataBuffer.getBufferAddress(), 
            dataBuffer.getCurrentOffset());

      // Save the original ID of the items in this map
      uint32 nbrOriginalIDs = m_originalIDs.size();
      mc2dbg1 << "To save " << nbrOriginalIDs << " original ID:s" << endl;
      DataBuffer origIDs(4 + nbrOriginalIDs*12);
      origIDs.writeNextLong(nbrOriginalIDs);
      map<uint32, struct originalIDs_t>::iterator p = m_originalIDs.begin();
      while (p != m_originalIDs.end()) {
         origIDs.writeNextLong(p->first);
         origIDs.writeNextLong(p->second.origMapID);
         origIDs.writeNextLong(p->second.origItemID);
         mc2dbg4 << "Saving itemID " << p->first << " orig("
                 << p->second.origMapID << "." << p->second.origItemID 
                 << ")" << endl;
         p++;
      }

      // Write the original IDs to file
      write(outfile, 
            origIDs.getBufferAddress(), 
            origIDs.getCurrentOffset());
      
      // Write the array of filter stacks.
      if (m_simplifiedGfxStack != NULL) {

         int numElements = m_nbrGfxPolygons * NBR_SIMPLIFIED_COUNTRY_GFX;
         // 10MB should be enough.
         for (byte i = 0; i < NBR_SIMPLIFIED_COUNTRY_GFX; i++) {
            // And each stack for that level
            for (uint32 j = 0; j < m_nbrGfxPolygons; j++) {
               // The number of elements of this stack.
               numElements += m_simplifiedGfxStack[i][j]->getStackSize();
            }
         }

         mc2dbg4 << "required stack size="<<4*numElements+12<<endl;

         DataBuffer* stackBuf = new DataBuffer(4*numElements + 12);

         // Write the number of bytes to follow (filled in later)
         stackBuf->writeNextLong(0);
         
         // Nbr levels of stack.
         stackBuf->writeNextLong(NBR_SIMPLIFIED_COUNTRY_GFX);

         // Nbr of polygons per level.
         stackBuf->writeNextLong(m_nbrGfxPolygons);
         // For each level.
         for (byte i = 0; i < NBR_SIMPLIFIED_COUNTRY_GFX; i++) {
            // And each stack for that level
            for (uint32 j = 0; j < m_nbrGfxPolygons; j++) {
               // The number of elements of this stack.
               Stack* curStack = m_simplifiedGfxStack[i][j];
               stackBuf->writeNextLong(curStack->getStackSize());
               // And write all elements
               for (uint32 k = 0; k < curStack->getStackSize(); k++) {
                  stackBuf->writeNextLong(curStack->getElementAt(k));
               }
            }
         }
         // Fill in size
         stackBuf->writeLong( stackBuf->getCurrentOffset() - 4, 0);
         write(outfile, 
               stackBuf->getBufferAddress(), 
               stackBuf->getCurrentOffset());
         delete stackBuf;
      }
      

   } else {
      mc2log << error << here << " Failed to save country overview map" 
             << endl;
   }

   return (retVal);
}
void Ym3812::UpdateSoundBuffer(Dword frameNumber, SoundBufferData & soundBuffer)
{
	Qword currentTime = timer.GetTime();

	//If this is the first call to UpdateSoundBuffer, or there are no samples to update
	if(frameNumber == 1 || soundBuffer.numSamples == 0)
	{
		//Apply all of the register writes
		for(std::vector <RegisterWrite>::const_iterator i = registerWrites.begin();
			i != registerWrites.end(); ++i)
		{
			ApplyRegisterWrite(i->address, i->data);
		}
	}
	else
	{
		//Otherwise, convert the times stored with the register writes into sample numbers
		for(std::vector <RegisterWrite>::iterator i = registerWrites.begin();
			i != registerWrites.end(); ++i)
		{
			i->numSamples = static_cast<Dword>(	((i->time - lastUpdateTime) * soundBuffer.numSamples) /
												(currentTime - lastUpdateTime));
		}

		//Allocate a temporary data buffer
#ifdef USE_FMOPL
		std::vector <SignedWord> dataBuffer(soundBuffer.numSamples);
#endif

#ifdef USE_YM3812_CHANNEL
		std::vector <SignedDword> dataBuffer(soundBuffer.numSamples);
#endif

		//Loop through the register writes
		Dword sample = 0;

		for(std::vector <RegisterWrite>::const_iterator i = registerWrites.begin();
			i != registerWrites.end(); ++i)
		{
			//Generate samples up to the point of this write
			Dword samplesToGenerate = i->numSamples - sample;
			
			GenerateSamples(samplesToGenerate, &dataBuffer[sample]);

			sample += samplesToGenerate;

			//Apply the register write
			ApplyRegisterWrite(i->address, i->data);
		}

		//Generate the remaining samples
		GenerateSamples(soundBuffer.numSamples - sample, &dataBuffer[sample]);

		//Copy the data to the sound buffer
		for(Dword i = 0; i < soundBuffer.numSamples; ++i)
		{
			soundBuffer.data[i * 2    ] += dataBuffer[i];
			soundBuffer.data[i * 2 + 1] += dataBuffer[i];
		}
	}

	registerWrites.clear();
	lastUpdateTime = currentTime;
}
bool
WriteableMapModuleNoticeContainer::save( const char* filename )
{
   mc2dbg << "[WMMNC]: Saving..." << endl;

   int version = 1;
   // Assumes that the average MapModuleNotice is less than
   // 256 kB
   // TODO: Calculate the size
   uint32 noticesSize=0;
   for (uint32 i = 0; i < getSize(); i++){
      noticesSize+=getElementAt( i )->getSizeInDataBuffer(version);  
   }
   
   DataBuffer dataBuffer(noticesSize +
                         m_mapTree.getSizeInDataBuffer()+2000000 +
                         mapSupCovSizeInDataBuffer() );
   dataBuffer.fillWithZeros();
   //   DataBuffer dataBuffer((getSize() + 1) * 262144*8 +
   //                         m_mapTree.getSizeInDataBuffer()+2000000 );
   
   dataBuffer.writeNextLong(0);         // Old size
   dataBuffer.writeNextLong(0);         // Old nbritems
   dataBuffer.writeNextLong(0);         // New length
   dataBuffer.writeNextLong(version);   // Version
   dataBuffer.writeNextLong(getSize()); // Nbr mapModulenotices
   for( uint32 i = 0; i < getSize(); ++i ) {
      mc2dbg << "[WMMNC]: Saving notice"
             << m_allNotices[i]->getMapID() << endl;
      m_allNotices[i]->save(&dataBuffer, version);
   }

   // Save the ItemIDTree
   mc2dbg << "[WMMNC]: Saving mapTree" << endl;
   m_mapTree.save(&dataBuffer);

   // Save the regions
   mc2dbg << "[WMMNC]: Saving regions" << endl;
   int nbrRegions = m_regions.size();
   dataBuffer.writeNextLong(nbrRegions);
   for( topRegionMap_t::const_iterator it = m_regions.begin();
        it != m_regions.end();
        ++it ) {
      it->second->save(&dataBuffer);
   }
   
   // Save the RegionIDTree
   mc2dbg << "[WMMNC]: Saving regionTree" << endl;
   m_regionTree.save(&dataBuffer);
   
   // Save map supplier coverage data
   mc2dbg << "[WMMNC]: Saving map supplier coverage data" << endl;
   saveMapSupCoverage(&dataBuffer);
   mc2dbg << "[WMMNC]: Done saving map supplier coverage data" << endl;

   // TotalSize, but not including old size,nbr items and new length
   dataBuffer.writeLong(dataBuffer.getCurrentOffset()-12, 8);
   int fd;
   errno = 0;
#  ifdef __linux
   fd = creat(filename, S_IRUSR | S_IWUSR | // owner rw
                        S_IRGRP | S_IWGRP | // group rw
                        S_IROTH );          // other r
#  else   
   fd = creat(filename, 664);
#  endif
   
   if (fd <= 0) { 
      mc2log << error << "MapModuleNoticeContainer::Save(), File error"
             << strerror(errno) << endl;
      return false;
   } else {
      // Fill in TotalSize
      write(fd, 
            dataBuffer.getBufferAddress(),
            dataBuffer.getCurrentOffset() );
   }
   ::close(fd);
   mc2dbg << "[WMMNC]: Everything saved" << endl;
   return true;
}
示例#18
0
bool ossimH5Reader::getTile(ossimImageData* result, ossim_uint32 resLevel)
{
   bool status = false;

   m_mutex.lock();
   
   //---
   // Not open, this tile source bypassed, or invalid res level,
   // return a blank tile.
   //---
   if( isOpen() && isSourceEnabled() && isValidRLevel(resLevel) &&
       result && (result->getNumberOfBands() == getNumberOfOutputBands()) )
   {
      result->ref(); // Increment ref count.
      
      //---
      // Check for overview tile.  Some overviews can contain r0 so always
      // call even if resLevel is 0.  Method returns true on success, false
      // on error.
      //---
      status = getOverviewTile(resLevel, result);

      if (!status) // Did not get an overview tile.
      {
         status = true;
         
         ossimIrect tile_rect = result->getImageRectangle();

         if ( ! tile_rect.completely_within(getImageRectangle(0)) )
         {
            // We won't fill totally so make blank first.
            result->makeBlank();
         }
         
         if (getImageRectangle(0).intersects(tile_rect))
         {
            // Make a clip rect.
            ossimIrect clipRect = tile_rect.clipToRect(getImageRectangle(0));
            
            if (tile_rect.completely_within( clipRect) == false)
            {
               // Not filling whole tile so blank it out first.
               result->makeBlank();
            }

            // Create buffer to hold the clip rect for a single band.
            ossim_uint32 clipRectSizeInBytes = clipRect.area() *
               ossim::scalarSizeInBytes( m_entries[m_currentEntry].getScalarType() );
            vector<char> dataBuffer(clipRectSizeInBytes);

            // Get the data.
            for (ossim_uint32 band = 0; band < getNumberOfInputBands(); ++band)
            {
               // Hdf5 file to buffer:
               m_entries[m_currentEntry].getTileBuf(&dataBuffer.front(), clipRect, band);

               if ( m_entries[m_currentEntry].getScalarType() == OSSIM_FLOAT32 )
               {
                  //---
                  // NPP VIIRS data has null of "-999.3".
                  // Scan and fix non-standard null value.
                  //---
                  const ossim_float32 NP = getNullPixelValue(band);
                  const ossim_uint32 COUNT = clipRect.area();
                  ossim_float32* float_buffer = (ossim_float32*)&dataBuffer.front();
                  for ( ossim_uint32 i = 0; i < COUNT; ++i )
                  {
                     if ( float_buffer[i] <= -999.0 ) float_buffer[i] = NP;
                  }
               }

               // Buffer to tile:
               result->loadBand((void*)&dataBuffer.front(), clipRect, band);
            }

            // Validate the tile, i.e. full, partial, empty.
            result->validate();
         }
         else // No intersection...
         {
            result->makeBlank();
         }
      }

      result->unref();  // Decrement ref count.
   }

   m_mutex.unlock();

   return status;
}
示例#19
0
// ---------------------------------------------------------------------------
//  XPathScanner: Scan methods
// ---------------------------------------------------------------------------
bool XPathScanner::scanExpression(const XMLCh* const data,
                                  int currentOffset,
                                  const int endOffset,
                                  ValueVectorOf<int>* const tokens) {

    bool      starIsMultiplyOperator = false;
    int       nameOffset = -1;
    int       nameHandle = -1;
    int       prefixHandle = -1;
    XMLCh     ch;
    XMLBuffer dataBuffer(128, tokens->getMemoryManager());

    while (true) {

        if (currentOffset == endOffset) {
            break;
        }

        ch = data[currentOffset];

        while (XMLChar1_0::isWhitespace(ch)) {

            if (++currentOffset == endOffset) {
                break;
            }

            ch = data[currentOffset];
        }

        if (currentOffset == endOffset) {
            break;
        }
        //
        // [28] ExprToken ::= '(' | ')' | '[' | ']' | '.' | '..' | '@' | ',' | '::'
        //                  | NameTest | NodeType | Operator | FunctionName
        //                  | AxisName | Literal | Number | VariableReference
        //
        XMLByte chartype = (ch >= 0x80) ? CHARTYPE_NONASCII : fASCIICharMap[ch];

        switch (chartype) {
        case CHARTYPE_OPEN_PAREN:       // '('
            addToken(tokens, XercesXPath::EXPRTOKEN_OPEN_PAREN);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_CLOSE_PAREN:      // ')'
            addToken(tokens, XercesXPath::EXPRTOKEN_CLOSE_PAREN);
            starIsMultiplyOperator = true;
            ++currentOffset;
            break;
        case CHARTYPE_OPEN_BRACKET:     // '['
            addToken(tokens, XercesXPath::EXPRTOKEN_OPEN_BRACKET);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_CLOSE_BRACKET:    // ']'
            addToken(tokens, XercesXPath::EXPRTOKEN_CLOSE_BRACKET);
            starIsMultiplyOperator = true;
            ++currentOffset;
            break;
                //
                // [30] Number ::= Digits ('.' Digits?)? | '.' Digits
                //                                         ^^^^^^^^^^
                //
        case CHARTYPE_PERIOD:           // '.', '..' or '.' Digits
            if (currentOffset + 1 == endOffset) {
                addToken(tokens, XercesXPath::EXPRTOKEN_PERIOD);
                starIsMultiplyOperator = true;
                currentOffset++;
                break;
            }

            ch = data[currentOffset + 1];

            if (ch == chPeriod) {            // '..'
                addToken(tokens, XercesXPath::EXPRTOKEN_DOUBLE_PERIOD);
                starIsMultiplyOperator = true;
                currentOffset += 2;
            } else if (ch >= chDigit_0 && ch <= chDigit_9) {
                addToken(tokens, XercesXPath::EXPRTOKEN_NUMBER);
                starIsMultiplyOperator = true;
                currentOffset = scanNumber(data, endOffset, currentOffset, tokens);
            } else if (ch == chForwardSlash) {
                addToken(tokens, XercesXPath::EXPRTOKEN_PERIOD);
                starIsMultiplyOperator = true;
                currentOffset++;
            } else if (ch == chPipe) { // '|'
                addToken(tokens, XercesXPath::EXPRTOKEN_PERIOD);
                starIsMultiplyOperator = true;
                currentOffset++;
            } else if (XMLChar1_0::isWhitespace(ch)) {
                do {
                    if (++currentOffset == endOffset)
                        break;

                    ch = data[currentOffset];
                } while (XMLChar1_0::isWhitespace(ch));

                if (currentOffset == endOffset || ch == chPipe) {
				    addToken(tokens, XercesXPath::EXPRTOKEN_PERIOD);
                    starIsMultiplyOperator = true;
                    break;
                }
            } else {
                ThrowXMLwithMemMgr(XPathException, XMLExcepts::XPath_InvalidChar, tokens->getMemoryManager());
            }

            break;
        case CHARTYPE_ATSIGN:           // '@'
            addToken(tokens, XercesXPath::EXPRTOKEN_ATSIGN);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_COMMA:            // ','
            addToken(tokens, XercesXPath::EXPRTOKEN_COMMA);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_COLON:            // '::'
            if (++currentOffset == endOffset) {
                return false; // REVISIT
            }
            ch = data[currentOffset];

            if (ch != chColon) {
                return false; // REVISIT
            }
            addToken(tokens, XercesXPath::EXPRTOKEN_DOUBLE_COLON);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_SLASH:            // '/' and '//'
            if (++currentOffset == endOffset) {
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_SLASH);
                starIsMultiplyOperator = false;
                break;
            }

            ch = data[currentOffset];

            if (ch == chForwardSlash) { // '//'
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_DOUBLE_SLASH);
                starIsMultiplyOperator = false;
                ++currentOffset;
            } else {
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_SLASH);
                starIsMultiplyOperator = false;
            }
            break;
        case CHARTYPE_UNION:            // '|'
            addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_UNION);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_PLUS:             // '+'
            addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_PLUS);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_MINUS:            // '-'
            addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_MINUS);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_EQUAL:            // '='
            addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_EQUAL);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_EXCLAMATION:      // '!='
            if (++currentOffset == endOffset) {
                return false; // REVISIT
            }

            ch = data[currentOffset];

            if (ch != chEqual) {
                return false; // REVISIT
            }

            addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_NOT_EQUAL);
            starIsMultiplyOperator = false;
            ++currentOffset;
            break;
        case CHARTYPE_LESS: // '<' and '<='
            if (++currentOffset == endOffset) {
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_LESS);
                starIsMultiplyOperator = false;
                break;
            }

            ch = data[currentOffset];

            if (ch == chEqual) { // '<='
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_LESS_EQUAL);
                starIsMultiplyOperator = false;
                ++currentOffset;
            } else {
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_LESS);
                starIsMultiplyOperator = false;
            }
            break;
        case CHARTYPE_GREATER: // '>' and '>='
            if (++currentOffset == endOffset) {
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_GREATER);
                starIsMultiplyOperator = false;
                break;
            }

            ch = data[currentOffset];

            if (ch == chEqual) { // '>='
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_GREATER_EQUAL);
                starIsMultiplyOperator = false;
                ++currentOffset;
            } else {
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_GREATER);
                starIsMultiplyOperator = false;
            }
            break;
        //
        // [29] Literal ::= '"' [^"]* '"' | "'" [^']* "'"
        //
        case CHARTYPE_QUOTE:            // '\"' or '\''
            {
                XMLCh qchar = ch;
                if (++currentOffset == endOffset) {
                    return false; // REVISIT
                }

                ch = data[currentOffset];

                int litOffset = currentOffset;
                while (ch != qchar) {
                    if (++currentOffset == endOffset) {
                        return false; // REVISIT
                    }

                    ch = data[currentOffset];
                }

                addToken(tokens, XercesXPath::EXPRTOKEN_LITERAL);
                starIsMultiplyOperator = true;

                dataBuffer.set(data + litOffset, currentOffset - litOffset);
                tokens->addElement(fStringPool->addOrFind(dataBuffer.getRawBuffer()));
                ++currentOffset;
                break;
            }
        //
        // [30] Number ::= Digits ('.' Digits?)? | '.' Digits
        // [31] Digits ::= [0-9]+
        //
        case CHARTYPE_DIGIT:
            addToken(tokens, XercesXPath::EXPRTOKEN_NUMBER);
            starIsMultiplyOperator = true;
            currentOffset = scanNumber(data, endOffset, currentOffset, tokens);
            break;
        //
        // [36] VariableReference ::= '$' QName
        //
        case CHARTYPE_DOLLAR:
            if (++currentOffset == endOffset) {
                return false; // REVISIT
            }
            nameOffset = currentOffset;
            currentOffset = scanNCName(data, endOffset, currentOffset);

            if (currentOffset == nameOffset) {
                return false; // REVISIT
            }

            if (currentOffset < endOffset) {
                ch = data[currentOffset];
            }
            else {
                ch = 0;
            }

            dataBuffer.set(data + nameOffset, currentOffset - nameOffset);
            nameHandle = fStringPool->addOrFind(dataBuffer.getRawBuffer());
            prefixHandle = -1;

            if (ch == chColon) {

                prefixHandle = nameHandle;
                if (++currentOffset == endOffset) {
                    return false; // REVISIT
                }
                nameOffset = currentOffset;
                currentOffset = scanNCName(data, endOffset, currentOffset);

                if (currentOffset == nameOffset) {
                    return false; // REVISIT
                }

                dataBuffer.set(data + nameOffset, currentOffset - nameOffset);
                nameHandle = fStringPool->addOrFind(dataBuffer.getRawBuffer());
            }
            addToken(tokens, XercesXPath::EXPRTOKEN_VARIABLE_REFERENCE);
            starIsMultiplyOperator = true;
            tokens->addElement(prefixHandle);
            tokens->addElement(nameHandle);
            break;
        //
        // [37] NameTest ::= '*' | NCName ':' '*' | QName
        // [34] MultiplyOperator ::= '*'
        //
        case CHARTYPE_STAR:             // '*'
            //
            // 3.7 Lexical Structure
            //
            //  If there is a preceding token and the preceding token is not one of @, ::, (, [, , or
            //  an Operator, then a * must be recognized as a MultiplyOperator.
            //
            // Otherwise, the token must not be recognized as a MultiplyOperator.
            //
            if (starIsMultiplyOperator) {
                addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_MULT);
                starIsMultiplyOperator = false;
            } else {
                addToken(tokens, XercesXPath::EXPRTOKEN_NAMETEST_ANY);
                starIsMultiplyOperator = true;
            }

            ++currentOffset;
            break;
        //
        // NCName, QName and non-terminals
        //
        case CHARTYPE_NONASCII: // possibly a valid non-ascii 'Letter' (BaseChar | Ideographic)
        case CHARTYPE_LETTER:
        case CHARTYPE_UNDERSCORE:
            //
            // 3.7 Lexical Structure
            //
            //  If there is a preceding token and the preceding token is not one of @, ::, (, [, , or
            //  an Operator, then an NCName must be recognized as an OperatorName.
            //
            //  If the character following an NCName (possibly after intervening ExprWhitespace) is (,
            //  then the token must be recognized as a NodeType or a FunctionName.
            //
            //  If the two characters following an NCName (possibly after intervening ExprWhitespace)
            //  are ::, then the token must be recognized as an AxisName.
            //
            //  Otherwise, the token must not be recognized as an OperatorName, a NodeType, a
            //  FunctionName, or an AxisName.
            //
            // [33] OperatorName ::= 'and' | 'or' | 'mod' | 'div'
            // [38] NodeType ::= 'comment' | 'text' | 'processing-instruction' | 'node'
            // [35] FunctionName ::= QName - NodeType
            // [6] AxisName ::= (see above)
            //
            // [37] NameTest ::= '*' | NCName ':' '*' | QName
            // [5] NCName ::= (Letter | '_') (NCNameChar)*
            // [?] NCNameChar ::= Letter | Digit | '.' | '-' | '_'  (ascii subset of 'NCNameChar')
            // [?] QName ::= (NCName ':')? NCName
            // [?] Letter ::= [A-Za-z]                              (ascii subset of 'Letter')
            // [?] Digit ::= [0-9]                                  (ascii subset of 'Digit')
            //
            nameOffset = currentOffset;
            currentOffset = scanNCName(data, endOffset, currentOffset);
            if (currentOffset == nameOffset) {
                return false; // REVISIT
			}

            if (currentOffset < endOffset) {
                ch = data[currentOffset];
            }
            else {
                ch = 0;
            }

            dataBuffer.set(data + nameOffset, currentOffset - nameOffset);
            nameHandle = fStringPool->addOrFind(dataBuffer.getRawBuffer());

            bool isNameTestNCName = false;
            bool isAxisName = false;
            prefixHandle = -1;

            if (ch == chColon) {

                if (++currentOffset == endOffset) {
                    return false; // REVISIT
                }

                ch = data[currentOffset];

                if (ch == chAsterisk) {
                    if (++currentOffset < endOffset) {
                        ch = data[currentOffset];
                    }

                    isNameTestNCName = true;
                } else if (ch == chColon) {
                    if (++currentOffset < endOffset) {
                        ch = data[currentOffset];
                    }

                    isAxisName = true;
                } else {
                    prefixHandle = nameHandle;
                    nameOffset = currentOffset;
                    currentOffset = scanNCName(data, endOffset, currentOffset);
                    if (currentOffset == nameOffset) {
                        return false; // REVISIT
                    }
                    if (currentOffset < endOffset) {
                        ch = data[currentOffset];
                    }
                    else {
                        ch = 0;
                    }

                    dataBuffer.set(data + nameOffset, currentOffset - nameOffset);
                    nameHandle = fStringPool->addOrFind(dataBuffer.getRawBuffer());
                }
            }
            //
            // [39] ExprWhitespace ::= S
            //
            while (XMLChar1_0::isWhitespace(ch)) {
                if (++currentOffset == endOffset) {
                    break;
                }
                ch = data[currentOffset];
            }

            //
            //  If there is a preceding token and the preceding token is not one of @, ::, (, [, , or
            //  an Operator, then an NCName must be recognized as an OperatorName.
            //
            if (starIsMultiplyOperator) {
                if (nameHandle == fAndSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_AND);
                    starIsMultiplyOperator = false;
                } else if (nameHandle == fOrSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_OR);
                    starIsMultiplyOperator = false;
                } else if (nameHandle == fModSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_MOD);
                    starIsMultiplyOperator = false;
                } else if (nameHandle == fDivSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_OPERATOR_DIV);
                    starIsMultiplyOperator = false;
                } else {
                    return false; // REVISIT
                }

                if (isNameTestNCName) {
                    return false; // REVISIT - NCName:* where an OperatorName is required
                } else if (isAxisName) {
                    return false; // REVISIT - AxisName:: where an OperatorName is required
                }
                break;
            }
            //
            //  If the character following an NCName (possibly after intervening ExprWhitespace) is (,
            //  then the token must be recognized as a NodeType or a FunctionName.
            //
            if (ch == chOpenParen && !isNameTestNCName && !isAxisName) {
                if (nameHandle == fCommentSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_NODETYPE_COMMENT);
                } else if (nameHandle == fTextSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_NODETYPE_TEXT);
                } else if (nameHandle == fPISymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_NODETYPE_PI);
                } else if (nameHandle == fNodeSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_NODETYPE_NODE);
                } else {
                    addToken(tokens, XercesXPath::EXPRTOKEN_FUNCTION_NAME);
                    tokens->addElement(prefixHandle);
                    tokens->addElement(nameHandle);
                }
                addToken(tokens, XercesXPath::EXPRTOKEN_OPEN_PAREN);
                starIsMultiplyOperator = false;
                ++currentOffset;
                break;
            }

            //
            //  If the two characters following an NCName (possibly after intervening ExprWhitespace)
            //  are ::, then the token must be recognized as an AxisName.
            //
            if (isAxisName ||
                (ch == chColon && currentOffset + 1 < endOffset &&
                 data[currentOffset + 1] == chColon)) {

                if (nameHandle == fAncestorSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_ANCESTOR);
                } else if (nameHandle == fAncestorOrSelfSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_ANCESTOR_OR_SELF);
                } else if (nameHandle == fAttributeSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_ATTRIBUTE);
                } else if (nameHandle == fChildSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_CHILD);
                } else if (nameHandle == fDescendantSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_DESCENDANT);
                } else if (nameHandle == fDescendantOrSelfSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_DESCENDANT_OR_SELF);
                } else if (nameHandle == fFollowingSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_FOLLOWING);
                } else if (nameHandle == fFollowingSiblingSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_FOLLOWING_SIBLING);
                } else if (nameHandle == fNamespaceSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_NAMESPACE);
                } else if (nameHandle == fParentSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_PARENT);
                } else if (nameHandle == fPrecedingSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_PRECEDING);
                } else if (nameHandle == fPrecedingSiblingSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_PRECEDING_SIBLING);
                } else if (nameHandle == fSelfSymbol) {
                    addToken(tokens, XercesXPath::EXPRTOKEN_AXISNAME_SELF);
                } else {
                    return false; // REVISIT
                }

                if (isNameTestNCName) {
                    return false; // REVISIT - "NCName:* ::" where "AxisName ::" is required
                }

                addToken(tokens, XercesXPath::EXPRTOKEN_DOUBLE_COLON);
                starIsMultiplyOperator = false;
                if (!isAxisName) {
                    currentOffset += 2;
                }
                break;
            }
            //
            //  Otherwise, the token must not be recognized as an OperatorName, a NodeType, a
            //  FunctionName, or an AxisName.
            //
            if (isNameTestNCName) {
                addToken(tokens, XercesXPath::EXPRTOKEN_NAMETEST_NAMESPACE);
                tokens->addElement(nameHandle);
            } else {
                addToken(tokens, XercesXPath::EXPRTOKEN_NAMETEST_QNAME);
                tokens->addElement(prefixHandle);
                tokens->addElement(nameHandle);
            }

            starIsMultiplyOperator = true;
            break;
        }
    }

    return true;
}
示例#20
0
autoEEG EEG_readFromBdfFile (MelderFile file) {
	try {
		autofile f = Melder_fopen (file, "rb");
		char buffer [81];
		fread (buffer, 1, 8, f); buffer [8] = '\0';
		bool is24bit = buffer [0] == (char) 255;
		fread (buffer, 1, 80, f); buffer [80] = '\0';
		trace (U"Local subject identification: \"", Melder_peek8to32 (buffer), U"\"");
		fread (buffer, 1, 80, f); buffer [80] = '\0';
		trace (U"Local recording identification: \"", Melder_peek8to32 (buffer), U"\"");
		fread (buffer, 1, 8, f); buffer [8] = '\0';
		trace (U"Start date of recording: \"", Melder_peek8to32 (buffer), U"\"");
		fread (buffer, 1, 8, f); buffer [8] = '\0';
		trace (U"Start time of recording: \"", Melder_peek8to32 (buffer), U"\"");
		fread (buffer, 1, 8, f); buffer [8] = '\0';
		long numberOfBytesInHeaderRecord = atol (buffer);
		trace (U"Number of bytes in header record: ", numberOfBytesInHeaderRecord);
		fread (buffer, 1, 44, f); buffer [44] = '\0';
		trace (U"Version of data format: \"", Melder_peek8to32 (buffer), U"\"");
		fread (buffer, 1, 8, f); buffer [8] = '\0';
		long numberOfDataRecords = strtol (buffer, nullptr, 10);
		trace (U"Number of data records: ", numberOfDataRecords);
		fread (buffer, 1, 8, f); buffer [8] = '\0';
		double durationOfDataRecord = atof (buffer);
		trace (U"Duration of a data record: ", durationOfDataRecord);
		fread (buffer, 1, 4, f); buffer [4] = '\0';
		long numberOfChannels = atol (buffer);
		trace (U"Number of channels in data record: ", numberOfChannels);
		if (numberOfBytesInHeaderRecord != (numberOfChannels + 1) * 256)
			Melder_throw (U"Number of bytes in header record (", numberOfBytesInHeaderRecord,
				U") doesn't match number of channels (", numberOfChannels, U").");
		autostring32vector channelNames (1, numberOfChannels);
		for (long ichannel = 1; ichannel <= numberOfChannels; ichannel ++) {
			fread (buffer, 1, 16, f); buffer [16] = '\0';   // labels of the channels
			/*
			 * Strip all final spaces.
			 */
			for (int i = 15; i >= 0; i --) {
				if (buffer [i] == ' ') {
					buffer [i] = '\0';
				} else {
					break;
				}
			}
			channelNames [ichannel] = Melder_8to32 (buffer);
			trace (U"Channel <<", channelNames [ichannel], U">>");
		}
		bool hasLetters = str32equ (channelNames [numberOfChannels], U"EDF Annotations");
		double samplingFrequency = NUMundefined;
		for (long channel = 1; channel <= numberOfChannels; channel ++) {
			fread (buffer, 1, 80, f); buffer [80] = '\0';   // transducer type
		}
		for (long channel = 1; channel <= numberOfChannels; channel ++) {
			fread (buffer, 1, 8, f); buffer [8] = '\0';   // physical dimension of channels
		}
		autoNUMvector <double> physicalMinimum (1, numberOfChannels);
		for (long ichannel = 1; ichannel <= numberOfChannels; ichannel ++) {
			fread (buffer, 1, 8, f); buffer [8] = '\0';
			physicalMinimum [ichannel] = atof (buffer);
		}
		autoNUMvector <double> physicalMaximum (1, numberOfChannels);
		for (long ichannel = 1; ichannel <= numberOfChannels; ichannel ++) {
			fread (buffer, 1, 8, f); buffer [8] = '\0';
			physicalMaximum [ichannel] = atof (buffer);
		}
		autoNUMvector <double> digitalMinimum (1, numberOfChannels);
		for (long ichannel = 1; ichannel <= numberOfChannels; ichannel ++) {
			fread (buffer, 1, 8, f); buffer [8] = '\0';
			digitalMinimum [ichannel] = atof (buffer);
		}
		autoNUMvector <double> digitalMaximum (1, numberOfChannels);
		for (long ichannel = 1; ichannel <= numberOfChannels; ichannel ++) {
			fread (buffer, 1, 8, f); buffer [8] = '\0';
			digitalMaximum [ichannel] = atof (buffer);
		}
		for (long channel = 1; channel <= numberOfChannels; channel ++) {
			fread (buffer, 1, 80, f); buffer [80] = '\0';   // prefiltering
		}
		long numberOfSamplesPerDataRecord = 0;
		for (long channel = 1; channel <= numberOfChannels; channel ++) {
			fread (buffer, 1, 8, f); buffer [8] = '\0';   // number of samples in each data record
			long numberOfSamplesInThisDataRecord = atol (buffer);
			if (samplingFrequency == NUMundefined) {
				numberOfSamplesPerDataRecord = numberOfSamplesInThisDataRecord;
				samplingFrequency = numberOfSamplesInThisDataRecord / durationOfDataRecord;
			}
			if (numberOfSamplesInThisDataRecord / durationOfDataRecord != samplingFrequency)
				Melder_throw (U"Number of samples per data record in channel ", channel,
					U" (", numberOfSamplesInThisDataRecord,
					U") doesn't match sampling frequency of channel 1 (", samplingFrequency, U").");
		}
		for (long channel = 1; channel <= numberOfChannels; channel ++) {
			fread (buffer, 1, 32, f); buffer [32] = '\0';   // reserved
		}
		double duration = numberOfDataRecords * durationOfDataRecord;
		autoEEG him = EEG_create (0, duration);
		his numberOfChannels = numberOfChannels;
		autoSound me = Sound_createSimple (numberOfChannels, duration, samplingFrequency);
		Melder_assert (my nx == numberOfSamplesPerDataRecord * numberOfDataRecords);
		autoNUMvector <unsigned char> dataBuffer (0L, 3 * numberOfSamplesPerDataRecord - 1);
		for (long record = 1; record <= numberOfDataRecords; record ++) {
			for (long channel = 1; channel <= numberOfChannels; channel ++) {
				double factor = channel == numberOfChannels ? 1.0 : physicalMinimum [channel] / digitalMinimum [channel];
				if (channel < numberOfChannels - EEG_getNumberOfExtraSensors (him.peek())) factor /= 1000000.0;
				if (is24bit) {
					fread (& dataBuffer [0], 3, numberOfSamplesPerDataRecord, f);
					unsigned char *p = & dataBuffer [0];
					for (long i = 1; i <= numberOfSamplesPerDataRecord; i ++) {
						long sample = i + (record - 1) * numberOfSamplesPerDataRecord;
						Melder_assert (sample <= my nx);
						uint8_t lowByte = *p ++, midByte = *p ++, highByte = *p ++;
						uint32_t externalValue = ((uint32_t) highByte << 16) | ((uint32_t) midByte << 8) | (uint32_t) lowByte;
						if ((highByte & 128) != 0)   // is the 24-bit sign bit on?
							externalValue |= 0xFF000000;   // extend negative sign to 32 bits
						my z [channel] [sample] = (int32_t) externalValue * factor;
					}
				} else {
					fread (& dataBuffer [0], 2, numberOfSamplesPerDataRecord, f);
					unsigned char *p = & dataBuffer [0];
					for (long i = 1; i <= numberOfSamplesPerDataRecord; i ++) {
						long sample = i + (record - 1) * numberOfSamplesPerDataRecord;
						Melder_assert (sample <= my nx);
						uint8 lowByte = *p ++, highByte = *p ++;
						uint16 externalValue = (uint16) ((uint16) highByte << 8) | (uint16) lowByte;
						my z [channel] [sample] = (int16) externalValue * factor;
					}
				}
			}
		}
		int numberOfStatusBits = 8;
		for (long i = 1; i <= my nx; i ++) {
			unsigned long value = (long) my z [numberOfChannels] [i];
			if (value & 0x0000FF00) {
				numberOfStatusBits = 16;
			}
		}
		autoTextGrid thee;
		if (hasLetters) {
			thee = TextGrid_create (0, duration, U"Mark Trigger", U"Mark Trigger");
			autoMelderString letters;
			double time = NUMundefined;
			for (long i = 1; i <= my nx; i ++) {
				unsigned long value = (long) my z [numberOfChannels] [i];
				for (int byte = 1; byte <= numberOfStatusBits / 8; byte ++) {
					unsigned long mask = byte == 1 ? 0x000000ff : 0x0000ff00;
					char32 kar = byte == 1 ? (value & mask) : (value & mask) >> 8;
					if (kar != U'\0' && kar != 20) {
						MelderString_appendCharacter (& letters, kar);
					} else if (letters. string [0] != U'\0') {
						if (letters. string [0] == U'+') {
							if (NUMdefined (time)) {
								try {
									TextGrid_insertPoint (thee.peek(), 1, time, U"");
								} catch (MelderError) {
									Melder_throw (U"Did not insert empty mark (", letters. string, U") on Mark tier.");
								}
								time = NUMundefined;   // defensive
							}
							time = Melder_atof (& letters. string [1]);
							MelderString_empty (& letters);
						} else {
							if (! NUMdefined (time)) {
								Melder_throw (U"Undefined time for label at sample ", i, U".");
							}
							try {
								if (Melder_nequ (letters. string, U"Trigger-", 8)) {
									try {
										TextGrid_insertPoint (thee.peek(), 2, time, & letters. string [8]);
									} catch (MelderError) {
										Melder_clearError ();
										trace (U"Duplicate trigger at ", time, U" seconds: ", & letters. string [8]);
									}
								} else {
									TextGrid_insertPoint (thee.peek(), 1, time, & letters. string [0]);
								}
							} catch (MelderError) {
								Melder_throw (U"Did not insert mark (", letters. string, U") on Trigger tier.");
							}
							time = NUMundefined;   // crucial
							MelderString_empty (& letters);
						}
					}
				}
			}
			if (NUMdefined (time)) {
				TextGrid_insertPoint (thee.peek(), 1, time, U"");
				time = NUMundefined;   // defensive
			}
		} else {
			thee = TextGrid_create (0, duration,
				numberOfStatusBits == 8 ? U"S1 S2 S3 S4 S5 S6 S7 S8" : U"S1 S2 S3 S4 S5 S6 S7 S8 S9 S10 S11 S12 S13 S14 S15 S16", U"");
			for (int bit = 1; bit <= numberOfStatusBits; bit ++) {
				unsigned long bitValue = 1 << (bit - 1);
				IntervalTier tier = (IntervalTier) thy tiers -> item [bit];
				for (long i = 1; i <= my nx; i ++) {
					unsigned long previousValue = i == 1 ? 0 : (long) my z [numberOfChannels] [i - 1];
					unsigned long thisValue = (long) my z [numberOfChannels] [i];
					if ((thisValue & bitValue) != (previousValue & bitValue)) {
						double time = i == 1 ? 0.0 : my x1 + (i - 1.5) * my dx;
						if (time != 0.0)
							TextGrid_insertBoundary (thee.peek(), bit, time);
						if ((thisValue & bitValue) != 0)
							TextGrid_setIntervalText (thee.peek(), bit, tier -> intervals -> size, U"1");
					}
				}
			}
		}
		f.close (file);
		his channelNames = channelNames.transfer();
		his sound = me.move();
		his textgrid = thee.move();
		if (EEG_getNumberOfCapElectrodes (him.peek()) == 32) {
			EEG_setChannelName (him.peek(), 1, U"Fp1");
			EEG_setChannelName (him.peek(), 2, U"AF3");
			EEG_setChannelName (him.peek(), 3, U"F7");
			EEG_setChannelName (him.peek(), 4, U"F3");
			EEG_setChannelName (him.peek(), 5, U"FC1");
			EEG_setChannelName (him.peek(), 6, U"FC5");
			EEG_setChannelName (him.peek(), 7, U"T7");
			EEG_setChannelName (him.peek(), 8, U"C3");
			EEG_setChannelName (him.peek(), 9, U"CP1");
			EEG_setChannelName (him.peek(), 10, U"CP5");
			EEG_setChannelName (him.peek(), 11, U"P7");
			EEG_setChannelName (him.peek(), 12, U"P3");
			EEG_setChannelName (him.peek(), 13, U"Pz");
			EEG_setChannelName (him.peek(), 14, U"PO3");
			EEG_setChannelName (him.peek(), 15, U"O1");
			EEG_setChannelName (him.peek(), 16, U"Oz");
			EEG_setChannelName (him.peek(), 17, U"O2");
			EEG_setChannelName (him.peek(), 18, U"PO4");
			EEG_setChannelName (him.peek(), 19, U"P4");
			EEG_setChannelName (him.peek(), 20, U"P8");
			EEG_setChannelName (him.peek(), 21, U"CP6");
			EEG_setChannelName (him.peek(), 22, U"CP2");
			EEG_setChannelName (him.peek(), 23, U"C4");
			EEG_setChannelName (him.peek(), 24, U"T8");
			EEG_setChannelName (him.peek(), 25, U"FC6");
			EEG_setChannelName (him.peek(), 26, U"FC2");
			EEG_setChannelName (him.peek(), 27, U"F4");
			EEG_setChannelName (him.peek(), 28, U"F8");
			EEG_setChannelName (him.peek(), 29, U"AF4");
			EEG_setChannelName (him.peek(), 30, U"Fp2");
			EEG_setChannelName (him.peek(), 31, U"Fz");
			EEG_setChannelName (him.peek(), 32, U"Cz");
		} else if (EEG_getNumberOfCapElectrodes (him.peek()) == 64) {
			EEG_setChannelName (him.peek(), 1, U"Fp1");
			EEG_setChannelName (him.peek(), 2, U"AF7");
			EEG_setChannelName (him.peek(), 3, U"AF3");
			EEG_setChannelName (him.peek(), 4, U"F1");
			EEG_setChannelName (him.peek(), 5, U"F3");
			EEG_setChannelName (him.peek(), 6, U"F5");
			EEG_setChannelName (him.peek(), 7, U"F7");
			EEG_setChannelName (him.peek(), 8, U"FT7");
			EEG_setChannelName (him.peek(), 9, U"FC5");
			EEG_setChannelName (him.peek(), 10, U"FC3");
			EEG_setChannelName (him.peek(), 11, U"FC1");
			EEG_setChannelName (him.peek(), 12, U"C1");
			EEG_setChannelName (him.peek(), 13, U"C3");
			EEG_setChannelName (him.peek(), 14, U"C5");
			EEG_setChannelName (him.peek(), 15, U"T7");
			EEG_setChannelName (him.peek(), 16, U"TP7");
			EEG_setChannelName (him.peek(), 17, U"CP5");
			EEG_setChannelName (him.peek(), 18, U"CP3");
			EEG_setChannelName (him.peek(), 19, U"CP1");
			EEG_setChannelName (him.peek(), 20, U"P1");
			EEG_setChannelName (him.peek(), 21, U"P3");
			EEG_setChannelName (him.peek(), 22, U"P5");
			EEG_setChannelName (him.peek(), 23, U"P7");
			EEG_setChannelName (him.peek(), 24, U"P9");
			EEG_setChannelName (him.peek(), 25, U"PO7");
			EEG_setChannelName (him.peek(), 26, U"PO3");
			EEG_setChannelName (him.peek(), 27, U"O1");
			EEG_setChannelName (him.peek(), 28, U"Iz");
			EEG_setChannelName (him.peek(), 29, U"Oz");
			EEG_setChannelName (him.peek(), 30, U"POz");
			EEG_setChannelName (him.peek(), 31, U"Pz");
			EEG_setChannelName (him.peek(), 32, U"CPz");
			EEG_setChannelName (him.peek(), 33, U"Fpz");
			EEG_setChannelName (him.peek(), 34, U"Fp2");
			EEG_setChannelName (him.peek(), 35, U"AF8");
			EEG_setChannelName (him.peek(), 36, U"AF4");
			EEG_setChannelName (him.peek(), 37, U"AFz");
			EEG_setChannelName (him.peek(), 38, U"Fz");
			EEG_setChannelName (him.peek(), 39, U"F2");
			EEG_setChannelName (him.peek(), 40, U"F4");
			EEG_setChannelName (him.peek(), 41, U"F6");
			EEG_setChannelName (him.peek(), 42, U"F8");
			EEG_setChannelName (him.peek(), 43, U"FT8");
			EEG_setChannelName (him.peek(), 44, U"FC6");
			EEG_setChannelName (him.peek(), 45, U"FC4");
			EEG_setChannelName (him.peek(), 46, U"FC2");
			EEG_setChannelName (him.peek(), 47, U"FCz");
			EEG_setChannelName (him.peek(), 48, U"Cz");
			EEG_setChannelName (him.peek(), 49, U"C2");
			EEG_setChannelName (him.peek(), 50, U"C4");
			EEG_setChannelName (him.peek(), 51, U"C6");
			EEG_setChannelName (him.peek(), 52, U"T8");
			EEG_setChannelName (him.peek(), 53, U"TP8");
			EEG_setChannelName (him.peek(), 54, U"CP6");
			EEG_setChannelName (him.peek(), 55, U"CP4");
			EEG_setChannelName (him.peek(), 56, U"CP2");
			EEG_setChannelName (him.peek(), 57, U"P2");
			EEG_setChannelName (him.peek(), 58, U"P4");
			EEG_setChannelName (him.peek(), 59, U"P6");
			EEG_setChannelName (him.peek(), 60, U"P8");
			EEG_setChannelName (him.peek(), 61, U"P10");
			EEG_setChannelName (him.peek(), 62, U"PO8");
			EEG_setChannelName (him.peek(), 63, U"PO4");
			EEG_setChannelName (him.peek(), 64, U"O2");
		}
		return him;
	} catch (MelderError) {