Example #1
0
        public void CopyQualifiedTypeName()
        {
            InteropUtilities.CopyQualifiedTypeName(null, null, "", "");
            InteropUtilities.CopyQualifiedTypeName(null, null, "Alpha", "Beta");

            var buffer = new char[12];

            void ClearBuffer()
            {
                for (int i = 0; i < buffer.Length; i++)
                {
                    buffer[i] = 'x';
                }
            }

            fixed(char *bufferPtr = &buffer[0])
            {
                int length;

                ClearBuffer();

                InteropUtilities.CopyQualifiedTypeName(null, &length, "", "");
                Assert.Equal(0, length);
                length = -1;

                InteropUtilities.CopyQualifiedTypeName(bufferPtr + 1, &length, "", "");
                AssertEx.Equal(new char[] { 'x', '\0', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x' }, buffer);
                Assert.Equal(0, length);

                ClearBuffer();

                InteropUtilities.CopyQualifiedTypeName(null, &length, "", "B");
                Assert.Equal(1, length);
                length = -1;

                InteropUtilities.CopyQualifiedTypeName(bufferPtr + 1, &length, "", "B");
                AssertEx.Equal(new char[] { 'x', 'B', '\0', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x' }, buffer);
                Assert.Equal(1, length);

                ClearBuffer();

                InteropUtilities.CopyQualifiedTypeName(null, &length, "A", "B");
                Assert.Equal(3, length);
                length = -1;

                InteropUtilities.CopyQualifiedTypeName(bufferPtr + 1, &length, "A", "B");
                AssertEx.Equal(new char[]  { 'x', 'A', '.', 'B', '\0', 'x', 'x', 'x', 'x', 'x', 'x', 'x' }, buffer);
                Assert.Equal(3, length);

                ClearBuffer();

                InteropUtilities.CopyQualifiedTypeName(null, &length, "Alpha", "Beta");
                Assert.Equal(10, length);
                length = -1;

                InteropUtilities.CopyQualifiedTypeName(bufferPtr, &length, "Alpha", "Beta");
                AssertEx.Equal(new char[] { 'A', 'l', 'p', 'h', 'a', '.', 'B', 'e', 't', 'a', '\0', 'x' }, buffer);
                Assert.Equal(10, length);
            }
        }
Example #2
0
        private void PollScanProgress()
        {
            IntPtr json       = HBFunctions.hb_get_state_json(this.hbHandle);
            string statusJson = Marshal.PtrToStringAnsi(json);

            this.log.LogMessage(statusJson, LogMessageType.Progress, LogLevel.Trace);
            JsonState state = JsonConvert.DeserializeObject <JsonState>(statusJson);

            if (state != null && state.State == NativeConstants.HB_STATE_SCANNING)
            {
                if (this.ScanProgress != null)
                {
                    this.ScanProgress(this, new ScanProgressEventArgs(state.Scanning.Progress, state.Scanning.Preview, state.Scanning.PreviewCount, state.Scanning.Title, state.Scanning.TitleCount));
                }
            }
            else if (state != null && state.State == NativeConstants.HB_STATE_SCANDONE)
            {
                var    jsonMsg  = HBFunctions.hb_get_title_set_json(this.hbHandle);
                string scanJson = InteropUtilities.ToStringFromUtf8Ptr(jsonMsg);
                this.log.LogMessage(scanJson, LogMessageType.Progress, LogLevel.Trace);
                this.titles       = JsonConvert.DeserializeObject <JsonScanObject>(scanJson);
                this.featureTitle = this.titles.MainFeature;

                this.scanPollTimer.Stop();

                if (this.ScanCompleted != null)
                {
                    this.ScanCompleted(this, new System.EventArgs());
                }
            }
        }
Example #3
0
        /// <summary>
        /// Starts a scan of the given path.
        /// </summary>
        /// <param name="path">
        /// The path of the video to scan.
        /// </param>
        /// <param name="previewCount">
        /// The number of previews to make on each title.
        /// </param>
        /// <param name="minDuration">
        /// The minimum duration of a title to show up on the scan.
        /// </param>
        /// <param name="titleIndex">
        /// The title index to scan (1-based, 0 for all titles).
        /// </param>
        /// <param name="clEnabled">
        /// OpenCL enabled.
        /// </param>
        public void StartScan(string path, int previewCount, TimeSpan minDuration, int titleIndex, bool clEnabled = false)
        {
            this.previewCount = previewCount;

            IntPtr pathPtr = InteropUtilities.ToUtf8PtrFromString(path);

            HBFunctions.hb_opencl_set_enable(this.hbHandle, clEnabled ? 1 : 0);
            HBFunctions.hb_scan(this.hbHandle, pathPtr, titleIndex, previewCount, 1, (ulong)(minDuration.TotalSeconds * 90000));
            Marshal.FreeHGlobal(pathPtr);

            this.scanPollTimer          = new Timer();
            this.scanPollTimer.Interval = ScanPollIntervalMs;

            // Lambda notation used to make sure we can view any JIT exceptions the method throws
            this.scanPollTimer.Elapsed += (o, e) =>
            {
                try
                {
                    this.PollScanProgress();
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                    this.log.LogMessage(exc.ToString(), LogMessageType.API, LogLevel.Error);
                }
            };
            this.scanPollTimer.Start();
        }
Example #4
0
        public static void MarshalUtf16ToReadOnlySpan(string value, int maxLength, string expectedResult)
        {
            var span   = InteropUtilities.MarshalStringToUtf16(value);
            var result = InteropUtilities.MarshalUtf16ToReadOnlySpan(span.AsPointer(), maxLength).AsString();

            Assert.That(result, Is.EqualTo(expectedResult));
        }
Example #5
0
        /// <summary>
        /// Starts a scan of the given path.
        /// </summary>
        /// <param name="path">
        /// The path of the video to scan.
        /// </param>
        /// <param name="previewCount">
        /// The number of previews to make on each title.
        /// </param>
        /// <param name="minDuration">
        /// The minimum duration of a title to show up on the scan.
        /// </param>
        /// <param name="titleIndex">
        /// The title index to scan (1-based, 0 for all titles).
        /// </param>
        public void StartScan(string path, int previewCount, TimeSpan minDuration, int titleIndex)
        {
            this.PreviewCount = previewCount;

            IntPtr pathPtr = InteropUtilities.ToUtf8PtrFromString(path);

            HBFunctions.hb_scan(this.Handle, pathPtr, titleIndex, previewCount, 1, (ulong)(minDuration.TotalSeconds * 90000));
            Marshal.FreeHGlobal(pathPtr);

            this.scanPollTimer          = new Timer();
            this.scanPollTimer.Interval = ScanPollIntervalMs;

            // Lambda notation used to make sure we can view any JIT exceptions the method throws
            this.scanPollTimer.Elapsed += (o, e) =>
            {
                try
                {
                    this.PollScanProgress();
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                    HandBrakeUtils.SendErrorEvent(exc.ToString());
                }
            };
            this.scanPollTimer.Start();
        }
Example #6
0
        public void StartEncode(JsonEncodeObject encodeObject)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
            };

            string encode = JsonConvert.SerializeObject(encodeObject, Formatting.Indented, settings);

            HBFunctions.hb_add_json(this.hbHandle, InteropUtilities.ToUtf8PtrFromString(encode));
            HBFunctions.hb_start(this.hbHandle);

            this.encodePollTimer          = new Timer();
            this.encodePollTimer.Interval = EncodePollIntervalMs;

            this.encodePollTimer.Elapsed += (o, e) =>
            {
                try
                {
                    this.PollEncodeProgress();
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            };
            this.encodePollTimer.Start();
        }
Example #7
0
        public RawPreviewData GetPreview(JsonEncodeObject settings, int previewNumber)
        {
            // Fetch the image data from LibHb
            string     taskJson             = JsonSerializer.Serialize(settings, JsonSettings.Options);
            IntPtr     resultingImageStruct = HBFunctions.hb_get_preview3_json(this.Handle, previewNumber, taskJson);
            hb_image_s image = InteropUtilities.ToStructureFromPtr <hb_image_s>(resultingImageStruct);

            // Copy the filled image buffer to a managed array.
            int stride_width    = image.plane[0].stride;
            int stride_height   = image.plane[0].height_stride;
            int imageBufferSize = stride_width * stride_height;

            byte[] managedBuffer = new byte[imageBufferSize];
            Marshal.Copy(image.plane[0].data, managedBuffer, 0, imageBufferSize);

            RawPreviewData preview = new RawPreviewData(managedBuffer, stride_width, stride_height, image.width, image.height);

            // Close the image so we don't leak memory.
            IntPtr nativeJobPtrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));

            Marshal.WriteIntPtr(nativeJobPtrPtr, resultingImageStruct);
            HBFunctions.hb_image_close(nativeJobPtrPtr);
            Marshal.FreeHGlobal(nativeJobPtrPtr);

            return(preview);
        }
Example #8
0
        /// <summary>
        /// Converts a native language structure to a Language object.
        /// </summary>
        /// <param name="language">
        /// The structure to convert.
        /// </param>
        /// <returns>
        /// The converted structure.
        /// </returns>
        internal static Language NativeToLanguage(iso639_lang_t language)
        {
            string englishName = InteropUtilities.ToStringFromUtf8Ptr(language.eng_name);
            string nativeName  = InteropUtilities.ToStringFromUtf8Ptr(language.native_name);

            return(new Language(englishName, nativeName, language.iso639_2));
        }
Example #9
0
        public static List <int> GetQsvAdaptorList()
        {
            IntPtr gpuListPtr = HBFunctions.hb_qsv_adapters_list();

            List <int> gpuList = InteropUtilities.ToListFromHandBrakeList <int>(gpuListPtr);

            return(gpuList);
        }
Example #10
0
        /// <summary>
        /// The get preset from file.
        /// </summary>
        /// <param name="filename">
        /// The filename.
        /// </param>
        /// <returns>
        /// The <see cref="PresetCategory"/>.
        /// </returns>
        public static PresetTransportContainer GetPresetFromFile(string filename)
        {
            IntPtr presetStringPointer = HBFunctions.hb_presets_read_file_json(InteropUtilities.ToUtf8PtrFromString(filename));
            string presetJson          = Marshal.PtrToStringAnsi(presetStringPointer);

            log.LogMessage(presetJson, LogMessageType.API, LogLevel.Debug);

            PresetTransportContainer preset = JsonConvert.DeserializeObject <PresetTransportContainer>(presetJson);

            return(preset);
        }
Example #11
0
        public static string GetVideoQualityRateControlName(string encoderShortName)
        {
            HBVideoEncoder encoder = GetVideoEncoder(encoderShortName);

            if (encoder != null)
            {
                return(InteropUtilities.ToStringFromUtf8Ptr(HBFunctions.hb_video_quality_get_name((uint)encoder.Id)));
            }

            return(string.Empty);
        }
Example #12
0
        private bool IsMfpNeogotiated(Guid wlanInterfaceId)
        {
            bool       negotiated = false;
            Win32Error retVal     = WlanGetMFPNegotiated(ref wlanInterfaceId, ref negotiated);

            if (retVal != Win32Error.ERROR_SUCCESS)
            {
                testLogger.LogError("WlanGetMFPNegotiated Returned " + retVal);
                throw InteropUtilities.GetExceptionForWin32Error(retVal);
            }
            return(negotiated);
        }
Example #13
0
        /// <summary>
        /// Converts a native language structure to a Language object.
        /// </summary>
        /// <param name="language">The structure to convert.</param>
        /// <returns>The converted structure.</returns>
        public static Language NativeToLanguage(iso639_lang_t language)
        {
            string englishName = InteropUtilities.ToStringFromUtf8Ptr(language.eng_name);
            string nativeName  = InteropUtilities.ToStringFromUtf8Ptr(language.native_name);

            return(new Language
            {
                Code = language.iso639_2,
                EnglishName = englishName,
                NativeName = nativeName
            });
        }
Example #14
0
        public static List <int> GetQsvAdaptorList()
        {
            if (HandBrakeHardwareEncoderHelper.IsQsvAvailable)
            {
                IntPtr gpuListPtr = HBFunctions.hb_qsv_adapters_list();

                List <int> gpuList = InteropUtilities.ToListFromHandBrakeList <int>(gpuListPtr);

                return(gpuList);
            }

            return(new List <int>());
        }
Example #15
0
        public RawPreviewData GetPreview(PreviewSettings settings, int previewNumber, bool deinterlace)
        {
            SourceTitle title = this.Titles.TitleList.FirstOrDefault(t => t.Index == settings.TitleNumber);

            // Create the Expected Output Geometry details for libhb.
            hb_geometry_settings_s uiGeometry = new hb_geometry_settings_s
            {
                crop      = new[] { settings.Cropping.Top, settings.Cropping.Bottom, settings.Cropping.Left, settings.Cropping.Right },
                itu_par   = 0,
                keep      = (int)AnamorphicFactory.KeepSetting.HB_KEEP_WIDTH + (settings.KeepDisplayAspect ? 0x04 : 0), // TODO Keep Width?
                maxWidth  = settings.MaxWidth,
                maxHeight = settings.MaxHeight,
                mode      = (int)(hb_anamorphic_mode_t)settings.Anamorphic,
                modulus   = settings.Modulus ?? 16,
                geometry  = new hb_geometry_s
                {
                    height = settings.Height,
                    width  = settings.Width,
                    par    = settings.Anamorphic != Anamorphic.Custom && settings.Anamorphic != Anamorphic.Automatic
                        ? new hb_rational_t {
                        den = title.Geometry.PAR.Den, num = title.Geometry.PAR.Num
                    }
                        : new hb_rational_t {
                        den = settings.PixelAspectY, num = settings.PixelAspectX
                    }
                }
            };

            // Fetch the image data from LibHb
            IntPtr     resultingImageStuct = hbFunctions.hb_get_preview2(this.Handle, settings.TitleNumber, previewNumber, ref uiGeometry, deinterlace ? 1 : 0);
            hb_image_s image = InteropUtilities.ToStructureFromPtr <hb_image_s>(resultingImageStuct);

            // Copy the filled image buffer to a managed array.
            int stride_width    = image.plane[0].stride;
            int stride_height   = image.plane[0].height_stride;
            int imageBufferSize = stride_width * stride_height;  // int imageBufferSize = outputWidth * outputHeight * 4;

            byte[] managedBuffer = new byte[imageBufferSize];
            Marshal.Copy(image.plane[0].data, managedBuffer, 0, imageBufferSize);

            RawPreviewData preview = new RawPreviewData(managedBuffer, stride_width, stride_height, image.width, image.height);

            // Close the image so we don't leak memory.
            IntPtr nativeJobPtrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));

            Marshal.WriteIntPtr(nativeJobPtrPtr, resultingImageStuct);
            hbFunctions.hb_image_close(nativeJobPtrPtr);
            Marshal.FreeHGlobal(nativeJobPtrPtr);

            return(preview);
        }
        private void PollScanProgress()
        {
            IntPtr json       = HBFunctions.hb_get_state_json(this.hbHandle);
            string statusJson = Marshal.PtrToStringAnsi(json);

            this.log.LogMessage(statusJson, LogMessageType.Progress, LogLevel.Trace);
            JsonState state = null;

            if (!string.IsNullOrEmpty(statusJson))
            {
                state = JsonConvert.DeserializeObject <JsonState>(statusJson);
            }

            TaskState taskState = state != null?TaskState.FromRepositoryValue(state.State) : null;

            if (taskState != null && (taskState == TaskState.Scanning || taskState == TaskState.Searching))
            {
                if (this.ScanProgress != null && state.Scanning != null)
                {
                    this.ScanProgress(this, new ScanProgressEventArgs(state.Scanning.Progress, state.Scanning.Preview, state.Scanning.PreviewCount, state.Scanning.Title, state.Scanning.TitleCount));
                }
            }
            else if (taskState != null && taskState == TaskState.ScanDone)
            {
                this.scanPollTimer.Stop();

                var jsonMsg = HBFunctions.hb_get_title_set_json(this.hbHandle);
                this.titlesJson = InteropUtilities.ToStringFromUtf8Ptr(jsonMsg);
                this.log.LogMessage(this.titlesJson, LogMessageType.Progress, LogLevel.Trace);

                if (string.IsNullOrEmpty(this.titlesJson))
                {
                    this.log.LogMessage("Scan Error: No Scan Data Returned.", LogMessageType.API, LogLevel.Error);
                }
                else
                {
                    this.titles = JsonConvert.DeserializeObject <JsonScanObject>(this.titlesJson);
                    if (this.titles != null)
                    {
                        this.featureTitle = this.titles.MainFeature;
                    }
                }

                if (this.ScanCompleted != null)
                {
                    this.ScanCompleted(this, new System.EventArgs());
                }
            }
        }
