private void viewBox_MouseDown(object sender, MouseButtonEventArgs e) { Point pos = e.GetPosition(theImage); Psf = PSF.FromBitmap(Picture.Image, new System.Drawing.Point((int)pos.X, (int)pos.Y)); imgPsfPreview.Source = ToBitmap(Psf.ToRawImage()); }
public static Psf FromFile(string filepath) { List <string> lines = new List <string>(System.IO.File.ReadAllLines(filepath)); Psf psf = FromLines(lines); return(psf); }
/** * @brief * Perform a single iteration * * @return The new estimate of the image */ public ImageF Iterate() { ImageF In = Psf.Convolute(Sn); ImageF Cn = Psf.ConvoluteTranspose(Image / In); Sn *= Cn; return(Sn); }
public static bool IsSonyAdpcmRow(byte[] potentialAdpcm, bool doAdditionalChecks, int rowNumber) { bool ret = true; if ((potentialAdpcm[((rowNumber * 0x10) + 1)] > 7) || (potentialAdpcm[(rowNumber * 0x10)] > 0x4C)) { ret = false; } else if (doAdditionalChecks && ((potentialAdpcm[0] == 0) && (potentialAdpcm[1] != 2) && (Psf.GetCountOfZeroBytes(potentialAdpcm) > 14))) { ret = false; } return(ret); }
public static void InvokePipelineForEach(IEnumerable <PSObject> input) { List <PSObject> items = new List <PSObject>(input); if (items.Count == 0) { return; } // keep $_ var dash = Psf.Engine.SessionState.PSVariable.GetValue("_"); // set $_ to a sample for TabExpansion Psf.Engine.SessionState.PSVariable.Set("_", items[0]); try { // show the dialog, get the code UI.InputDialog ui = new UI.InputDialog() { Title = Res.Me, History = Res.HistoryApply, UseLastHistory = true, Prompt = new string[] { "For each $_ in " + items.Count + " selected:" } }; if (!ui.Show()) { return; } string code = ui.Text.Trim(); if (code.Length == 0) { return; } // invoke the pipeline using the input Psf.Engine.SessionState.PSVariable.Set("_", items); Psf.Act("$_ | .{process{ " + code + " }}", null, false); } finally { // restore $_ Psf.Engine.SessionState.PSVariable.Set("_", dash); } }
public static Psf FromLines(IEnumerable <string> lines) { List <string> llines = lines.ToList(); Psf psf = new Psf(); psf.header = Collect_HEADER(ref llines); psf.title = Collect_NTITLE(ref llines); psf.atoms = CollectAtoms(ref llines); psf.bonds = CollectBonds(ref llines); psf.angles = CollectAngles(ref llines); psf.dihedrals = CollectDihedrals(ref llines); psf.impropers = CollectImpropers(ref llines); psf.donors = CollectDonors(ref llines); psf.acceptors = CollectAcceptors(ref llines); return(psf); }
public void LoadTest() { var psf = new Psf(); psf.Load(File.OpenRead("../../../TestInput/PARAM.SFO")); foreach (var pair in psf.EntryDictionary) { Console.WriteLine("{0}:{1}", pair.Key, pair.Value); } Assert.Equal(psf.EntryDictionary["BOOTABLE"], 1); Assert.Equal(psf.EntryDictionary["CATEGORY"], "UG"); Assert.Equal(psf.EntryDictionary["DISC_ID"], "TEST99999"); Assert.Equal(psf.EntryDictionary["DISC_NUMBER"], 1); Assert.Equal(psf.EntryDictionary["DISC_TOTAL"], 1); Assert.Equal(psf.EntryDictionary["DISC_VERSION"], "9.99"); Assert.Equal(psf.EntryDictionary["PARENTAL_LEVEL"], 5); Assert.Equal(psf.EntryDictionary["PSP_SYSTEM_VER"], "3.33"); Assert.Equal(psf.EntryDictionary["REGION"], 32768); Assert.Equal(psf.EntryDictionary["TITLE"], "GAME TITLE TITLE"); }
private static void FillGameEntryFromSfo(GameEntry Entry, Psf ParamSfo) { var Entries = ParamSfo.EntryDictionary; Entry.APP_VER = (string)Entries.GetOrDefault("APP_VER", "01.00"); Entry.BOOTABLE = (int)Entries.GetOrDefault("BOOTABLE", 1) != 0; Entry.CATEGORY = (string)Entries.GetOrDefault("CATEGORY", "UG"); Entry.DISC_ID = (string)Entries.GetOrDefault("DISC_ID", "XXXX99999"); if (string.IsNullOrWhiteSpace(Entry.DiscId0)) { Entry.DiscId0 = Entry.DISC_ID.Substring(0, 4) + "-" + Entry.DISC_ID.Substring(4); } Entry.DISC_NUMBER = (int)Entries.GetOrDefault("DISC_NUMBER", 1); Entry.DISC_TOTAL = (int)Entries.GetOrDefault("DISC_TOTAL", 1); Entry.DISC_VERSION = (string)Entries.GetOrDefault("DISC_VERSION", "1.00"); Entry.DRIVER_PATH = (string)Entries.GetOrDefault("DRIVER_PATH", ""); Entry.GAMEDATA_ID = (string)Entries.GetOrDefault("GAMEDATA_ID", "XXXX99999"); Entry.HRKGMP_VER = (int)Entries.GetOrDefault("HRKGMP_VER", 19); Entry.PARENTAL_LEVEL = (int)Entries.GetOrDefault("PARENTAL_LEVEL", 5); Entry.PSP_SYSTEM_VER = (string)Entries.GetOrDefault("PSP_SYSTEM_VER", "1.00"); Entry.REGION = (int)Entries.GetOrDefault("REGION", 32768); Entry.TITLE = (string)Entries.GetOrDefault("TITLE", "Unknown Title"); Entry.USE_USB = ((int)Entries.GetOrDefault("USE_USB", 0)) != 0; }
public static GameEntry HandleIso(string IsoFile) { var IsoFileInfo = new FileInfo(IsoFile); Psf ParamSfo; var Entry = new GameEntry(); byte[] Icon0Png; string UmdData = string.Empty; if (DefaultIcon == null) { var TempMemoryStream = new MemoryStream(); Properties.Resources.icon0.Save(TempMemoryStream, ImageFormat.Png); DefaultIcon = TempMemoryStream.ToArray(); } using (var IsoStream = File.OpenRead(IsoFile)) { switch (new FormatDetector().DetectSubType(IsoStream)) { case FormatDetector.SubType.Pbp: var PBP = new Pbp().Load(File.OpenRead(IsoFile)); ParamSfo = new Psf(PBP[Pbp.Types.ParamSfo]); Icon0Png = PBP.ContainsKey(Pbp.Types.Icon0Png) ? PBP[Pbp.Types.Icon0Png].ReadAll() : DefaultIcon; UmdData = "---"; break; case FormatDetector.SubType.Iso: case FormatDetector.SubType.Cso: case FormatDetector.SubType.Dax: using (var Iso = IsoLoader.GetIso(IsoFile)) { var FileSystem = new HleIoDriverIso(Iso); if (!FileSystem.FileExists("/PSP_GAME/PARAM.SFO")) { throw (new Exception($"Not a PSP ISO '{IsoFile}'")); } ParamSfo = new Psf(new MemoryStream(FileSystem.OpenRead("/PSP_GAME/PARAM.SFO").ReadAll())); if (FileSystem.FileExists("/UMD_DATA.BIN")) { UmdData = FileSystem.OpenRead("/UMD_DATA.BIN").ReadAllContentsAsString(); } Icon0Png = FileSystem.FileExists("/PSP_GAME/ICON0.PNG") ? FileSystem.OpenRead("/PSP_GAME/ICON0.PNG").ReadAll() : DefaultIcon; Entry.PatchedWithPrometheus = FileSystem.FileExists("/PSP_GAME/SYSDIR/prometheus.prx") || FileSystem.FileExists("/PSP_GAME/SYSDIR/EBOOT.OLD"); } break; default: return(null); } } FillGameEntryFromSfo(Entry, ParamSfo); Entry.IsoSize = IsoFileInfo.Length; Entry.Hash = GetHash(IsoFile); Entry.IsoFile = IsoFile; Entry.DiscId0 = UmdData.Split('|')[0]; Entry.Icon0Png = Icon0Png; return(Entry); }
public void _LoadFile(string fileName) { //GC.Collect(); SetVirtualFolder(Path.GetDirectoryName(fileName)); var memoryStream = new PspMemoryStream(PspMemory); var arguments = new[] { "ms0:/PSP/GAME/virtual/EBOOT.PBP", }; Stream loadStream = File.OpenRead(fileName); //using () { var elfLoadStreamTry = new List <Stream>(); //Stream ElfLoadStream = null; var format = new FormatDetector().DetectSubType(loadStream); string title = null; switch (format) { case FormatDetector.SubType.Pbp: { var pbp = new Pbp().Load(loadStream); elfLoadStreamTry.Add(pbp[Pbp.Types.PspData]); Logger.TryCatch(() => { var paramSfo = new Psf().Load(pbp[Pbp.Types.ParamSfo]); if (paramSfo.EntryDictionary.ContainsKey("TITLE")) { title = (string)paramSfo.EntryDictionary["TITLE"]; } if (paramSfo.EntryDictionary.ContainsKey("PSP_SYSTEM_VER")) { HleConfig.FirmwareVersion = paramSfo.EntryDictionary["PSP_SYSTEM_VER"].ToString(); } }); } break; case FormatDetector.SubType.Elf: elfLoadStreamTry.Add(loadStream); break; case FormatDetector.SubType.Dax: case FormatDetector.SubType.Cso: case FormatDetector.SubType.Iso: { arguments[0] = "disc0:/PSP/GAME/SYSDIR/EBOOT.BIN"; var iso = SetIso(fileName); Logger.TryCatch(() => { var paramSfo = new Psf().Load(iso.Root.Locate("/PSP_GAME/PARAM.SFO").Open()); title = (string)paramSfo.EntryDictionary["TITLE"]; }); var filesToTry = new[] { "/PSP_GAME/SYSDIR/BOOT.BIN", "/PSP_GAME/SYSDIR/EBOOT.BIN", "/PSP_GAME/SYSDIR/EBOOT.OLD", }; foreach (var fileToTry in filesToTry) { try { elfLoadStreamTry.Add(iso.Root.Locate(fileToTry).Open()); } catch (Exception e) { Console.WriteLine(e); } //if (ElfLoadStream.Length != 0) break; } /* * if (ElfLoadStream.Length == 0) * { * throw (new Exception(String.Format("{0} files are empty", String.Join(", ", FilesToTry)))); * } */ } break; default: throw (new NotImplementedException("Can't load format '" + format + "'")); } Exception loadException = null; HleModuleGuest hleModuleGuest = null; foreach (var elfLoadStream in elfLoadStreamTry) { try { loadException = null; if (elfLoadStream.Length < 256) { throw(new InvalidProgramException("File too short")); } hleModuleGuest = Loader.LoadModule( elfLoadStream, memoryStream, MemoryManager.GetPartition(MemoryPartitions.User), ModuleManager, title, moduleName: fileName, isMainModule: true ); loadException = null; break; } catch (InvalidProgramException e) { loadException = e; } } if (loadException != null) { throw loadException; } RegisterSyscalls(); const uint startArgumentAddress = 0x08000100; var endArgumentAddress = startArgumentAddress; var argumentsChunk = arguments .Select(argument => Encoding.UTF8.GetBytes(argument + "\0")) .Aggregate(new byte[] { }, (accumulate, chunk) => accumulate.Concat(chunk)) ; var reservedSyscallsPartition = MemoryManager.GetPartition(MemoryPartitions.Kernel0).Allocate( 0x100, Name: "ReservedSyscallsPartition" ); var argumentsPartition = MemoryManager.GetPartition(MemoryPartitions.Kernel0).Allocate( argumentsChunk.Length, Name: "ArgumentsPartition" ); PspMemory.WriteBytes(argumentsPartition.Low, argumentsChunk); Debug.Assert(ThreadManForUser != null); // @TODO: Use Module Manager //var MainThread = ThreadManager.Create(); //var CpuThreadState = MainThread.CpuThreadState; var currentCpuThreadState = new CpuThreadState(CpuProcessor); { if (hleModuleGuest == null) { //throw new InvalidOperationException("hleModuleGuest == null"); } //CpuThreadState.PC = Loader.InitInfo.PC; currentCpuThreadState.Gp = hleModuleGuest.InitInfo.Gp; currentCpuThreadState.CallerModule = hleModuleGuest; var threadId = (int)ThreadManForUser.sceKernelCreateThread(currentCpuThreadState, "<EntryPoint>", hleModuleGuest.InitInfo.Pc, 10, 0x1000, PspThreadAttributes.ClearStack, null); //var Thread = HleThreadManager.GetThreadById(ThreadId); ThreadManForUser._sceKernelStartThread(currentCpuThreadState, threadId, argumentsPartition.Size, argumentsPartition.Low); //Console.WriteLine("RA: 0x{0:X}", CurrentCpuThreadState.RA); } currentCpuThreadState.DumpRegisters(); MemoryManager.GetPartition(MemoryPartitions.User).Dump(); //ModuleManager.LoadedGuestModules.Add(HleModuleGuest); //MainThread.CurrentStatus = HleThread.Status.Ready; } }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pPsfDataFinderStruct, DoWorkEventArgs e) { PsfDataFinderStruct psfStruct = (PsfDataFinderStruct)pPsfDataFinderStruct; this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format("[{0}]{1}", pPath, Environment.NewLine); this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); long offset; string seqName; int seqNumber = 0; ArrayList seqFiles = new ArrayList(); bool seqNamingMessageDisplayed = false; string sepName; int sepNumber = 0; ArrayList sepFiles = new ArrayList(); bool sepNamingMessageDisplayed = false; int vhNumber = 0; int minSampleSize = -1; int maxSampleSize = -1; int minRowLength; VhStruct vhObject; long sampleOffset; ArrayList vhArrayList = new ArrayList(); ArrayList emptyRowList = new ArrayList(); ProbableVbStruct potentialVb; ProbableVbStruct[] potentialVbList; byte[] vbRow = new byte[0x10]; long previousVbOffset = -1; // improve algorithm later using (FileStream fs = File.OpenRead(pPath)) { string destinationFolder = Path.Combine(Path.GetDirectoryName(pPath), Path.GetFileNameWithoutExtension(pPath)); // get VH files #region VH EXTRACT this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" Extracting VH{0}", Environment.NewLine); this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); offset = 0; while ((offset = ParseFile.GetNextOffset(fs, offset, XsfUtil.VAB_SIGNATURE)) > -1) { vhObject = new VhStruct(); vhObject.FileName = String.Format("{0}_{1}.VH", Path.GetFileNameWithoutExtension(pPath), vhNumber++.ToString("X4")); vhObject.startingOffset = offset; vhObject.vhProgramCount = BitConverter.ToUInt16(ParseFile.ParseSimpleOffset(fs, (offset + 0x12), 2), 0); vhObject.vbSampleCount = BitConverter.ToUInt16(ParseFile.ParseSimpleOffset(fs, (offset + 0x16), 2), 0); vhObject.vbSampleSizes = new uint[vhObject.vbSampleCount]; vhObject.length = 2592 + (512 * vhObject.vhProgramCount); vhObject.vabSize = BitConverter.ToUInt32(ParseFile.ParseSimpleOffset(fs, offset + 0xC, 4), 0); vhObject.expectedVbLength = vhObject.vabSize - vhObject.length; vhObject.offsetTableOffset = offset + (512 * vhObject.vhProgramCount) + 2080; vhObject.offsetTableOffset += 2; // not sure but seems to be needed vhObject.IsSmallSamplePresent = false; vhObject.HasHeaderMismatch = false; for (int i = 0; i < vhObject.vbSampleCount; i++) { sampleOffset = vhObject.offsetTableOffset + (i * 2); vhObject.vbSampleSizes[i] = (uint)BitConverter.ToUInt16(ParseFile.ParseSimpleOffset(fs, sampleOffset, 2), 0); vhObject.vbSampleSizes[i] <<= 3; vhObject.expectedVbLengthBySample += vhObject.vbSampleSizes[i]; if ((minSampleSize < 0) || (vhObject.vbSampleSizes[i] < minSampleSize)) { minSampleSize = (int)vhObject.vbSampleSizes[i]; if (minSampleSize < Psf.MIN_ADPCM_ROW_SIZE) { vhObject.IsSmallSamplePresent = true; } } // update max sample size if ((maxSampleSize < 0) || (vhObject.vbSampleSizes[i] > maxSampleSize)) { maxSampleSize = (int)vhObject.vbSampleSizes[i]; } } if (vhObject.expectedVbLength != vhObject.expectedVbLengthBySample) { vhObject.HasHeaderMismatch = true; //vhObject.expectedVbLength = vhObject.expectedVbLengthBySample; //this.progressStruct.Clear(); //this.progressStruct.GenericMessage = String.Format(" Warning, for VH <{0}>, header does not match samples' lengths. Ignoring header value.{1}", vhObject.FileName, Environment.NewLine); //this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); } vhArrayList.Add(vhObject); // extract file ParseFile.ExtractChunkToFile(fs, vhObject.startingOffset, (int)vhObject.length, Path.Combine(destinationFolder, vhObject.FileName), true, true); offset += 1; } #endregion // get SEQ Files #region SEQ EXTRACT this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" Extracting SEQ{0}", Environment.NewLine); this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); // get SEQ file list seqFiles = Psf.GetSeqFileList(fs, psfStruct.UseSeqMinimumSize, psfStruct.MinimumSize); foreach (Psf.ProbableItemStruct seq in seqFiles) { if (seq.length > 0) { if (psfStruct.ReorderSeqFiles) { if ((vhArrayList.Count < seqFiles.Count)) { if (!seqNamingMessageDisplayed) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format( "Warning, cannot reorder SEQ files, there are less VH files than SEQ files.{0}", Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); seqNamingMessageDisplayed = true; } seqName = String.Format("{0}_{1}.SEQ", Path.GetFileNameWithoutExtension(pPath), seqNumber++.ToString("X4")); } else { vhObject = (VhStruct)vhArrayList[vhArrayList.Count - seqFiles.Count + seqNumber++]; seqName = Path.ChangeExtension(vhObject.FileName, ".SEQ"); } } else { seqName = String.Format("{0}_{1}.SEQ", Path.GetFileNameWithoutExtension(pPath), seqNumber++.ToString("X4")); } ParseFile.ExtractChunkToFile(fs, seq.offset, (int)seq.length, Path.Combine(destinationFolder, seqName), true, true); } else { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format(" Warning SEQ found with length less than 0, at Offset 0x{1}: {2}{3}", seq.offset.ToString("X8"), seq.length.ToString("X8"), Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } } #endregion // get SEP Files #region SEP EXTRACT this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" Extracting SEP{0}", Environment.NewLine); this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); // get SEP file list sepFiles = Psf.GetSepFileList(fs); foreach (Psf.ProbableItemStruct sep in sepFiles) { if (sep.length > 0) { if (psfStruct.ReorderSeqFiles) { if ((vhArrayList.Count < sepFiles.Count)) { if (!sepNamingMessageDisplayed) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format( "Warning, cannot reorder SEP files, there are less VH files than SEP files.{0}", Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); sepNamingMessageDisplayed = true; } sepName = String.Format("{0}_{1}.SEP", Path.GetFileNameWithoutExtension(pPath), sepNumber++.ToString("X4")); } else { vhObject = (VhStruct)vhArrayList[vhArrayList.Count - sepFiles.Count + sepNumber++]; sepName = Path.ChangeExtension(vhObject.FileName, ".SEP"); } } else { sepName = String.Format("{0}_{1}.SEP", Path.GetFileNameWithoutExtension(pPath), sepNumber++.ToString("X4")); } ParseFile.ExtractChunkToFile(fs, sep.offset, (int)sep.length, Path.Combine(destinationFolder, sepName), true, true); } else { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format(" Warning SEP found with length less than 0, at Offset 0x{1}: {2}{3}", sep.offset.ToString("X8"), sep.length.ToString("X8"), Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } } #endregion // get VB files #region VB EXTRACT this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" Extracting VB...WARNING, THIS WILL TAKE A LONG TIME...{0}", Environment.NewLine); this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); offset = 0; // setup arrays for checking skips VhStruct[] vhList = (VhStruct[])vhArrayList.ToArray(typeof(VhStruct)); Psf.ProbableItemStruct[] seqList = (Psf.ProbableItemStruct[])seqFiles.ToArray(typeof(Psf.ProbableItemStruct)); Psf.ProbableItemStruct[] sepList = (Psf.ProbableItemStruct[])sepFiles.ToArray(typeof(Psf.ProbableItemStruct)); // build list of potential adpcm start indexes (VB_START_BYTES) potentialVb = new ProbableVbStruct(); // check for the smallest found size or use default //minRowLength = (minSampleSize / 0x10) - 1; // divide into rows //if ((minRowLength > 0) && (minRowLength > MIN_ADPCM_ROW_COUNT)) //{ minRowLength = Psf.MIN_ADPCM_ROW_COUNT; //} while ((offset = ParseFile.GetNextOffset(fs, offset, Psf.VB_START_BYTES, psfStruct.UseZeroOffsetForVb, 0x10, 0)) > -1) { //if (offset >= 0x42E83) //{ // int r = 1; //} if (!CancellationPending) { try { vbRow = ParseFile.ParseSimpleOffset(fs, offset, vbRow.Length); // check for potential sony adpcm signature, and also make sure this offset is not inside another // more easily parsed file since those formats are solid //if ((!InsideAnotherFile(offset, vhList, seqList, sepList)) && // (IsPotentialAdpcm(fs, offset + 0x10, minRowLength))) if (Psf.IsPotentialAdpcm(fs, offset + 0x10, minRowLength, false)) { // check if we have passed a different file type and reset previousVbOffset if we did if (SteppedOverAnotherFile(previousVbOffset, offset, vhList, seqList, sepList)) { // need to add flag here so length calculation doesn't screw up? previousVbOffset = -1; } // check if we have exceeded the max sample size and reset previous offset // so the chunk size check doesn't apply if ((offset - previousVbOffset) > maxSampleSize) { previousVbOffset = -1; } // try to preserve proper VB chunk size if ((previousVbOffset == -1) || ((offset - previousVbOffset) % 0x10 == 0)) { previousVbOffset = offset; potentialVb.offset = offset; emptyRowList.Add(potentialVb); } } } catch (Exception vbEx) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format(" ERROR finding VB for <{0}> at Offset 0x{1}: {2}{3}", pPath, offset.ToString("X8"), vbEx.Message, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } offset += 1; } else { e.Cancel = true; return; } } potentialVbList = (ProbableVbStruct[])emptyRowList.ToArray(typeof(ProbableVbStruct)); // set probable lengths for (int i = 0; i < potentialVbList.Length; i++) { if (i > 0) { potentialVbList[i - 1].length = (uint)(potentialVbList[i].offset - potentialVbList[i - 1].offset); } } // compare VH sample sizes to potential adpcm sizes/indexes vhObject.startingOffset = 0; vhObject.length = 0; vhObject.vbStartingOffset = 0; vhObject.vbLength = 0; string vbName; string newFileName; string[] dupeFileNames; for (int i = 0; i < vhArrayList.Count; i++) { vhObject = (VhStruct)vhArrayList[i]; if (vhObject.vbSampleSizes.Length < 1) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format(" ERROR building VB for <{0}>: {1} refers to a single VAG, cannot determine proper VB. Skipping...{2}", pPath, vhObject.FileName, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } else { for (int j = 0; j < potentialVbList.Length; j++) { // we have a potential match or are at the last item. skip rows that are too small if ((vhObject.vbSampleSizes[0] < Psf.MIN_ADPCM_ROW_SIZE) || (vhObject.vbSampleSizes[0] <= potentialVbList[j].length) || (potentialVbList[j].length == 0)) { try { vhObject = PopulateVbOffsetLength(fs, potentialVbList, j, vhObject, psfStruct.RelaxVbEofRestrictions); if (vhObject.vbLength > 0) { // check for other BD files that matched and rename accordingly dupeFileNames = Directory.GetFiles(destinationFolder, Path.GetFileNameWithoutExtension(vhObject.FileName) + "*.VB"); if (dupeFileNames.Length >= 1) { vbName = String.Format("{0}_{1}.VB", Path.GetFileNameWithoutExtension(vhObject.FileName), (dupeFileNames.Length).ToString("X4")); if (dupeFileNames.Length == 1) { // rename existing newFileName = String.Format("{0}_{1}.VB", Path.GetFileNameWithoutExtension(vhObject.FileName), (dupeFileNames.Length - 1).ToString("X4")); File.Move(dupeFileNames[0], Path.Combine(Path.GetDirectoryName(dupeFileNames[0]), newFileName)); } } else { vbName = Path.ChangeExtension(vhObject.FileName, ".VB"); } ParseFile.ExtractChunkToFile(fs, vhObject.vbStartingOffset, (int)vhObject.vbLength, Path.Combine(destinationFolder, vbName), true, true); } } catch (Exception ex) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format(" ERROR building VB for <{0}>: {1}{2}", pPath, ex.Message, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } } // if (vhObject.vbSampleSizes[0] == potentialVbList[j].length) } // for (int j = 0; j < potentialVbList.Length; j++) } } #endregion } }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pExtractSonyAdpcmStruct, DoWorkEventArgs e) { ExtractSonyAdpcmStruct extractSonyAdpcmStruct = (ExtractSonyAdpcmStruct)pExtractSonyAdpcmStruct; long offset = extractSonyAdpcmStruct.StartOffset; ArrayList adpcmList = new ArrayList(); Psf.ProbableItemStruct adpcmDataItem = new Psf.ProbableItemStruct(); int fileCount = 0; string outputPath = Path.Combine(Path.GetDirectoryName(pPath), "_sony_adpcm_ext"); string outputFileName; string outputFilePath; bool previousRowIsZeroes = false; FileInfo fi = new FileInfo(pPath); using (FileStream fs = File.Open(pPath, FileMode.Open, FileAccess.Read)) { while (offset < fi.Length) { if (!CancellationPending) { if (ExtractSonyAdpcmWorker.IsPotentialAdpcm(fs, offset, Psf.MIN_ADPCM_ROW_SIZE, false, ref previousRowIsZeroes)) { // create probable adpcm item adpcmDataItem.Init(); // set starting offset adpcmDataItem.offset = offset; // move to next row offset += Psf.SONY_ADPCM_ROW_SIZE; // loop until end while (Psf.IsSonyAdpcmRow(fs, offset)) { offset += Psf.SONY_ADPCM_ROW_SIZE; } adpcmDataItem.length = (uint)(offset - adpcmDataItem.offset); adpcmList.Add(adpcmDataItem); } offset += 1; } else { e.Cancel = true; return; } } // extract files foreach (Psf.ProbableItemStruct p in adpcmList) { outputFileName = String.Format("{0}_{1}.bin", Path.GetFileNameWithoutExtension(pPath), fileCount.ToString("X8")); outputFilePath = Path.Combine(outputPath, outputFileName); ParseFile.ExtractChunkToFile(fs, p.offset, (int)p.length, outputFilePath, extractSonyAdpcmStruct.OutputBatchFiles, extractSonyAdpcmStruct.OutputBatchFiles); fileCount++; } } }
private void DockPanel_Loaded(object sender, RoutedEventArgs e) { imgPsfPreview.Source = ToBitmap(Psf.ToRawImage()); }
protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pPspSeqDataFinderStruct, DoWorkEventArgs e) { PspSeqDataFinderStruct pspStruct = (PspSeqDataFinderStruct)pPspSeqDataFinderStruct; long offset; int phdNumber = 0; PphdStruct phdObject; ArrayList phdArrayList = new ArrayList(); string midName; int midNumber = 0; Psf.ProbableItemStruct midEntry; ArrayList midFiles = new ArrayList(); bool midNamingMessageDisplayed = false; Midi midiFile = new Midi(); Psf.ProbableItemStruct potentialPbd; Psf.ProbableItemStruct[] potentialPbdList; byte[] pbdRow = new byte[Psf.SONY_ADPCM_ROW_SIZE]; ArrayList emptyRowList = new ArrayList(); // display file name this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format("[{0}]{1}", pPath, Environment.NewLine); this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); // open file using (FileStream fs = File.OpenRead(pPath)) { string destinationFolder = Path.Combine(Path.GetDirectoryName(pPath), Path.GetFileNameWithoutExtension(pPath)); // get PHD files #region PHD EXTRACT this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" Extracting PHD{0}", Environment.NewLine); this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); offset = 0; while ((offset = ParseFile.GetNextOffset(fs, offset, PPHD_SIGNATURE)) > -1) { try { // get PPHD data phdObject = GetPphdData(fs, offset); phdObject.FileName = String.Format("{0}_{1}.PHD", Path.GetFileNameWithoutExtension(pPath), phdNumber++.ToString("X4")); // extract the file ParseFile.ExtractChunkToFile(fs, offset, (int)phdObject.length, Path.Combine(destinationFolder, phdObject.FileName), true, true); // add to array phdArrayList.Add(phdObject); } catch (Exception pphdEx) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format(" Error extracting PPHD at offset 0x{0}: {1}{2}", offset.ToString("X8"), pphdEx.Message, Environment.NewLine); ReportProgress(progress, this.progressStruct); } // increment offset offset += 1; } #endregion // get MID Files #region MID EXTRACT this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" Extracting MID{0}", Environment.NewLine); this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); midEntry = new Psf.ProbableItemStruct(); offset = 0; // build file list while ((offset = ParseFile.GetNextOffset(fs, offset, Midi.ASCII_SIGNATURE_MTHD)) > -1) { midiFile.Initialize(fs, pPath, offset); midEntry.offset = midiFile.FileStartOffset; midEntry.length = (uint)midiFile.TotalFileLength; midFiles.Add(midEntry); offset += 1; } foreach (Psf.ProbableItemStruct mid in midFiles) { if (pspStruct.ReorderMidFiles) { if (phdArrayList.Count < midFiles.Count) { if (!midNamingMessageDisplayed) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format( "Warning, cannot reorder MID files, there are less PHD files than MID files.{0}", Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); midNamingMessageDisplayed = true; } midName = String.Format("{0}_{1}.MID", Path.GetFileNameWithoutExtension(pPath), midNumber++.ToString("X4")); } else { phdObject = (PphdStruct)phdArrayList[phdArrayList.Count - midFiles.Count + midNumber++]; midName = Path.ChangeExtension(phdObject.FileName, ".MID"); } } else { midName = String.Format("{0}_{1}.MID", Path.GetFileNameWithoutExtension(pPath), midNumber++.ToString("X4")); } ParseFile.ExtractChunkToFile(fs, mid.offset, (int)mid.length, Path.Combine(destinationFolder, midName), true, true); } #endregion // get PBD files #region PBD EXTRACT this.progressStruct.Clear(); this.progressStruct.GenericMessage = String.Format(" Extracting PBD...WARNING, THIS CAN TAKE A LONG TIME...{0}", Environment.NewLine); this.ReportProgress(Constants.ProgressMessageOnly, this.progressStruct); offset = 0; // build list of potential adpcm start indexes potentialPbd = new Psf.ProbableItemStruct(); // build list of potential adpcm start indexes while ((offset = ParseFile.GetNextOffset(fs, offset, Psf.VB_START_BYTES, pspStruct.UseZeroOffsetForPbd, 0x10L, 0x00L, true)) > -1) { try { pbdRow = ParseFile.ParseSimpleOffset(fs, offset, pbdRow.Length); if (Psf.IsPotentialAdpcm(fs, offset + 0x10, Psf.MIN_ADPCM_ROW_COUNT, false)) { potentialPbd.offset = offset; emptyRowList.Add(potentialPbd); } } catch (Exception pbdEx) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format(" ERROR finding BD for <{0}> at Offset 0x{1}: {2}{3}", pPath, offset.ToString("X8"), pbdEx.Message, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } offset += 1; } potentialPbdList = (Psf.ProbableItemStruct[])emptyRowList.ToArray(typeof(Psf.ProbableItemStruct)); // set probable lengths for (int i = 0; i < potentialPbdList.Length; i++) { if (i > 0) { potentialPbdList[i - 1].length = (uint)(potentialPbdList[i].offset - potentialPbdList[i - 1].offset); } } // compare PHD sample sizes to potential adpcm sizes/indexes phdObject.startingOffset = 0; phdObject.length = 0; phdObject.pbdStartingOffset = 0; phdObject.pbdLength = 0; string pbdName; string newFileName; string[] dupeFileNames; for (int i = 0; i < phdArrayList.Count; i++) { phdObject = (PphdStruct)phdArrayList[i]; if (phdObject.vagLengths.Length < 1) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format(" ERROR building PBD for <{0}>: {1} refers to a single VAG, cannot determine proper PBD. Skipping...{2}", pPath, phdObject.FileName, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } else { for (int j = 0; j < potentialPbdList.Length; j++) { // we have a potential match or are at the last item. if ((phdObject.vagLengths[0] <= potentialPbdList[j].length) || (potentialPbdList[j].length == 0)) { try { phdObject = PopulatePbdOffsetLength(fs, potentialPbdList, j, phdObject); if (phdObject.pbdLength > 0) { // check for other BD files that matched and rename accordingly dupeFileNames = Directory.GetFiles(destinationFolder, Path.GetFileNameWithoutExtension(phdObject.FileName) + "*.PBD"); if (dupeFileNames.Length >= 1) { pbdName = String.Format("{0}_{1}.PBD", Path.GetFileNameWithoutExtension(phdObject.FileName), (dupeFileNames.Length).ToString("X4")); if (dupeFileNames.Length == 1) { // rename existing newFileName = String.Format("{0}_{1}.PBD", Path.GetFileNameWithoutExtension(phdObject.FileName), (dupeFileNames.Length - 1).ToString("X4")); File.Move(dupeFileNames[0], Path.Combine(Path.GetDirectoryName(dupeFileNames[0]), newFileName)); } } else { pbdName = Path.ChangeExtension(phdObject.FileName, ".PBD"); } ParseFile.ExtractChunkToFile(fs, phdObject.pbdStartingOffset, phdObject.pbdLength, Path.Combine(destinationFolder, pbdName), true, true); } } catch (Exception ex) { this.progressStruct.Clear(); this.progressStruct.ErrorMessage = String.Format(" ERROR building BD for <{0}>: {1}{2}", pPath, ex.Message, Environment.NewLine); this.ReportProgress(this.progress, this.progressStruct); } } } } } #endregion } }
public static void SelfTest() { string filepath = @"C:\Users\htna\htnasvn_htna\VisualStudioSolutions\Library2\HTLib2.Bioinfo\Sample\1a6g_autopsf.psf"; Psf psf = Psf.FromFile(filepath); }