protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pXsfRecompressDataStruct, DoWorkEventArgs e) { XsfRecompressDataStruct xsfRecompressDataStruct = (XsfRecompressDataStruct)pXsfRecompressDataStruct; XsfRecompressStruct xsfRecompressStruct = new XsfRecompressStruct(); xsfRecompressStruct.CompressionLevel = xsfRecompressDataStruct.CompressionLevel; string outputPath = XsfUtil.ReCompressDataSection(pPath, xsfRecompressStruct); }
protected override void OnDoWork(DoWorkEventArgs e) { if (XsfUtil.IsPythonPresentInPath()) { base.OnDoWork(e); } else { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = "ERROR: A directory containing the Python Interpreter (python.exe) cannot be found in your PATH environment variable."; ReportProgress(0, this.progressStruct); } }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pEasyPsfDriverExtractionStruct, DoWorkEventArgs e) { byte[] initialProgramCounter; uint initialProgramCounterValue; uint pcOffsetSeq; uint pcOffsetVb; uint pcOffsetVh; uint lengthSeq; uint lengthVb; uint lengthVh; byte[] vhNumberOfPrograms; UInt16 vhNumberOfProgramsValue; Xsf2ExeStruct decompressionOptions = new Xsf2ExeStruct(); decompressionOptions.IncludeExtension = false; decompressionOptions.StripGsfHeader = false; string extractedDataSectionPath = XsfUtil.ExtractCompressedDataSection(pPath, decompressionOptions); if (!String.IsNullOrEmpty(extractedDataSectionPath)) { using (FileStream fs = File.OpenRead(extractedDataSectionPath)) { // get offset of initial program counter initialProgramCounter = ParseFile.ParseSimpleOffset(fs, 0x10, 4); initialProgramCounterValue = BitConverter.ToUInt32(initialProgramCounter, 0); pcOffsetSeq = initialProgramCounterValue - PC_OFFSET_CORRECTION; pcOffsetVb = BitConverter.ToUInt32(ParseFile.ParseSimpleOffset(fs, (long)(pcOffsetSeq - 4), 4), 0) - PC_OFFSET_CORRECTION; pcOffsetVh = BitConverter.ToUInt32(ParseFile.ParseSimpleOffset(fs, (long)(pcOffsetSeq - 8), 4), 0) - PC_OFFSET_CORRECTION; lengthSeq = pcOffsetVb - pcOffsetSeq; lengthVb = pcOffsetVh - pcOffsetVb; vhNumberOfPrograms = ParseFile.ParseSimpleOffset(fs, (long)(pcOffsetVh + 0x12), 2); vhNumberOfProgramsValue = BitConverter.ToUInt16(vhNumberOfPrograms, 0); lengthVh = (UInt16)((512 * vhNumberOfProgramsValue) + 2592); // extract files ParseFile.ExtractChunkToFile(fs, (long)pcOffsetSeq, (int)lengthSeq, Path.ChangeExtension(pPath, ".seq")); ParseFile.ExtractChunkToFile(fs, (long)pcOffsetVh, (int)lengthVh, Path.ChangeExtension(pPath, ".vh")); ParseFile.ExtractChunkToFile(fs, (long)pcOffsetVb, (int)lengthVb, Path.ChangeExtension(pPath, ".vb")); } // using (FileStream fs = File.OpenRead(pPath)) // delete extracted data File.Delete(extractedDataSectionPath); } // if (!String.IsNullOrEmpty(extractedDataSectionPath)) }
private void loadSelectedTrack() { string selectedFilePath; ListBoxFileInfoObject listBoxFile; if (lbFiles.SelectedIndices.Count == 1) { listBoxFile = (ListBoxFileInfoObject)(this.lbFiles.Items[this.lbFiles.SelectedIndex]); selectedFilePath = listBoxFile.FilePath; using (FileStream fs = File.Open(selectedFilePath, FileMode.Open, FileAccess.Read)) { Type formatType = FormatUtil.getObjectType(fs); if (formatType != null) { this.vgmData = (IXsfTagFormat)Activator.CreateInstance(formatType); this.vgmData.Initialize(fs, selectedFilePath); this.tbGame.Text = this.vgmData.GetGameTag(); this.tbArtist.Text = this.vgmData.GetArtistTag(); this.tbCopyright.Text = this.vgmData.GetCopyrightTag(); this.tbGenre.Text = this.vgmData.GetGenreTag(); this.tbYear.Text = this.vgmData.GetYearTag(); this.tbXsfBy.Text = this.vgmData.GetXsfByTag(); this.tbTagger.Text = this.vgmData.GetTaggerTag(); if (this.cbGenerateTitleFromFilename.Checked) { this.tbTitle.Text = XsfUtil.GetTitleForFileName(selectedFilePath, this.cbRemoveBrackets.Checked); } else { this.tbTitle.Text = this.vgmData.GetTitleTag(); } this.tbLength.Text = this.vgmData.GetLengthTag(); this.tbFade.Text = this.vgmData.GetFadeTag(); this.tbVolume.Text = this.vgmData.GetVolumeTag(); this.tbComments.Text = this.vgmData.GetCommentTag(); } } this.setTitleTagEnable(); } }
private void grpSourceFiles_DragDrop(object sender, DragEventArgs e) { // check for PsyQ in PATH if (!XsfUtil.IsPsyQPathVariablePresent()) { MessageBox.Show( ConfigurationManager.AppSettings["Form_PsfStubCreator_ErrPsyQPath"], ConfigurationManager.AppSettings["Form_Global_ErrorWindowTitle"]); } else if (!XsfUtil.IsPsyQSdkPresent()) { MessageBox.Show( ConfigurationManager.AppSettings["Form_PsfStubCreator_IntroText"], ConfigurationManager.AppSettings["Form_Global_ErrorWindowTitle"]); } else if (this.validateInputs()) { string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false); PsfStubMakerStruct bwStruct = new PsfStubMakerStruct(); bwStruct.SourcePaths = s; bwStruct.UseSeqFunctions = this.cbSeqFunctions.Checked; bwStruct.DriverText = this.tbDriverText.Text; bwStruct.IncludeReverb = this.cbIncludeReverb.Checked; bwStruct.PsfDrvLoad = this.tbPsfDrvLoad.Text; bwStruct.PsfDrvSize = this.tbPsfDrvSize.Text; bwStruct.PsfDrvParam = this.tbPsfDrvParam.Text; bwStruct.PsfDrvParamSize = this.tbPadDrvParamSize.Text; bwStruct.MySeq = this.tbMySeq.Text; bwStruct.MySeqSize = this.tbMySeqSize.Text; bwStruct.MyVh = this.tbMyVh.Text; bwStruct.MyVhSize = this.tbMyVhSize.Text; bwStruct.MyVb = this.tbMyVb.Text; bwStruct.MyVbSize = this.tbMyVbSize.Text; bwStruct.OverrideDriverLoadAddress = cbOverrideDriverOffset.Checked; bwStruct.RelaxLoadAddressRestriction = cbRelaxPsfLoadAddress.Checked; base.backgroundWorker_Execute(bwStruct); } }
private string getWarnings(PsfPsyQAddresses addresses) { PropertyInfo psyQValue; string lineValue; StringBuilder warnings = new StringBuilder(); foreach (string label in XsfUtil.GetPsyQFunctionList()) { psyQValue = addresses.GetType().GetProperty(label); lineValue = (string)psyQValue.GetValue(addresses, null); if (String.IsNullOrEmpty(lineValue)) { warnings.AppendFormat(" Warning: {0} function not found.{1}", label, Environment.NewLine); } } return(warnings.ToString()); }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pXsfCompressedProgramExtractorStruct, DoWorkEventArgs e) { XsfCompressedProgramExtractorStruct xsfCompressedProgramExtractorStruct = (XsfCompressedProgramExtractorStruct)pXsfCompressedProgramExtractorStruct; // Extract Compressed Data Xsf2ExeStruct xsf2ExeStruct = new Xsf2ExeStruct(); xsf2ExeStruct.IncludeExtension = xsfCompressedProgramExtractorStruct.includeExtension; xsf2ExeStruct.StripGsfHeader = xsfCompressedProgramExtractorStruct.stripGsfHeader; XsfUtil.ExtractCompressedDataSection(pPath, xsf2ExeStruct); // Extract Reserved Section if (xsfCompressedProgramExtractorStruct.extractReservedSection) { XsfUtil.ExtractReservedSection(pPath, xsf2ExeStruct); } }
private void time2sfs(Time2sfStruct pTime2sfStruct, DoWorkEventArgs e) { if (!CancellationPending) { string outputMessages; Time2sfStruct t = new Time2sfStruct(); t.Mini2sfDirectory = pTime2sfStruct.Mini2sfDirectory; t.SdatPath = pTime2sfStruct.SdatPath; t.DoSingleLoop = pTime2sfStruct.DoSingleLoop; try { XsfUtil.Time2sfFolder(t, out outputMessages); this.progressStruct.Clear(); if (!String.IsNullOrEmpty(outputMessages)) { this.progressStruct.ErrorMessage = String.Format("ERROR: {0}", outputMessages) + Environment.NewLine; } ReportProgress(100, this.progressStruct); } catch (Exception _e) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format("ERROR: {0}", _e.Message) + Environment.NewLine; ReportProgress(0, this.progressStruct); } } else { e.Cancel = true; return; } }
static void Main(string[] args) { string filename; string compressionLevel; int compressionLevelValue; string outputPath = null; XsfRecompressStruct xsfStruct; if ((args.Length < 1) || (args.Length > 2)) { usage(); } else { filename = Path.GetFullPath(args[0]); if (args.Length == 2) { compressionLevel = args[1]; } else { compressionLevel = "0"; } try { if (!int.TryParse(compressionLevel, out compressionLevelValue) || (compressionLevelValue > 9) || (compressionLevelValue < 0)) { Console.WriteLine(" Error parsing compression level. Input must be an integer between 0 and 9."); } else if (!File.Exists(filename)) { Console.WriteLine(String.Format(" Error: Input file cannot be found <{0}>", filename)); } else if (XsfUtil.GetXsfFormatString(filename) == null) { Console.WriteLine(" Error: Input file does not seem to be an xSF file."); } else { xsfStruct = new XsfRecompressStruct(); xsfStruct.CompressionLevel = compressionLevelValue; outputPath = XsfUtil.ReCompressDataSection(filename, xsfStruct); if (String.IsNullOrEmpty(outputPath)) { Console.WriteLine(" Complete: No data section to compress."); } else { Console.WriteLine(String.Format(" Complete: Recompressed and output to <{0}>", outputPath)); } } } catch (Exception ex) { Console.WriteLine(String.Format(" Error: {0}", ex.Message)); } } }
private void rewritePsfOCycleDriverSource(string driverSourceCodePath, PsfPsyQAddresses addresses, PsfStubMakerStruct stubMakerParameters) { int lineNumber; string inputLine; string tempFilePath = Path.GetTempFileName(); string lineItem; string lineFormat; string lineValue; PropertyInfo psyQValue; Dictionary <int, string> psyQSourceCodeLineNumber = XsfUtil.getPsyQSourceCodeLineNumberList(); Dictionary <string, string> psyQSourceCode = XsfUtil.getPsyQSourceCodeList(); // open reader using (StreamReader reader = new StreamReader(File.Open(driverSourceCodePath, FileMode.Open, FileAccess.Read))) { // open writer for temp file using (StreamWriter writer = new StreamWriter(File.Open(tempFilePath, FileMode.Create, FileAccess.Write))) { lineNumber = 1; while ((inputLine = reader.ReadLine()) != null) { if (psyQSourceCodeLineNumber.ContainsKey(lineNumber)) { if (stubMakerParameters.OverrideDriverLoadAddress && lineNumber == PsfDrvLoadLineNo) { writer.WriteLine(String.Format("#define PSFDRV_LOAD ({0})", stubMakerParameters.PsfDrvLoad)); } else { lineItem = psyQSourceCodeLineNumber[lineNumber]; lineFormat = psyQSourceCode[lineItem]; psyQValue = addresses.GetType().GetProperty(lineItem); lineValue = (string)psyQValue.GetValue(addresses, null); if (!String.IsNullOrEmpty(lineValue)) { writer.WriteLine(String.Format(lineFormat, lineValue)); } else { // comment out this line writer.WriteLine(String.Format("//{0}", inputLine)); } } } else { switch (lineNumber) { case DoSeqDefineLineNo: if (!stubMakerParameters.UseSeqFunctions) { writer.WriteLine("#undef DO_SEQ"); } else { writer.WriteLine(inputLine); } break; case COMMENT_REVERB_OPEN: if (!stubMakerParameters.IncludeReverb) { writer.WriteLine("/*"); } else { writer.WriteLine(inputLine); } break; case COMMENT_REVERB_CLOSE: if (!stubMakerParameters.IncludeReverb) { writer.WriteLine("*/"); } else { writer.WriteLine(inputLine); } break; case PsfDrvSizeLineNo: this.rewriteOptionalLine(writer, stubMakerParameters.OverrideDriverLoadAddress, "#define PSFDRV_SIZE ({0})", stubMakerParameters.PsfDrvSize, inputLine); break; case PsfDrvParamLineNo: this.rewriteOptionalLine(writer, stubMakerParameters.OverrideDriverLoadAddress, "#define PSFDRV_PARAM ({0})", stubMakerParameters.PsfDrvParam, inputLine); break; case PsfDrvParamSizeLineNo: this.rewriteOptionalLine(writer, stubMakerParameters.OverrideDriverLoadAddress, "#define PSFDRV_PARAM_SIZE ({0})", stubMakerParameters.PsfDrvParamSize, inputLine); break; case MySeqLineNo: this.rewriteOptionalLine(writer, stubMakerParameters.OverrideDriverLoadAddress, "#define MY_SEQ ({0})", stubMakerParameters.MySeq, inputLine); break; case MySeqSizeLineNo: this.rewriteOptionalLine(writer, stubMakerParameters.OverrideDriverLoadAddress, "#define MY_SEQ_SIZE ({0})", stubMakerParameters.MySeqSize, inputLine); break; case MyVhLineNo: this.rewriteOptionalLine(writer, stubMakerParameters.OverrideDriverLoadAddress, "#define MY_VH ({0})", stubMakerParameters.MyVh, inputLine); break; case MyVhSizeLineNo: this.rewriteOptionalLine(writer, stubMakerParameters.OverrideDriverLoadAddress, "#define MY_VH_SIZE ({0})", stubMakerParameters.MyVhSize, inputLine); break; case MyVbLineNo: this.rewriteOptionalLine(writer, stubMakerParameters.OverrideDriverLoadAddress, "#define MY_VB ({0})", stubMakerParameters.MyVb, inputLine); break; case MyVbSizeLineNo: this.rewriteOptionalLine(writer, stubMakerParameters.OverrideDriverLoadAddress, "#define MY_VB_SIZE ({0})", stubMakerParameters.MyVbSize, inputLine); break; default: writer.WriteLine(inputLine); break; } } lineNumber++; } } // using (StreamWriter writer... } // using (StreamReader reader... // overwrite original File.Copy(tempFilePath, driverSourceCodePath, true); }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pPsfStubMakerStruct, DoWorkEventArgs e) { if (XsfUtil.IsPsxExe(pPath)) { this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format("[{0}]", pPath) + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); PsfStubMakerStruct stubMakerParameters = (PsfStubMakerStruct)pPsfStubMakerStruct; string sigFindDestination; string sigFind2Destination; string sigDatDestination; string driverDestination; string psfOCycleSourceDestination; string psfOCycleMakeFileDestination; string arguments; string standardOutput; string standardError; bool isProcessSuccessful; PsfPsyQAddresses sigFindAddresses = null; string psfdrvObjFileName; string psfdrvBinFileName; string psfdrvDestinationFileName; ////////////////////////// // prepare working folder ////////////////////////// this.progressStruct.Clear(); this.progressStruct.GenericMessage = " - Preparing working folder." + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); if (!Directory.Exists(PsfStubMakerWorker.WorkingFolderPath)) { Directory.CreateDirectory(PsfStubMakerWorker.WorkingFolderPath); } sigFindDestination = Path.Combine(PsfStubMakerWorker.WorkingFolderPath, Path.GetFileName(PsfStubMakerWorker.SigFindFilePath)); sigFind2Destination = Path.Combine(PsfStubMakerWorker.WorkingFolderPath, Path.GetFileName(PsfStubMakerWorker.SigFind2FilePath)); sigDatDestination = Path.Combine(PsfStubMakerWorker.WorkingFolderPath, Path.GetFileName(PsfStubMakerWorker.SigDatFilePath)); driverDestination = Path.Combine(PsfStubMakerWorker.WorkingFolderPath, Path.GetFileName(pPath).Replace(" ", String.Empty)); psfOCycleSourceDestination = Path.Combine(PsfStubMakerWorker.WorkingFolderPath, Path.GetFileName(PsfStubMakerWorker.PsfOCycleSourceCodeFilePath)); psfOCycleMakeFileDestination = Path.Combine(PsfStubMakerWorker.WorkingFolderPath, Path.GetFileName(PsfStubMakerWorker.PsfOCycleMakeFilePath)); File.Copy(PsfStubMakerWorker.SigFindFilePath, sigFindDestination, true); File.Copy(PsfStubMakerWorker.SigFind2FilePath, sigFind2Destination, true); File.Copy(PsfStubMakerWorker.SigDatFilePath, sigDatDestination, true); File.Copy(pPath, driverDestination, true); File.Copy(PsfStubMakerWorker.PsfOCycleSourceCodeFilePath, psfOCycleSourceDestination, true); File.Copy(PsfStubMakerWorker.PsfOCycleMakeFilePath, psfOCycleMakeFileDestination, true); //////////////////// // call sigfind.exe //////////////////// this.progressStruct.Clear(); this.progressStruct.GenericMessage = " - Execute sigfind/sigfind2." + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); arguments = String.Format("{0}", Path.GetFileName(driverDestination)); isProcessSuccessful = FileUtil.ExecuteExternalProgram(sigFindDestination, arguments, PsfStubMakerWorker.WorkingFolderPath, out standardOutput, out standardError); ///////////////////// // get psyQAddresses ///////////////////// if ((isProcessSuccessful) && (String.IsNullOrEmpty(standardError)) && (!standardOutput.Contains("ERROR"))) { sigFindAddresses = XsfUtil.GetSigFindItems( new MemoryStream(System.Text.Encoding.ASCII.GetBytes(standardOutput)), stubMakerParameters.RelaxLoadAddressRestriction); } ///////////////// // call sigfind2 ///////////////// arguments = String.Format("{0}", Path.GetFileName(driverDestination)); isProcessSuccessful = FileUtil.ExecuteExternalProgram(sigFind2Destination, arguments, PsfStubMakerWorker.WorkingFolderPath, out standardOutput, out standardError); ///////////////////// // get psyQAddresses ///////////////////// if ((isProcessSuccessful) && (String.IsNullOrEmpty(standardError)) && (!standardOutput.Contains("ERROR"))) { sigFindAddresses = XsfUtil.GetSigFindItems( new MemoryStream(System.Text.Encoding.ASCII.GetBytes(standardOutput)), stubMakerParameters.RelaxLoadAddressRestriction, sigFindAddresses); } ///////////////////////// // get additional values ///////////////////////// sigFindAddresses = this.getAdditionalDriverInfo(sigFindAddresses, stubMakerParameters, driverDestination); ////////////////////////////// // rewrite driver source code ////////////////////////////// this.progressStruct.Clear(); this.progressStruct.GenericMessage = " - Rewriting driver source and batch file." + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); this.rewritePsfOCycleDriverSource(psfOCycleSourceDestination, sigFindAddresses, stubMakerParameters); ///////////////////// // rewrite make file ///////////////////// this.rewritePsfOCycleMakeFile(psfOCycleMakeFileDestination, sigFindAddresses, stubMakerParameters); ////////////////////////////////// // delete old files if they exist ////////////////////////////////// psfdrvObjFileName = Path.Combine(PsfStubMakerWorker.WorkingFolderPath, "psfdrv.obj"); psfdrvBinFileName = Path.Combine(PsfStubMakerWorker.WorkingFolderPath, "psfdrv.bin"); if (File.Exists(psfdrvObjFileName)) { File.Delete(psfdrvObjFileName); } if (File.Exists(psfdrvBinFileName)) { File.Delete(psfdrvBinFileName); } //////////////// // compile stub //////////////// this.progressStruct.Clear(); this.progressStruct.GenericMessage = " - Compiling stub." + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); arguments = String.Empty; isProcessSuccessful = FileUtil.ExecuteExternalProgram(psfOCycleMakeFileDestination, arguments, PsfStubMakerWorker.WorkingFolderPath, out standardOutput, out standardError); this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" STDOUT: {0}{1}", standardOutput, Environment.NewLine); ReportProgress(Constants.ProgressMessageOnly, progressStruct); this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" STDERR: {0}{1}", standardError, Environment.NewLine); ReportProgress(Constants.ProgressMessageOnly, progressStruct); //////////////////////////////////////// // copy driver and source to source dir //////////////////////////////////////// psfdrvDestinationFileName = Path.Combine(Path.GetDirectoryName(pPath), Path.GetFileName(pPath) + ".stub.bin"); if (!File.Exists(psfdrvBinFileName)) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = "[ERROR from VGMToolbox] Compiled output file not found. Compilation has failed. Stub file source code will be copied to your source directory for examination." + Environment.NewLine; ReportProgress(this.progress, progressStruct); } else { File.Copy(psfdrvBinFileName, psfdrvDestinationFileName, true); } File.Copy(psfOCycleSourceDestination, Path.Combine(Path.GetDirectoryName(pPath), Path.GetFileName(pPath) + ".stub.c"), true); ////////////////////// // remove working dir ////////////////////// this.progressStruct.Clear(); this.progressStruct.GenericMessage = " - Delete working folder." + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); if (Directory.Exists(PsfStubMakerWorker.WorkingFolderPath)) { Directory.Delete(PsfStubMakerWorker.WorkingFolderPath, true); } // output warnings this.progressStruct.Clear(); this.progressStruct.GenericMessage = getWarnings(sigFindAddresses); ReportProgress(Constants.ProgressMessageOnly, progressStruct); } else { this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format("[{0}] Skipped. Does not have a valid PS-X EXE signature.", pPath) + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); } }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pUnpkPsf2Struct, DoWorkEventArgs e) { XsfUtil.SplitVab(pPath, true, true); }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pXsfTagUpdaterStruct, DoWorkEventArgs e) { XsfTagUpdaterStruct xsfTagUpdaterStruct = (XsfTagUpdaterStruct)pXsfTagUpdaterStruct; Type formatType = null; IXsfTagFormat vgmData = null; using (FileStream fs = File.OpenRead(pPath)) { formatType = FormatUtil.getObjectType(fs); if (formatType != null) { vgmData = (IXsfTagFormat)Activator.CreateInstance(formatType); vgmData.Initialize(fs, pPath); } } if (vgmData != null) { XsfTagSetter xts; xts = new XsfTagSetter(vgmData.SetArtistTag); updateXsfTag(xts, xsfTagUpdaterStruct.ArtistTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetGameTag); updateXsfTag(xts, xsfTagUpdaterStruct.GameTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetYearTag); updateXsfTag(xts, xsfTagUpdaterStruct.YearTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetGenreTag); updateXsfTag(xts, xsfTagUpdaterStruct.GenreTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetCommentTag); updateXsfTag(xts, xsfTagUpdaterStruct.CommentTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetCopyrightTag); updateXsfTag(xts, xsfTagUpdaterStruct.CopyrightTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetXsfByTag); updateXsfTag(xts, xsfTagUpdaterStruct.XsfByTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetTaggerTag); updateXsfTag(xts, xsfTagUpdaterStruct.TaggerTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetSystemTag); updateXsfTag(xts, xsfTagUpdaterStruct.SystemTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); if (xsfTagUpdaterStruct.GenerateTitleFromFilename) { xsfTagUpdaterStruct.TitleTag = XsfUtil.GetTitleForFileName(pPath, xsfTagUpdaterStruct.RemoveBracketInfoFromTitle); xts = new XsfTagSetter(vgmData.SetTitleTag); updateXsfTag(xts, xsfTagUpdaterStruct.TitleTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); } if (!xsfTagUpdaterStruct.IsBatchMode) { xts = new XsfTagSetter(vgmData.SetVolumeTag); updateXsfTag(xts, xsfTagUpdaterStruct.VolumeTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetLengthTag); updateXsfTag(xts, xsfTagUpdaterStruct.LengthTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetFadeTag); updateXsfTag(xts, xsfTagUpdaterStruct.FadeTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetTitleTag); updateXsfTag(xts, xsfTagUpdaterStruct.TitleTag, xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); } else if (xsfTagUpdaterStruct.AddToBatchFile) { // reset tags with existing values to add to batch script xts = new XsfTagSetter(vgmData.SetVolumeTag); updateXsfTag(xts, vgmData.GetVolumeTag(), xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetLengthTag); updateXsfTag(xts, vgmData.GetLengthTag(), xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetFadeTag); updateXsfTag(xts, vgmData.GetFadeTag(), xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); xts = new XsfTagSetter(vgmData.SetTitleTag); updateXsfTag(xts, vgmData.GetTitleTag(), xsfTagUpdaterStruct.RemoveEmptyTags, xsfTagUpdaterStruct.AddToBatchFile); } vgmData.UpdateTags(); } }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pMk2sfStruct, DoWorkEventArgs e) { this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format("Processing: [{0}]{1}", pPath, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); NdsTo2sfStruct workingStruct = (NdsTo2sfStruct)pMk2sfStruct; string ndsTo2sfOutputPath = Path.Combine(Path.GetDirectoryName(pPath), String.Format("{0}{1}", Path.GetFileNameWithoutExtension(pPath), XsfUtil.NDSTO2SF_FOLDER_SUFFIX)); // Build Nds object Nds ndsFile = new Nds(); using (FileStream ndsStream = File.OpenRead(pPath)) { ndsFile.Initialize(ndsStream, pPath); } //------------------------ // extract 2SFs and STRMs //------------------------ bool filesWereRipped = XsfUtil.NdsTo2sf(pPath, TESTPACK_FULL_PATH, workingStruct.UseSmapNames); // output info this.progressStruct.Clear(); if (!filesWereRipped) { this.progressStruct.GenericMessage = String.Format(" No extractable SSEQ/STRM/SWAR data found.{0}", Environment.NewLine); } else { this.progressStruct.GenericMessage = String.Format(" SSEQ/STRM/SWAR Data extracted.{0}", Environment.NewLine); } this.ReportProgress(this.progress, this.progressStruct); //--------------- // extract SWAVs //--------------- this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" Searching for SWAVs{0}", Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); string swavMessages = String.Empty; FindOffsetStruct findOffsetStruct = new FindOffsetStruct(); findOffsetStruct.CutFile = true; findOffsetStruct.SearchString = "53574156FFFE"; findOffsetStruct.TreatSearchStringAsHex = true; findOffsetStruct.SearchStringOffset = "0"; findOffsetStruct.OutputFileExtension = ".swav"; findOffsetStruct.IsCutSizeAnOffset = true; findOffsetStruct.CutSize = "8"; findOffsetStruct.CutSizeOffsetSize = "4"; findOffsetStruct.IsLittleEndian = true; findOffsetStruct.OutputFolder = Path.Combine(ndsTo2sfOutputPath, "SWAV"); ParseFile.FindOffsetAndCutFile(pPath, findOffsetStruct, out swavMessages, false, false); //-------------- // extract ADXs //-------------- this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" Searching for ADXs{0}", Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); string adxMessages = String.Empty; CriUtil.ExtractAdxStreams(pPath, ndsFile.GameSerial, Path.Combine(ndsTo2sfOutputPath, "ADX"), out adxMessages); }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pPsf2SettingsUpdaterStruct, DoWorkEventArgs e) { Psf2SettingsUpdaterStruct iniStruct = (Psf2SettingsUpdaterStruct)pPsf2SettingsUpdaterStruct; string workingFolder = String.Empty; ////////////////////// // copy existing tags ////////////////////// string formatString = XsfUtil.GetXsfFormatString(pPath); Dictionary <string, string> tagHash; Xsf psf2File, newPsf2File; if (!String.IsNullOrEmpty(formatString) && formatString.Equals(Xsf.FormatNamePsf2)) { try { using (FileStream fs = File.Open(pPath, FileMode.Open, FileAccess.Read)) { // initialize file psf2File = new Xsf(); psf2File.Initialize(fs, pPath); // copy tags tagHash = psf2File.GetTagHash(); } /////////////// // unpack Psf2 /////////////// workingFolder = Path.Combine(Path.GetDirectoryName(pPath), Path.GetFileNameWithoutExtension(pPath)); string unpackFolder = Path.Combine(workingFolder, "unpack_dir"); XsfUtil.UnpackPsf2(pPath, unpackFolder); /////////////////// // parse .ini file /////////////////// Psf2.Psf2IniSqIrxStruct originalIni; string[] originalIniFiles = Directory.GetFiles(unpackFolder, "*.ini"); if (originalIniFiles.Length > 0) { using (FileStream iniFs = File.Open(originalIniFiles[0], FileMode.Open, FileAccess.Read)) { originalIni = Psf2.ParseClsIniFile(iniFs); } //////////////////// // update .ini file //////////////////// iniStruct.IniSettings = UpdateClsIniFile(iniStruct.IniSettings, originalIni, iniStruct.RemoveEmptySettings); File.Delete(originalIniFiles[0]); Psf2.WriteClsIniFile(iniStruct.IniSettings, originalIniFiles[0]); /////////////// // repack Psf2 /////////////// string psf2FileName = Path.GetFileName(pPath); /////////////////// // copy mkpsf2.exe /////////////////// string mkpsf2Destination = Path.Combine(workingFolder, Path.GetFileName(MKPSF2_SOURCE_PATH)); File.Copy(MKPSF2_SOURCE_PATH, mkpsf2Destination, true); ////////////////// // run mkpsf2.exe ////////////////// string arguments = String.Format(" \"{0}\" \"{1}\"", psf2FileName, unpackFolder); Process makePsf2Process = new Process(); makePsf2Process.StartInfo = new ProcessStartInfo(mkpsf2Destination, arguments); makePsf2Process.StartInfo.UseShellExecute = false; makePsf2Process.StartInfo.CreateNoWindow = true; makePsf2Process.StartInfo.WorkingDirectory = workingFolder; bool isSuccess = makePsf2Process.Start(); makePsf2Process.WaitForExit(); makePsf2Process.Close(); makePsf2Process.Dispose(); //////////////// // replace tags //////////////// string newPsf2FilePath = Path.Combine(workingFolder, psf2FileName); using (FileStream newFs = File.Open(newPsf2FilePath, FileMode.Open, FileAccess.Read)) { // initialize new file newPsf2File = new Xsf(); newPsf2File.Initialize(newFs, newPsf2FilePath); } // update to use old tag hash newPsf2File.TagHash = tagHash; newPsf2File.UpdateTags(); ///////////////////////// // replace original file ///////////////////////// File.Copy(newPsf2FilePath, pPath, true); } } catch (Exception ex) { throw ex; } finally { // delete working folder if (Directory.Exists(workingFolder)) { Directory.Delete(workingFolder, true); } } } }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pPsf2SqExtractorStruct, DoWorkEventArgs e) { string outputSqFileName; string[] libPaths; string[] sqFiles; string[] iniFiles; Psf2.Psf2IniSqIrxStruct psf2IniStruct; string filePath; string fileDir; string fileName; string outputDir; string libOutputDir; string formatString = XsfUtil.GetXsfFormatString(pPath); if (!String.IsNullOrEmpty(formatString) && (formatString.Equals(Xsf.FormatNamePsf2))) { filePath = Path.GetFullPath(pPath); fileDir = Path.GetDirectoryName(filePath); fileName = Path.GetFileNameWithoutExtension(filePath); outputDir = XsfUtil.UnpackPsf2(filePath); // parse ini iniFiles = Directory.GetFiles(outputDir, "PSF2.INI", SearchOption.AllDirectories); if (iniFiles.Length > 0) { using (FileStream iniFs = File.Open(iniFiles[0], FileMode.Open, FileAccess.Read)) { // parse ini file to get SQ info psf2IniStruct = Psf2.ParseClsIniFile(iniFs); } using (FileStream fs = File.OpenRead(pPath)) { Psf2 psf2File = new Psf2(); psf2File.Initialize(fs, pPath); // check for libs libPaths = psf2File.GetLibPathArray(); } if ((libPaths == null) || (libPaths.Length == 0)) // PSF2 { // copy the SQ file out (should only be one) sqFiles = Directory.GetFiles(outputDir, psf2IniStruct.SqFileName, SearchOption.AllDirectories); if (sqFiles.Length > 0) { if (!String.IsNullOrEmpty(psf2IniStruct.SequenceNumber)) { outputSqFileName = String.Format("{0}_n={1}.SQ", outputDir, psf2IniStruct.SequenceNumber); } else { outputSqFileName = String.Format("{0}.SQ", outputDir); } File.Copy(sqFiles[0], outputSqFileName, true); } } else // miniPSF2 { // unpack each lib, looking for the needed file foreach (string libPath in libPaths) { fileDir = Path.GetDirectoryName(libPath); fileName = Path.GetFileNameWithoutExtension(libPath); libOutputDir = Path.Combine(fileDir, fileName); if (!extractedLibHash.ContainsKey(libPath)) { libOutputDir = XsfUtil.UnpackPsf2(libPath); extractedLibHash.Add(libPath, libOutputDir.ToUpper()); } // look for the file in this lib sqFiles = Directory.GetFiles(libOutputDir, psf2IniStruct.SqFileName, SearchOption.AllDirectories); if (sqFiles.Length > 0) { if (!String.IsNullOrEmpty(psf2IniStruct.SequenceNumber)) { outputSqFileName = String.Format("{0}_n={1}.SQ", outputDir, psf2IniStruct.SequenceNumber); } else { outputSqFileName = String.Format("{0}.SQ", outputDir); } File.Copy(sqFiles[0], outputSqFileName, true); break; } // delete the unpkpsf2 output folder if (Directory.Exists(libOutputDir)) { Directory.Delete(libOutputDir, true); } } // foreach (string libPath in libPaths) } } // if (iniFiles.Length > 0) // delete the unpkpsf2 output folder if ((Directory.Exists(outputDir)) && (!extractedLibHash.ContainsValue(outputDir.ToUpper()))) { Directory.Delete(outputDir, true); } } // if (!String.IsNullOrEmpty(formatString) && (formatString.Equals(Xsf.FORMAT_NAME_PSF2))) }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pUnpkPsf2Struct, DoWorkEventArgs e) { XsfUtil.UnpackPsf2(pPath); }
static void Main(string[] args) { if ((args.Length > 3) || (args.Length < 2)) { Console.WriteLine("usage: sdatopt.exe fileName start_sequence end_sequence"); Console.WriteLine(" sdatopt.exe fileName ALL"); Console.WriteLine(" sdatopt.exe fileName PREP"); Console.WriteLine(" sdatopt.exe fileName MAP smap_file"); Console.WriteLine(" sdatopt.exe fileName MAP"); Console.WriteLine(); Console.WriteLine("fileName: .sdat or .2sflib containing SDAT to optimize"); Console.WriteLine("start_sequence: starting sequence number to keep"); Console.WriteLine("end_sequence: endinging sequence number to keep"); Console.WriteLine("ALL: use this if you wish to keep all sequences"); Console.WriteLine("PREP: use this to output an SMAP to use for sequence selection. Delete the entire line of sequences you do not want to include."); Console.WriteLine("MAP smap_file: uses smap_file from PREP to select sequences to keep."); Console.WriteLine("MAP: looks for an smap file based on the sdat name select sequences to keep. Must be in proper format."); } else { Sdat sdat = null; bool is2sfSource = false;; string sdatDirectory; string sdatOptimizingFileName; string sdatOptimizingPath; string sdatCompletedFileName; string sdatCompletedPath; int startSequence = Sdat.NO_SEQUENCE_RESTRICTION; int endSequence = Sdat.NO_SEQUENCE_RESTRICTION; string[] extractedSdats = null; string decompressedDataPath = null; string extractedToFolder = null; ArrayList cleanupList = new ArrayList(); string filename = Path.GetFullPath(args[0]); string smapFileName = null; if (!File.Exists(filename)) { Console.WriteLine("Cannot find SDAT: {0}", filename); return; } if (args[1].Trim().ToUpper().Equals("MAP")) { if (args.Length < 3) { smapFileName = Path.ChangeExtension(filename, Smap.FILE_EXTENSION); } else { smapFileName = Path.GetFullPath(args[2]); } if (!File.Exists(smapFileName)) { Console.WriteLine("Cannot find SMAP: {0}", smapFileName); return; } } sdatDirectory = Path.GetDirectoryName(filename); sdatOptimizingFileName = String.Format("{0}_OPTIMIZING{1}", Path.GetFileNameWithoutExtension(filename), Path.GetExtension(filename)); sdatOptimizingPath = Path.Combine(sdatDirectory, sdatOptimizingFileName); sdatCompletedFileName = String.Format("{0}_OPTIMIZED{1}", Path.GetFileNameWithoutExtension(filename), Path.GetExtension(filename)); sdatCompletedPath = Path.Combine(sdatDirectory, sdatCompletedFileName); try { File.Copy(filename, sdatOptimizingPath, true); using (FileStream fs = File.Open(sdatOptimizingPath, FileMode.Open, FileAccess.Read)) { Type dataType = FormatUtil.getObjectType(fs); if (dataType != null) { if (dataType.Name.Equals("Sdat")) { Console.WriteLine("Input file is an SDAT."); Console.WriteLine("Building Internal SDAT."); sdat = new Sdat(); sdat.Initialize(fs, sdatOptimizingPath); } else if (dataType.Name.Equals("Xsf")) // is an Xsf, confirm it is a 2sf { Xsf libFile = new Xsf(); libFile.Initialize(fs, sdatOptimizingPath); if (libFile.GetFormat().Equals(Xsf.FormatName2sf)) { Console.WriteLine("Input file is a 2SF."); is2sfSource = true; // close stream, we're gonna need this file fs.Close(); fs.Dispose(); // unpack compressed section Console.WriteLine("Decompressing Compressed Data section of 2SF."); Xsf2ExeStruct xsf2ExeStruct = new Xsf2ExeStruct(); xsf2ExeStruct.IncludeExtension = true; xsf2ExeStruct.StripGsfHeader = false; decompressedDataPath = XsfUtil.ExtractCompressedDataSection(sdatOptimizingPath, xsf2ExeStruct); // extract SDAT Console.WriteLine("Extracting SDAT from Decompressed Compressed Data Section."); VGMToolbox.util.FindOffsetStruct findOffsetStruct = new VGMToolbox.util.FindOffsetStruct(); findOffsetStruct.SearchString = Sdat.ASCII_SIGNATURE_STRING; findOffsetStruct.TreatSearchStringAsHex = true; findOffsetStruct.CutFile = true; findOffsetStruct.SearchStringOffset = "0"; findOffsetStruct.CutSize = "8"; findOffsetStruct.CutSizeOffsetSize = "4"; findOffsetStruct.IsCutSizeAnOffset = true; findOffsetStruct.OutputFileExtension = ".sdat"; findOffsetStruct.IsLittleEndian = true; findOffsetStruct.UseTerminatorForCutSize = false; findOffsetStruct.TerminatorString = null; findOffsetStruct.TreatTerminatorStringAsHex = false; findOffsetStruct.IncludeTerminatorLength = false; findOffsetStruct.ExtraCutSizeBytes = null; string output; extractedToFolder = ParseFile.FindOffsetAndCutFile(decompressedDataPath, findOffsetStruct, out output, false, false); // create SDAT object Console.WriteLine("Building Internal SDAT."); extractedSdats = Directory.GetFiles(extractedToFolder, "*.sdat"); if (extractedSdats.Length > 1) { Console.WriteLine("Sorry, this 2SF file contains more than 1 SDAT. sdatopt cannot currently handle this."); return; } else if (extractedSdats.Length == 0) { Console.WriteLine("ERROR: Did not find an SDAT in the Decompressed Data Section."); return; } else { using (FileStream sdatFs = File.Open(extractedSdats[0], FileMode.Open, FileAccess.Read)) { sdat = new Sdat(); sdat.Initialize(sdatFs, extractedSdats[0]); } } } } else { Console.WriteLine("ERROR: Cannot determine format of the input file."); return; } } } if (sdat != null) { if (args[1].Trim().ToUpper().Equals("PREP")) { sdat.BuildSmapPrep(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename)); } else if (args[1].Trim().ToUpper().Equals("MAP")) { ArrayList allowedSequences = buildSequenceList(smapFileName); Console.WriteLine("Optimizing SDAT."); sdat.OptimizeForZlib(allowedSequences); } else { if (!args[1].Trim().ToUpper().Equals("ALL")) { if (!String.IsNullOrEmpty(args[1])) { startSequence = (int)VGMToolbox.util.ByteConversion.GetLongValueFromString(args[1]); } if (!String.IsNullOrEmpty(args[2])) { endSequence = (int)VGMToolbox.util.ByteConversion.GetLongValueFromString(args[2]); } } Console.WriteLine("Optimizing SDAT."); sdat.OptimizeForZlib(startSequence, endSequence); } } if (is2sfSource) { if (!args[1].Trim().ToUpper().Equals("PREP")) { // replace SDAT section Console.WriteLine("Inserting SDAT back into Decompressed Compressed Data Section."); long sdatOffset; using (FileStream dcFs = File.Open(decompressedDataPath, FileMode.Open, FileAccess.ReadWrite)) { sdatOffset = ParseFile.GetNextOffset(dcFs, 0, Sdat.ASCII_SIGNATURE); } FileInfo fi = new FileInfo(extractedSdats[0]); FileUtil.ReplaceFileChunk(extractedSdats[0], 0, fi.Length, decompressedDataPath, sdatOffset); // rebuild 2sf Console.WriteLine("Rebuilding 2sf File."); string bin2PsfStdOut = String.Empty; string bin2PsfStdErr = String.Empty; XsfUtil.Bin2Psf(Path.GetExtension(filename).Substring(1), (int)Xsf.Version2sf, decompressedDataPath, ref bin2PsfStdOut, ref bin2PsfStdErr); Console.WriteLine("Cleaning up intermediate files."); File.Copy(Path.ChangeExtension(decompressedDataPath, Path.GetExtension(filename)), sdatOptimizingPath, true); File.Delete(Path.ChangeExtension(decompressedDataPath, Path.GetExtension(filename))); } File.Delete(decompressedDataPath); Directory.Delete(extractedToFolder, true); } if (!args[1].Trim().ToUpper().Equals("PREP")) { Console.WriteLine("Copying to OPTIMIZED file."); File.Copy(sdatOptimizingPath, sdatCompletedPath, true); } Console.WriteLine("Deleting OPTIMIZING file."); File.Delete(sdatOptimizingPath); Console.WriteLine("Optimization Complete."); } catch (Exception ex) { Console.WriteLine(String.Format("ERROR: {0}", ex.Message)); } } }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pPsxSeqExtractStruct, DoWorkEventArgs e) { PsxSeqExtractStruct psxSeqExtractStruct = (PsxSeqExtractStruct)pPsxSeqExtractStruct; int minutes; double seconds; int loopStartMinutes = 0; double loopStartSeconds = 0; int loopEndMinutes = 0; double loopEndSeconds = 0; StringBuilder batchFile = new StringBuilder(); string batchFilePath; string extractedSq = XsfUtil.ExtractPsxSequenceForTiming(pPath, psxSeqExtractStruct.forceSepType, psxSeqExtractStruct.SepSeqOffset, psxSeqExtractStruct.SepSeqIndexLength, -1); if (!String.IsNullOrEmpty(extractedSq)) { PsxSequence psxSeq = null; using (FileStream fs = File.OpenRead(extractedSq)) { PsxSequence.PsxSqInitStruct initStruct = new PsxSequence.PsxSqInitStruct(); initStruct.force2Loops = psxSeqExtractStruct.force2Loops; initStruct.forceOppositeFormatType = false; initStruct.forceSepType = psxSeqExtractStruct.forceSepType; initStruct.forceSeqType = psxSeqExtractStruct.forceSeqType; try { psxSeq = new PsxSequence(fs, initStruct); } catch (PsxSeqFormatException) { // sometimes the version number is wrong, (Devil Summoner 1-50b.minipsf) initStruct.forceOppositeFormatType = true; psxSeq = new PsxSequence(fs, initStruct); } } if (psxSeq != null) { double timingInfoSeconds = psxSeq.TimingInfo.TimeInSeconds; double loopStartInSeconds = psxSeq.TimingInfo.LoopStartInSeconds; double loopEndInSeconds = psxSeq.TimingInfo.LoopEndInSeconds; int timingInfoFadeInSeconds = psxSeq.TimingInfo.FadeInSeconds; // loop entire track if (psxSeqExtractStruct.loopEntireTrack) { timingInfoSeconds = 2d * psxSeq.TimingInfo.TimeInSeconds; timingInfoFadeInSeconds = 10; } // Add line to batch file. minutes = (int)(timingInfoSeconds / 60d); seconds = timingInfoSeconds - (minutes * 60); // seconds = Math.Ceiling(seconds); if (loopStartInSeconds > -1) { loopStartMinutes = (int)(loopStartInSeconds / 60d); loopStartSeconds = loopStartInSeconds - (loopStartMinutes * 60); } if (loopEndInSeconds > -1) { loopEndMinutes = (int)(loopEndInSeconds / 60d); loopEndSeconds = loopEndInSeconds - (loopEndMinutes * 60); } // shouldn't be needed without Math.Ceiling call, but whatever if (seconds >= 60) { minutes++; seconds -= 60d; } if ((loopStartInSeconds > -1) && (loopEndInSeconds > -1)) { batchFile.AppendLine( String.Format( "REM {0}: Loop Start: {1}:{2} Loop Finish: {3}:{4}", Path.GetFileName(pPath), loopStartMinutes.ToString(), loopStartSeconds.ToString().PadLeft(2, '0'), loopEndMinutes.ToString(), loopEndSeconds.ToString().PadLeft(2, '0'))); } batchFile.AppendFormat("psfpoint.exe -length=\"{0}:{1}\" -fade=\"{2}\" \"{3}\"", minutes.ToString(), seconds.ToString().PadLeft(2, '0'), timingInfoFadeInSeconds.ToString(), Path.GetFileName(pPath)); batchFile.AppendLine(); batchFile.AppendLine(); batchFilePath = Path.Combine(Path.GetDirectoryName(pPath), BATCH_FILE_NAME); if (!File.Exists(batchFilePath)) { using (FileStream cfs = File.Create(batchFilePath)) { }; } using (StreamWriter sw = new StreamWriter(File.Open(batchFilePath, FileMode.Append, FileAccess.Write))) { sw.Write(batchFile.ToString()); } // report warnings if (!String.IsNullOrEmpty(psxSeq.TimingInfo.Warnings)) { this.progressStruct.Clear(); progressStruct.GenericMessage = String.Format("{0}{1} WARNINGS{2} {3}", pPath, Environment.NewLine, Environment.NewLine, psxSeq.TimingInfo.Warnings); ReportProgress(this.Progress, progressStruct); } } File.Delete(extractedSq); } }
private void Make2sfFiles(Mk2sfStruct pMk2sfStruct) { string sdatDestinationPath; string TwoSFDestinationPath; string sdatPrefix; string testpackDestinationPath; string unallowedDestinationPath; string strmDestinationPath; Sdat sdat; // Build Paths if (String.IsNullOrEmpty(pMk2sfStruct.GameSerial)) { sdatDestinationPath = Path.Combine(pMk2sfStruct.DestinationFolder, Path.GetFileName(pMk2sfStruct.SourcePath)); } else { sdatDestinationPath = Path.Combine(pMk2sfStruct.DestinationFolder, pMk2sfStruct.GameSerial + Path.GetExtension(pMk2sfStruct.SourcePath)); } TwoSFDestinationPath = Path.Combine(pMk2sfStruct.DestinationFolder, Path.GetFileNameWithoutExtension(sdatDestinationPath)); sdatPrefix = Path.GetFileNameWithoutExtension(sdatDestinationPath); testpackDestinationPath = Path.Combine(pMk2sfStruct.DestinationFolder, Path.GetFileName(TESTPACK_FULL_PATH)); unallowedDestinationPath = Path.Combine(TwoSFDestinationPath, "UnAllowed Sequences"); strmDestinationPath = TwoSFDestinationPath; // Copy SDAT to destination folder try { File.Copy(pMk2sfStruct.SourcePath, sdatDestinationPath, false); } catch (Exception sdatException) { throw new IOException(String.Format("Error: Cannot copy SDAT <{0}> to destination directory: {1}.", sdatDestinationPath, sdatException.Message)); } // Copy STRMs this.progressStruct.Clear(); this.progressStruct.GenericMessage = "Copying STRM files" + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); using (FileStream sdatStream = File.OpenRead(sdatDestinationPath)) { sdat = new Sdat(); sdat.Initialize(sdatStream, sdatDestinationPath); sdat.ExtractStrms(sdatStream, strmDestinationPath); } // Update Volume for (int i = 0; i < pMk2sfStruct.VolumeChangeList.Length; i++) { if (pMk2sfStruct.VolumeChangeList[i].newValue != pMk2sfStruct.VolumeChangeList[i].oldValue) { sdat.UpdateSseqVolume(i, pMk2sfStruct.VolumeChangeList[i].newValue); } } // Optimize SDAT this.progressStruct.Clear(); this.progressStruct.GenericMessage = "Optimizing SDAT" + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); using (FileStream sdatStream = File.OpenRead(sdatDestinationPath)) { sdat = new Sdat(); sdat.Initialize(sdatStream, sdatDestinationPath); } sdat.OptimizeForZlib(pMk2sfStruct.AllowedSequences); // Copy testpack.nds File.Copy(TESTPACK_FULL_PATH, testpackDestinationPath, true); // Create 2SF output path if (!Directory.Exists(TwoSFDestinationPath)) { Directory.CreateDirectory(TwoSFDestinationPath); } // Build 2SFs this.progressStruct.Clear(); this.progressStruct.GenericMessage = "Build 2SFs" + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); XsfUtil.Make2sfSet(testpackDestinationPath, sdatDestinationPath, GetMinAllowedSseq(pMk2sfStruct.AllowedSequences), GetMaxAllowedSseq(pMk2sfStruct.AllowedSequences), TwoSFDestinationPath); // Move unallowed Sequences string unallowedFileName; string unallowedFilePath; foreach (int unallowedSequenceNumber in pMk2sfStruct.UnAllowedSequences) { unallowedFileName = String.Format("{0}-{1}.mini2sf", sdatPrefix, unallowedSequenceNumber.ToString("x4")); unallowedFilePath = Path.Combine(TwoSFDestinationPath, unallowedFileName); if (!Directory.Exists(unallowedDestinationPath)) { Directory.CreateDirectory(unallowedDestinationPath); } if (File.Exists(unallowedFilePath)) { File.Copy(unallowedFilePath, Path.Combine(unallowedDestinationPath, unallowedFileName), true); File.Delete(unallowedFilePath); } } // Add Tags this.progressStruct.Clear(); this.progressStruct.GenericMessage = "Tagging Output" + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); XsfBasicTaggingStruct tagStruct = new XsfBasicTaggingStruct(); tagStruct.TagArtist = pMk2sfStruct.TagArtist; tagStruct.TagCopyright = pMk2sfStruct.TagCopyright; tagStruct.TagYear = pMk2sfStruct.TagYear; tagStruct.TagGame = pMk2sfStruct.TagGame; tagStruct.TagComment = "uses Legacy of Ys: Book II driver hacked by Caitsith2"; tagStruct.TagXsfByTagName = "-2sfby"; tagStruct.TagXsfByTagValue = "VGMToolbox"; string taggingBatchPath = XsfUtil.BuildBasicTaggingBatch(TwoSFDestinationPath, tagStruct, "*.mini2sf"); XsfUtil.ExecutePsfPointBatchScript(taggingBatchPath, true); // Time 2SFs this.progressStruct.Clear(); this.progressStruct.GenericMessage = "Timing Output" + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); string outputTimerMessages; Time2sfStruct timerStruct = new Time2sfStruct(); timerStruct.DoSingleLoop = false; timerStruct.Mini2sfDirectory = TwoSFDestinationPath; timerStruct.SdatPath = pMk2sfStruct.SourcePath; XsfUtil.Time2sfFolder(timerStruct, out outputTimerMessages); // Delete Files this.progressStruct.Clear(); this.progressStruct.GenericMessage = "Cleaning Up" + Environment.NewLine; ReportProgress(Constants.ProgressMessageOnly, progressStruct); if (File.Exists(sdatDestinationPath)) { File.Delete(sdatDestinationPath); } if (File.Exists(testpackDestinationPath)) { File.Delete(testpackDestinationPath); } }
private void migrateTags(Xsf2sfTagMigratorStruct pXsf2sfTagMigratorStruct) { Dictionary <int, string> sourceFiles = new Dictionary <int, string>(); int songNumber; Xsf source2sf; Xsf destination2sf; string renameFilePath; try { // build source list foreach (string f in Directory.GetFiles(pXsf2sfTagMigratorStruct.SourceDirectory, "*.*")) { songNumber = XsfUtil.GetSongNumberForYoshiIslandMini2sf(f); if (songNumber != XsfUtil.InvalidData) { if (!sourceFiles.ContainsKey(songNumber)) { sourceFiles.Add(songNumber, f); } else { this.progress = 0; this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format( "Warning duplicate track ID for <{0}>. Does the V1 set use 2 .2sflibs? Skipping...{1}", f, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } } } } catch (Exception _ex) { this.progress = 0; this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format("Error building source directory list: {0}{1}", _ex.Message, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } if (sourceFiles.Count > 0) { this.maxFiles = FileUtil.GetFileCount(new string[] { pXsf2sfTagMigratorStruct.DestinationDirectory }, false); // loop through destination foreach (string f in Directory.GetFiles(pXsf2sfTagMigratorStruct.DestinationDirectory, "*.*")) { this.progress = (++fileCount * 100) / maxFiles; try { songNumber = XsfUtil.GetSongNumberForMini2sf(f); // check for source if ((songNumber != XsfUtil.InvalidData) && (sourceFiles.ContainsKey(songNumber))) { // copy the tags XsfTagCopyStruct xtcStruct = new XsfTagCopyStruct(); xtcStruct.CopyEmptyTags = pXsf2sfTagMigratorStruct.CopyEmptyTags; xtcStruct.UpdateArtistTag = pXsf2sfTagMigratorStruct.UpdateArtistTag; xtcStruct.UpdateCommentTag = pXsf2sfTagMigratorStruct.UpdateCommentTag; xtcStruct.UpdateCopyrightTag = pXsf2sfTagMigratorStruct.UpdateCopyrightTag; xtcStruct.UpdateFadeTag = pXsf2sfTagMigratorStruct.UpdateFadeTag; xtcStruct.UpdateGameTag = pXsf2sfTagMigratorStruct.UpdateGameTag; xtcStruct.UpdateGenreTag = pXsf2sfTagMigratorStruct.UpdateGenreTag; xtcStruct.UpdateLengthTag = pXsf2sfTagMigratorStruct.UpdateLengthTag; xtcStruct.UpdateSystemTag = false; xtcStruct.UpdateTitleTag = pXsf2sfTagMigratorStruct.UpdateTitleTag; xtcStruct.UpdateVolumeTag = pXsf2sfTagMigratorStruct.UpdateVolumeTag; xtcStruct.UpdateXsfByTag = pXsf2sfTagMigratorStruct.UpdateXsfByTag; xtcStruct.UpdateYearTag = pXsf2sfTagMigratorStruct.UpdateYearTag; using (FileStream sourceFs = File.Open(sourceFiles[songNumber], FileMode.Open, FileAccess.Read)) { source2sf = new Xsf(); source2sf.Initialize(sourceFs, sourceFiles[songNumber]); } using (FileStream destinationFs = File.Open(f, FileMode.Open, FileAccess.Read)) { destination2sf = new Xsf(); destination2sf.Initialize(destinationFs, f); } XsfUtil.CopyTags(source2sf, destination2sf, xtcStruct); // rename the file if (pXsf2sfTagMigratorStruct.UpdateFileName) { renameFilePath = Path.Combine(Path.GetDirectoryName(f), Path.GetFileNameWithoutExtension(sourceFiles[songNumber]) + Path.GetExtension(f)); File.Move(f, renameFilePath); } } this.progressStruct.Clear(); this.progressStruct.FileName = f; this.ReportProgress(this.progress, this.progressStruct); } catch (Exception _ex2) { this.progressStruct.Clear(); this.progressStruct.FileName = f; this.progressStruct.ErrorMessage = String.Format("Error updating <{0}>: {1}{2}", f, _ex2.Message, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } } //foreach } else { this.progress = 0; this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format("ERROR, no 2SFs found in source directory.{0}", Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pPsf2TimerStruct, DoWorkEventArgs e) { string outputSqFileName = null; string[] libPaths; string[] sqFiles; string[] iniFiles; Psf2.Psf2IniSqIrxStruct psf2IniStruct; string filePath; string fileDir; string fileName; string outputDir; string libOutputDir; Ps2SequenceData.Ps2SqTimingStruct psf2Time; int minutes; double seconds; int sequenceNumber = 0; StringBuilder batchFile = new StringBuilder(); string batchFilePath; string formatString = XsfUtil.GetXsfFormatString(pPath); if (!String.IsNullOrEmpty(formatString) && (formatString.Equals(Xsf.FormatNamePsf2))) { filePath = Path.GetFullPath(pPath); fileDir = Path.GetDirectoryName(filePath); fileName = Path.GetFileNameWithoutExtension(filePath); outputDir = XsfUtil.UnpackPsf2(filePath); // parse ini iniFiles = Directory.GetFiles(outputDir, "PSF2.INI", SearchOption.AllDirectories); if (iniFiles.Length > 0) { using (FileStream iniFs = File.Open(iniFiles[0], FileMode.Open, FileAccess.Read)) { // parse ini file to get SQ info psf2IniStruct = Psf2.ParseClsIniFile(iniFs); } using (FileStream fs = File.OpenRead(pPath)) { Psf2 psf2File = new Psf2(); psf2File.Initialize(fs, pPath); // check for libs libPaths = psf2File.GetLibPathArray(); } // copy the SQ file out (should only be one) sqFiles = Directory.GetFiles(outputDir, psf2IniStruct.SqFileName, SearchOption.AllDirectories); if (sqFiles.Length > 0) { if (!String.IsNullOrEmpty(psf2IniStruct.SequenceNumber)) { sequenceNumber = int.Parse(psf2IniStruct.SequenceNumber); outputSqFileName = String.Format("{0}_n={1}.SQ", outputDir, psf2IniStruct.SequenceNumber); } else { outputSqFileName = String.Format("{0}.SQ", outputDir); } File.Copy(sqFiles[0], outputSqFileName, true); } else // miniPSF2 { // unpack each lib, looking for the needed file foreach (string libPath in libPaths) { fileDir = Path.GetDirectoryName(libPath); fileName = Path.GetFileNameWithoutExtension(libPath); libOutputDir = Path.Combine(fileDir, fileName); if (!extractedLibHash.ContainsKey(libPath)) { libOutputDir = XsfUtil.UnpackPsf2(libPath); extractedLibHash.Add(libPath, libOutputDir.ToUpper()); } // look for the file in this lib sqFiles = Directory.GetFiles(libOutputDir, psf2IniStruct.SqFileName, SearchOption.AllDirectories); if (sqFiles.Length > 0) { if (!String.IsNullOrEmpty(psf2IniStruct.SequenceNumber)) { sequenceNumber = int.Parse(psf2IniStruct.SequenceNumber); outputSqFileName = String.Format("{0}_n={1}.SQ", outputDir, psf2IniStruct.SequenceNumber); } else { outputSqFileName = String.Format("{0}.SQ", outputDir); } File.Copy(sqFiles[0], outputSqFileName, true); break; } // delete the unpkpsf2 output folder if (Directory.Exists(libOutputDir)) { Directory.Delete(libOutputDir, true); } } // foreach (string libPath in libPaths) } // get time and add to script if (!String.IsNullOrEmpty(outputSqFileName)) { psf2Time = XsfUtil.GetTimeForPsf2File(outputSqFileName, sequenceNumber); File.Delete(outputSqFileName); // delete SQ file minutes = (int)(psf2Time.TimeInSeconds / 60d); seconds = (psf2Time.TimeInSeconds - (minutes * 60)); // seconds = Math.Ceiling(seconds); // shouldn't be needed without Math.Ceiling call, but whatever if (seconds >= 60) { minutes++; seconds -= 60d; } batchFile.AppendFormat("psfpoint.exe -length=\"{0}:{1}\" -fade=\"{2}\" \"{3}\"", minutes.ToString(), seconds.ToString().PadLeft(2, '0'), psf2Time.FadeInSeconds.ToString(), Path.GetFileName(pPath)); batchFile.Append(Environment.NewLine); batchFilePath = Path.Combine(Path.GetDirectoryName(pPath), BATCH_FILE_NAME); if (!File.Exists(batchFilePath)) { using (FileStream cfs = File.Create(batchFilePath)) { }; } using (StreamWriter sw = new StreamWriter(File.Open(batchFilePath, FileMode.Append, FileAccess.Write))) { sw.Write(batchFile.ToString()); } // report warnings if (!String.IsNullOrEmpty(psf2Time.Warnings)) { this.progressStruct.Clear(); progressStruct.GenericMessage = String.Format("{0}{1} WARNINGS{2} {3}", pPath, Environment.NewLine, Environment.NewLine, psf2Time.Warnings); ReportProgress(this.Progress, progressStruct); } } } // if (iniFiles.Length > 0) // delete the unpkpsf2 output folder if ((Directory.Exists(outputDir)) && (!extractedLibHash.ContainsValue(outputDir.ToUpper()))) { Directory.Delete(outputDir, true); } } // if (psf2File.getFormat().Equals(Xsf.FORMAT_NAME_PSF2) && (!psf2File.IsFileLibrary())) }