public MainWindow(IAppArguments appArguments) { using var sw = new BenchmarkTimer("MainWindow", Log); Log.Debug($"Initializing MainWindow for process {appArguments.ProcessId}"); InitializeComponent(); sw.Step($"BAML loaded"); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); using var sw = new BenchmarkTimer("MainWindow initialization routine", Log); Log.Info($"Application startup detected, PID: {Process.GetCurrentProcess().Id}"); SingleInstanceValidationRoutine(true); sw.Step("Registering overlay"); var micSwitchOverlayDependencyName = "MicSwitchOverlayAllWindows"; container.RegisterOverlayController(micSwitchOverlayDependencyName, micSwitchOverlayDependencyName); var matcher = new RegexStringMatcher().AddToWhitelist(".*"); container.RegisterWindowTracker(micSwitchOverlayDependencyName, matcher); var overlayController = container.Resolve <IOverlayWindowController>(micSwitchOverlayDependencyName); var overlayViewModelFactory = container.Resolve <IFactory <IMicSwitchOverlayViewModel, IOverlayWindowController> >(); var overlayViewModel = overlayViewModelFactory.Create(overlayController).AddTo(Anchors); overlayController.RegisterChild(overlayViewModel); var mainWindow = container.Resolve <MainWindow.Views.MainWindow>(); sw.Step($"Main window view initialized"); var viewController = new WindowViewController(mainWindow); var mainWindowViewModel = container.Resolve <IMainWindowViewModel>(new DependencyOverride <IViewController>(viewController)).AddTo(Anchors); sw.Step($"Main window view model resolved"); mainWindow.DataContext = mainWindowViewModel; sw.Step($"Main window view model assigned"); mainWindow.Show(); sw.Step($"Main window shown"); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); InitializeContainer(); using var sw = new BenchmarkTimer("MainWindow initialization routine", Log); Log.Info($"Application startup detected, PID: {Process.GetCurrentProcess().Id}"); Log.Debug("Resolving squirrel events handler"); var squirrelEventsHandler = Container.Resolve <ISquirrelEventsHandler>(); Log.Debug(() => $"Resolved squirrel events handler: {squirrelEventsHandler}"); SingleInstanceValidationRoutine(true); var configProvider = Container.Resolve <IConfigProvider>(); var defaultConfigProviderStrategy = Container.Resolve <UseDefaultIfFailureConfigProviderStrategy>(); configProvider.RegisterStrategy(defaultConfigProviderStrategy); Log.Debug("Loading initial configuration"); configProvider.Reload(); Log.Debug("Initial configuration loaded"); InitializeUpdateSettings(); sw.Step("Actualizing configuration format"); Log.Debug("Initializing config provider"); var hotkeyConfigProvider = Container.Resolve <IConfigProvider <MicSwitchHotkeyConfig> >(); var overlayConfigProvider = Container.Resolve <IConfigProvider <MicSwitchOverlayConfig> >(); var mainConfigProvider = Container.Resolve <IConfigProvider <MicSwitchConfig> >(); ActualizeConfig(mainConfigProvider, hotkeyConfigProvider); ActualizeConfig(mainConfigProvider, overlayConfigProvider); ActualizeConfig(mainConfigProvider); sw.Step("Registering overlay"); var overlayController = Container.Resolve <IOverlayWindowController>(WellKnownWindows.AllWindows); var overlayViewModelFactory = Container.Resolve <IFactory <IMicSwitchOverlayViewModel, IOverlayWindowController> >(); var overlayViewModel = overlayViewModelFactory.Create(overlayController).AddTo(Anchors); var mainWindow = Container.Resolve <MainWindow.Views.MainWindow>(); Current.MainWindow = mainWindow; sw.Step($"Main window view initialized"); var viewController = new WindowViewController(mainWindow); var mainWindowViewModel = Container.Resolve <IMainWindowViewModel>( new DependencyOverride <IWindowViewController>(viewController), new DependencyOverride <IOverlayWindowController>(overlayController)).AddTo(Anchors); sw.Step($"Main window view model resolved"); mainWindow.DataContext = mainWindowViewModel; sw.Step($"Main window view model assigned"); mainWindow.Show(); sw.Step($"Main window shown"); }
public async UniTask Initialize() { // Clear Clear(); foreach (var type in new[] { typeof(Text), typeof(Sprite), typeof(Line), typeof(Video), typeof(Controller), typeof(NoteController) }) { TypedComponentRenderers[type] = new List <StoryboardComponentRenderer>(); } var timer = new BenchmarkTimer("StoryboardRenderer initialization"); bool Predicate <TO>(TO obj) where TO : Object => !obj.IsManuallySpawned(); await SpawnObjects <NoteController, NoteControllerState, NoteControllerRenderer>(Storyboard.NoteControllers.Values.ToList(), noteController => new NoteControllerRenderer(this, noteController), Predicate); timer.Time("NoteController"); // Spawn note placeholder transforms await SpawnObjects <Text, TextState, TextRenderer>(Storyboard.Texts.Values.ToList(), text => new TextRenderer(this, text), Predicate); timer.Time("Text"); await SpawnObjects <Sprite, SpriteState, SpriteRenderer>(Storyboard.Sprites.Values.ToList(), sprite => new SpriteRenderer(this, sprite), Predicate); timer.Time("Sprite"); await SpawnObjects <Line, LineState, LineRenderer>(Storyboard.Lines.Values.ToList(), line => new LineRenderer(this, line), Predicate); timer.Time("Line"); await SpawnObjects <Video, VideoState, VideoRenderer>(Storyboard.Videos.Values.ToList(), line => new VideoRenderer(this, line), Predicate); timer.Time("Video"); await SpawnObjects <Controller, ControllerState, ControllerRenderer>(Storyboard.Controllers.Values.ToList(), controller => new ControllerRenderer(this, controller), Predicate); timer.Time("Controller"); timer.Time(); // Clear on abort/retry/complete Game.onGameDisposed.AddListener(_ => { Dispose(); }); Game.onGamePaused.AddListener(_ => { // TODO: Pause SB }); Game.onGameWillUnpause.AddListener(_ => { // TODO: Unpause SB }); }
static public void Main(string[] args) { ConfirmQuickSyncReadiness.HaltIfNotReady(); Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; // keep ascending directories until 'media' folder is found for (int i = 0; i < 10 && !Directory.Exists("Media"); i++) { Directory.SetCurrentDirectory(".."); } Directory.SetCurrentDirectory("Media"); mfxIMPL impl = mfxIMPL.MFX_IMPL_AUTO; CodecId inputCodecId = CodecId.MFX_CODEC_JPEG; CodecId outputCodecId = CodecId.MFX_CODEC_JPEG; string outputExtension = ".transcoded.264";//this should match codecld above string inFilename; inFilename = @"C:\x\core-imaging-playground\images\IMG_2301.jpg"; // inFilename = "BigBuckBunny_320x180.264"; //inFilename = "BigBuckBunny_1920x1080.264"; //inFilename = "BigBuckBunny_3840x2160.264"; string outFilename = Path.ChangeExtension(inFilename, outputExtension); Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory); Console.WriteLine("Input filename: {0}", inFilename); Console.WriteLine(); if (!File.Exists(inFilename)) { Console.WriteLine("Input file not found. Press any key to exit."); Console.ReadKey(); return; } Stream infs, outfs; BenchmarkTimer bt = null; #if !ENABLE_BENCHMARK infs = File.Open(inFilename, FileMode.Open); outfs = File.Open(outFilename, FileMode.Create); #else // delete this code for most simple example // * Benchmark Mode * // this block does a couple things: // 1. causes the file to be pre-read into memory so we are not timing disk reads. // 2. replaces the output stream with a NullStream so nothing gets written to disk. // 3. Starts the timer for benchmarking // this pre-reads file into memory for benchmarking // maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024; Console.WriteLine("Pre-reading input"); infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open)); Console.WriteLine("Input read"); outfs = new NullStream(); bt = new BenchmarkTimer(); bt.Start(); //int minimumFrames = 4000; #endif Console.WriteLine("Output filename: {0}", Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT")); Console.WriteLine(); var config = TranscoderConfiguration.BuildTranscoderConfigurationFromStream(infs, inputCodecId, outputCodecId); var transcoder = new StreamTranscoder(infs, config, impl, false); string impltext = QuickSyncStatic.ImplementationString(transcoder.lowLevelTranscoder.session); Console.WriteLine("Implementation = {0}", impltext); //string memtext = QuickSyncStatic.ImplementationString(transcoder.lowLevelTranscoder.deviceSetup.memType); //Console.WriteLine("Memory type = {0}", memtext); int modulo = 100; int count = 0; foreach (var item in transcoder.GetFrames()) { outfs.Write(item.bitstream, 0, item.bytesAvailable); if (++count % modulo == 0) { Console.Write("Frames transcoded {0}\r", count); } } Console.WriteLine("Frames transcoded {0}", count); Console.WriteLine(); if (bt != null) { bt.StopAndReport(count, infs.Position, outfs.Position); } infs.Close(); outfs.Close(); if (Debugger.IsAttached) { Console.WriteLine("done - press a key to exit"); Console.ReadKey(); } }
static void Main(string[] args) { ConfirmQuickSyncReadiness.HaltIfNotReady(); Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; // keep ascending directories until 'media' folder is found for (int i = 0; i < 10 && !Directory.Exists("Media"); i++) { Directory.SetCurrentDirectory(".."); } Directory.SetCurrentDirectory("Media"); int width, height; string inFilename; mfxIMPL impl = mfxIMPL.MFX_IMPL_AUTO; FourCC fourcc = FourCC.NV12; // supported: RGB3 RGB4 BGR4 BGR3 NV12 I420 IYUV YUY2 UYVY YV12 P411 P422 inFilename = "BigBuckBunny_320x180." + fourcc + ".yuv"; width = 320; height = 180; //inFilename = "BigBuckBunny_1920x1080." + fourcc + ".yuv"; width = 1920; height = 1080; string outFilename = Path.ChangeExtension(inFilename, "enc.264"); Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory); Console.WriteLine("Input filename: {0}", inFilename); Console.WriteLine("Input width: {0} Input height: {1}", width, height); Console.WriteLine(); if (!File.Exists(inFilename)) { Console.WriteLine("Input file not found."); Console.WriteLine("Please let Decoder1 run to completion to create input file"); Console.WriteLine("Press any key to exit."); Console.ReadKey(); return; } Stream infs, outfs; BenchmarkTimer bt = null; #if !ENABLE_BENCHMARK infs = File.Open(inFilename, FileMode.Open); outfs = File.Open(outFilename, FileMode.Create); #else // delete this code for most simple example // * Benchmark Mode * // this block does a couple things: // 1. causes the file to be pre-read into memory so we are not timing disk reads. // 2. replaces the output stream with a NullStream so nothing gets written to disk. // 3. Starts the timer for benchmarking // this pre-reads file into memory for benchmarking long maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024; Console.WriteLine("Pre-reading input"); infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open), maximumMemoryToAllocate); Console.WriteLine("Input read"); outfs = new NullStream(); bt = new BenchmarkTimer(); bt.Start(); int minimumFrames = 4000; #endif Console.WriteLine("Output filename: {0}", Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT")); Console.WriteLine(); mfxVideoParam mfxEncParams = new mfxVideoParam(); mfxEncParams.mfx.CodecId = CodecId.MFX_CODEC_AVC; mfxEncParams.mfx.TargetUsage = TargetUsage.MFX_TARGETUSAGE_BALANCED; mfxEncParams.mfx.TargetKbps = 2000; mfxEncParams.mfx.RateControlMethod = RateControlMethod.MFX_RATECONTROL_VBR; mfxEncParams.mfx.FrameInfo.FrameRateExtN = 30; mfxEncParams.mfx.FrameInfo.FrameRateExtD = 1; mfxEncParams.mfx.FrameInfo.FourCC = FourCC.NV12; mfxEncParams.mfx.FrameInfo.ChromaFormat = ChromaFormat.MFX_CHROMAFORMAT_YUV420; mfxEncParams.mfx.FrameInfo.PicStruct = PicStruct.MFX_PICSTRUCT_PROGRESSIVE; mfxEncParams.mfx.FrameInfo.CropX = 0; mfxEncParams.mfx.FrameInfo.CropY = 0; mfxEncParams.mfx.FrameInfo.CropW = (ushort)width; mfxEncParams.mfx.FrameInfo.CropH = (ushort)height; // Width must be a multiple of 16 // Height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture mfxEncParams.mfx.FrameInfo.Width = QuickSyncStatic.ALIGN16(width); mfxEncParams.mfx.FrameInfo.Height = QuickSyncStatic.AlignHeightTo32or16(height, mfxEncParams.mfx.FrameInfo.PicStruct); mfxEncParams.IOPattern = IOPattern.MFX_IOPATTERN_IN_SYSTEM_MEMORY; // must be 'in system memory' mfxEncParams.AsyncDepth = 4; // Pipeline depth. Best at 4 BitStreamChunk bsc = new BitStreamChunk(); //where we receive compressed frame data //var encoder = new LowLevelEncoder2(mfxEncParams, impl); ILowLevelEncoder encoder = new LowLevelEncoder(mfxEncParams, impl); string impltext = QuickSyncStatic.ImplementationString(encoder.session); Console.WriteLine("Implementation = {0}", impltext); //string memtext = QuickSyncStatic.ImplementationString(encoder.deviceSetup.memType); //Console.WriteLine("Memory type = {0}", memtext); var formatConverter = new NV12FromXXXXConverter(fourcc, width, height); int inputFrameLength = width * height * VideoUtility.GetBitsPerPixel(fourcc) / 8; byte[] uncompressed = new byte[inputFrameLength]; int count = 0; while (infs.Read(uncompressed, 0, inputFrameLength) == inputFrameLength) { int ix = encoder.GetFreeFrameIndex(); //get index of free surface formatConverter.ConvertToNV12FrameSurface(ref encoder.Frames[ix], uncompressed, 0); encoder.EncodeFrame(ix, ref bsc); if (bsc.bytesAvailable > 0) { outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable); if (++count % 100 == 0) { Console.Write("Frame {0}\r", count); } } #if ENABLE_BENCHMARK // delete this code for most simple example if (infs.Position + inputFrameLength - 1 >= infs.Length) { infs.Position = 0; } if (count >= minimumFrames) { break; } #endif } while (encoder.Flush(ref bsc)) { if (bsc.bytesAvailable > 0) { outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable); if (++count % 100 == 0) { Console.Write("Frame {0}\r", count); } } } if (bt != null) { bt.StopAndReport(count, infs.Position, outfs.Position); } infs.Close(); outfs.Close(); encoder.Dispose(); Console.WriteLine("Encoded {0} frames", count); if (Debugger.IsAttached) { Console.WriteLine("done - press a key to exit"); Console.ReadKey(); } }
public static IEnumerator StartServer(bool doLoad, string saveFileOverride, bool allowOutOfDateSaves) { float timeScale = UnityEngine.Time.timeScale; if (ConVar.Time.pausewhileloading) { UnityEngine.Time.timeScale = 0f; } RCon.Initialize(); BaseEntity.Query.Server = new BaseEntity.Query.EntityTree(8096f); if ((bool)SingletonComponent <WorldSetup> .Instance) { yield return(SingletonComponent <WorldSetup> .Instance.StartCoroutine(SingletonComponent <WorldSetup> .Instance.InitCoroutine())); } if ((bool)SingletonComponent <DynamicNavMesh> .Instance && SingletonComponent <DynamicNavMesh> .Instance.enabled && !AiManager.nav_disable) { yield return(SingletonComponent <DynamicNavMesh> .Instance.StartCoroutine(SingletonComponent <DynamicNavMesh> .Instance.UpdateNavMeshAndWait())); } if ((bool)SingletonComponent <AiManager> .Instance && SingletonComponent <AiManager> .Instance.enabled) { SingletonComponent <AiManager> .Instance.Initialize(); if (!AiManager.nav_disable && AI.npc_enable && TerrainMeta.Path != null) { foreach (MonumentInfo monument in TerrainMeta.Path.Monuments) { if (monument.HasNavmesh) { yield return(monument.StartCoroutine(monument.GetMonumentNavMesh().UpdateNavMeshAndWait())); } } if ((bool)TerrainMeta.Path && (bool)TerrainMeta.Path.DungeonRoot) { DungeonNavmesh dungeonNavmesh = TerrainMeta.Path.DungeonRoot.AddComponent <DungeonNavmesh>(); dungeonNavmesh.NavMeshCollectGeometry = NavMeshCollectGeometry.PhysicsColliders; dungeonNavmesh.LayerMask = 65537; yield return(dungeonNavmesh.StartCoroutine(dungeonNavmesh.UpdateNavMeshAndWait())); } else { Debug.LogError("Failed to find DungeonRoot, NOT generating Dungeon navmesh"); } } } GameObject gameObject = GameManager.server.CreatePrefab("assets/bundled/prefabs/system/server.prefab"); Object.DontDestroyOnLoad(gameObject); ServerMgr serverMgr = gameObject.GetComponent <ServerMgr>(); serverMgr.Initialize(doLoad, saveFileOverride, allowOutOfDateSaves); yield return(CoroutineEx.waitForSecondsRealtime(0.1f)); SaveRestore.InitializeEntityLinks(); yield return(CoroutineEx.waitForSecondsRealtime(0.1f)); SaveRestore.InitializeEntitySupports(); yield return(CoroutineEx.waitForSecondsRealtime(0.1f)); SaveRestore.InitializeEntityConditionals(); yield return(CoroutineEx.waitForSecondsRealtime(0.1f)); SaveRestore.GetSaveCache(); yield return(CoroutineEx.waitForSecondsRealtime(0.1f)); BaseGameMode.CreateGameMode(); yield return(CoroutineEx.waitForSecondsRealtime(0.1f)); serverMgr.OpenConnection(); CompanionServer.Server.Initialize(); using (BenchmarkTimer.New("Boombox.LoadStations")) { BoomBox.LoadStations(); } if (ConVar.Time.pausewhileloading) { UnityEngine.Time.timeScale = timeScale; } WriteToLog("Server startup complete"); }
private IEnumerator Start() { WriteToLog("Bootstrap Startup"); BenchmarkTimer.Enabled = Facepunch.Utility.CommandLine.Full.Contains("+autobench"); BenchmarkTimer timer = BenchmarkTimer.New("bootstrap"); if (!UnityEngine.Application.isEditor) { ExceptionReporter.InitializeFromUrl("https://*****:*****@sentry.io/51080"); ExceptionReporter.Disabled = !Facepunch.Utility.CommandLine.Full.Contains("-official") && !Facepunch.Utility.CommandLine.Full.Contains("-server.official") && !Facepunch.Utility.CommandLine.Full.Contains("+official") && !Facepunch.Utility.CommandLine.Full.Contains("+server.official"); BuildInfo current = BuildInfo.Current; if (current.Scm.Branch != null && current.Scm.Branch.StartsWith("main")) { ExceptionReporter.InitializeFromUrl("https://*****:*****@sentry.io/1836389"); ExceptionReporter.Disabled = false; } } if (AssetBundleBackend.Enabled) { AssetBundleBackend newBackend = new AssetBundleBackend(); using (BenchmarkTimer.New("bootstrap;bundles")) { yield return(StartCoroutine(LoadingUpdate("Opening Bundles"))); newBackend.Load("Bundles/Bundles"); FileSystem.Backend = newBackend; } if (FileSystem.Backend.isError) { ThrowError(FileSystem.Backend.loadingError); yield break; } using (BenchmarkTimer.New("bootstrap;bundlesindex")) { newBackend.BuildFileIndex(); } } if (FileSystem.Backend.isError) { ThrowError(FileSystem.Backend.loadingError); yield break; } if (!UnityEngine.Application.isEditor) { WriteToLog(SystemInfoGeneralText.currentInfo); } UnityEngine.Texture.SetGlobalAnisotropicFilteringLimits(1, 16); if (isErrored) { yield break; } using (BenchmarkTimer.New("bootstrap;gamemanifest")) { yield return(StartCoroutine(LoadingUpdate("Loading Game Manifest"))); GameManifest.Load(); yield return(StartCoroutine(LoadingUpdate("DONE!"))); } using (BenchmarkTimer.New("bootstrap;selfcheck")) { yield return(StartCoroutine(LoadingUpdate("Running Self Check"))); SelfCheck.Run(); } if (isErrored) { yield break; } yield return(StartCoroutine(LoadingUpdate("Bootstrap Tier0"))); using (BenchmarkTimer.New("bootstrap;tier0")) { Init_Tier0(); } using (BenchmarkTimer.New("bootstrap;commandlinevalues")) { ConsoleSystem.UpdateValuesFromCommandLine(); } yield return(StartCoroutine(LoadingUpdate("Bootstrap Systems"))); using (BenchmarkTimer.New("bootstrap;init_systems")) { Init_Systems(); } yield return(StartCoroutine(LoadingUpdate("Bootstrap Config"))); using (BenchmarkTimer.New("bootstrap;init_config")) { Init_Config(); } if (!isErrored) { yield return(StartCoroutine(LoadingUpdate("Loading Items"))); using (BenchmarkTimer.New("bootstrap;itemmanager")) { ItemManager.Initialize(); } if (!isErrored) { yield return(StartCoroutine(DedicatedServerStartup())); timer?.Dispose(); GameManager.Destroy(base.gameObject); } } }
public async UniTask <List <Level> > LoadFromMetadataFiles(LevelType type, List <string> jsonPaths, bool forceReload = false) { var lowMemory = false; Application.lowMemory += OnLowMemory; void OnLowMemory() { lowMemory = true; } var loadedCount = 0; var tasks = new List <UniTask>(); var results = new List <Level>(); int index; for (index = 0; index < jsonPaths.Count; index++) { var loadIndex = index; async UniTask LoadLevel() { var timer = new BenchmarkTimer($"Level loader ({loadIndex + 1} / {jsonPaths.Count})") { Enabled = false }; var jsonPath = jsonPaths[loadIndex]; try { FileInfo info; try { info = new FileInfo(jsonPath); if (info.Directory == null) { throw new FileNotFoundException(info.ToString()); } } catch (Exception e) { Debug.LogWarning(e); Debug.LogWarning($"{jsonPath} could not be read"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}"); return; } var path = info.Directory.FullName + Path.DirectorySeparatorChar; if (!forceReload && loadedPaths.Contains(path)) { Debug.LogWarning($"Level from {path} is already loaded"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}"); return; } Debug.Log($"Loading {loadIndex + 1}/{jsonPaths.Count} from {path}"); if (!File.Exists(jsonPath)) { Debug.LogWarning($"level.json not found at {jsonPath}"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}"); return; } await UniTask.SwitchToThreadPool(); var meta = JsonConvert.DeserializeObject <LevelMeta>(File.ReadAllText(jsonPath)); await UniTask.SwitchToMainThread(); timer.Time("Deserialization"); if (meta == null) { Debug.LogWarning($"Invalid level.json at {jsonPath}"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}"); return; } if (type != LevelType.Temp && LoadedLocalLevels.ContainsKey(meta.id)) { if (LoadedLocalLevels[meta.id].Type == LevelType.Tier && type == LevelType.User) { Debug.LogWarning($"Community level cannot override tier level"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}"); return; } if (LoadedLocalLevels[meta.id].Meta.version > meta.version) { Debug.LogWarning($"Level to load has smaller version than loaded level"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}"); return; } loadedPaths.Remove(LoadedLocalLevels[meta.id].Path); } // Sort charts meta.SortCharts(); // Reject invalid level meta if (!meta.Validate()) { Debug.LogWarning($"Invalid metadata in level.json at {jsonPath}"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}"); return; } timer.Time("Validate"); var db = Context.Database; await UniTask.SwitchToThreadPool(); var level = Level.FromLocal(path, type, meta, db); var record = level.Record; if (record.AddedDate == DateTimeOffset.MinValue) { record.AddedDate = Context.Library.Levels.ContainsKey(level.Id) ? Context.Library.Levels[level.Id].Date : info.LastWriteTimeUtc; level.SaveRecord(); } await UniTask.SwitchToMainThread(); timer.Time("LevelRecord"); if (type != LevelType.Temp) { LoadedLocalLevels[meta.id] = level; loadedPaths.Add(path); // Generate thumbnail if (!File.Exists(level.Path + CoverThumbnailFilename)) { var thumbnailPath = "file://" + level.Path + level.Meta.background.path; if (lowMemory) { // Give up Debug.LogWarning($"Low memory!"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}"); return; } using (var request = UnityWebRequest.Get(thumbnailPath)) { await request.SendWebRequest(); if (request.isNetworkError || request.isHttpError) { Debug.LogWarning(request.error); Debug.LogWarning($"Cannot get background texture from {thumbnailPath}"); Debug.LogWarning( $"Skipped generating thumbnail for {loadIndex + 1}/{jsonPaths.Count}: {meta.id} ({path})"); return; } var coverTexture = request.downloadHandler.data.ToTexture2D(); if (coverTexture == null) { Debug.LogWarning(request.error); Debug.LogWarning($"Cannot get background texture from {thumbnailPath}"); Debug.LogWarning( $"Skipped generating thumbnail for {loadIndex + 1}/{jsonPaths.Count}: {meta.id} ({path})"); return; } if (lowMemory) { // Give up Object.Destroy(coverTexture); Debug.LogWarning($"Low memory!"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}"); return; } var croppedTexture = TextureScaler.FitCrop(coverTexture, Context.LevelThumbnailWidth, Context.LevelThumbnailHeight); if (lowMemory) { // Give up Object.Destroy(coverTexture); Object.Destroy(croppedTexture); Debug.LogWarning($"Low memory!"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}"); return; } var bytes = croppedTexture.EncodeToJPG(); Object.Destroy(coverTexture); Object.Destroy(croppedTexture); await UniTask.DelayFrame(0); // Reduce load to prevent crash try { File.WriteAllBytes(level.Path + CoverThumbnailFilename, bytes); Debug.Log( $"Thumbnail generated {loadIndex + 1}/{jsonPaths.Count}: {level.Id} ({thumbnailPath})"); await UniTask.DelayFrame(0); // Reduce load to prevent crash } catch (Exception e) { Debug.LogWarning(e); Debug.LogWarning($"Could not write to {level.Path + CoverThumbnailFilename}"); Debug.LogWarning( $"Skipped generating thumbnail for {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}"); } } timer.Time("Generate thumbnail"); } } results.Add(level); OnLevelLoadProgress.Invoke(meta.id, ++loadedCount, jsonPaths.Count); Debug.Log($"Loaded {loadIndex + 1}/{jsonPaths.Count}: {meta.id} "); timer.Time("OnLevelLoadProgressEvent"); } catch (Exception e) { Debug.LogError(e); Debug.LogError($"Unexpected error while loading from {jsonPath}"); Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}"); } timer.Time(); } tasks.Add(LoadLevel()); } await UniTask.WhenAll(tasks); Application.lowMemory -= OnLowMemory; return(results); }
public EyeOverlayViewModel( [NotNull] [Dependency(WellKnownWindows.AllWindows)] IWindowTracker mainWindowTracker, [NotNull] IOverlayWindowController overlayWindowController, [NotNull] IAuraModelController auraModelController, [NotNull] IWindowListProvider windowListProvider, [NotNull] ISelectionAdornerViewModel selectionAdorner, [NotNull] [Dependency(WellKnownSchedulers.UI)] IScheduler uiScheduler) { using var sw = new BenchmarkTimer("Initialization", Log, nameof(EyeOverlayViewModel)); SelectionAdorner = selectionAdorner.AddTo(Anchors); activeConfigEditorAnchors.AddTo(Anchors); this.mainWindowTracker = mainWindowTracker; this.overlayWindowController = overlayWindowController; this.auraModelController = auraModelController; this.windowListProvider = windowListProvider; MinSize = new Size(32, 32); SizeToContent = SizeToContent.Manual; Width = 400; Height = 400; Left = 200; Top = 200; IsUnlockable = true; Title = "EyeAuras"; EnableHeader = false; thumbnailOpacity.SetDefaultValue(DefaultThumbnailOpacity); ResetRegionCommandExecuted(); sw.Step("Basic properties initialized"); WhenLoaded .Take(1) .Subscribe(ApplyConfig) .AddTo(Anchors); sw.Step("WhenLoaded executed"); resetRegionCommand = CommandWrapper.Create(ResetRegionCommandExecuted, ResetRegionCommandCanExecute); selectRegionCommand = CommandWrapper.Create(SelectRegionCommandExecuted, SelectRegionCommandCanExecute); closeConfigEditorCommand = CommandWrapper.Create(CloseConfigEditorCommandExecuted); fitOverlayCommand = CommandWrapper.Create<double?>(FitOverlayCommandExecuted); setAttachedWindowCommand = CommandWrapper.Create<WindowHandle>(SetAttachedWindowCommandExecuted); setClickThroughCommand = CommandWrapper.Create<bool?>(SetClickThroughModeExecuted); DisableAuraCommand = CommandWrapper.Create(() => auraModelController.IsEnabled = false); CloseCommand = CommandWrapper.Create(CloseCommandExecuted, auraModelController.WhenAnyValue(x => x.CloseController).Select(CloseCommandCanExecute)); ToggleLockStateCommand = CommandWrapper.Create( () => { if (IsLocked && UnlockWindowCommand.CanExecute(null)) { UnlockWindowCommand.Execute(null); } else if (!IsLocked && LockWindowCommand.CanExecute(null)) { LockWindowCommand.Execute(null); } else { throw new ApplicationException($"Something went wrong - invalid Overlay Lock state: {new {IsLocked, IsUnlockable, CanUnlock = UnlockWindowCommand.CanExecute(null), CanLock = LockWindowCommand.CanExecute(null) }}"); } }); auraModelController.WhenAnyValue(x => x.Name) .Where(x => !string.IsNullOrEmpty(x)) .Subscribe(x => OverlayName = x) .AddTo(Anchors); this.RaiseWhenSourceValue(x => x.ActiveThumbnailOpacity, thumbnailOpacity, x => x.Value).AddTo(Anchors); this.RaiseWhenSourceValue(x => x.ThumbnailOpacity, this, x => x.ActiveThumbnailOpacity).AddTo(Anchors); this.RaiseWhenSourceValue(x => x.SourceBounds, Region, x => x.Bounds).AddTo(Anchors); isInEditMode = Observable.Merge( this.WhenAnyProperty(x => x.IsInSelectMode, x => x.IsLocked)) .Select(change => IsInSelectMode || !IsLocked) .ToPropertyHelper(this, x => x.IsInEditMode, uiScheduler) .AddTo(Anchors); this.WhenAnyValue(x => x.IsLocked) .Where(x => x && isInSelectMode) .Subscribe(() => IsInSelectMode = false) .AddTo(Anchors); aspectRatio = this.WhenAnyProperty(x => x.Bounds, x => x.ViewModelLocation) .Select(change => Width >= 0 && Height >= 0 ? Width / Height : double.PositiveInfinity) .ToPropertyHelper(this, x => x.AspectRatio, uiScheduler) .AddTo(Anchors); sw.ResetStep(); configEditorSupplier = new Lazy<OverlayConfigEditor>(() => CreateConfigEditor(this)); sw.Step("Initialized Config editor"); }
public OverlayAuraModelBase( [NotNull] ISharedContext sharedContext, [NotNull] IAuraRepository repository, [NotNull] IConfigSerializer configSerializer, [NotNull] IUniqueIdGenerator idGenerator, [NotNull] IFactory <IEyeOverlayViewModel, IOverlayWindowController, IAuraModelController> overlayViewModelFactory, [NotNull] IFactory <IOverlayWindowController, IWindowTracker> overlayWindowControllerFactory, [NotNull] IFactory <WindowTracker, IStringMatcher> windowTrackerFactory, [NotNull][Dependency(WellKnownSchedulers.UI)] IScheduler uiScheduler, [NotNull][Dependency(WellKnownSchedulers.Background)] IScheduler bgScheduler) { defaultAuraName = $"Aura #{Interlocked.Increment(ref GlobalAuraIdx)}"; Name = defaultAuraName; Id = idGenerator.Next(); using var sw = new BenchmarkTimer($"[{Name}({Id})] OverlayAuraModel initialization", Log, nameof(OverlayAuraModelBase)); var auraTriggers = new ComplexAuraTrigger(); Triggers = auraTriggers.Triggers; var auraActions = new ComplexAuraAction(); OnEnterActions = auraActions.Actions; this.repository = repository; this.configSerializer = configSerializer; var matcher = new RegexStringMatcher().AddToWhitelist(".*"); var windowTracker = windowTrackerFactory .Create(matcher) .AddTo(Anchors); var overlayController = overlayWindowControllerFactory .Create(windowTracker) .AddTo(Anchors); sw.Step($"Overlay controller created: {overlayController}"); var overlayViewModel = overlayViewModelFactory .Create(overlayController, this) .AddTo(Anchors); sw.Step($"Overlay view model created: {overlayViewModel}"); Overlay = overlayViewModel; Observable.Merge( overlayViewModel.WhenValueChanged(x => x.AttachedWindow, false).ToUnit(), overlayViewModel.WhenValueChanged(x => x.IsLocked, false).ToUnit(), this.WhenValueChanged(x => x.IsActive, false).ToUnit()) .StartWithDefault() .Select( () => new { OverlayShouldBeShown = IsActive || !overlayViewModel.IsLocked, WindowIsAttached = overlayViewModel.AttachedWindow != null }) .Subscribe(x => overlayController.IsEnabled = x.OverlayShouldBeShown && x.WindowIsAttached) .AddTo(Anchors); sw.Step($"Overlay view model initialized: {overlayViewModel}"); Observable.CombineLatest( auraTriggers.WhenAnyValue(x => x.IsActive), sharedContext.SystemTrigger.WhenValueChanged(x => x.IsActive)) .DistinctUntilChanged() .Subscribe(x => IsActive = x.All(isActive => isActive), Log.HandleException) .AddTo(Anchors); auraTriggers.WhenAnyValue(x => x.IsActive) .WithPrevious((prev, curr) => new { prev, curr }) .Where(x => x.prev == false && x.curr) .Subscribe(ExecuteOnEnterActions, Log.HandleException) .AddTo(Anchors); this.repository.KnownEntities .ToObservableChangeSet() .SkipInitial() .Throttle(ModelsReloadTimeout, bgScheduler) .ObserveOn(uiScheduler) .Subscribe( () => { var properties = Properties; ReloadCollections(properties); }) .AddTo(Anchors); var modelPropertiesToIgnore = new[] { nameof(IAuraTrigger.IsActive), nameof(IAuraTrigger.TriggerDescription), nameof(IAuraTrigger.TriggerName), }.ToImmutableHashSet(); //FIXME Properties mechanism should have inverted logic - only important parameters must matter Observable.Merge( this.WhenAnyProperty(x => x.Name, x => x.TargetWindow, x => x.IsEnabled).Select(x => $"[{Name}].{x.EventArgs.PropertyName} property changed"), Overlay.WhenAnyProperty().Where(x => !modelPropertiesToIgnore.Contains(x.EventArgs.PropertyName)).Select(x => $"[{Name}].{nameof(Overlay)}.{x.EventArgs.PropertyName} property changed"), Triggers.ToObservableChangeSet().Select(x => $"[{Name}({Id})] Trigger list changed, item count: {Triggers.Count}"), Triggers.ToObservableChangeSet().WhenPropertyChanged().Where(x => !modelPropertiesToIgnore.Contains(x.EventArgs.PropertyName)).Select(x => $"[{Name}].{x.Sender}.{x.EventArgs.PropertyName} Trigger property changed"), OnEnterActions.ToObservableChangeSet().Select(x => $"[{Name}({Id})] Action list changed, item count: {OnEnterActions.Count}"), OnEnterActions.ToObservableChangeSet().WhenPropertyChanged().Where(x => !modelPropertiesToIgnore.Contains(x.EventArgs.PropertyName)).Select(x => $"[{Name}].{x.Sender}.{x.EventArgs.PropertyName} Action property changed")) .Subscribe(reason => RaisePropertyChanged(nameof(Properties))) .AddTo(Anchors); Disposable.Create(() => { Log.Debug( $"Disposed Aura {Name}({Id}) (aka {defaultAuraName}), triggers: {Triggers.Count}, actions: {OnEnterActions.Count}"); OnEnterActions.Clear(); Triggers.Clear(); }).AddTo(Anchors); sw.Step($"Overlay model properties initialized"); overlayController.RegisterChild(overlayViewModel).AddTo(Anchors); sw.Step($"Overlay registration completed: {this}"); }
public void Parse() { if ((bool?)RootObject["compiled"] == true) { // Directly load into memory ((JArray)RootObject["texts"]).Select(it => it.ToObject <Text>()).ForEach(it => Texts[it.Id] = it); ((JArray)RootObject["sprites"]).Select(it => it.ToObject <Sprite>()).ForEach(it => Sprites[it.Id] = it); ((JArray)RootObject["videos"]).Select(it => it.ToObject <Video>()).ForEach(it => Videos[it.Id] = it); ((JArray)RootObject["lines"]).Select(it => it.ToObject <Line>()).ForEach(it => Lines[it.Id] = it); ((JArray)RootObject["controllers"]).Select(it => it.ToObject <Controller>()).ForEach(it => Controllers[it.Id] = it); ((JArray)RootObject["note_controllers"]).Select(it => it.ToObject <NoteController>()).ForEach(it => NoteControllers[it.Id] = it); } else { // Parse // Templates if (RootObject["templates"] != null) { foreach (var templateProperty in RootObject["templates"].Children <JProperty>()) { Templates[templateProperty.Name] = templateProperty.Value.ToObject <JObject>(); } } void ParseStateObjects <TO, TS>(string rootTokenName, Dictionary <string, TO> addToDictionary, Action <JObject> tokenPreprocessor = null) where TO : Object <TS>, new() where TS : ObjectState, new() { if (RootObject[rootTokenName] == null) { return; } foreach (var childToken in (JArray)RootObject[rootTokenName]) { foreach (var objectToken in PopulateJObjects((JObject)childToken)) { tokenPreprocessor?.Invoke(objectToken); var obj = LoadObject <TO, TS>(objectToken); if (obj != null) { if (addToDictionary.ContainsKey(obj.Id)) { Debug.LogError($"Storyboard: Redefinition of element {obj.Id}"); continue; } addToDictionary[obj.Id] = obj; } } } } var timer = new BenchmarkTimer("Storyboard parsing"); ParseStateObjects <Text, TextState>("texts", Texts); timer.Time("Text"); ParseStateObjects <Sprite, SpriteState>("sprites", Sprites); timer.Time("Sprite"); ParseStateObjects <Video, VideoState>("videos", Videos); timer.Time("Videos"); ParseStateObjects <Line, LineState>("lines", Lines); timer.Time("Lines"); ParseStateObjects <NoteController, NoteControllerState>("note_controllers", NoteControllers, token => { // Note controllers have time default to zero if (token["time"] == null) { token["time"] = 0; } }); timer.Time("NoteController"); ParseStateObjects <Controller, ControllerState>("controllers", Controllers, token => { // Controllers have time default to zero if (token["time"] == null) { token["time"] = 0; } }); timer.Time("Controller"); timer.Time(); // Trigger if (RootObject["triggers"] != null) { foreach (var objectToken in (JArray)RootObject["triggers"]) { Triggers.Add(LoadTrigger(objectToken)); } } } }
public void Initialize() { initialDragLineObjectCount = initialNoteObjectCount[NoteType.DragHead] + initialNoteObjectCount[NoteType.DragChild] + initialNoteObjectCount[NoteType.CDragHead] + initialNoteObjectCount[NoteType.CDragChild]; var timer = new BenchmarkTimer("Game ObjectPool"); foreach (var type in initialNoteObjectCount.Keys) { for (var i = 0; i < initialNoteObjectCount[type]; i++) { Collect(notePoolItems[type], Instantiate(notePoolItems[type], new NoteInstantiateProvider { Type = type })); } } timer.Time("Notes"); for (var i = 0; i < initialDragLineObjectCount; i++) { Collect(dragLinePoolItem, Instantiate(dragLinePoolItem, new PoolItemInstantiateProvider())); } timer.Time("DragLines"); var chart = Game.Chart; var map = new Dictionary <EffectController.Effect, int> { { EffectController.Effect.Clear, chart.MaxSamePageNonDragTypeNoteCount * 2 }, { EffectController.Effect.ClearDrag, chart.MaxSamePageDragTypeNoteCount * 2 }, { EffectController.Effect.Miss, chart.MaxSamePageNoteCount * 2 }, { EffectController.Effect.Hold, chart.MaxSamePageHoldTypeNoteCount * 16 * 2 } }; foreach (var pair in map) { var effect = pair.Key; var count = pair.Value; Debug.Log($"{effect} => {count}"); for (var i = 0; i < count; i++) { Collect(effectPoolItems[effect], Instantiate( effectPoolItems[effect], new ParticleSystemInstantiateProvider { Prefab = Game.effectController.GetPrefab(effect), Parent = Game.effectController.EffectParentTransform })); } } timer.Time("Effects"); timer.Time(); }
static public void Main() { ConfirmQuickSyncReadiness.HaltIfNotReady(); Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; // keep ascending directories until 'media' folder is found for (int i = 0; i < 10 && !Directory.Exists("Media"); i++) { Directory.SetCurrentDirectory(".."); } Directory.SetCurrentDirectory("Media"); mfxIMPL impl = mfxIMPL.MFX_IMPL_AUTO; //automatic GPU/CPU mode CodecId codecId = CodecId.MFX_CODEC_AVC; // avc fourcc supported: RGB3 RGB4 BGR4 BGR3 NV12 I420 IYUV YUY2 UYVY YV12 P411 P422 FourCC fourcc = FourCC.NV12; string fourccString = fourcc.ToString().Substring(0, 4); string inFilename; inFilename = "BigBuckBunny_320x180.264"; //inFilename = "BigBuckBunny_1920x1080.264"; //inFilename = "BigBuckBunny_3840x2160.264"; string outFilename = Path.ChangeExtension(inFilename, fourccString + ".yuv"); Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory); Console.WriteLine("Input filename: {0}", inFilename); Console.WriteLine(); if (!File.Exists(inFilename)) { Console.WriteLine("Input file not found. Press any key to exit."); Console.ReadKey(); return; } Stream infs, outfs; BenchmarkTimer bt = null; #if !ENABLE_BENCHMARK infs = File.Open(inFilename, FileMode.Open); outfs = File.Open(outFilename, FileMode.Create); #else // delete this code for most simple example // * Benchmark Mode * // this block does a couple things: // 1. causes the file to be pre-read into memory so we are not timing disk reads. // 2. replaces the output stream with a NullStream so nothing gets written to disk. // 3. Starts the timer for benchmarking // this pre-reads file into memory for benchmarking // maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024; Console.WriteLine("Pre-reading input"); infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open)); Console.WriteLine("Input read"); outfs = new NullStream(); bt = new BenchmarkTimer(); bt.Start(); //int minimumFrames = 4000; #endif Console.WriteLine("Output filename: {0}", Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT")); Console.WriteLine(); var outIOPattern = IOPattern.MFX_IOPATTERN_OUT_SYSTEM_MEMORY; mfxVideoParam decoderParameters = QuickSyncStatic.ReadFileHeaderInfo(codecId, impl, infs, outIOPattern); decoderParameters.mfx.FrameInfo.FourCC = fourcc; var decoder = new StreamDecoder(infs, CodecId.MFX_CODEC_AVC, impl, outIOPattern); string impltext = QuickSyncStatic.ImplementationString(decoder.lowLevelDecoder.session); Console.WriteLine("Implementation = {0}", impltext); var formatConverter = new NV12ToXXXXConverter(fourcc, decoder.width, decoder.height); int count = 0; foreach (var frame in decoder.GetFrames()) { var frameBytes = formatConverter.ConvertFromNV12(frame.Data); // Convert to format requested outfs.Write(frameBytes, 0, frameBytes.Length); if (++count % 100 == 0) { Console.Write("Frame {0}\r", count); } } Console.WriteLine("Decoded {0} frames", count); Console.WriteLine(); if (bt != null) { bt.StopAndReport(count, infs.Position, outfs.Position); } infs.Close(); outfs.Close(); // make sure program always waits for user, except F5-Release run if (!UnitTest.IsRunning && Debugger.IsAttached || Environment.GetEnvironmentVariable("VisualStudioVersion") == null) { Console.WriteLine("done - press a key to exit"); Console.ReadKey(); } }
unsafe static void Main(string[] args) { ConfirmQuickSyncReadiness.HaltIfNotReady(); Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; // keep ascending directories until 'media' folder is found for (int i = 0; i < 10 && !Directory.Exists("Media"); i++) { Directory.SetCurrentDirectory(".."); } Directory.SetCurrentDirectory("Media"); CodecId codecId = CodecId.MFX_CODEC_JPEG; FourCC fourcc = FourCC.UYVY; // supported: RGB4, YUY2 NV12 [UYVY through tricks! see below] mfxIMPL impl = mfxIMPL.MFX_IMPL_AUTO; int width, height; string inFilename; //inFilename = "BigBuckBunny_320x180." + fourcc + ".yuv"; width = 320; height = 180; inFilename = "BigBuckBunny_1920x1080." + fourcc + ".yuv"; width = 1920; height = 1080; string outFilename = Path.ChangeExtension(inFilename, "enc.jpeg"); Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory); Console.WriteLine("Input filename: {0}", inFilename); Console.WriteLine("Input width: {0} Input height: {1}", width, height); if (!File.Exists(inFilename)) { Console.WriteLine("Input file not found."); Console.WriteLine("Please let Decoder1 run to completion to create input file"); Console.WriteLine("Press any key to exit."); Console.ReadKey(); return; } Stream infs, outfs; BenchmarkTimer bt = null; #if !ENABLE_BENCHMARK infs = File.Open(inFilename, FileMode.Open); outfs = File.Open(outFilename, FileMode.Create); #else // delete this code for most simple example // * Benchmark Mode * // this block does a couple things: // 1. causes the file to be pre-read into memory so we are not timing disk reads. // 2. replaces the output stream with a NullStream so nothing gets written to disk. // 3. Starts the timer for benchmarking // this pre-reads file into memory for benchmarking long maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024; Console.WriteLine("Pre-reading input"); infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open), maximumMemoryToAllocate); Console.WriteLine("Input read"); outfs = new NullStream(); bt = new BenchmarkTimer(); bt.Start(); int minimumFrames = 4000; #endif Console.WriteLine("Output filename: {0}", Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT")); Console.WriteLine(); // The encoder cannot encode UYVY, but if you are the only decoder of the JPEG // files, you can encode UYVY as YUY2 and everything is good. if (fourcc == FourCC.UYVY) { fourcc = FourCC.YUY2; } mfxVideoParam mfxEncParams = new mfxVideoParam(); mfxEncParams.mfx.CodecId = codecId; mfxEncParams.mfx.TargetUsage = TargetUsage.MFX_TARGETUSAGE_BALANCED; //mfxEncParams.mfx.TargetKbps = 2000; //mfxEncParams.mfx.RateControlMethod = RateControlMethod.MFX_RATECONTROL_VBR; mfxEncParams.mfx.Quality = 90; mfxEncParams.mfx.Interleaved = 1; mfxEncParams.mfx.FrameInfo.FrameRateExtN = 30; mfxEncParams.mfx.FrameInfo.FrameRateExtD = 1; mfxEncParams.mfx.FrameInfo.FourCC = fourcc; switch (fourcc) { case FourCC.NV12: case FourCC.YV12: mfxEncParams.mfx.FrameInfo.ChromaFormat = ChromaFormat.MFX_CHROMAFORMAT_YUV420; break; case FourCC.YUY2: mfxEncParams.mfx.FrameInfo.ChromaFormat = ChromaFormat.MFX_CHROMAFORMAT_YUV422V; // fatal on SKYLAKE! mfxEncParams.mfx.FrameInfo.ChromaFormat = ChromaFormat.MFX_CHROMAFORMAT_YUV422; break; case FourCC.RGB4: mfxEncParams.mfx.FrameInfo.ChromaFormat = ChromaFormat.MFX_CHROMAFORMAT_YUV444; break; default: Trace.Assert(false); break; } mfxEncParams.mfx.FrameInfo.PicStruct = PicStruct.MFX_PICSTRUCT_PROGRESSIVE; mfxEncParams.mfx.FrameInfo.CropX = 0; mfxEncParams.mfx.FrameInfo.CropY = 0; mfxEncParams.mfx.FrameInfo.CropW = (ushort)width; mfxEncParams.mfx.FrameInfo.CropH = (ushort)height; // Width must be a multiple of 16 // Height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture mfxEncParams.mfx.FrameInfo.Width = QuickSyncStatic.ALIGN16(width); mfxEncParams.mfx.FrameInfo.Height = QuickSyncStatic.AlignHeightTo32or16(height, mfxEncParams.mfx.FrameInfo.PicStruct); mfxEncParams.IOPattern = IOPattern.MFX_IOPATTERN_IN_SYSTEM_MEMORY; // must be 'in system memory' mfxEncParams.AsyncDepth = 4; // Pipeline depth. Best at 4 mfxEncParams.mfx.FrameInfo.Width = QuickSyncStatic.ALIGN32(width); mfxEncParams.mfx.FrameInfo.Height = QuickSyncStatic.ALIGN32(height); BitStreamChunk bsc = new BitStreamChunk(); //where we receive compressed frame data ILowLevelEncoder encoder = new LowLevelEncoder(mfxEncParams, impl); //ILowLevelEncoder encoder = new LowLevelEncoder(mfxEncParams, impl); string impltext = QuickSyncStatic.ImplementationString(encoder.session); Console.WriteLine("Implementation = {0}", impltext); // not needed for YUY2 encoding //var formatConverter = new NV12FromXXXXConverter(fileFourcc, width, height); int inputFrameLength = width * height * VideoUtility.GetBitsPerPixel(fourcc) / 8; byte[] uncompressed = new byte[inputFrameLength]; int count = 0; // we do not call encoder.LockFrame() and encoder.UnlockFrame() as this example is // for system memory. while (infs.Read(uncompressed, 0, inputFrameLength) == inputFrameLength) { int ix = encoder.GetFreeFrameIndex(); //this call relys locks in authoritative array of surf //formatConverter.ConvertToNV12FrameSurface(ref encoder.Frames[ix], uncompressed, 0); mfxFrameSurface1 *f = (mfxFrameSurface1 *)encoder.Frames[ix]; switch (fourcc) { case FourCC.NV12: Trace.Assert(f->Data.Pitch == width * 1); fixed(byte *aa = &uncompressed[0]) FastMemcpyMemmove.memcpy(f->Data.Y, (IntPtr)aa, height * width); fixed(byte *aa = &uncompressed[height * width]) FastMemcpyMemmove.memcpy(f->Data.UV, (IntPtr)aa, height / 2 * width); break; case FourCC.YUY2: Trace.Assert(f->Data.Pitch == width * 2); fixed(byte *aa = &uncompressed[0]) FastMemcpyMemmove.memcpy(f->Data.Y, (IntPtr)aa, height * width * 2); break; default: Trace.Assert(false); break; } encoder.EncodeFrame(ix, ref bsc); if (bsc.bytesAvailable > 0) { outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable); if (++count % 100 == 0) { Console.Write("Frame {0}\r", count); } } #if ENABLE_BENCHMARK // delete this code for most simple example if (infs.Position + inputFrameLength - 1 >= infs.Length) { infs.Position = 0; } if (count >= minimumFrames) { break; } #endif } while (encoder.Flush(ref bsc)) { if (bsc.bytesAvailable > 0) { outfs.Write(bsc.bitstream, 0, bsc.bytesAvailable); if (++count % 100 == 0) { Console.Write("Frame {0}\r", count); } } } if (bt != null) { bt.StopAndReport(count, infs.Position, outfs.Position); } infs.Close(); outfs.Close(); encoder.Dispose(); Console.WriteLine("Encoded {0} frames", count); // make sure program always waits for user, except F5-Release run if (Debugger.IsAttached || Environment.GetEnvironmentVariable("VisualStudioVersion") == null) { Console.WriteLine("done - press a key to exit"); Console.ReadKey(); } }
unsafe static void Main(string[] args) { ConfirmQuickSyncReadiness.HaltIfNotReady(); Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; // keep ascending directories until 'media' folder is found for (int i = 0; i < 10 && !Directory.Exists("Media"); i++) { Directory.SetCurrentDirectory(".."); } Directory.SetCurrentDirectory("Media"); CodecId codecId = CodecId.MFX_CODEC_JPEG; FourCC fourcc = FourCC.UYVY; // supported: RGB4, YUY2 NV12 [UYVY through tricks! see below] mfxIMPL impl = mfxIMPL.MFX_IMPL_AUTO; string fourccString = fourcc.ToString().Substring(0, 4); string inFilename; //inFilename = "BigBuckBunny_320x180.UYVY.enc.jpeg"; inFilename = "BigBuckBunny_1920x1080.UYVY.enc.jpeg"; //inFilename = "BigBuckBunny_3840x2160.UYVY.enc.jpeg"; string outFilename = Path.ChangeExtension(inFilename, ".yuv"); Console.WriteLine("Working directory: {0}", Environment.CurrentDirectory); Console.WriteLine("Input filename: {0}", inFilename); Console.WriteLine(); if (!File.Exists(inFilename)) { Console.WriteLine("Input file not found. Press any key to exit."); Console.ReadKey(); return; } Stream infs, outfs; BenchmarkTimer bt = null; #if !ENABLE_BENCHMARK infs = File.Open(inFilename, FileMode.Open); outfs = File.Open(outFilename, FileMode.Create); #else // delete this code for most simple example // * Benchmark Mode * // this block does a couple things: // 1. causes the file to be pre-read into memory so we are not timing disk reads. // 2. replaces the output stream with a NullStream so nothing gets written to disk. // 3. Starts the timer for benchmarking // this pre-reads file into memory for benchmarking long maximumMemoryToAllocate = (long)4L * 1024 * 1024 * 1024; Console.WriteLine("Pre-reading input"); infs = new PreReadLargeMemoryStream(File.Open(inFilename, FileMode.Open), maximumMemoryToAllocate); Console.WriteLine("Input read"); outfs = new NullStream(); bt = new BenchmarkTimer(); bt.Start(); int minimumFrames = 4000; #endif Console.WriteLine("Output filename: {0}", Path.GetFileName((outfs as FileStream)?.Name ?? "NO OUTPUT")); Console.WriteLine(); var outIOPattern = IOPattern.MFX_IOPATTERN_OUT_SYSTEM_MEMORY; // The encoder cannot encode UYVY, but if you are the only decoder of the JPEG // files, you can encode UYVY as YUY2 and everything is good. if (fourcc == FourCC.UYVY) { fourcc = FourCC.YUY2; } mfxVideoParam decoderParameters = QuickSyncStatic.ReadFileHeaderInfo(codecId, impl, infs, outIOPattern); decoderParameters.mfx.FrameInfo.FourCC = fourcc; AssignChromaFormat(fourcc, ref decoderParameters); var decoder = new StreamDecoder(infs, decoderParameters, null, impl); #if ENABLE_BENCHMARK // delete this code for most simple example decoder.benchmarkNeverStopMode = true; #endif string impltext = QuickSyncStatic.ImplementationString(decoder.lowLevelDecoder.session); Console.WriteLine("Implementation = {0}", impltext); // not needed //var formatConverter = new NV12ToXXXXConverter(fourcc, decoder.width, decoder.height); int width = decoderParameters.mfx.FrameInfo.CropW; int height = decoderParameters.mfx.FrameInfo.CropH; var tmpbuf = new byte[width * height * 2]; int count = 0; foreach (var frame in decoder.GetFrames()) { //var frameBytes = formatConverter.ConvertFromNV12(frame.Data); // Convert to format requested Trace.Assert(frame.Data.Pitch == width * 2); // yuy2 only fixed(byte *aa = &tmpbuf[0]) FastMemcpyMemmove.memcpy((IntPtr)aa, frame.Data.Y, height * width * 2); outfs.Write(tmpbuf, 0, tmpbuf.Length); if (++count % 100 == 0) { Console.Write("Frame {0}\r", count); } #if ENABLE_BENCHMARK // delete this code for most simple example if (count > minimumFrames) { break; } #endif } if (bt != null) { bt.StopAndReport(count, infs.Position, outfs.Position); } infs.Close(); outfs.Close(); Console.WriteLine("Decoded {0} frames", count); // make sure program always waits for user, except F5-Release run if (Debugger.IsAttached || Environment.GetEnvironmentVariable("VisualStudioVersion") == null) { Console.WriteLine("done - press a key to exit"); Console.ReadKey(); } }