Пример #1
0
 virtual void SetUp() {
   blob_top_vec_.push_back(blob_top_data_);
   blob_top_vec_.push_back(blob_top_label_);
   Caffe::set_random_seed(seed_);
   // Create test input file.
   MakeTempFilename(&filename_);
   std::ofstream outfile(filename_.c_str(), std::ofstream::out);
   LOG(INFO) << "Using temporary file " << filename_;
   for (int i = 0; i < 5; ++i) {
     outfile << EXAMPLES_SOURCE_DIR "images/cat.jpg " << i << std::endl;
   }
   outfile.close();
   // Create test input file for images of distinct sizes.
   MakeTempFilename(&filename_reshape_);
   std::ofstream reshapefile(filename_reshape_.c_str(), std::ofstream::out);
   LOG(INFO) << "Using temporary file " << filename_reshape_;
   reshapefile << EXAMPLES_SOURCE_DIR "images/cat.jpg " << 0 << std::endl;
   reshapefile << EXAMPLES_SOURCE_DIR "images/fish-bike.jpg " << 1
               << std::endl;
   reshapefile.close();
   // Create test input file for images with space in names
   MakeTempFilename(&filename_space_);
   std::ofstream spacefile(filename_space_.c_str(), std::ofstream::out);
   LOG(INFO) << "Using temporary file " << filename_space_;
   spacefile << EXAMPLES_SOURCE_DIR "images/cat.jpg " << 0 << std::endl;
   spacefile << EXAMPLES_SOURCE_DIR "images/cat gray.jpg " << 1 << std::endl;
   spacefile.close();
 }
Пример #2
0
bool C4Record::StartStreaming(bool fInitial) {
  if (!fRecording) return false;
  if (fStreaming) return false;

  // Get temporary file name
  StdCopyStrBuf sTempFilename(sFilename);
  MakeTempFilename(&sTempFilename);

  // Save start state (without copy of scenario!)
  C4GameSaveRecord saveRec(fInitial, Index, Game.Parameters.isLeague(), false);
  if (!saveRec.Save(sTempFilename.getData())) return FALSE;
  saveRec.Close();

  // Add file into stream, delete file
  fStreaming = true;
  if (!StreamFile(sTempFilename.getData(), sFilename.getData())) {
    fStreaming = false;
    return false;
  }

  // Okay
  EraseFile(sTempFilename.getData());
  iStreamingPos = 0;
  return true;
}
Пример #3
0
bool C4Record::AddFile(const char *szLocalFilename, const char *szAddAs,
                       bool fDelete) {
  if (!fRecording) return false;

  // Streaming?
  if (fStreaming) {
    // Special stripping for streaming
    StdCopyStrBuf szFile(szLocalFilename);
    if (SEqualNoCase(GetExtension(szAddAs), "c4p")) {
      // Create a copy
      MakeTempFilename(&szFile);
      if (!CopyItem(szLocalFilename, szFile.getData())) return false;
      // Strip it
      if (!C4Player::Strip(szFile.getData(), true)) return false;
    }

    // Add to stream
    if (!StreamFile(szFile.getData(), szAddAs)) return false;

    // Remove temporary file
    if (szFile != szLocalFilename) EraseItem(szFile.getData());
  }

  // Add to record group
  if (fDelete) {
    if (!RecordGrp.Move(szLocalFilename, szAddAs)) return false;
  } else {
    if (!RecordGrp.Add(szLocalFilename, szAddAs)) return false;
  }

  return true;
}
 HDF5OutputLayerTest()
     : input_file_name_(ABS_TEST_DATA_DIR "/sample_data.h5"),
       blob_data_(new Blob<Dtype>()),
       blob_label_(new Blob<Dtype>()),
       num_(5),
       channels_(8),
       height_(5),
       width_(5) {
   MakeTempFilename(&output_file_name_);
 }
 HDF5OutputLayerTest()
     : input_file_name_(
       CMAKE_SOURCE_DIR "caffe/test/test_data/sample_data.h5"),
       blob_data_(new Blob<Dtype>()),
       blob_label_(new Blob<Dtype>()),
       num_(5),
       channels_(8),
       height_(5),
       width_(5) {
   MakeTempFilename(&output_file_name_);
 }