Example #17
0
        private void PollScanProgress()
        {
            IntPtr    json       = HBFunctions.hb_get_state_json(this.Handle);
            string    statusJson = Marshal.PtrToStringAnsi(json);
            JsonState state      = null;

            if (!string.IsNullOrEmpty(statusJson))
            {
                state = JsonSerializer.Deserialize <JsonState>(statusJson, JsonSettings.Options);
            }

            TaskState taskState = state != null?TaskState.FromRepositoryValue(state.State) : null;

            if (taskState != null && (taskState == TaskState.Scanning || taskState == TaskState.Searching))
            {
                if (this.ScanProgress != null && state.Scanning != null)
                {
                    this.ScanProgress(this, new ScanProgressEventArgs(state.Scanning.Progress, state.Scanning.Preview, state.Scanning.PreviewCount, state.Scanning.Title, state.Scanning.TitleCount));
                }
            }
            else if (taskState != null && taskState == TaskState.ScanDone)
            {
                this.scanPollTimer.Stop();

                var jsonMsg = HBFunctions.hb_get_title_set_json(this.Handle);
                this.TitlesJson = InteropUtilities.ToStringFromUtf8Ptr(jsonMsg);

                if (!string.IsNullOrEmpty(this.TitlesJson))
                {
                    this.Titles = JsonSerializer.Deserialize <JsonScanObject>(this.TitlesJson, JsonSettings.Options);
                    if (this.Titles != null)
                    {
                        this.FeatureTitle = this.Titles.MainFeature;
                    }
                }

                if (this.ScanCompleted != null)
                {
                    this.ScanCompleted(this, new System.EventArgs());
                }
            }
        }
