Esempio n. 1
0
/*
 * Read the next TIFF directory from a file
 * and convert it to the internal format.
 * We read directories sequentially.
 */
static uint64
ReadDirectory(int fd, unsigned int ix, uint64 off)
{
	uint16 dircount;
	uint32 direntrysize;
	void* dirmem = NULL;
	uint64 nextdiroff = 0;
	uint32 n;
	uint8* dp;

	if (off == 0)			/* no more directories */
		goto done;
#if defined(__WIN32__) && defined(_MSC_VER)
	if (_lseeki64(fd, (__int64)off, SEEK_SET) != (__int64)off) {
#else
	if (lseek(fd, (off_t)off, SEEK_SET) != (off_t)off) {
#endif
		Fatal("Seek error accessing TIFF directory");
		goto done;
	}
	if (!bigtiff) {
		if (read(fd, (char*) &dircount, sizeof (uint16)) != sizeof (uint16)) {
			ReadError("directory count");
			goto done;
		}
		if (swabflag)
			TIFFSwabShort(&dircount);
		direntrysize = 12;
	} else {
		uint64 dircount64 = 0;
		if (read(fd, (char*) &dircount64, sizeof (uint64)) != sizeof (uint64)) {
			ReadError("directory count");
			goto done;
		}
		if (swabflag)
			TIFFSwabLong8(&dircount64);
		if (dircount64>0xFFFF) {
			Error("Sanity check on directory count failed");
			goto done;
		}
		dircount = (uint16)dircount64;
		direntrysize = 20;
	}
	dirmem = _TIFFmalloc(dircount * direntrysize);
	if (dirmem == NULL) {
		Fatal("No space for TIFF directory");
		goto done;
	}
	n = read(fd, (char*) dirmem, dircount*direntrysize);
	if (n != dircount*direntrysize) {
		n /= direntrysize;
		Error(
#if defined(__WIN32__) && defined(_MSC_VER)
	    "Could only read %lu of %u entries in directory at offset %#I64x",
		      (unsigned long)n, dircount, (unsigned __int64) off);
#else
	    "Could only read %lu of %u entries in directory at offset %#llx",
		      (unsigned long)n, dircount, (unsigned long long) off);
#endif
		dircount = n;
		nextdiroff = 0;
	} else {
		if (!bigtiff) {
	void CPlinkAlternatePhenotypeFile::Read()
	{
		Verbose("    Processing Alternate Phenotypes: [%s]", filename.c_str());
		CPlinkLexer lex(filename);
		CToken tok;
		AlternatePhenotypeRecord apr;

		cPhenotypes = 0;
		cIndividuals = 0;

		lex.NextToken(tok);
		while (tok.type != tokEOF)
		{
			if (tok.type == tokEOL)
			{
				lex.NextToken(tok);
				continue;
			}

			lex.ExpectId(tok, apr.idFamily, "FamilyID");
			lex.ExpectId(tok, apr.idIndividual, "IndividualID");

			if ((records.size() == 0) && (apr.idFamily == "FID") && (apr.idIndividual == "IID"))
			{
				// Get the header row
				size_t iPhenotype = 0;
				std::string phenotypeName;

				while (tok.type != tokEOF)
				{
					if (tok.type == tokEOL)
					{
						lex.NextToken(tok);
						break;
					}
					lex.ExpectId(tok, phenotypeName, "Phenotype Name");
					if (phenotypeLabelIndex.count(phenotypeName))
					{
						// alternate phenotype columns are 1 based for the user so add 1 on output.
						Fatal("Duplicate phenotype name [%s] in column %d and %d", phenotypeName.c_str(), iPhenotype + 1, phenotypeLabelIndex[phenotypeName] + 1);
					}
					phenotypeLabelIndex[phenotypeName] = iPhenotype++;
					phenotypeNames.push_back(phenotypeName);
				}

				cPhenotypes = iPhenotype;
			}
			else
			{
				// now get the alternative phenotype array and add it to records
				apr.phenotypes.clear();
				while (tok.type != tokEOF)
				{
					if (tok.type == tokEOL)
					{
						break;
					}
					limix::mfloat_t d;
					int bitBucket;
					lex.ExpectPhenotype(tok, d, bitBucket);
					apr.phenotypes.push_back(d);
				}

				// Validate we have the right number of alternative phenotypes.
				if (apr.phenotypes.size() != cPhenotypes)
				{
					if (cPhenotypes != 0)
					{
						Fatal("Alternate Phenotype file formating error in line [%d]."
							"\n                 Expected %d phenotype entries, found %d.",
							tok.line, cPhenotypes, apr.phenotypes.size());
					}

					// we didn't know how many phenotypes to expect because we
					//   didn't have labels. Create the dumy labels now that we 
					//   have read in the first line
					cPhenotypes = apr.phenotypes.size();

					char phenotypeLabel[64];
					for (size_t iPhenotypeName = 0; iPhenotypeName < cPhenotypes; ++iPhenotypeName)
					{
						sprintf(phenotypeLabel, "Phenotype_%03d", (int)(phenotypeNames.size() + 1));
						//DEBUG: - old version used "NoName" for any unnamed phenotype
						//         enable functionality until tests 'oracle' files are updated.
						char *fastLmmTesting = getenv("FastLmmTesting");
						if (fastLmmTesting != nullptr)
						{
							strcpy(phenotypeLabel, "NoName");
						}
						phenotypeLabelIndex[phenotypeLabel] = phenotypeNames.size();
						phenotypeNames.push_back(phenotypeLabel);
					}
				}

				// Validate we have a unique family:individual name and add it to the index.
				std::string key = KeyFromIdFamilyAndIdIndividual(apr.idFamily, apr.idIndividual);
				if (phenotypeIndividualIdIndex.count(key))
				{
					Fatal("Duplicate Family:Individual id [%s] found in lines %d and %d", key.c_str(), phenotypeIndividualIdIndex[key] + 1, tok.line);
				}

				phenotypeIndividualIdIndex[key] = records.size();
				records.push_back(apr);
				++cIndividuals;
				lex.NextToken(tok);      // advance to next token
			}
		}

		Verbose("              Individuals Processed: %7d", cIndividuals);
		Verbose("          Phenotypes per Individual: %7d", cPhenotypes);
	}
Esempio n. 3
0
static void
dump(int fd, uint64 diroff)
{
	unsigned i;

	lseek(fd, (off_t) 0, 0);
	if (read(fd, (char*) &hdr, sizeof (TIFFHeaderCommon)) != sizeof (TIFFHeaderCommon))
		ReadError("TIFF header");
	if (hdr.common.tiff_magic != TIFF_BIGENDIAN
	    && hdr.common.tiff_magic != TIFF_LITTLEENDIAN &&
#if HOST_BIGENDIAN
	    /* MDI is sensitive to the host byte order, unlike TIFF */
	    MDI_BIGENDIAN != hdr.common.tiff_magic
#else
	    MDI_LITTLEENDIAN != hdr.common.tiff_magic
#endif
	   ) {
		Fatal("Not a TIFF or MDI file, bad magic number %u (%#x)",
		    hdr.common.tiff_magic, hdr.common.tiff_magic);
	}
	if (hdr.common.tiff_magic == TIFF_BIGENDIAN
	    || hdr.common.tiff_magic == MDI_BIGENDIAN)
		swabflag = !bigendian;
	else
		swabflag = bigendian;
	if (swabflag)
		TIFFSwabShort(&hdr.common.tiff_version);
	if (hdr.common.tiff_version==42)
	{
		if (read(fd, (char*) &hdr.classic.tiff_diroff, 4) != 4)
			ReadError("TIFF header");
		if (swabflag)
			TIFFSwabLong(&hdr.classic.tiff_diroff);
		printf("Magic: %#x <%s-endian> Version: %#x <%s>\n",
		    hdr.classic.tiff_magic,
		    hdr.classic.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
		    42,"ClassicTIFF");
		if (diroff == 0)
			diroff = hdr.classic.tiff_diroff;
	}
	else if (hdr.common.tiff_version==43)
	{
		if (read(fd, (char*) &hdr.big.tiff_offsetsize, 12) != 12)
			ReadError("TIFF header");
		if (swabflag)
		{
			TIFFSwabShort(&hdr.big.tiff_offsetsize);
			TIFFSwabShort(&hdr.big.tiff_unused);
			TIFFSwabLong8(&hdr.big.tiff_diroff);
		}
		printf("Magic: %#x <%s-endian> Version: %#x <%s>\n",
		    hdr.big.tiff_magic,
		    hdr.big.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
		    43,"BigTIFF");
		printf("OffsetSize: %#x Unused: %#x\n",
		    hdr.big.tiff_offsetsize,hdr.big.tiff_unused);
		if (diroff == 0)
			diroff = hdr.big.tiff_diroff;
		bigtiff = 1;
	}
	else
		Fatal("Not a TIFF file, bad version number %u (%#x)",
		    hdr.common.tiff_version, hdr.common.tiff_version);
	for (i = 0; diroff != 0; i++) {
		if (i > 0)
			putchar('\n');
		diroff = ReadDirectory(fd, i, diroff);
	}
}
int RemoteCameraRtsp::Capture( Image &image )
{
	AVPacket packet;
	uint8_t* directbuffer;
	int frameComplete = false;
	
	/* Request a writeable buffer of the target image */
	directbuffer = image.WriteBuffer(width, height, colours, subpixelorder);
	if(directbuffer == NULL) {
		Error("Failed requesting writeable buffer for the captured image.");
		return (-1);
	}
	
    while ( true )
    {
        buffer.clear();
        if ( !rtspThread->isRunning() )
            return (-1);

        if ( rtspThread->getFrame( buffer ) )
        {
            Debug( 3, "Read frame %d bytes", buffer.size() );
            Debug( 4, "Address %p", buffer.head() );
            Hexdump( 4, buffer.head(), 16 );

            if ( !buffer.size() )
                return( -1 );

            if(mCodecContext->codec_id == AV_CODEC_ID_H264)
            {
                // SPS and PPS frames should be saved and appended to IDR frames
                int nalType = (buffer.head()[3] & 0x1f);
                
                // SPS
                if(nalType == 7)
                {
                    lastSps = buffer;
                    continue;
                }
                // PPS
                else if(nalType == 8)
                {
                    lastPps = buffer;
                    continue;
                }
                // IDR
                else if(nalType == 5)
                {
                    buffer += lastSps;
                    buffer += lastPps;
                }
            }

            av_init_packet( &packet );
            
	    while ( !frameComplete && buffer.size() > 0 )
	    {
		packet.data = buffer.head();
		packet.size = buffer.size();
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 25, 0)
		int len = avcodec_decode_video2( mCodecContext, mRawFrame, &frameComplete, &packet );
#else
		int len = avcodec_decode_video( mCodecContext, mRawFrame, &frameComplete, packet.data, packet.size );
#endif
		if ( len < 0 )
		{
			Error( "Error while decoding frame %d", frameCount );
			Hexdump( Logger::ERROR, buffer.head(), buffer.size()>256?256:buffer.size() );
			buffer.clear();
			continue;
		}
		Debug( 2, "Frame: %d - %d/%d", frameCount, len, buffer.size() );
		//if ( buffer.size() < 400 )
		   //Hexdump( 0, buffer.head(), buffer.size() );
		   
		buffer -= len;

	    }
            if ( frameComplete ) {
	       
		Debug( 3, "Got frame %d", frameCount );
			    
		avpicture_fill( (AVPicture *)mFrame, directbuffer, imagePixFormat, width, height);
			
#if HAVE_LIBSWSCALE
		if(mConvertContext == NULL) {
			if(config.cpu_extensions && sseversion >= 20) {
				mConvertContext = sws_getContext( mCodecContext->width, mCodecContext->height, mCodecContext->pix_fmt, width, height, imagePixFormat, SWS_BICUBIC | SWS_CPU_CAPS_SSE2, NULL, NULL, NULL );
			} else {
				mConvertContext = sws_getContext( mCodecContext->width, mCodecContext->height, mCodecContext->pix_fmt, width, height, imagePixFormat, SWS_BICUBIC, NULL, NULL, NULL );
			}
			if(mConvertContext == NULL)
				Fatal( "Unable to create conversion context");
		}
	
		if ( sws_scale( mConvertContext, mRawFrame->data, mRawFrame->linesize, 0, mCodecContext->height, mFrame->data, mFrame->linesize ) < 0 )
			Fatal( "Unable to convert raw format %u to target format %u at frame %d", mCodecContext->pix_fmt, imagePixFormat, frameCount );
#else // HAVE_LIBSWSCALE
		Fatal( "You must compile ffmpeg with the --enable-swscale option to use RTSP cameras" );
#endif // HAVE_LIBSWSCALE
	
		frameCount++;

	     } /* frame complete */
	     
	     av_free_packet( &packet );
	} /* getFrame() */
 
	if(frameComplete)
		return (0);
	
    }
    return (0) ;
}
Esempio n. 5
0
// Function to validate an authentication string
User *zmLoadAuthUser( const char *auth, bool use_remote_addr )
{
#if HAVE_DECL_MD5 || HAVE_DECL_GNUTLS_FINGERPRINT
#ifdef HAVE_GCRYPT_H
    // Special initialisation for libgcrypt
    if ( !gcry_check_version( GCRYPT_VERSION ) )
    {
        Fatal( "Unable to initialise libgcrypt" );
    }
    gcry_control( GCRYCTL_DISABLE_SECMEM, 0 );
    gcry_control( GCRYCTL_INITIALIZATION_FINISHED, 0 );
#endif // HAVE_GCRYPT_H

	const char *remote_addr = "";
	if ( use_remote_addr )
	{
		remote_addr = getenv( "REMOTE_ADDR" );
		if ( !remote_addr )
		{
			Warning( "Can't determine remote address, using null" );
			remote_addr = "";
		}
	}

	Debug( 1, "Attempting to authenticate user from auth string '%s'", auth );
    char sql[ZM_SQL_SML_BUFSIZ] = "";
	snprintf( sql, sizeof(sql), "select Username, Password, Enabled, Stream+0, Events+0, Control+0, Monitors+0, System+0, MonitorIds from Users where Enabled = 1" );

	if ( mysql_query( &dbconn, sql ) )
	{
		Error( "Can't run query: %s", mysql_error( &dbconn ) );
		exit( mysql_errno( &dbconn ) );
	}

	MYSQL_RES *result = mysql_store_result( &dbconn );
	if ( !result )
	{
		Error( "Can't use query result: %s", mysql_error( &dbconn ) );
		exit( mysql_errno( &dbconn ) );
	}
	int n_users = mysql_num_rows( result );

	if ( n_users < 1 )
	{
		Warning( "Unable to authenticate user" );
		return( 0 );
	}

	while( MYSQL_ROW dbrow = mysql_fetch_row( result ) )
	{
		const char *user = dbrow[0];
		const char *pass = dbrow[1];

		char auth_key[512] = "";
		char auth_md5[32+1] = "";
      size_t md5len = 32;
      unsigned char md5sum[md5len];

		time_t now = time( 0 );
		int max_tries = 2;

		for ( int i = 0; i < max_tries; i++, now -= (60*60) )
		{
			struct tm *now_tm = localtime( &now );

			snprintf( auth_key, sizeof(auth_key), "%s%s%s%s%d%d%d%d", 
				config.auth_hash_secret,
				user,
				pass,
				remote_addr,
				now_tm->tm_hour,
				now_tm->tm_mday,
				now_tm->tm_mon,
				now_tm->tm_year
			);

#if HAVE_DECL_MD
			MD5( (unsigned char *)auth_key, strlen(auth_key), md5sum );
#elif HAVE_DECL_GNUTLS_FINGERPRINT
            gnutls_datum_t md5data = { (unsigned char *)auth_key, strlen(auth_key) };
            gnutls_fingerprint( GNUTLS_DIG_MD5, &md5data, md5sum, &md5len );
#endif
			auth_md5[0] = '\0';
			for ( unsigned int j = 0; j < md5len; j++ )
			{
				sprintf( &auth_md5[2*j], "%02x", md5sum[j] );
			}
			Debug( 1, "Checking auth_key '%s' -> auth_md5 '%s'", auth_key, auth_md5 );

			if ( !strcmp( auth, auth_md5 ) )
			{
				// We have a match
				User *user = new User( dbrow );
				Info( "Authenticated user '%s'", user->getUsername() );
				return( user );
			}
		}
	}
#else // HAVE_DECL_MD5
	Error( "You need to build with gnutls or openssl installed to use hash based authentication" );
#endif // HAVE_DECL_MD5
	return( 0 );
}
Esempio n. 6
0
void create_sfi_geo(const char* geoTag)
{

  //fGlobalTrans->SetTranslation(0.0,0.0,0.0);

  // -------   Load media from media file   -----------------------------------
  FairGeoLoader*    geoLoad = new FairGeoLoader("TGeo","FairGeoLoader");
  FairGeoInterface* geoFace = geoLoad->getGeoInterface();
  TString geoPath = gSystem->Getenv("VMCWORKDIR");
  TString medFile = geoPath + "/geometry/media_r3b.geo";
  geoFace->setMediaFile(medFile);
  geoFace->readMedia();
  gGeoMan = gGeoManager;
  // --------------------------------------------------------------------------



  // -------   Geometry file name (output)   ----------------------------------
  TString geoFileName = geoPath + "/geometry/sfi_";
  geoFileName = geoFileName + geoTag + ".geo.root";
  // --------------------------------------------------------------------------



  // -----------------   Get and create the required media    -----------------
  FairGeoMedia*   geoMedia = geoFace->getMedia();
  FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder();

  FairGeoMedium* mAir      = geoMedia->getMedium("Air");
  if ( ! mAir ) Fatal("Main", "FairMedium Air not found");
  geoBuild->createMedium(mAir);
  TGeoMedium* pMed2 = gGeoMan->GetMedium("Air");
  if ( ! pMed2 ) Fatal("Main", "Medium Air not found");

  FairGeoMedium* mVac      = geoMedia->getMedium("vacuum");
  if ( ! mVac ) Fatal("Main", "FairMedium vacuum not found");
  geoBuild->createMedium(mVac);
  TGeoMedium* pMed1 = gGeoMan->GetMedium("vacuum");
  if ( ! pMed1 ) Fatal("Main", "Medium vacuum not found");
  
  FairGeoMedium* mGfi      = geoMedia->getMedium("plasticForGFI");
  if ( ! mGfi ) Fatal("Main", "FairMedium plasticForGFI not found");
  geoBuild->createMedium(mGfi);
  TGeoMedium* pMed35 = gGeoMan->GetMedium("plasticForGFI");
  if ( ! pMed35 ) Fatal("Main", "Medium plasticForGFI not found");

  FairGeoMedium* mAl      = geoMedia->getMedium("aluminium");
  if ( ! mAl ) Fatal("Main", "FairMedium aluminium not found");
  geoBuild->createMedium(mAl);
  TGeoMedium* pMed21 = gGeoMan->GetMedium("aluminium");
  if ( ! pMed21 ) Fatal("Main", "Medium aluminium not found");
  // --------------------------------------------------------------------------



  // --------------   Create geometry and top volume  -------------------------
  gGeoMan = (TGeoManager*)gROOT->FindObject("FAIRGeom");
  gGeoMan->SetName("GFIgeom");
  TGeoVolume* top = new TGeoVolumeAssembly("TOP");
  gGeoMan->SetTopVolume(top);
  // --------------------------------------------------------------------------
  
  //LABPOS(GFI1,-73.274339,0.069976,513.649524)
  Float_t dx = -73.274339; //dE tracker, correction due to wrong angle
  Float_t dy = 0.069976;
  Float_t dz = 513.649524;
  
  TGeoRotation *pMatrix3 = new TGeoRotation();
  //pMatrix3->RotateY(-16.7);
  TGeoCombiTrans*
  pMatrix2 = new TGeoCombiTrans("", dx,dy,dz,pMatrix3);

  //LABPOS(GFI2,-147.135037,0.069976,729.680342)
  dx = -147.135037; //dE tracker, correction due to wrong angle
  dy = 0.069976;
  dz = 729.680342;

  TGeoRotation *pMatrix5 = new TGeoRotation();
  //pMatrix5->RotateY(-16.7);
  TGeoCombiTrans*
  pMatrix4 = new TGeoCombiTrans("", dx,dy,dz,pMatrix5);
  
  
  // World definition
  TGeoVolume* pWorld = gGeoManager->GetTopVolume();
  pWorld->SetVisLeaves(kTRUE);
  
  // SHAPES, VOLUMES AND GEOMETRICAL HIERARCHY 
  
  // Volume: GFILogWorld
  
  TGeoVolume*   pGFILogWorld = new TGeoVolumeAssembly("GFILogWorld");
  pGFILogWorld->SetVisLeaves(kTRUE);
  
  // Global positioning
  pWorld->AddNode( pGFILogWorld, 0, pMatrix2 );
  
  Float_t detector_size = 5.120000;
  Float_t fiber_thickness = 0.020000; 
  
  TGeoShape *pGFITube = new TGeoBBox("GFITube", fiber_thickness/2,detector_size/2,fiber_thickness/2);
  
  TGeoVolume* pGFILog = new TGeoVolume("SFILog",pGFITube, pMed35);

  TGeoShape *pGFITubeActive = new TGeoBBox("GFITubeActive", (fiber_thickness * .98)/2, detector_size/2-0.0001, (fiber_thickness * .98)/2);

  TGeoVolume* pGFILogActive = new TGeoVolume("SFI1Log",pGFITubeActive,pMed35);
  
  pGFILog->SetLineColor((Color_t) 1);
  pGFILog->SetVisLeaves(kTRUE);
  
  TGeoRotation *pMatrixTube = new TGeoRotation();
  pMatrixTube->RotateZ(90);
  
  pGFILog -> AddNode(pGFILogActive, 0, new TGeoCombiTrans());
  
  for(int fiber_id = 0; fiber_id < detector_size / fiber_thickness; fiber_id++)
  {
     pGFILogWorld->AddNode(pGFILog, fiber_id, 
		new TGeoCombiTrans("", 
			-detector_size / 2 + (fiber_id + .5) * fiber_thickness, 
			0,
			0,
			new TGeoRotation()
		)
	);
      pGFILogWorld->AddNode(pGFILog, fiber_id + detector_size / fiber_thickness, 
		new TGeoCombiTrans("", 
			0,
			-detector_size / 2 + (fiber_id + .5) * fiber_thickness,
			fiber_thickness,
			pMatrixTube
		)
	);
  }
  
  // Add the sensitive part
//  AddSensitiveVolume(pGFILog);
//  fNbOfSensitiveVol+=1;
  
  
  
  // ---------------   Finish   -----------------------------------------------
  gGeoMan->CloseGeometry();
  gGeoMan->CheckOverlaps(0.001);
  gGeoMan->PrintOverlaps();
  gGeoMan->Test();

  TFile* geoFile = new TFile(geoFileName, "RECREATE");
  top->Write();
  geoFile->Close();
  // --------------------------------------------------------------------------
}
int RemoteCameraRtsp::PrimeCapture()
{
    Debug( 2, "Waiting for sources" );
    for ( int i = 0; i < 100 && !rtspThread->hasSources(); i++ )
    {
        usleep( 100000 );
    }
    if ( !rtspThread->hasSources() )
        Fatal( "No RTSP sources" );

    Debug( 2, "Got sources" );

    mFormatContext = rtspThread->getFormatContext();

    // Find first video stream present
    mVideoStreamId = -1;
    
    for ( unsigned int i = 0; i < mFormatContext->nb_streams; i++ )
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(51,2,1)
	if ( mFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO )
#else
	if ( mFormatContext->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
#endif
        {
            mVideoStreamId = i;
            break;
        }
    if ( mVideoStreamId == -1 )
        Fatal( "Unable to locate video stream" );

    // Get a pointer to the codec context for the video stream
    mCodecContext = mFormatContext->streams[mVideoStreamId]->codec;

    // Find the decoder for the video stream
    mCodec = avcodec_find_decoder( mCodecContext->codec_id );
    if ( mCodec == NULL )
        Panic( "Unable to locate codec %d decoder", mCodecContext->codec_id );

    // Open codec
#if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(53, 7, 0)
    if ( avcodec_open( mCodecContext, mCodec ) < 0 )
#else
    if ( avcodec_open2( mCodecContext, mCodec, 0 ) < 0 )
#endif
        Panic( "Can't open codec" );

    // Allocate space for the native video frame
    mRawFrame = avcodec_alloc_frame();

    // Allocate space for the converted video frame
    mFrame = avcodec_alloc_frame();
    
	if(mRawFrame == NULL || mFrame == NULL)
		Fatal( "Unable to allocate frame(s)");
	
	int pSize = avpicture_get_size( imagePixFormat, width, height );
	if( (unsigned int)pSize != imagesize) {
		Fatal("Image size mismatch. Required: %d Available: %d",pSize,imagesize);
	}
/*	
#if HAVE_LIBSWSCALE
	if(!sws_isSupportedInput(mCodecContext->pix_fmt)) {
		Fatal("swscale does not support the codec format: %c%c%c%c",(mCodecContext->pix_fmt)&0xff,((mCodecContext->pix_fmt>>8)&0xff),((mCodecContext->pix_fmt>>16)&0xff),((mCodecContext->pix_fmt>>24)&0xff));
	}

	if(!sws_isSupportedOutput(imagePixFormat)) {
		Fatal("swscale does not support the target format: %c%c%c%c",(imagePixFormat)&0xff,((imagePixFormat>>8)&0xff),((imagePixFormat>>16)&0xff),((imagePixFormat>>24)&0xff));
	}
	
#else // HAVE_LIBSWSCALE
    Fatal( "You must compile ffmpeg with the --enable-swscale option to use RTSP cameras" );
#endif // HAVE_LIBSWSCALE
*/

    return( 0 );
}
Esempio n. 8
0
//
//  Load OBJ file
//
int LoadOBJ(const char* file)
{
   int k;
   int  Nv,Nn,Nt;  //  Number of vertex, normal and textures
   int  Mv,Mn,Mt;  //  Maximum vertex, normal and textures
   float* V;       //  Array of vertexes
   float* N;       //  Array of normals
   float* T;       //  Array if textures coordinates
   char*  line;    //  Line pointer
   char*  str;     //  String pointer

   //  Open file
   FILE* f = fopen(file,"r");
   if (!f) Fatal("Cannot open file %s\n",file);

   // Reset materials
   mtl = NULL;
   Nmtl = 0;

   //  Start new displaylist
   int list = glGenLists(1);
   glNewList(list,GL_COMPILE);
   //  Push attributes for textures
   glPushAttrib(GL_TEXTURE_BIT);

   //  Read vertexes and facets
   V  = N  = T  = NULL;
   Nv = Nn = Nt = 0;
   Mv = Mn = Mt = 0;
   while ((line = readline(f)))
   {
      //  Vertex coordinates (always 3)
      if (line[0]=='v' && line[1]==' ')
         readcoord(line+2,3,&V,&Nv,&Mv);
      //  Normal coordinates (always 3)
      else if (line[0]=='v' && line[1] == 'n')
         readcoord(line+2,3,&N,&Nn,&Mn);
      //  Texture coordinates (always 2)
      else if (line[0]=='v' && line[1] == 't')
         readcoord(line+2,2,&T,&Nt,&Mt);
      //  Read and draw facets
      else if (line[0]=='f')
      {
         line++;
         //  Read Vertex/Texture/Normal triplets
         glBegin(GL_POLYGON);
         while ((str = getword(&line)))
         {
            int Kv,Kt,Kn;
            //  Try Vertex/Texture/Normal triplet
            if (sscanf(str,"%d/%d/%d",&Kv,&Kt,&Kn)==3)
            {
               if (Kv<0 || Kv>Nv/3) Fatal("Vertex %d out of range 1-%d\n",Kv,Nv/3);
               if (Kn<0 || Kn>Nn/3) Fatal("Normal %d out of range 1-%d\n",Kn,Nn/3);
               if (Kt<0 || Kt>Nt/2) Fatal("Texture %d out of range 1-%d\n",Kt,Nt/2);
            }
            //  Try Vertex//Normal pairs
            else if (sscanf(str,"%d//%d",&Kv,&Kn)==2)
            {
               if (Kv<0 || Kv>Nv/3) Fatal("Vertex %d out of range 1-%d\n",Kv,Nv/3);
               if (Kn<0 || Kn>Nn/3) Fatal("Normal %d out of range 1-%d\n",Kn,Nn/3);
               Kt = 0;
            }
            //  Try Vertex index
            else if (sscanf(str,"%d",&Kv)==1)
            {
               if (Kv<0 || Kv>Nv/3) Fatal("Vertex %d out of range 1-%d\n",Kv,Nv/3);
               Kn = 0;
               Kt = 0;
            }
            //  This is an error
            else
               Fatal("Invalid facet %s\n",str);
            //  Draw vectors
            if (Kt) glTexCoord2fv(T+2*(Kt-1));
            if (Kn) glNormal3fv(N+3*(Kn-1));
            if (Kv) glVertex3fv(V+3*(Kv-1));
         }
         glEnd();
      }
      //  Use material
      else if ((str = readstr(line,"usemtl")))
         SetMaterial(str);
      //  Load materials
      else if ((str = readstr(line,"mtllib")))
         LoadMaterial(str);
      //  Skip this line
   }
   fclose(f);
   //  Pop attributes (textures)
   glPopAttrib();
   glEndList();

   //  Free materials
   for (k=0;k<Nmtl;k++)
      free(mtl[k].name);
   free(mtl);

   //  Free arrays
   free(V);
   free(T);
   free(N);

   return list;
}
Esempio n. 9
0
/*
 *  Load texture from BMP file
 */
unsigned int LoadTexBMP(const char* file)
{
   unsigned int   texture;    // Texture name
   FILE*          f;          // File pointer
   unsigned short magic;      // Image magic
   unsigned int   dx,dy,size; // Image dimensions
   unsigned short nbp,bpp;    // Planes and bits per pixel
   unsigned char* image;      // Image data
   unsigned int   k;          // Counter
   int            max;        // Maximum texture dimensions

   //  Open file
   f = fopen(file,"rb");
   if (!f) Fatal("Cannot open file %s\n",file);
   //  Check image magic
   if (fread(&magic,2,1,f)!=1) Fatal("Cannot read magic from %s\n",file);
   if (magic!=0x4D42 && magic!=0x424D) Fatal("Image magic not BMP in %s\n",file);
   //  Seek to and read header
   if (fseek(f,16,SEEK_CUR) || fread(&dx ,4,1,f)!=1 || fread(&dy ,4,1,f)!=1 ||
       fread(&nbp,2,1,f)!=1 || fread(&bpp,2,1,f)!=1 || fread(&k,4,1,f)!=1)
     Fatal("Cannot read header from %s\n",file);
   //  Reverse bytes on big endian hardware (detected by backwards magic)
   if (magic==0x424D)
   {
      Reverse(&dx,4);
      Reverse(&dy,4);
      Reverse(&nbp,2);
      Reverse(&bpp,2);
      Reverse(&k,4);
   }
   //  Check image parameters
   glGetIntegerv(GL_MAX_TEXTURE_SIZE,&max);
   if (dx<1 || int(dx)>max) Fatal("%s image width %d out of range 1-%d\n",file,dx,max);
   if (dy<1 || int(dy)>max) Fatal("%s image height %d out of range 1-%d\n",file,dy,max);
   if (nbp!=1)  Fatal("%s bit planes is not 1: %d\n",file,nbp);
   if (bpp!=24) Fatal("%s bits per pixel is not 24: %d\n",file,bpp);
   if (k!=0)    Fatal("%s compressed files not supported\n",file);
#ifndef GL_VERSION_2_0
   //  OpenGL 2.0 lifts the restriction that texture size must be a power of two
   for (k=1;k<dx;k*=2);
   if (k!=dx) Fatal("%s image width not a power of two: %d\n",file,dx);
   for (k=1;k<dy;k*=2);
   if (k!=dy) Fatal("%s image height not a power of two: %d\n",file,dy);
#endif

   //  Allocate image memory
   size = 3*dx*dy;
   image = (unsigned char*) malloc(size);
   if (!image) Fatal("Cannot allocate %d bytes of memory for image %s\n",size,file);
   //  Seek to and read image
   if (fseek(f,20,SEEK_CUR) || fread(image,size,1,f)!=1) Fatal("Error reading data from image %s\n",file);
   fclose(f);
   //  Reverse colors (BGR -> RGB)
   for (k=0;k<size;k+=3)
   {
      unsigned char temp = image[k];
      image[k]   = image[k+2];
      image[k+2] = temp;
   }

   //  Sanity check
   ErrCheck("LoadTexBMP");
   //  Generate 2D texture
   glGenTextures(1,&texture);
   glBindTexture(GL_TEXTURE_2D,texture);
   //  Copy image
   glTexImage2D(GL_TEXTURE_2D,0,3,dx,dy,0,GL_RGB,GL_UNSIGNED_BYTE,image);
   if (glGetError()) Fatal("Error in glTexImage2D %s %dx%d\n",file,dx,dy);
   //  Scale linearly when image size doesn't match
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

   //  Free image memory
   free(image);
   //  Return texture name
   return texture;
}
Esempio n. 10
0
static void LoadDatabase(FILE *f, int loud)
{
	int ni,na,nw,nr,mc,pr,tr,wl,lt,mn,trm;
	int ct;
	short lo;
	Action *ap;
	Room *rp;
	Item *ip;
/* Load the header */

	if(fscanf(f,"%*d %d %d %d %d %d %d %d %d %d %d %d",
		&ni,&na,&nw,&nr,&mc,&pr,&tr,&wl,&lt,&mn,&trm)<10)
		Fatal("Invalid database(bad header)");
	GameHeader.NumItems=ni;
	Items=(Item *)MemAlloc(sizeof(Item)*(ni+1));
	GameHeader.NumActions=na;
	Actions=(Action *)MemAlloc(sizeof(Action)*(na+1));
	GameHeader.NumWords=nw;
	GameHeader.WordLength=wl;
	Verbs=MemAlloc(sizeof(char *)*(nw+1));
	Nouns=MemAlloc(sizeof(char *)*(nw+1));
	GameHeader.NumRooms=nr;
	Rooms=(Room *)MemAlloc(sizeof(Room)*(nr+1));
	GameHeader.MaxCarry=mc;
	GameHeader.PlayerRoom=pr;
	GameHeader.Treasures=tr;
	GameHeader.LightTime=lt;
	LightRefill=lt;
	GameHeader.NumMessages=mn;
	Messages=MemAlloc(sizeof(char *)*(mn+1));
	GameHeader.TreasureRoom=trm;

/* Load the actions */

	ct=0;
	ap=Actions;
	if(loud)
		printf("Reading %d actions.\n",na);
	while(ct<na+1)
	{
		if(fscanf(f,"%hu %hu %hu %hu %hu %hu %hu %hu",
			&ap->Vocab,
			&ap->Condition[0],
			&ap->Condition[1],
			&ap->Condition[2],
			&ap->Condition[3],
			&ap->Condition[4],
			&ap->Action[0],
			&ap->Action[1])!=8)
		{
			printf("Bad action line (%d)\n",ct);
			exit(1);
		}
		ap++;
		ct++;
	}
	ct=0;
	if(loud)
		printf("Reading %d word pairs.\n",nw);
	while(ct<nw+1)
	{
		Verbs[ct]=ReadString(f);
		Nouns[ct]=ReadString(f);
		ct++;
	}
	ct=0;
	rp=Rooms;
	if(loud)
		printf("Reading %d rooms.\n",nr);
	while(ct<nr+1)
	{
		if(fscanf(f,"%hd %hd %hd %hd %hd %hd",
			&rp->Exits[0],&rp->Exits[1],&rp->Exits[2],
			&rp->Exits[3],&rp->Exits[4],&rp->Exits[5])!=6)
		{
			printf("Bad room line (%d)\n",ct);
			exit(1);
		}
		rp->Text=ReadString(f);
		ct++;
		rp++;
	}
	ct=0;
	if(loud)
		printf("Reading %d messages.\n",mn);
	while(ct<mn+1)
	{
		Messages[ct]=ReadString(f);
		ct++;
	}
	ct=0;
	if(loud)
		printf("Reading %d items.\n",ni);
	ip=Items;
	while(ct<ni+1)
	{
		ip->Text=ReadString(f);
		ip->AutoGet=strchr(ip->Text,'/');
		/* Some games use // to mean no auto get/drop word! */
		if(ip->AutoGet && strcmp(ip->AutoGet,"//") && strcmp(ip->AutoGet,"/*"))
		{
			char *t;
			*ip->AutoGet++=0;
			t=strchr(ip->AutoGet,'/');
			if(t!=NULL)
				*t=0;
		}
		if(fscanf(f,"%hd",&lo)!=1)
		{
			printf("Bad item line (%d)\n",ct);
			exit(1);
		}
		ip->Location=(unsigned char)lo;
		ip->InitialLoc=ip->Location;
		ip++;
		ct++;
	}
	ct=0;
	/* Discard Comment Strings */
	while(ct<na+1)
	{
		free(ReadString(f));
		ct++;
	}
	if(fscanf(f,"%d",&ct)!=1)
	{
		puts("Cannot read version");
		exit(1);
	}
	if(loud)
		printf("Version %d.%02d of Adventure ",
		ct/100,ct%100);
	if(fscanf(f,"%d",&ct)!=1)
	{
		puts("Cannot read adventure number");
		exit(1);
	}
	if(loud)
		printf("%d.\nLoad Complete.\n\n",ct);
}
Esempio n. 11
0
void glk_main(void)
{
	FILE *f;
	int vb,no;

	Bottom = glk_window_open(0, 0, 0, wintype_TextBuffer, 1);
	if(Bottom == NULL)
		glk_exit();
	glk_set_window(Bottom);

	if(game_file == NULL)
		Fatal("No game provided");

	f = fopen(game_file, "r");
	if(f==NULL)
		Fatal("Cannot open game");

	if (Options & TRS80_STYLE)
	{
		Width = 64;
		TopHeight = 11;
	}
	else
	{
		Width = 80;
		TopHeight = 10;
	}

	if(split_screen)
	{
		Top = glk_window_open(Bottom, winmethod_Above | winmethod_Fixed, TopHeight, wintype_TextGrid, 0);
		if(Top == NULL)
		{
			split_screen = 0;
			Top = Bottom;
		}
	}
	else
	{
		Top = Bottom;
	}

	Output("\
Scott Free, A Scott Adams game driver in C.\n\
Release 1.14, (c) 1993,1994,1995 Swansea University Computer Society.\n\
Distributed under the GNU software license\n\n");
	LoadDatabase(f,(Options&DEBUGGING)?1:0);
	fclose(f);
	srand(time(NULL));
	while(1)
	{
		glk_tick();

		PerformActions(0,0);

		Look();

		if(GetInput(&vb,&no) == -1)
			continue;
		switch(PerformActions(vb,no))
		{
			case -1:Output("I don't understand your command. ");
				break;
			case -2:Output("I can't do that yet. ");
				break;
		}
		/* Brian Howarth games seem to use -1 for forever */
		if(Items[LIGHT_SOURCE].Location/*==-1*/!=DESTROYED && GameHeader.LightTime!= -1)
		{
			GameHeader.LightTime--;
			if(GameHeader.LightTime<1)
			{
				BitFlags|=(1<<LIGHTOUTBIT);
				if(Items[LIGHT_SOURCE].Location==CARRIED ||
					Items[LIGHT_SOURCE].Location==MyLoc)
				{
					if(Options&SCOTTLIGHT)
						Output("Light has run out! ");
					else
						Output("Your light has run out. ");
				}
				if(Options&PREHISTORIC_LAMP)
					Items[LIGHT_SOURCE].Location=DESTROYED;
			}
			else if(GameHeader.LightTime<25)
			{
				if(Items[LIGHT_SOURCE].Location==CARRIED ||
					Items[LIGHT_SOURCE].Location==MyLoc)
				{

					if(Options&SCOTTLIGHT)
					{
						Output("Light runs out in ");
						OutputNumber(GameHeader.LightTime);
						Output(" turns. ");
					}
					else
					{
						if(GameHeader.LightTime%5==0)
							Output("Your light is growing dim. ");
					}
				}
			}
		}
	}
}
Esempio n. 12
0
void create_fsal_up_threads()
{
  int rc, id;
  pthread_attr_t attr_thr;
  fsal_up_arg_t *fsal_up_args;
  exportlist_t *pcurrent;

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

  /* Initialization of thread attrinbutes borrowed from nfs_init.c */
  if(pthread_attr_init(&attr_thr) != 0)
    LogDebug(COMPONENT_THREAD, "can't init pthread's attributes");

  if(pthread_attr_setscope(&attr_thr, PTHREAD_SCOPE_SYSTEM) != 0)
    LogDebug(COMPONENT_THREAD, "can't set pthread's scope");

  if(pthread_attr_setdetachstate(&attr_thr, PTHREAD_CREATE_JOINABLE) != 0)
    LogDebug(COMPONENT_THREAD, "can't set pthread's join state");

  if(pthread_attr_setstacksize(&attr_thr, THREAD_STACK_SIZE) != 0)
    LogDebug(COMPONENT_THREAD, "can't set pthread's stack size");

  /* The admin thread is the only other thread that may be
   * messing around with the export entries. */

  //  LOCK EXPORT LIST
  for(pcurrent = nfs_param.pexportlist;
      pcurrent != NULL;
      pcurrent = pcurrent->next)
    {
      if (pcurrent->use_fsal_up == FALSE)
        continue;

      /* Make sure there are not multiple fsal_up_threads handling multiple
       * exports on the same filesystem. This could potentially cause issues. */
      LogEvent(COMPONENT_INIT, "Checking if export id %d with filesystem "
               "id %llu.%llu already has an assigned FSAL_UP thread.",
               pcurrent->fsalid, pcurrent->filesystem_id.major,
               pcurrent->filesystem_id.minor);

      id = fsal_up_thread_exists(pcurrent);
      if (id)
        {
          LogEvent(COMPONENT_INIT, "Filesystem %llu.%llu already has an "
                   "assigned FSAL_UP with export id %d so export w/ id %d"
                   " is not being assigned a new FSAL_UP thread.",
                   pcurrent->filesystem_id.major,
                   pcurrent->filesystem_id.minor, id, pcurrent->id);
          continue;
        }
      else
        {
          LogEvent(COMPONENT_INIT, "Filesystem %llu.%llu export id %d does not"
                   " have an FSAL_UP thread yet, creating a thread now.",
                   pcurrent->filesystem_id.major, pcurrent->filesystem_id.minor,
                   pcurrent->id);

          if((fsal_up_args =
              (fsal_up_arg_t *) Mem_Alloc(sizeof(fsal_up_arg_t))) == NULL)
            {
              LogError(COMPONENT_INIT, ERR_SYS, ERR_MALLOC, errno);
              Fatal();
            }

	  memset(fsal_up_args, 0, sizeof(fsal_up_arg_t));
          fsal_up_args->export_entry = pcurrent;

          if( ( rc = pthread_create( &pcurrent->fsal_up_thr, &attr_thr,
                                     fsal_up_thread,(void *)fsal_up_args)) != 0)
            {
              Mem_Free(fsal_up_args);
              LogFatal(COMPONENT_THREAD,
                       "Could not create fsal_up_thread, error = %d (%s)",
                       errno, strerror(errno));
              Fatal();
            }
        }
    }
}
Esempio n. 13
0
void *fsal_up_thread(void *Arg)
{
  fsal_status_t status;
  int rc;
  fsal_up_arg_t *fsal_up_args = (fsal_up_arg_t *)Arg;
  fsal_up_event_bus_context_t fsal_up_context;
  fsal_up_event_bus_parameter_t fsal_up_bus_param;
  fsal_up_event_bus_filter_t * pupebfilter = NULL;
  fsal_up_filter_list_t *filter = NULL;
  fsal_up_event_t *pevent_head, *event, *tmpevent;
  fsal_up_event_functions_t *event_func;
  fsal_count_t nb_events_found, event_nb;
  fsal_time_t timeout;
  char thr_name[40];

  memset(&fsal_up_bus_param, 0, sizeof(fsal_up_event_bus_parameter_t));
  memset(&fsal_up_context, 0, sizeof(fsal_up_event_bus_context_t));

  snprintf(thr_name, sizeof(thr_name), "FSAL UP Thread for filesystem %llu.%llu",
           fsal_up_args->export_entry->filesystem_id.major,
           fsal_up_args->export_entry->filesystem_id.minor);
  SetNameFunction(thr_name);

#ifndef _NO_BUDDY_SYSTEM
  if((rc = BuddyInit(&nfs_param.buddy_param_fsal_up)) != BUDDY_SUCCESS)
    {
      /* Failed init */
      LogFatal(COMPONENT_FSAL_UP,
               "FSAL_UP: Memory manager could not be initialized");
      Fatal();
    }
  LogInfo(COMPONENT_FSAL_UP,
          "FSAL_UP: Memory manager for filesystem %llu.%llu export id %d"
          " successfully initialized",
          fsal_up_args->export_entry->filesystem_id.major,
          fsal_up_args->export_entry->filesystem_id.minor,
          fsal_up_args->export_entry->id);
#endif

  /* Set the FSAL UP functions that will be used to process events. */
  event_func = get_fsal_up_functions(fsal_up_args->export_entry->fsal_up_type);
  if (event_func == NULL)
    {
      LogCrit(COMPONENT_FSAL_UP, "Error: FSAL UP TYPE: %s does not exist. "
              "Exiting FSAL UP thread.", fsal_up_args->export_entry->fsal_up_type);
      Mem_Free(Arg);
      return NULL;
    }

  /* Get fsal up context from FSAL */
  /* It is expected that the export entry and event_pool will be referenced
   * in the returned callback context structure. */
  memcpy(&fsal_up_context.FS_export_context,
         &fsal_up_args->export_entry->FS_export_context,
         sizeof(fsal_export_context_t));

  fsal_up_context.event_pool = &nfs_param.fsal_up_param.event_pool;

  LogDebug(COMPONENT_FSAL_UP, "Initializing FSAL Callback context.");
  status = FSAL_UP_Init(&fsal_up_bus_param, &fsal_up_context);
  if (FSAL_IS_ERROR(status))
    {
      LogCrit(COMPONENT_FSAL_UP, "Error: Could not initialize FSAL UP for"
              " filesystem %llu.%llu export %d. Exiting FSAL UP thread.",
              fsal_up_args->export_entry->filesystem_id.major,
              fsal_up_args->export_entry->filesystem_id.minor,
              fsal_up_args->export_entry->id);
    }

  /* Add filters ... later if needed we could add arguments to filters
   * configurable from configuration files. */
  for(filter = fsal_up_args->export_entry->fsal_up_filter_list;
      filter != NULL; filter = filter->next)
    {
      LogEvent(COMPONENT_FSAL_UP, "Applying filter \"%s\" to FSAL UP thread "
               "for filesystem id %llu.%llu export id %d.", filter->name,
              fsal_up_args->export_entry->filesystem_id.major,
              fsal_up_args->export_entry->filesystem_id.minor,
              fsal_up_args->export_entry->id);

      /* Find predefined filter */
      pupebfilter = find_filter(filter->name);
      if (pupebfilter == NULL)
        {
          LogCrit(COMPONENT_FSAL_UP, "Error: Could not find filter named \"%s\".",
                   filter->name);
        }

      /* Applying filter */
      FSAL_UP_AddFilter(pupebfilter, &fsal_up_context);
    }


  /* Set the timeout for getting events. */
  timeout = fsal_up_args->export_entry->fsal_up_timeout;

  /* Start querying for events and processing. */
  while(1)
    {
      /* pevent is passed in as a single empty node, it's expected the
       * FSAL will use the event_pool in the bus_context to populate
       * this array by adding to the pevent_head->next attribute. */
      event_nb = 0;
      nb_events_found = 0;
      pevent_head = NULL;
      LogDebug(COMPONENT_FSAL_UP, "Requesting event from FSAL Callback interface.");
      status = FSAL_UP_GetEvents(&pevent_head,     /* out */
                                 &event_nb,        /* in/out */
                                 timeout,          /* in */
                                 &nb_events_found, /* out */
                                 &fsal_up_context);/* in */
      if (FSAL_IS_ERROR(status))
        {
          if (status.major == ERR_FSAL_TIMEOUT)
            LogDebug(COMPONENT_FSAL_UP, "FSAL_UP_EB_GetEvents() hit the timeout"
                     " limit of %u.%u seconds for filesystem id %llu.%llu export id"
                     " %d.", timeout.seconds, timeout.nseconds,
                     fsal_up_args->export_entry->filesystem_id.major,
                     fsal_up_args->export_entry->filesystem_id.minor,
                     fsal_up_args->export_entry->id);
          else if (status.major == ERR_FSAL_NOTSUPP)
            {
              LogCrit(COMPONENT_FSAL_UP, "Exiting FSAL UP Thread for filesystem"
                      " id %llu.%llu export id %u because the FSAL Callback"
                      " Interface is not supported for this FSAL type.",
                      fsal_up_args->export_entry->filesystem_id.major,
                      fsal_up_args->export_entry->filesystem_id.minor,
                      fsal_up_args->export_entry->id);
              return NULL;
            }
          else
            LogDebug(COMPONENT_FSAL_UP, "Error: FSAL_UP_EB_GetEvents() "
                     "failed");
        }

      LogDebug(COMPONENT_FSAL_UP, "Received %lu events to process for filesystem"
                     " id %llu.%llu export id %u.",
               event_nb,
               fsal_up_args->export_entry->filesystem_id.major,
               fsal_up_args->export_entry->filesystem_id.minor,
               fsal_up_args->export_entry->id);

      /* process the list of events */
      for(event = pevent_head; event != NULL;)
        {
          status = process_event(event, event_func);
          if (FSAL_IS_ERROR(status))
            {
              LogDebug(COMPONENT_FSAL_UP, "Error: Event could not be processed "
                       "for filesystem %llu.%llu export id %u.",
                       fsal_up_args->export_entry->filesystem_id.major,
                       fsal_up_args->export_entry->filesystem_id.minor,
                       fsal_up_args->export_entry->id);
            }
          tmpevent = event;
          event = event->next_event;
          ReleaseToPool(tmpevent, &nfs_param.fsal_up_param.event_pool);
          event_nb--;
        }

      LogDebug(COMPONENT_FSAL_UP, "%lu events not found for filesystem"
               " %llu.%llu export id %u", event_nb,
               fsal_up_args->export_entry->filesystem_id.major,
               fsal_up_args->export_entry->filesystem_id.minor,
               fsal_up_args->export_entry->id);
    }

  Mem_Free(Arg);
  return NULL;
}                               /* fsal_up_thread */
Esempio n. 14
0
// =====================================================================================
//  TEX_InitFromWad
// =====================================================================================
bool            TEX_InitFromWad()
{
    int             i, j;
    wadinfo_t       wadinfo;
    char            szTmpWad[1024]; // arbitrary, but needs to be large.
    char*           pszWadFile;
    const char*     pszWadroot;
    wadpath_t*      currentwad;

    Log("\n"); // looks cleaner

    szTmpWad[0] = 0;
    pszWadroot = getenv("WADROOT");

#ifdef HLCSG_AUTOWAD
    autowad_UpdateUsedWads();
#endif

    // for eachwadpath
    for (i = 0; i < g_iNumWadPaths; i++)
    {
        FILE*           texfile;                           // temporary used in this loop
        bool            bExcludeThisWad = false;

        currentwad = g_pWadPaths[i];
        pszWadFile = currentwad->path;


#ifdef HLCSG_AUTOWAD
        #ifdef _DEBUG
        Log("[dbg] Attempting to parse wad: '%s'\n", pszWadFile);
        #endif

        if (g_bWadAutoDetect && !currentwad->usedtextures)
            continue;

        #ifdef _DEBUG
        Log("[dbg] Parsing wad\n");
        #endif
#endif

        texfiles[nTexFiles] = fopen(pszWadFile, "rb");

        #ifdef SYSTEM_WIN32
        if (!texfiles[nTexFiles])
        {
            // cant find it, maybe this wad file has a hard code drive
            if (pszWadFile[1] == ':')
            {
                pszWadFile += 2;                           // skip past the drive
                texfiles[nTexFiles] = fopen(pszWadFile, "rb");
            }
        }
        #endif

        if (!texfiles[nTexFiles] && pszWadroot)
        {
            char            szTmp[_MAX_PATH];
            char            szFile[_MAX_PATH];
            char            szSubdir[_MAX_PATH];

            ExtractFile(pszWadFile, szFile);

            ExtractFilePath(pszWadFile, szTmp);
            ExtractFile(szTmp, szSubdir);

            // szSubdir will have a trailing separator
            safe_snprintf(szTmp, _MAX_PATH, "%s" SYSTEM_SLASH_STR "%s%s", pszWadroot, szSubdir, szFile);
            texfiles[nTexFiles] = fopen(szTmp, "rb");

            #ifdef SYSTEM_POSIX
            if (!texfiles[nTexFiles])
            {
                // if we cant find it, Convert to lower case and try again
                strlwr(szTmp);
                texfiles[nTexFiles] = fopen(szTmp, "rb");
            }
            #endif
        }

        if (!texfiles[nTexFiles])
        {
            // still cant find it, error out
            Fatal(assume_COULD_NOT_FIND_WAD, "Could not open wad file %s", pszWadFile);
            continue;
        }

        // look and see if we're supposed to include the textures from this WAD in the bsp.
        WadInclude_i it;
        for (it = g_WadInclude.begin(); it != g_WadInclude.end(); it++)
        {
            if (stristr(pszWadFile, it->c_str()))
            {
                Log("Including Wadfile: %s\n", pszWadFile);
                bExcludeThisWad = true;             // wadincluding this one
                s_WadIncludeMap[nTexFiles] = true;
                break;
            }
        }

        if (!bExcludeThisWad)
        {
            Log("Using Wadfile: %s\n", pszWadFile);
            safe_snprintf(szTmpWad, 1024, "%s%s;", szTmpWad, pszWadFile);
        }

        // temp assignment to make things cleaner:
        texfile = texfiles[nTexFiles];

        // read in this wadfiles information
        SafeRead(texfile, &wadinfo, sizeof(wadinfo));

        // make sure its a valid format
        if (strncmp(wadinfo.identification, "WAD2", 4) && strncmp(wadinfo.identification, "WAD3", 4))
        {
            Log(" - ");
            Error("%s isn't a Wadfile!", pszWadFile);
        }

        wadinfo.numlumps        = LittleLong(wadinfo.numlumps);
        wadinfo.infotableofs    = LittleLong(wadinfo.infotableofs);

        // read in lump
        if (fseek(texfile, wadinfo.infotableofs, SEEK_SET))
            Warning("fseek to %d in wadfile %s failed\n", wadinfo.infotableofs, pszWadFile);

        // memalloc for this lump
        lumpinfo = (lumpinfo_t*)realloc(lumpinfo, (nTexLumps + wadinfo.numlumps) * sizeof(lumpinfo_t));

        // for each texlump
        for (j = 0; j < wadinfo.numlumps; j++, nTexLumps++)
        {
            SafeRead(texfile, &lumpinfo[nTexLumps], (sizeof(lumpinfo_t) - sizeof(int)) );  // iTexFile is NOT read from file

            if (!TerminatedString(lumpinfo[nTexLumps].name, MAXWADNAME))
            {
                lumpinfo[nTexLumps].name[MAXWADNAME - 1] = 0;
                Log(" - ");
                Warning("Unterminated texture name : wad[%s] texture[%d] name[%s]\n", pszWadFile, nTexLumps, lumpinfo[nTexLumps].name);
            }

            CleanupName(lumpinfo[nTexLumps].name, lumpinfo[nTexLumps].name);

            lumpinfo[nTexLumps].filepos = LittleLong(lumpinfo[nTexLumps].filepos);
            lumpinfo[nTexLumps].disksize = LittleLong(lumpinfo[nTexLumps].disksize);
            lumpinfo[nTexLumps].iTexFile = nTexFiles;

            if (lumpinfo[nTexLumps].disksize > MAX_TEXTURE_SIZE)
            {
                Log(" - ");
                Warning("Larger than expected texture (%d bytes): '%s'",
                    lumpinfo[nTexLumps].disksize, lumpinfo[nTexLumps].name);
            }

        }

        // AJM: this feature is dependant on autowad. :(
        // CONSIDER: making it standard?
#ifdef HLCSG_AUTOWAD
        {
            double percused = ((float)(currentwad->usedtextures) / (float)(g_numUsedTextures)) * 100;
            Log(" - Contains %i used texture%s, %2.2f percent of map (%d textures in wad)\n",
                currentwad->usedtextures, currentwad->usedtextures == 1 ? "" : "s", percused, wadinfo.numlumps);
        }
#endif

        nTexFiles++;
        hlassume(nTexFiles < MAX_TEXFILES, assume_MAX_TEXFILES);
    }

    //Log("num of used textures: %i\n", g_numUsedTextures);

    // AJM: Tommy suggested i add this warning message in, and  it certianly doesnt
    //  hurt to be cautious. Especially one of the possible side effects he mentioned was svc_bad
    if (nTexFiles > 8)
    {
        Log("\n");
        Warning("More than 8 wadfiles are in use. (%i)\n"
                "This may be harmless, and if no strange side effects are occurring, then\n"
                "it can safely be ignored. However, if your map starts exhibiting strange\n"
                "or obscure errors, consider this as suspect.\n"
                , nTexFiles);
    }

    // sort texlumps in memory by name
    qsort((void*)lumpinfo, (size_t) nTexLumps, sizeof(lumpinfo[0]), lump_sorter_by_name);

    SetKeyValue(&g_entities[0], "wad", szTmpWad);

    Log("\n");
    CheckFatal();
    return true;
}