Пример #6
0
bool C4ScenarioSection::EnsureTempStore(bool fExtractLandscape,
                                        bool fExtractObjects) {
  // if it's temp store already, don't do anything
  if (szTempFilename) return true;
  // make temp filename
  char *szTmp = const_cast<char *>(
      Config.AtTempPath(szFilename ? GetFilename(szFilename) : szName));
  MakeTempFilename(szTmp);
  // main section: extract section files from main scenario group (create group
  // as open dir)
  if (!szFilename) {
    if (!CreateDirectory(szTmp, NULL)) return false;
    C4Group hGroup;
    if (!hGroup.Open(szTmp, TRUE)) {
      EraseItem(szTmp);
      return false;
    }
    // extract all desired section files
    Game.ScenarioFile.ResetSearch();
    char fn[_MAX_FNAME + 1];
    *fn = 0;
    while (Game.ScenarioFile.FindNextEntry(C4FLS_Section, fn))
      if (fExtractLandscape || !WildcardMatch(C4FLS_SectionLandscape, fn))
        if (fExtractObjects || !WildcardMatch(C4FLS_SectionObjects, fn))
          Game.ScenarioFile.ExtractEntry(fn, szTmp);
    hGroup.Close();
  } else {
    // subsection: simply extract section from main group
    if (!Game.ScenarioFile.ExtractEntry(szFilename, szTmp)) return false;
    // delete undesired landscape/object files
    if (!fExtractLandscape || !fExtractObjects) {
      C4Group hGroup;
      if (hGroup.Open(szFilename)) {
        if (!fExtractLandscape) hGroup.Delete(C4FLS_SectionLandscape);
        if (!fExtractObjects) hGroup.Delete(C4FLS_SectionObjects);
      }
    }
  }
  // copy temp filename
  szTempFilename = new char[strlen(szTmp) + 1];
  SCopy(szTmp, szTempFilename, _MAX_PATH);
  // done, success
  return true;
}
static RageFileObjDirect *MakeFileObjDirect( RString sPath, int iMode, int &iError )
{
	int iFD;
	if( iMode & RageFile::READ )
	{
		iFD = DoOpen( sPath, O_BINARY|O_RDONLY, 0666 );

		/* XXX: Windows returns EACCES if we try to open a file on a CDROM that isn't
		 * ready, instead of something like ENODEV.  We want to return that case as
		 * ENOENT, but we can't distinguish it from file permission errors. */
	}
	else
	{
		RString sOut;
		if( iMode & RageFile::STREAMED )
			sOut = sPath;
		else
			sOut = MakeTempFilename(sPath);

		/* Open a temporary file for writing. */
		iFD = DoOpen( sOut, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0666 );
	}

	if( iFD == -1 )
	{
		iError = errno;
		return NULL;
	}

#if defined(UNIX)
	struct stat st;
	if( fstat(iFD, &st) != -1 && (st.st_mode & S_IFDIR) )
	{
		iError = EISDIR;
		close( iFD );
		return NULL;
	}
#endif

	return new RageFileObjDirect( sPath, iFD, iMode );
}
Пример #8
0
TYPED_TEST(DataTransformTest, TestMeanFile) {
  TransformationParameter transform_param;
  const bool unique_pixels = true;  // pixels are consecutive ints [0,size]
  const int_tp label = 0;
  const int_tp channels = 3;
  const int_tp height = 4;
  const int_tp width = 5;
  const int_tp size = channels * height * width;

  // Create a mean file
  string* mean_file = new string();
  MakeTempFilename(mean_file);
  BlobProto blob_mean;
  blob_mean.set_num(1);
  blob_mean.set_channels(channels);
  blob_mean.set_height(height);
  blob_mean.set_width(width);

  for (int_tp j = 0; j < size; ++j) {
      blob_mean.add_data(j);
  }

  LOG(INFO) << "Using temporary mean_file " << *mean_file;
  WriteProtoToBinaryFile(blob_mean, *mean_file);

  transform_param.set_mean_file(*mean_file);
  Datum datum;
  FillDatum(label, channels, height, width, unique_pixels, &datum);
  Blob<TypeParam>* blob = new Blob<TypeParam>(1, channels, height, width);
  DataTransformer<TypeParam>* transformer =
      new DataTransformer<TypeParam>(transform_param, TEST,
                                     Caffe::GetDefaultDevice());
  transformer->InitRand();
  transformer->Transform(datum, blob);
  for (int_tp j = 0; j < blob->count(); ++j) {
      EXPECT_EQ(blob->cpu_data()[j], 0);
  }
}
Пример #9
0
bool RageFileObjDirect::OpenInternal( const CString &sPath, int iMode, int &iError )
{
	m_sPath = sPath;
	m_iMode = iMode;

	if( iMode & RageFile::READ )
	{
		m_iFD = DoOpen( sPath, O_BINARY|O_RDONLY, 0666 );
		/* XXX: Windows returns EACCES if we try to open a file on a CDROM that isn't
		 * ready, instead of something like ENODEV.  We want to return that case as
		 * ENOENT, but we can't distinguish it from file permission errors. */
	}
	else
	{
		CString sOut;
		/* open a temporary file if we're not streaming */
		if( iMode & RageFile::STREAMED )
			sOut = sPath;
		else
			sOut = MakeTempFilename(sPath);

		/* Open a temporary file for writing. */
		m_iFD = DoOpen( sOut, O_BINARY|O_WRONLY|O_CREAT|O_TRUNC, 0666 );
	}

	if( m_iFD == -1 )
	{
		iError = errno;
		return false;
	}

	/* enable the write buffer if we're writing data */
	if( iMode & RageFile::WRITE )
		this->EnableWriteBuffering( BUFFER_SIZE );

	return true;
}
Пример #10
0
TYPED_TEST(DataTransformTest, TestMeanFile) {
    TransformationParameter transform_param;
    const bool unique_pixels = true;  // pixels are consecutive ints [0,size]
    const int label = 0;
    const int channels = 3;
    const int height = 4;
    const int width = 5;
    const int size = channels * height * width;

    // Create a mean file
    string mean_file;
    MakeTempFilename(&mean_file);
    BlobProto blob_mean;
    blob_mean.set_num(1);
    blob_mean.set_channels(channels);
    blob_mean.set_height(height);
    blob_mean.set_width(width);

    for (int j = 0; j < size; ++j) {
        blob_mean.add_data(j);
    }

    LOG(INFO) << "Using temporary mean_file " << mean_file;
    WriteProtoToBinaryFile(blob_mean, mean_file);

    transform_param.set_mean_file(mean_file);
    Datum datum;
    FillDatum(label, channels, height, width, unique_pixels, &datum);
    Blob<TypeParam> blob(1, channels, height, width);
    DataTransformer<TypeParam> transformer(transform_param, TEST);
    transformer.InitRand();
    transformer.Transform(datum, &blob);
    for (int j = 0; j < blob.count(); ++j) {
        EXPECT_EQ(blob.cpu_data()[j], 0);
    }
}
Пример #11
0
bool C4StartupNetDlg::DoOK()
{
	// OK in chat mode? Forward to chat control
	if (GetDlgMode() == SNDM_Chat) return pChatCtrl->DlgEnter();
	// OK on editbox with text enetered: Add the specified IP for reference retrieval
	if (GetFocus() == pJoinAddressEdt)
	{
		const char *szDirectJoinAddress = pJoinAddressEdt->GetText();
		if (szDirectJoinAddress && *szDirectJoinAddress)
		{
			// First do some acrobatics to avoid trying to resolve addresses with leading
			// or trailing whitespace, which is easily pasted in with an IP address.
			// We can trivially skip whitespace at the beginning, but we need a copy to
			// omit whitespace at the end.
			while (std::isspace(*szDirectJoinAddress))
				// skip whitespace at the beginning
				++szDirectJoinAddress;
			if (!*szDirectJoinAddress)
				// entry empty, apart from whitespace
				return true;
			const char *szDirectJoinAddressEnd = szDirectJoinAddress + std::strlen(szDirectJoinAddress) - 1;
			while (std::isspace(*szDirectJoinAddressEnd))
				// skip whitespace at the end
				--szDirectJoinAddressEnd;
			if (*++szDirectJoinAddressEnd)
			{
				// Make a temporary copy of the part that is not trailing whitespace, if any
				std::string strDirectJoinAddressStripped(szDirectJoinAddress, szDirectJoinAddressEnd - szDirectJoinAddress);
				AddReferenceQuery(strDirectJoinAddressStripped.c_str(), C4StartupNetListEntry::NRQT_DirectJoin);
			}
			else
				AddReferenceQuery(szDirectJoinAddress, C4StartupNetListEntry::NRQT_DirectJoin);
			// Switch focus to list so another OK joins the specified address
			SetFocus(pGameSelList, true);
			return true;
		}
	}
	if (GetFocus() == pSearchFieldEdt)
	{
		UpdateList();
		return true;
	}
	// get currently selected item
	C4GUI::Element *pSelection = pGameSelList->GetSelectedItem();
	StdCopyStrBuf strNoJoin(LoadResStr("IDS_NET_NOJOIN"));
	if (!pSelection)
	{
		// no ref selected: Oh noes!
		::pGUI->ShowMessageModal(
		  LoadResStr("IDS_NET_NOJOIN_NOREF"),
		  strNoJoin.getData(),
		  C4GUI::MessageDialog::btnOK,
		  C4GUI::Ico_Error);
		return true;
	}
	C4StartupNetListEntry *pRefEntry = static_cast<C4StartupNetListEntry *>(pSelection);
	const char *szError;
	if ((szError = pRefEntry->GetError()))
	{
		// erroneous ref selected: Oh noes!
		::pGUI->ShowMessageModal(
		  FormatString(LoadResStr("IDS_NET_NOJOIN_BADREF"), szError).getData(),
		  strNoJoin.getData(),
		  C4GUI::MessageDialog::btnOK,
		  C4GUI::Ico_Error);
		return true;
	}
	C4Network2Reference *pRef = pRefEntry->GetReference();
	const char *szDirectJoinAddress = pRefEntry->GetJoinAddress();
	if (!pRef && !(szDirectJoinAddress && *szDirectJoinAddress))
	{
		// something strange has been selected (e.g., a masterserver entry). Error.
		::pGUI->ShowMessageModal(
		  LoadResStr("IDS_NET_NOJOIN_NOREF"),
		  strNoJoin.getData(),
		  C4GUI::MessageDialog::btnOK,
		  C4GUI::Ico_Error);
		return true;
	}
	// check if join to this reference is possible at all
	if (pRef)
	{
		// version mismatch
		C4GameVersion verThis;
		if (!(pRef->getGameVersion() == verThis))
		{
			::pGUI->ShowMessageModal(
			  FormatString(LoadResStr("IDS_NET_NOJOIN_BADVER"),
			               pRef->getGameVersion().GetString().getData(),
			               verThis.GetString().getData()).getData(),
			  strNoJoin.getData(),
			  C4GUI::MessageDialog::btnOK,
			  C4GUI::Ico_Error);
			return true;
		}
		if (pRef->getGameStatus().isPastLobby())
		{
			// no runtime join
			if (!pRef->isJoinAllowed())
			{
				if (!::pGUI->ShowMessageModal(
					  LoadResStr("IDS_NET_NOJOIN_NORUNTIME"),
					  strNoJoin.getData(),
					  C4GUI::MessageDialog::btnYes | C4GUI::MessageDialog::btnNo,
					  C4GUI::Ico_Error))
				{
					return true;
				}
			}
			else
			{
				if (!::pGUI->ShowMessageModal(
					  LoadResStr("IDS_NET_NOJOIN_RUNTIMEBROKEN"),
					  strNoJoin.getData(),
					  C4GUI::MessageDialog::btnYes | C4GUI::MessageDialog::btnNo,
					  C4GUI::Ico_Error))
				{
					return true;
				}
			}
		}
	}
	// OK; joining!
	if (pRef->isEditor())
	{
		bool success = false;
		// Editor mode join: Serialize reference to temp file and join on that
		// (could pass through environment, but that's hard to do platform-independent
		// (QProcessEnvironment? But then there's a Qt dependency in the network init code))
		StdStrBuf tmpfn(Config.AtTempPath("ocjoin"), true);
		MakeTempFilename(&tmpfn);
		StdStrBuf join_data = DecompileToBuf<StdCompilerINIWrite>(mkNamingAdapt(*pRef, "Reference"));
		if (join_data.getSize())
		{
			if (join_data.SaveToFile(tmpfn.getData()))
			{
				if (RestartApplication({"--editor", FormatString("--join=%s%s", C4Game::DirectJoinFilePrefix, tmpfn.getData()).getData()})) // hope for no " in temp path
				{
					// Application.Quit() has been called. Will quit after returning from this callback.
					// The temp file will be deleted by the new instance
					success = true;
				}
				else
				{
					EraseFile(tmpfn.getData());
				}
			}
		}
		if (!success)
		{
			C4GUI::TheScreen.ShowErrorMessage(LoadResStr("IDS_ERR_STARTEDITOR"));
		}
		return true;
	}
	else
	{
		// Player mode join
		// Take over reference
		pRefEntry->GrabReference();
		// Set join parameters
		*Game.ScenarioFilename = '\0';
		if (szDirectJoinAddress) SCopy(szDirectJoinAddress, Game.DirectJoinAddress, _MAX_PATH); else *Game.DirectJoinAddress = '\0';
		SCopy("Objects.ocd", Game.DefinitionFilenames);
		Game.NetworkActive = true;
		Game.fObserve = false;
		Game.pJoinReference.reset(pRef);
		// start with this set!
		Application.OpenGame();
		return true;
	}
}
Пример #12
0
BOOL C4UpdatePackage::DoUpdate(C4Group *pGrpFrom, C4GroupEx *pGrpTo,
                               const char *strFileName) {
    // group file?
    C4Group ItemGroupFrom;
    if (ItemGroupFrom.OpenAsChild(pGrpFrom, strFileName)) {
        // try to open target group
        C4GroupEx ItemGroupTo;
        char strTempGroup[_MAX_PATH + 1];
        strTempGroup[0] = 0;
        if (!ItemGroupTo.OpenAsChild(pGrpTo, strFileName)) {
            // create (emtpy) temp dir
            //			SCopy(GetCfg()->AtExePath("~tmp"), strTempGroup,
            //_MAX_PATH);
            MakeTempFilename(strTempGroup);
            // open/create it
            if (!ItemGroupTo.Open(strTempGroup, TRUE)) return FALSE;
        }
        // update children
        char ItemFileName[_MAX_PATH];
        ItemGroupFrom.ResetSearch();
        while (ItemGroupFrom.FindNextEntry("*", ItemFileName))
            if (!SEqual(ItemFileName, C4CFN_UpdateCore) &&
                    !SEqual(ItemFileName, C4CFN_UpdateEntries))
                DoUpdate(&ItemGroupFrom, &ItemGroupTo, ItemFileName);
        // set maker (always)
        ItemGroupTo.SetMaker(ItemGroupFrom.GetMaker());
        if (GrpUpdate) {
            DoGrpUpdate(&ItemGroupFrom, &ItemGroupTo);
            // write group (do not change any headers set by DoGrpUpdate!)
            ItemGroupTo.Close(FALSE);
            // temporary group?
            if (strTempGroup[0])
                if (!pGrpTo->Move(strTempGroup, strFileName)) return FALSE;
            // set core (C4Group::Save overwrites it)
            pGrpTo->SaveEntryCore(*pGrpFrom, strFileName);
            pGrpTo->SetSavedEntryCore(strFileName);
            // flag as no-resort
            pGrpTo->SetNoSort(strFileName);
        } else {
            // write group
            ItemGroupTo.Close(TRUE);
            // temporary group?
            if (strTempGroup[0])
                if (!pGrpTo->Move(strTempGroup, strFileName)) return FALSE;
        }
    } else {
        char strMsg[1024];
        sprintf(strMsg, "updating %s\\%s\n", pGrpTo->GetFullName().getData(),
                strFileName);
#ifdef _MSC_VER
        OutputDebugString(strMsg);
#elif _DEBUG
        puts(strMsg);
#endif
        if (!C4Group_CopyEntry(pGrpFrom, pGrpTo, strFileName)) return FALSE;
        // set core
        pGrpTo->SaveEntryCore(*pGrpFrom, strFileName);
        pGrpTo->SetSavedEntryCore(strFileName);
    }
    // ok
    return TRUE;
}
Пример #13
0
//----------------------------------------------------------------------------------------------
// PSG offset (small freq value, volume on) remover
// Returns number of offsets removed
//----------------------------------------------------------------------------------------------
int RemoveOffset(char *filename) {
  gzFile *in,*out;
  char *outfilename;
  struct TVGMHeader VGMHeader;
  signed int b0,b1,b2;
  BOOL SilencedChannels[3]={FALSE,FALSE,FALSE};
  unsigned short int PSGRegisters[8] = {0,0xf,0,0xf,0,0xf,0,0xf};
  int PSGLatchedRegister=0;

  long int NewLoopOffset=0;
  int NumOffsetsRemoved=0;
  int NoiseCh2=0;

  if (!FileExists(filename)) return 0;

  in=gzopen(filename,"rb");

  // Read header
  if(!ReadVGMHeader(in,&VGMHeader,FALSE)) {
    gzclose(in);
	return FALSE;
  }

  gzseek(in,VGM_DATA_OFFSET,SEEK_SET);

  outfilename=MakeTempFilename(filename);

  out=gzopen(outfilename,"wb0");  // No compression, since I'll recompress it later

  // copy header... update it later
  gzwrite(out,&VGMHeader,sizeof(VGMHeader));
  gzseek(out,VGM_DATA_OFFSET,SEEK_SET);

  // Process file
  do {
    if ((VGMHeader.LoopOffset) && (gztell(in)==VGMHeader.LoopOffset+LOOPDELTA)) NewLoopOffset=gztell(out)-LOOPDELTA;
    b0=gzgetc(in);
    switch (b0) {
    case VGM_GGST:  // GG stereo (1 byte data)
      // Just pass it through
      b1=gzgetc(in);
      gzputc(out,VGM_GGST);
      gzputc(out,b1);
      break;
    case VGM_PSG:  // PSG write (1 byte data)
      b1=gzgetc(in);

      if (b1&0x80) {
        // Latch/data byte   %1 cc t dddd
        PSGLatchedRegister=((b1>>4)&0x07);
        PSGRegisters[PSGLatchedRegister]=
          (PSGRegisters[PSGLatchedRegister] & 0x3f0)  // zero low 4 bits
          | (b1&0xf);                  // and replace with data
      } else {
        // Data byte
        if (!(PSGLatchedRegister%2)&&(PSGLatchedRegister<5))
          // Tone register
          PSGRegisters[PSGLatchedRegister]=
            (PSGRegisters[PSGLatchedRegister] & 0x00f)  // zero high 6 bits
            | ((b1&0x3f)<<4);              // and replace with data
        else
          // Other register
          PSGRegisters[PSGLatchedRegister]=b1&0x0f;    // Replace with data
      }
      // Analyse:
      switch (PSGLatchedRegister) {
      case 0:
      case 2:
      case 4:    // Tone registers
        if ((PSGRegisters[PSGLatchedRegister]<PSGCutoff) &&  // If freq is too low
          !((PSGLatchedRegister==4)&&NoiseCh2)               // and it's not tone2 controlling noise
		  ) {                                                // then silence that channel
          if (!SilencedChannels[PSGLatchedRegister/2]) {  // If channel hasn't already been silenced
              ++NumOffsetsRemoved;
              gzputc(out,VGM_PSG);
              gzputc(out,(char)(
                0x9f|                // %10011111
                (PSGLatchedRegister&0x6)<<4)    // %0cc00000
              );
              // Remember I've done it
              SilencedChannels[PSGLatchedRegister/2]=TRUE;
              // Output zero frequency
              gzputc(out,VGM_PSG);
              gzputc(out,(char)(0x80|(PSGLatchedRegister<<4)));
              gzputc(out,VGM_PSG);
              gzputc(out,0);
          }
        } else {  // Channel shouldn't be silent
          if (SilencedChannels[PSGLatchedRegister/2]) {  // If I've previously silenced this channel
            // then restore the volume
            gzputc(out,VGM_PSG);
            gzputc(out,(char)(
              0x90|                // %10010000
              (PSGLatchedRegister&0x6)<<4)|    // %0cc00000
              PSGRegisters[PSGLatchedRegister+1]  // %0000vvvv
            );
            SilencedChannels[PSGLatchedRegister/2]=FALSE;
          }
          // Write the frequency bytes
          gzputc(out,VGM_PSG);
          gzputc(out,(char)(0x80|(PSGLatchedRegister<<4)|PSGRegisters[PSGLatchedRegister]&0xf));
          gzputc(out,VGM_PSG);
          gzputc(out,(char)(PSGRegisters[PSGLatchedRegister]>>4));
        }
        break;
      case 6:    // Noise
        // Detect if it's ch2 noise
        NoiseCh2=((PSGRegisters[6]&0x3)==0x3);
        // Pass through
        gzputc(out,VGM_PSG);
        gzputc(out,b1);
        break;
      default:  // Volume
        if ((PSGLatchedRegister/2<3) &&        // Tone channel
          SilencedChannels[PSGLatchedRegister/2])  // Silenced
          break;                  // Don't write
        // Pass through
        gzputc(out,VGM_PSG);
        gzputc(out,b1);
        break;
      } // end switch
      break;
    case VGM_YM2413:  // YM2413
    case VGM_YM2612_0:  // YM2612 port 0
    case VGM_YM2612_1:  // YM2612 port 1
    case VGM_YM2151:  // YM2151
    case 0x55:  // Reserved up to 0x5f
    case 0x56:  // All have 2 bytes of data
    case 0x57:
    case 0x58:
    case 0x59:
    case 0x5a:
    case 0x5b:
    case 0x5c:
    case 0x5d:
    case 0x5e:
    case 0x5f:
      b1=gzgetc(in);
      b2=gzgetc(in);
      gzputc(out,b0);
      gzputc(out,b1);
      gzputc(out,b2);
      break;
    case VGM_PAUSE_WORD:  // Wait n samples
      b1=gzgetc(in);
      b2=gzgetc(in);
      gzputc(out,VGM_PAUSE_WORD);
      gzputc(out,b1);
      gzputc(out,b2);
      break;
    case VGM_PAUSE_60TH:  // Wait 1/60 s
      gzputc(out,VGM_PAUSE_60TH);
      break;
    case VGM_PAUSE_50TH:  // Wait 1/50 s
      gzputc(out,VGM_PAUSE_50TH);
      break;
//    case VGM_PAUSE_BYTE:  // Wait n samples
//      b1=gzgetc(in);
//      gzputc(out,VGM_PAUSE_BYTE);
//      gzputc(out,b1);
//      break;
    case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77:
    case 0x78: case 0x79: case 0x7a: case 0x7b: case 0x7c: case 0x7d: case 0x7e: case 0x7f: // Wait 1-16 samples
      gzputc(out,b0);
      break;
    case VGM_END:  // End of sound data
      gzputc(out,VGM_END);
      break;
    default:
      break;
    }
Пример #14
0
//----------------------------------------------------------------------------------------------
// Pause optimiser
//----------------------------------------------------------------------------------------------
BOOL OptimiseVGMPauses(char *filename) {
  gzFile *in,*out;
  struct TVGMHeader VGMHeader;
  char *outfilename,b0,b1,b2;
  long int OldLoopOffset;
  int i,PauseLength=0;

  if (!FileExists(filename)) return FALSE;

  // Open input file
  in=gzopen(filename,"rb");

  // Read its VGM header
  if(!ReadVGMHeader(in,&VGMHeader,FALSE)) {
    gzclose(in);
	return FALSE;
  }

  OldLoopOffset=VGMHeader.LoopOffset+LOOPDELTA;

  // Make the output filename...
  outfilename=MakeTempFilename(filename);
  
  // ...open it...
  out=gzopen(outfilename,"wb0");

  // ...skip to the data section...
  gzseek(in,VGM_DATA_OFFSET,SEEK_SET);
  gzseek(out,VGM_DATA_OFFSET,SEEK_SET);

  // ...and parse the input file
  // Go through the file; if it's a pause, add it to the total; if it's data, write the current total and zero it
  do {
    // Update loop point
    // Write any remaining pauyse being buffered first, though
    if (gztell(in)==OldLoopOffset) {
      WritePause(out,PauseLength);
      PauseLength=0;
      VGMHeader.LoopOffset=gztell(out)-LOOPDELTA;
    }

    b0=gzgetc(in);
    switch (b0) {
    case VGM_GGST:  // GG stereo
    case VGM_PSG:  // PSG write
      WritePause(out,PauseLength);
      PauseLength=0;
      b1=gzgetc(in);
      gzputc(out,b0);
      gzputc(out,b1);
      break;
    case VGM_YM2413:  // YM2413
    case VGM_YM2612_0:  // YM2612 port 0
    case VGM_YM2612_1:  // YM2612 port 1
    case VGM_YM2151:  // YM2151
    case 0x55:  // Reserved up to 0x5f
    case 0x56:  // All have 2 bytes of data
    case 0x57:
    case 0x58:
    case 0x59:
    case 0x5a:
    case 0x5b:
    case 0x5c:
    case 0x5d:
    case 0x5e:
    case 0x5f:
      WritePause(out,PauseLength);
      PauseLength=0;
      b1=gzgetc(in);
      b2=gzgetc(in);
      gzputc(out,b0);
      gzputc(out,b1);
      gzputc(out,b2);
      break;
    case VGM_PAUSE_WORD:  // Wait n samples
      b1=gzgetc(in);
      b2=gzgetc(in);
      PauseLength+=MAKEWORD(b1,b2);
      break;
    case VGM_PAUSE_60TH:  // Wait 1/60 s
      PauseLength+=LEN60TH;
      break;
    case VGM_PAUSE_50TH:  // Wait 1/50 s
      PauseLength+=LEN50TH;
      break;
//    case VGM_PAUSE_BYTE:  // Wait n samples
//      b1=gzgetc(in);
//      PauseLength+=b1;
//      break;
    case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77:
    case 0x78: case 0x79: case 0x7a: case 0x7b: case 0x7c: case 0x7d: case 0x7e: case 0x7f: // Wait 1-16 samples
      PauseLength+=(b0 & 0xf)+1;
      break;
    case VGM_END:  // End of sound data
      WritePause(out,PauseLength);
      PauseLength=0;
      b0=EOF;  // break out of loop
      break;
    default:
      break;
    }  // end switch
  } while (b0!=EOF);

  // At end:
  // 1. Write EOF mrker
  gzputc(out,VGM_END);
  // 2. Copy GD3 tag
  if (VGMHeader.GD3Offset) {
    struct TGD3Header GD3Header;
    int NewGD3Offset=gztell(out)-GD3DELTA;
    gzseek(in,VGMHeader.GD3Offset+GD3DELTA,SEEK_SET);
    gzread(in,&GD3Header,sizeof(GD3Header));
    gzwrite(out,&GD3Header,sizeof(GD3Header));
    for (i=0; i<GD3Header.Length; ++i) gzputc(out,gzgetc(in));
    VGMHeader.GD3Offset=NewGD3Offset;
  }
  // 3. Fill in VGM header
  VGMHeader.EoFOffset=gztell(out)-EOFDELTA;
  // LoopOffset updated while optimising

  gzclose(out);

  WriteVGMHeader(outfilename,VGMHeader);

  // Clean up
  gzclose(in);

  ReplaceFile(filename,outfilename);

  free(outfilename);

  return TRUE;
}
RageFileObjDirect::~RageFileObjDirect()
{
	bool bFailed = !FinalFlush();
	
	if( m_iFD != -1 )
	{
		if( close( m_iFD ) == -1 )
		{
			WARN( ssprintf("Error closing %s: %s", this->m_sPath.c_str(), strerror(errno)) );
			SetError( strerror(errno) );
			bFailed = true;
		}
	}

	if( !(m_iMode & RageFile::WRITE) || (m_iMode & RageFile::STREAMED) )
		return;

	/* We now have path written to MakeTempFilename(m_sPath).
	 * Rename the temporary file over the real path. */

	do
	{
		if( bFailed || WriteFailed() )
			break;

		/* We now have path written to MakeTempFilename(m_sPath). Rename the
		 * temporary file over the real path. This should be an atomic operation
		 * with a journalling filesystem. That is, there should be no
		 * intermediate state a JFS might restore the file we're writing (in the
		 * case of a crash/powerdown) to an empty or partial file. */

		RString sOldPath = MakeTempFilename(m_sPath);
		RString sNewPath = m_sPath;

#if defined(WIN32)
		if( WinMoveFile(DoPathReplace(sOldPath), DoPathReplace(sNewPath)) )
			return;

		/* We failed. */
		int err = GetLastError();
		const RString error = werr_ssprintf( err, "Error renaming \"%s\" to \"%s\"", sOldPath.c_str(), sNewPath.c_str() );
		WARN( ssprintf("%s", error.c_str()) );
		SetError( error );
		break;
#else
		if( rename( sOldPath, sNewPath ) == -1 )
		{
			WARN( ssprintf("Error renaming \"%s\" to \"%s\": %s", 
					sOldPath.c_str(), sNewPath.c_str(), strerror(errno)) );
			SetError( strerror(errno) );
			break;
		}


		if( m_iMode & RageFile::SLOW_FLUSH )
		{
			RString sError;
			if( !FlushDir(Dirname(m_sPath), sError) )
			{
				WARN( ssprintf("Error synchronizing fsync(%s dir): %s", this->m_sPath.c_str(), sError.c_str()) );
				SetError( sError );
			}
		}

		// Success.
		return;
#endif
	} while(0);

	// The write or the rename failed. Delete the incomplete temporary file.
	DoRemove( MakeTempFilename(m_sPath) );
}
Пример #16
0
BOOL C4UpdatePackage::MkUp(C4Group *pGrp1, C4Group *pGrp2, C4GroupEx *pUpGrp,
                           BOOL *fModified) {
    // (CAUTION: pGrp1 may be NULL - that means that there is no counterpart for
    // Grp2
    //           in the base group)

    // compare headers
    if (!pGrp1 || pGrp1->GetCreation() != pGrp2->GetCreation() ||
            pGrp1->GetOriginal() != pGrp2->GetOriginal() ||
            !SEqual(pGrp1->GetMaker(), pGrp2->GetMaker()) ||
            !SEqual(pGrp1->GetPassword(), pGrp2->GetPassword()))
        *fModified = TRUE;
    // set header
    pUpGrp->SetHead(*pGrp2);
    // compare entries
    char strItemName[_MAX_PATH], strItemName2[_MAX_PATH];
    StdStrBuf EntryList;
    strItemName[0] = strItemName2[0] = 0;
    pGrp2->ResetSearch();
    if (!*fModified) pGrp1->ResetSearch();
    int iChangedEntries = 0;
    while (pGrp2->FindNextEntry("*", strItemName, NULL, NULL, !!strItemName[0])) {
        // add to entry list
        if (!!EntryList) EntryList.AppendChar('|');
        EntryList.AppendFormat("%s=%d", strItemName, pGrp2->EntryTime(strItemName));
        // no modification detected yet? then check order
        if (!*fModified) {
            if (!pGrp1->FindNextEntry("*", strItemName2, NULL, NULL,
                                      !!strItemName2[0]))
                *fModified = TRUE;
            else if (!SEqual(strItemName, strItemName2))
                *fModified = TRUE;
        }

        // TODO: write DeleteEntries.txt

        // a child group?
        C4GroupEx ChildGrp2;
        if (ChildGrp2.OpenAsChild(pGrp2, strItemName)) {
            // open in Grp1
            C4Group *pChildGrp1 = new C4GroupEx();
            if (!pGrp1 || !pChildGrp1->OpenAsChild(pGrp1, strItemName)) {
                delete pChildGrp1;
                pChildGrp1 = NULL;
            }
            // open group for update data
            C4GroupEx UpdGroup;
            char strTempGroupName[_MAX_FNAME + 1];
            strTempGroupName[0] = 0;
            if (!UpdGroup.OpenAsChild(pUpGrp, strItemName)) {
                // create new group (may be temporary)
                // SCopy(GetCfg()->AtTempPath("~upd"), strTempGroupName, _MAX_FNAME);
                MakeTempFilename(strTempGroupName);
                if (!UpdGroup.Open(strTempGroupName, TRUE)) {
                    delete pChildGrp1;
                    WriteLog("Error: could not create temp group\n");
                    return FALSE;
                }
            }
            // do nested MkUp-search
            BOOL Modified = FALSE;
            BOOL fSuccess = MkUp(pChildGrp1, &ChildGrp2, &UpdGroup, &Modified);
            // sort & close
            extern const char **C4Group_SortList;
            UpdGroup.SortByList(C4Group_SortList, ChildGrp2.GetName());
            UpdGroup.Close(FALSE);
            // check entry times
            if (!pGrp1 ||
                    (pGrp1->EntryTime(strItemName) != pGrp2->EntryTime(strItemName)))
                Modified = TRUE;
            // add group (if modified)
            if (fSuccess && Modified) {
                if (strTempGroupName[0])
                    if (!pUpGrp->Move(strTempGroupName, strItemName)) {
                        WriteLog("Error: could not add modified group\n");
                        return FALSE;
                    }
                // copy core
                pUpGrp->SaveEntryCore(*pGrp2, strItemName);
                pUpGrp->SetSavedEntryCore(strItemName);
                // got a modification in a subgroup
                *fModified = TRUE;
                iChangedEntries++;
            } else
                // delete group (do not remove groups that existed before!)
                if (strTempGroupName[0])
                    if (remove(strTempGroupName))
                        if (rmdir(strTempGroupName)) {
                            WriteLog("Error: could not delete temporary directory\n");
                            return FALSE;
                        }
            delete pChildGrp1;
        } else {
            // compare them (size & crc32)
            if (!pGrp1 ||
                    pGrp1->EntrySize(strItemName) != pGrp2->EntrySize(strItemName) ||
                    pGrp1->EntryCRC32(strItemName) != pGrp2->EntryCRC32(strItemName)) {
                BOOL fCopied = FALSE;

                // save core (EntryCRC32 might set additional fields)
                pUpGrp->SaveEntryCore(*pGrp2, strItemName);

                // already in update grp?
                if (pUpGrp->EntryTime(strItemName) != pGrp2->EntryTime(strItemName) ||
                        pUpGrp->EntrySize(strItemName) != pGrp2->EntrySize(strItemName) ||
                        pUpGrp->EntryCRC32(strItemName) != pGrp2->EntryCRC32(strItemName)) {
                    // copy it
                    if (!C4Group_CopyEntry(pGrp2, pUpGrp, strItemName)) {
                        WriteLog("Error: could not add changed entry to update group\n");
                        return FALSE;
                    }
                    // set entry core
                    pUpGrp->SetSavedEntryCore(strItemName);
                    // modified...
                    *fModified = TRUE;
                    fCopied = TRUE;
                }
                iChangedEntries++;

                WriteLog("%s\\%s: update%s\n", pGrp2->GetFullName().getData(),
                         strItemName, fCopied ? "" : " (already in group)");
            }
        }
    }
    // write entries list (always)
    if (!pUpGrp->Add(C4CFN_UpdateEntries, EntryList, FALSE, TRUE)) {
        WriteLog("Error: could not save entry list!");
        return FALSE;
    }

    if (iChangedEntries > 0)
        WriteLog("%s: %d/%d changed (%s)\n", pGrp2->GetFullName().getData(),
                 iChangedEntries, pGrp2->EntryCount(),
                 *fModified ? "update" : "skip");

    // success
    return TRUE;
}
Пример #17
0
bool C4Playback::StreamToRecord(const char *szStream, StdStrBuf *pRecordFile) {
  // Load data
  StdBuf CompressedData;
  Log("Reading stream...");
  if (!CompressedData.LoadFromFile(szStream)) return false;

  // Decompress
  unsigned long iStreamSize = CompressedData.getSize() * 5;
  StdBuf StreamData;
  StreamData.New(iStreamSize);
  while (true) {
    // Initialize stream
    z_stream strm;
    ZeroMem(&strm, sizeof strm);
    strm.next_in = getMBufPtr<BYTE>(CompressedData);
    strm.avail_in = CompressedData.getSize();
    strm.next_out = getMBufPtr<BYTE>(StreamData);
    strm.avail_out = StreamData.getSize();

    // Decompress
    if (inflateInit(&strm) != Z_OK) return false;
    int ret = inflate(&strm, Z_FINISH);
    if (ret == Z_STREAM_END) {
      inflateEnd(&strm);
      break;
    }
    if (ret != Z_BUF_ERROR) return false;

    // All input consumed?
    iStreamSize = strm.total_out;
    if (strm.avail_in == 0) {
      Log("Stream data incomplete, using as much data as possible");
      break;
    }

    // Larger buffer needed
    StreamData.Grow(CompressedData.getSize());
    iStreamSize = StreamData.getSize();
  }
  StreamData.SetSize(iStreamSize);

  // Parse
  C4Playback Playback;
  Playback.ReadBinary(StreamData);
  LogF("Got %d chunks from stream", Playback.chunks.size());

  // Get first chunk, which must contain the initial
  chunks_t::iterator chunkIter = Playback.chunks.begin();
  if (chunkIter == Playback.chunks.end() || chunkIter->Type != RCT_File)
    return false;

  // Get initial chunk, go over file name
  StdBuf InitialData = *chunkIter->pFileData;
  const char *szInitialFilename = chunkIter->Filename.getData();

  // Put to temporary file and unpack
  char szInitial[_MAX_PATH + 1] = "~initial.tmp";
  MakeTempFilename(szInitial);
  if (!InitialData.SaveToFile(szInitial) || !C4Group_UnpackDirectory(szInitial))
    return false;

  // Load Scenario.txt from Initial
  C4Group Grp;
  C4Scenario Initial;
  if (!Grp.Open(szInitial) || !Initial.Load(Grp) || !Grp.Close()) return false;

  // Copy original scenario
  const char *szOrigin = Initial.Head.Origin.getData();
  char szRecord[_MAX_PATH + 1];
  SCopy(szStream, szRecord, _MAX_PATH);
  if (GetExtension(szRecord)) *(GetExtension(szRecord) - 1) = 0;
  SAppend(".c4s", szRecord, _MAX_PATH);
  LogF("Original scenario is %s, creating %s.", szOrigin, szRecord);
  if (!C4Group_CopyItem(szOrigin, szRecord, false, false)) return false;

  // Merge initial
  if (!Grp.Open(szRecord) || !Grp.Merge(szInitial)) return false;

  // Process other files in stream
  chunkIter->Delete();
  chunkIter = Playback.chunks.erase(chunkIter);
  while (chunkIter != Playback.chunks.end())
    if (chunkIter->Type == RCT_File) {
      LogF("Inserting %s...", chunkIter->Filename.getData());
      StdStrBuf Temp;
      Temp.Copy(chunkIter->Filename);
      MakeTempFilename(&Temp);
      if (!chunkIter->pFileData->SaveToFile(Temp.getData())) return false;
      if (!Grp.Move(Temp.getData(), chunkIter->Filename.getData()))
        return false;
      chunkIter = Playback.chunks.erase(chunkIter);
    } else
      chunkIter++;

  // Write record data
  StdBuf RecordData = Playback.ReWriteBinary();
  if (!Grp.Add(C4CFN_CtrlRec, RecordData, false, true)) return false;

  // Done
  Log("Writing record file...");
  Grp.Close();
  pRecordFile->Copy(szRecord);
  return true;
}