Example #18
0
        /// <summary>
        /// The get preset from file.
        /// </summary>
        /// <param name="filename">
        /// The filename.
        /// </param>
        /// <returns>
        /// The <see cref="PresetCategory"/>.
        /// </returns>
        public static PresetTransportContainer GetPresetsFromFile(string filename)
        {
            IntPtr presetStringPointer = HBFunctions.hb_presets_read_file_json(InteropUtilities.ToUtf8PtrFromString(filename));
            string presetJson          = Marshal.PtrToStringAnsi(presetStringPointer);

            if (!string.IsNullOrEmpty(presetJson))
            {
                // Check to see if we have a list of presets.
                if (presetJson.StartsWith("["))
                {
                    presetJson = "{ \"PresetList\":" + presetJson + " } ";
                }

                PresetTransportContainer preset = JsonConvert.DeserializeObject <PresetTransportContainer>(presetJson);

                return(preset);
            }

            return(null);
        }
Example #19
0
        public void StartEncode(string encodeJson)
        {
            HBFunctions.hb_add_json(this.Handle, InteropUtilities.ToUtf8PtrFromString(encodeJson));
            HBFunctions.hb_start(this.Handle);

            this.encodePollTimer          = new Timer();
            this.encodePollTimer.Interval = EncodePollIntervalMs;

            this.encodePollTimer.Elapsed += (o, e) =>
            {
                try
                {
                    this.PollEncodeProgress();
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            };
            this.encodePollTimer.Start();
        }
        /// <summary>
        /// Gets the language object for the given code.
        /// </summary>
        /// <param name="code">The ISO-639-2 code for the language.</param>
        /// <returns>Object that describes the language.</returns>
        public static Language Get(string code)
        {
            iso639_lang_t language = InteropUtilities.ToStructureFromPtr <iso639_lang_t>(HBFunctions.lang_for_code2(code));

            return(HandBrakeUnitConversionHelpers.NativeToLanguage(language));
        }
Example #21
0
        private void SwapChain_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            uint width, height;

            if (sender is Tuple <double, double> size)
            {
                width  = (uint)size.Item1;
                height = (uint)size.Item2;
            }
            else
            {
                width  = (uint)e.NewSize.Width;
                height = (uint)e.NewSize.Height;
            }
            if (width <= 0 || height <= 0)
            {
                return;
            }

            InitPipeline();

            m_d3dContext.Get()->ClearState();
            m_renderTargetView.Dispose();
            m_depthStencilView.Dispose();
            m_renderTargetView = new ComPtr <ID3D11RenderTargetView>();
            m_depthStencilView = new ComPtr <ID3D11DepthStencilView>();

            // resize the swap chain
            int hr = m_swapChain.Get()->ResizeBuffers(
                0,  // Don't change buffer count
                width,
                height,
                DXGI_FORMAT.DXGI_FORMAT_UNKNOWN, // Don't change format
                0                                // No flags
                );

            Marshal.ThrowExceptionForHR(hr);

            // (re)-create the render target view
            ComPtr <ID3D11Texture2D> backBuffer = new ComPtr <ID3D11Texture2D>();
            var d3d11Text2D = typeof(ID3D11Texture2D).GUID;
            D3D11_RENDER_TARGET_VIEW_DESC desc = new D3D11_RENDER_TARGET_VIEW_DESC
            {
                ViewDimension = D3D11_RTV_DIMENSION.D3D11_RTV_DIMENSION_BUFFER
            };

            m_renderTargetView = new ComPtr <ID3D11RenderTargetView>();

            if (FAILED(m_swapChain.Get()->GetBuffer(0, InteropUtilities.AsPointer(ref d3d11Text2D), (void **)backBuffer.GetAddressOf())))
            {
                throw new Exception("Direct3D was unable to acquire the back buffer!");
            }
            if (FAILED(m_d3dDevice.Get()->CreateRenderTargetView(
                           (ID3D11Resource *)backBuffer.Get(),
                           null,
                           m_renderTargetView.GetAddressOf())))
            {
                throw new Exception("Direct3D was unable to create the render target view!");
            }

            // create the depth and stencil buffer
            D3D11_TEXTURE2D_DESC     dsd;
            ComPtr <ID3D11Texture2D> dsBuffer = new ComPtr <ID3D11Texture2D>();

            backBuffer.Get()->GetDesc(&dsd);
            dsd.Format    = DXGI_FORMAT.DXGI_FORMAT_D24_UNORM_S8_UINT;
            dsd.Usage     = D3D11_USAGE.D3D11_USAGE_DEFAULT;
            dsd.BindFlags = (uint)D3D11_BIND_FLAG.D3D11_BIND_DEPTH_STENCIL;
            if (FAILED(m_d3dDevice.Get()->CreateTexture2D(&dsd, null, dsBuffer.GetAddressOf())))
            {
                throw new Exception("Direct3D was unable to create a 2D-texture!");
            }
            if (FAILED(m_d3dDevice.Get()->CreateDepthStencilView((ID3D11Resource *)dsBuffer.Get(), null, m_depthStencilView.GetAddressOf())))
            {
                throw new Exception("Direct3D was unable to create the depth and stencil buffer!");
            }

            // activate the depth and stencil buffer
            m_d3dContext.Get()->OMSetRenderTargets(1, m_renderTargetView.GetAddressOf(), m_depthStencilView.Get());

            // set the viewport to the entire backbuffer
            D3D11_VIEWPORT vp;

            vp.TopLeftX = 0;
            vp.TopLeftY = 0;
            vp.Width    = dsd.Width;
            vp.Height   = dsd.Height;
            vp.MinDepth = 0.0f;
            vp.MaxDepth = 1.0f;
            m_d3dContext.Get()->RSSetViewports(1, &vp);

            Present();
            //m_renderTargetView.Get()->Release();
            backBuffer.Get()->Release();
        }
Example #22
0
        void InitSwapChain()
        {
            var    panelUnknown            = Marshal.GetIUnknownForObject(SwapChain);
            IntPtr swapChainPanelNativePtr = IntPtr.Zero;

            try
            {
                var guid = Guid.Parse("63aad0b8-7c24-40ff-85a8-640d944cc325");
                Marshal.ThrowExceptionForHR(Marshal.QueryInterface(panelUnknown, ref guid, out swapChainPanelNativePtr));
            }
            finally
            {
                Marshal.Release(panelUnknown);
            }

            if (swapChainPanelNativePtr != IntPtr.Zero)
            {
                m_swapChainNative = (ISwapChainPanelNative *)swapChainPanelNativePtr;

                try
                {
                    #region Init SwapChain
                    DXGI_SWAP_CHAIN_DESC1 swapChainDesc = new DXGI_SWAP_CHAIN_DESC1
                    {
                        Width       = (uint)SwapChain.ActualWidth,
                        Height      = (uint)SwapChain.ActualHeight,
                        Format      = colorFormat,   // This is the most common swapchain format.
                        Stereo      = 0,
                        BufferUsage = (uint)(1L << (1 + 4)),
                        BufferCount = 2,
                        Scaling     = DXGI_SCALING.DXGI_SCALING_STRETCH,
                        SwapEffect  = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL,
                        Flags       = 0
                    };
                    swapChainDesc.SampleDesc.Count   = 1;                        // Don't use multi-sampling.
                    swapChainDesc.SampleDesc.Quality = 0;

                    // Get D3DDevice
                    // This flag adds support for surfaces with a different color channel
                    // ordering than the API default. It is required for compatibility with Direct2D.
                    D3D11_CREATE_DEVICE_FLAG creationFlags = D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_BGRA_SUPPORT;

                    #if DEBUG
                    // If the project is in a debug build, enable debugging via SDK Layers.
                    creationFlags |= D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_DEBUG;
                    #endif

                    // This example only uses feature level 9.1.
                    D3D_FEATURE_LEVEL[] featureLevels =
                    {
                        D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_9_1
                    };
                    var pFeatureLevel = D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_1;

                    // Create the Direct3D 11 API device object and a corresponding context.
                    D3D11CreateDevice(
                        (IDXGIAdapter *)IntPtr.Zero.ToPointer(), // Specify nullptr to use the default adapter.
                        D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_HARDWARE,
                        IntPtr.Zero,
                        (uint)creationFlags,
                        InteropUtilities.AsPointer(featureLevels.AsSpan()),
                        (uint)featureLevels.Length,
                        D3D11_SDK_VERSION,          // UWP apps must set this to D3D11_SDK_VERSION.
                        m_d3dDevice.GetAddressOf(), // Returns the Direct3D device created.
                        InteropUtilities.AsPointer(ref pFeatureLevel),
                        m_d3dContext.GetAddressOf() // Returns the device immediate context.
                        );

                    // QI for DXGI device
                    m_d3dDevice.As(ref m_dxgiDevice);

                    // Get the DXGI adapter.
                    IDXGIAdapter *dxgiAdapter;
                    m_dxgiDevice.Get()->GetAdapter(&dxgiAdapter);

                    // Get the DXGI factory.
                    IDXGIFactory2 *dxgiFactory;
                    var            dxgiFactoryGuid = typeof(IDXGIFactory2).GUID;
                    dxgiAdapter->GetParent(InteropUtilities.AsPointer(ref dxgiFactoryGuid), (void **)&dxgiFactory);

                    // Create a swap chain by calling CreateSwapChainForComposition.
                    dxgiFactory->CreateSwapChainForComposition(
                        (IUnknown *)(ID3D11Device *)m_d3dDevice,
                        &swapChainDesc,
                        null,        // Allow on any display.
                        m_swapChain.GetAddressOf()
                        );

                    m_swapChainNative.Get()->SetSwapChain((IDXGISwapChain *)m_swapChain.Get());
                    #endregion

                    InitPipeline();
                    InitGraphics();

                    int hr = m_swapChain.Get()->Present(1, 0);
                    Marshal.ThrowExceptionForHR(hr);

                    SwapChain.SizeChanged += SwapChain_SizeChanged;
                }
                finally
                {
                    m_swapChainNative.Get()->Release();
                }
            }
        }
Example #23
0
        public BitmapImage GetPreview(PreviewSettings settings, int previewNumber)
        {
            SourceTitle title = this.Titles.TitleList.FirstOrDefault(t => t.Index == settings.TitleNumber);

            Validate.NotNull(title, "GetPreview: Title should not have been null. This is probably a bug.");

            // Create the Expected Output Geometry details for libhb.
            hb_geometry_settings_s uiGeometry = new hb_geometry_settings_s
            {
                crop      = new[] { settings.Cropping.Top, settings.Cropping.Bottom, settings.Cropping.Left, settings.Cropping.Right },
                itu_par   = 0,
                keep      = (int)AnamorphicFactory.KeepSetting.HB_KEEP_WIDTH + (settings.KeepDisplayAspect ? 0x04 : 0), // TODO Keep Width?
                maxWidth  = settings.MaxWidth,
                maxHeight = settings.MaxHeight,
                mode      = (int)(hb_anamorphic_mode_t)settings.Anamorphic,
                modulus   = settings.Modulus ?? 16,
                geometry  = new hb_geometry_s
                {
                    height = settings.Height,
                    width  = settings.Width,
                    par    = settings.Anamorphic != Anamorphic.Custom
                        ? new hb_rational_t {
                        den = title.Geometry.PAR.Den, num = title.Geometry.PAR.Num
                    }
                        : new hb_rational_t {
                        den = settings.PixelAspectY, num = settings.PixelAspectX
                    }
                }
            };

            // Sanitize the input.
            Geometry resultGeometry = AnamorphicFactory.CreateGeometry(settings, new SourceVideoInfo(new Size(title.Geometry.Width, title.Geometry.Height), new Size(title.Geometry.PAR.Num, title.Geometry.PAR.Den)));
            int      width          = resultGeometry.Width * resultGeometry.PAR.Num / resultGeometry.PAR.Den;
            int      height         = resultGeometry.Height;

            uiGeometry.geometry.width   = width;
            uiGeometry.geometry.height  = height;
            uiGeometry.geometry.par.num = settings.PixelAspectX;
            uiGeometry.geometry.par.den = settings.PixelAspectY;

            // Fetch the image data from LibHb
            IntPtr     resultingImageStuct = HBFunctions.hb_get_preview2(this.hbHandle, settings.TitleNumber, previewNumber, ref uiGeometry, 0);
            hb_image_s image = InteropUtilities.ToStructureFromPtr <hb_image_s>(resultingImageStuct);

            // Copy the filled image buffer to a managed array.
            int stride_width    = image.plane[0].stride;
            int stride_height   = image.plane[0].height_stride;
            int imageBufferSize = stride_width * stride_height;  // int imageBufferSize = outputWidth * outputHeight * 4;

            byte[] managedBuffer = new byte[imageBufferSize];
            Marshal.Copy(image.plane[0].data, managedBuffer, 0, imageBufferSize);

            var        bitmap     = new Bitmap(width, height);
            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);

            IntPtr ptr = bitmapData.Scan0; // Pointer to the first pixel.

            for (int i = 0; i < image.height; i++)
            {
                try
                {
                    Marshal.Copy(managedBuffer, i * stride_width, ptr, stride_width);
                    ptr = IntPtr.Add(ptr, width * 4);
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc); // In theory, this will allow a partial image display if this happens. TODO add better logging of this.
                }
            }

            bitmap.UnlockBits(bitmapData);

            // Close the image so we don't leak memory.
            IntPtr nativeJobPtrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));

            Marshal.WriteIntPtr(nativeJobPtrPtr, resultingImageStuct);
            HBFunctions.hb_image_close(nativeJobPtrPtr);
            Marshal.FreeHGlobal(nativeJobPtrPtr);

            // Create a Bitmap Image for display.
            using (var memoryStream = new MemoryStream())
            {
                try
                {
                    bitmap.Save(memoryStream, ImageFormat.Bmp);
                }
                finally
                {
                    bitmap.Dispose();
                }

                var wpfBitmap = new BitmapImage();
                wpfBitmap.BeginInit();
                wpfBitmap.CacheOption  = BitmapCacheOption.OnLoad;
                wpfBitmap.StreamSource = memoryStream;
                wpfBitmap.EndInit();
                wpfBitmap.Freeze();

                return(wpfBitmap);
            }
        }
Example #24
0
        /// <summary>
        /// Gets a list of keys for custom settings for the filter.
        /// </summary>
        /// <param name="filter">The filter to look up.</param>
        /// <returns>The list of keys for custom settings for the filter.</returns>
        public static List <string> GetFilterKeys(int filter)
        {
            IntPtr ptr = hbFunctions.hb_filter_get_keys(filter);

            return(InteropUtilities.ToStringListFromArrayPtr(ptr));
        }
        public MemoryStream GetPreview(PreviewSettings settings, int previewNumber, bool deinterlace)
        {
            SourceTitle title = this.Titles.TitleList.FirstOrDefault(t => t.Index == settings.TitleNumber);

            // Create the Expected Output Geometry details for libhb.
            hb_geometry_settings_s uiGeometry = new hb_geometry_settings_s
            {
                crop      = new[] { settings.Cropping.Top, settings.Cropping.Bottom, settings.Cropping.Left, settings.Cropping.Right },
                itu_par   = 0,
                keep      = (int)AnamorphicFactory.KeepSetting.HB_KEEP_WIDTH + (settings.KeepDisplayAspect ? 0x04 : 0), // TODO Keep Width?
                maxWidth  = settings.MaxWidth,
                maxHeight = settings.MaxHeight,
                mode      = (int)(hb_anamorphic_mode_t)settings.Anamorphic,
                modulus   = settings.Modulus ?? 16,
                geometry  = new hb_geometry_s
                {
                    height = settings.Height,
                    width  = settings.Width,
                    par    = settings.Anamorphic != Anamorphic.Custom
                        ? new hb_rational_t {
                        den = title.Geometry.PAR.Den, num = title.Geometry.PAR.Num
                    }
                        : new hb_rational_t {
                        den = settings.PixelAspectY, num = settings.PixelAspectX
                    }
                }
            };

            // Fetch the image data from LibHb
            IntPtr     resultingImageStuct = HBFunctions.hb_get_preview2(this.hbHandle, settings.TitleNumber, previewNumber, ref uiGeometry, deinterlace ? 1 : 0);
            hb_image_s image = InteropUtilities.ToStructureFromPtr <hb_image_s>(resultingImageStuct);

            // Copy the filled image buffer to a managed array.
            int stride_width    = image.plane[0].stride;
            int stride_height   = image.plane[0].height_stride;
            int imageBufferSize = stride_width * stride_height;  // int imageBufferSize = outputWidth * outputHeight * 4;

            byte[] managedBuffer = new byte[imageBufferSize];
            Marshal.Copy(image.plane[0].data, managedBuffer, 0, imageBufferSize);

            var bitmap = new Bitmap(image.width, image.height);

            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, image.width, image.height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);

            IntPtr ptr = bitmapData.Scan0; // Pointer to the first pixel.

            for (int i = 0; i < image.height; i++)
            {
                try
                {
                    Marshal.Copy(managedBuffer, i * stride_width, ptr, stride_width);
                    ptr = IntPtr.Add(ptr, image.width * 4);
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc); // In theory, this will allow a partial image display if this happens. TODO add better logging of this.
                }
            }

            bitmap.UnlockBits(bitmapData);

            // Close the image so we don't leak memory.
            IntPtr nativeJobPtrPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));

            Marshal.WriteIntPtr(nativeJobPtrPtr, resultingImageStuct);
            HBFunctions.hb_image_close(nativeJobPtrPtr);
            Marshal.FreeHGlobal(nativeJobPtrPtr);

            // Converts Bitmap into MemoryStream for transport.
            var memoryStream = new MemoryStream();

            try
            {
                bitmap.Save(memoryStream, ImageFormat.Bmp);
            }
            finally
            {
                bitmap.Dispose();
            }

            return(memoryStream);
        }