Пример #1
0
        static MediaPlayer()
        {
#if WINDOWS_MEDIA_ENGINE
            MediaManager.Startup(true);
            using (var factory = new MediaEngineClassFactory())
                using (var attributes = new MediaEngineAttributes {
                    AudioCategory = AudioStreamCategory.GameMedia
                })
                {
                    var creationFlags = MediaEngineCreateFlags.AudioOnly;

#if WINDOWS_PHONE
                    // Frame-Server mode (The default) is the only one supported on WP8.
                    // http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681688(v=vs.105).aspx
                    // http://msdn.microsoft.com/en-us/library/windows/desktop/hh447921(v=vs.85).aspx

                    creationFlags = MediaEngineCreateFlags.None;
#endif
                    var mediaEngine = new MediaEngine(factory, attributes, creationFlags, MediaEngineExOnPlaybackEvent);
                    _mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();
                }

#if WINDOWS_PHONE
            _dispatcher = System.Windows.Deployment.Current.Dispatcher;
#else
            _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
#endif
#elif WINDOWS_MEDIA_SESSION
            MediaManager.Startup(true);
            MediaFactory.CreateMediaSession(null, out _session);
#endif
        }
Пример #2
0
        public virtual void Initialize(DeviceManager deviceManager)
        {
            lock (lockObject)
            {
                // Startup MediaManager
                MediaManager.Startup();

                // Setup multithread on the Direct3D11 device
                var multithread = deviceManager.DeviceDirect3D.QueryInterface <SharpDX.Direct3D.DeviceMultithread>();
                multithread.SetMultithreadProtected(true);

                // Create a DXGI Device Manager
                dxgiDeviceManager = new DXGIDeviceManager();
                dxgiDeviceManager.ResetDevice(deviceManager.DeviceDirect3D);

                // Setup Media Engine attributes
                var attributes = new MediaEngineAttributes
                {
                    DxgiManager       = dxgiDeviceManager,
                    VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm
                };

                using (var factory = new MediaEngineClassFactory())
                    mediaEngine = new MediaEngine(factory, attributes, MediaEngineCreateFlags.WaitForStableState, OnMediaEngineEvent);
                mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();
            }
        }
Пример #3
0
        private void SetupMediaFoundation()
        {
            using var mediaEngineAttributes = new MediaEngineAttributes()
                  {
                      // _SRGB doesn't work :/ Getting invalid argument exception later in TransferVideoFrame
                      AudioCategory     = SharpDX.Multimedia.AudioStreamCategory.GameMedia,
                      AudioEndpointRole = SharpDX.Multimedia.AudioEndpointRole.Multimedia,
                      VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm
                  };

            //var graphicsDevice = renderDrawContextHandle.Resource.GraphicsDevice;
            var device = ResourceManager.Instance().Device;

            //var device = SharpDXInterop.GetNativeDevice(graphicsDevice) as Device;
            if (device != null)
            {
                // Add multi thread protection on device (MF is multi-threaded)
                using var deviceMultithread = device.QueryInterface <DeviceMultithread>();
                deviceMultithread.SetMultithreadProtected(true);

                // Reset device
                using var manager = new DXGIDeviceManager();
                manager.ResetDevice(device);
                mediaEngineAttributes.DxgiManager = manager;
            }

            // using var classFactory = new MediaEngineClassFactory();
            // try
            // {
            //
            //     _engine = new MediaEngine(classFactory, mediaEngineAttributes);
            //     _engine.PlaybackEvent += Engine_PlaybackEvent;
            // }
            // catch (SharpDXException e)
            // {
            //     Log.Error("Failed to setup MediaEngine: " + e.Message);
            // }

            // Setup Media Engine attributes
            // Create a DXGI Device Manager
            dxgiDeviceManager = new DXGIDeviceManager();
            dxgiDeviceManager.ResetDevice(device);
            var attributes = new MediaEngineAttributes
            {
                DxgiManager       = dxgiDeviceManager,
                VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm
            };

            MediaManager.Startup();
            using (var factory = new MediaEngineClassFactory())
                _engine = new MediaEngine(factory, attributes, MediaEngineCreateFlags.WaitForStableState, Engine_PlaybackEvent);
        }
Пример #4
0
        static MediaPlayer()
        {
            MediaManager.Startup(true);

            using (var factory = new MediaEngineClassFactory())
                using (var attributes = new MediaEngineAttributes {
                    AudioCategory = AudioStreamCategory.GameMedia
                })
                {
                    var mediaEngine = new MediaEngine(factory, attributes, MediaEngineCreateFlags.AudioOnly, MediaEngineExOnPlaybackEvent);
                    _mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();
                }

            _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
        }
Пример #5
0
        partial void InitializeMediaImpl(string url, long startPosition, long length, ref bool succeeded)
        {
            succeeded = true;

            if (mediaEngine != null)
            {
                throw new InvalidOperationException();
            }

            try
            {
                //Assign our dxgi manager, and set format to bgra
                var attr = new MediaEngineAttributes
                {
                    VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    DxgiManager       = videoSystem.DxgiDeviceManager
                };

                mediaEngine = new MediaEngine(mediaEngineFactory, attr);

                // Register our PlayBackEvent
                mediaEngine.PlaybackEvent += OnPlaybackCallback;

                // set the video source
                var mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();

                var databaseUrl = videoComponent.Source?.CompressedDataUrl;
                if (databaseUrl == null)
                {
                    Logger.Info("The video source is null. The video won't play.");
                    throw new Exception();
                }
                videoFileStream = contentManager.OpenAsStream(databaseUrl, StreamFlags.Seekable);
                videoDataStream = new ByteStream(videoFileStream);

                // Creates an URL to the file
                var uri = new Uri(url, UriKind.RelativeOrAbsolute);

                // Set the source stream
                mediaEngineEx.SetSourceFromByteStream(videoDataStream, uri.AbsoluteUri);
            }
            catch
            {
                succeeded = false;
                ReleaseMedia();
            }
        }
Пример #6
0
        private static void PlatformInitialize()
        {
            MediaManager.Startup(true);
            using (var factory = new MediaEngineClassFactory())
                using (var attributes = new MediaEngineAttributes {
                    AudioCategory = AudioStreamCategory.GameMedia
                })
                {
                    var creationFlags = MediaEngineCreateFlags.AudioOnly;

                    var mediaEngine = new MediaEngine(factory, attributes, creationFlags, MediaEngineExOnPlaybackEvent);
                    _mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();
                }


            _dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
        }
Пример #7
0
        public StreamPlayer(Device device, int fps)
        {
            Device = device.QueryInterface <SharpDX.Direct3D11.Device>();
            using (var manager = new DXGIDeviceManager())
                using (var factory = new MediaEngineClassFactory())
                    using (var attributes = new MediaEngineAttributes(2))
                    {
                        manager.ResetDevice(device);
                        attributes.DxgiManager       = manager;
                        attributes.VideoOutputFormat = (int)Format.B8G8R8A8_UNorm;
                        var baseEngine = new MediaEngine(factory, attributes, playbackCallback: OnEngineEvent);
                        engine = baseEngine.QueryInterface <MediaEngineEx>();
                    }

            frameTime = TimeSpan.FromSeconds(1.0 / fps);
            SetCurrentState(StreamPlayerState.NoSource);
        }
Пример #8
0
        private void PlatformInitialize()
        {
            MediaManager.Startup();

            _devManager = new DXGIDeviceManager();
            _devManager.ResetDevice(Game.Instance.GraphicsDevice._d3dDevice);

            using (var factory = new MediaEngineClassFactory())
                using (var attributes = new MediaEngineAttributes
                {
                    VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    DxgiManager = _devManager
                })
                {
                    _mediaEngine = new MediaEngine(factory, attributes, MediaEngineCreateFlags.None, OnMediaEngineEvent);
                }
        }
Пример #9
0
        static MediaPlayer()
        {
#if WINDOWS_MEDIA_ENGINE
            MediaManager.Startup(true);
            using (var factory = new MediaEngineClassFactory())
                using (var attributes = new MediaEngineAttributes {
                    AudioCategory = AudioStreamCategory.GameMedia
                })
                {
                    var creationFlags = MediaEngineCreateFlags.AudioOnly;

                    var mediaEngine = new MediaEngine(factory, attributes, creationFlags, MediaEngineExOnPlaybackEvent);
                    _mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();
                }

            _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
#elif WINDOWS_MEDIA_SESSION
            MediaManagerState.CheckStartup();
            MediaFactory.CreateMediaSession(null, out _session);
#elif WINDOWS_PHONE
            PhoneApplicationService.Current.Activated += (sender, e) =>
            {
                if (_mediaElement != null)
                {
                    if (_mediaElement.Source == null && source != null)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => _mediaElement.Source = source);
                    }

                    // Ensure only one subscription
                    _mediaElement.MediaOpened -= MediaElement_MediaOpened;
                    _mediaElement.MediaOpened += MediaElement_MediaOpened;
                }
            };

            PhoneApplicationService.Current.Deactivated += (sender, e) =>
            {
                if (_mediaElement != null)
                {
                    source      = _mediaElement.Source;
                    elapsedTime = _mediaElement.Position;
                }
            };
#endif
        }
Пример #10
0
        private void PlatformSpecificInit()
        {
            // Setup Media Engine attributes
            using (var attributes = new MediaEngineAttributes {
                AudioEndpointRole = AudioEndpointRole.Console,
                AudioCategory = AudioStreamCategory.GameEffects
            })
            {
                var creationFlags = MediaEngineCreateFlags.None;
#if !SILICONSTUDIO_PLATFORM_WINDOWS_PHONE
                // MSDN: On the phone, the Media Engine only supports frame-server mode. Attempting to initialize the interface in either rendering mode or audio mode will fail.
                creationFlags |= MediaEngineCreateFlags.AudioOnly;
#endif
                using (var factory = new MediaEngineClassFactory())
                    mediaEngine = new MediaEngine(factory, attributes, creationFlags, OnMediaEngineEvent);

                mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();
            }
        }
Пример #11
0
        partial void InitializeMediaImpl(string url, long startPosition, long length, ref bool succeeded)
        {
            succeeded = true;

            if (mediaEngine != null)
            {
                throw new InvalidOperationException();
            }

            try
            {
                //Assign our dxgi manager, and set format to bgra
                var attr = new MediaEngineAttributes
                {
                    VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    DxgiManager       = videoSystem.DxgiDeviceManager,
                };

                mediaEngine = new MediaEngine(mediaEngineFactory, attr);

                // Register our PlayBackEvent
                mediaEngine.PlaybackEvent += OnPlaybackCallback;

                // set the video source
                var mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();

                videoFileStream = new VirtualFileStream(File.OpenRead(url), startPosition, startPosition + length);
                videoDataStream = new ByteStream(videoFileStream);

                // Creates an URL to the file
                var uri = new Uri(url, UriKind.RelativeOrAbsolute);

                // Set the source stream
                mediaEngineEx.SetSourceFromByteStream(videoDataStream, uri.AbsoluteUri);
            }
            catch
            {
                succeeded = false;
                ReleaseMedia();
            }
        }
Пример #12
0
        public VideoPlayer(NodeContext nodeContext)
        {
            renderDrawContextHandle = nodeContext.GetGameProvider()
                                      .Bind(g => RenderContext.GetShared(g.Services).GetThreadContext())
                                      .GetHandle() ?? throw new ServiceNotFoundException(typeof(IResourceProvider <Game>));

            colorSpaceConverter = new ColorSpaceConverter(renderDrawContextHandle.Resource);

            // Initialize MediaFoundation
            MediaManagerService.Initialize();

            using var mediaEngineAttributes = new MediaEngineAttributes()
                  {
                      // _SRGB doesn't work :/ Getting invalid argument exception later in TransferVideoFrame
                      AudioCategory     = SharpDX.Multimedia.AudioStreamCategory.GameMedia,
                      AudioEndpointRole = SharpDX.Multimedia.AudioEndpointRole.Multimedia,
                      VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm
                  };

            var graphicsDevice = renderDrawContextHandle.Resource.GraphicsDevice;
            var device         = SharpDXInterop.GetNativeDevice(graphicsDevice) as Device;

            if (device != null)
            {
                // Add multi thread protection on device (MF is multi-threaded)
                using var deviceMultithread = device.QueryInterface <DeviceMultithread>();
                deviceMultithread.SetMultithreadProtected(true);


                // Reset device
                using var manager = new DXGIDeviceManager();
                manager.ResetDevice(device);
                mediaEngineAttributes.DxgiManager = manager;
            }

            using var classFactory = new MediaEngineClassFactory();
            engine = new MediaEngine(classFactory, mediaEngineAttributes);
            engine.PlaybackEvent += Engine_PlaybackEvent;
        }
Пример #13
0
 public void Initialize(SharpDXContext context)
 {
     lock (this.lockObject)
     {
         this.sharpDxContext = context;
         MediaManager.Startup(false);
         this.multithread = this.sharpDxContext.D3DContext.QueryInterface <DeviceMultithread>();
         this.multithread.SetMultithreadProtected((Bool)true);
         this.dxgiDeviceManager = new DXGIDeviceManager();
         this.dxgiDeviceManager.ResetDevice((ComObject)this.sharpDxContext.D3DDevice);
         this.attributes = new MediaEngineAttributes(0)
         {
             DxgiManager       = this.dxgiDeviceManager,
             VideoOutputFormat = 87
         };
         using (MediaEngineClassFactory resource_0 = new MediaEngineClassFactory())
             this.mediaEngine = new MediaEngine(resource_0, this.attributes, MediaEngineCreateFlags.None, new MediaEngineNotifyDelegate(this.OnMediaEngineEvent));
         this.mediaEngineEx        = this.mediaEngine.QueryInterface <MediaEngineEx>();
         this.mediaEngine.Loop     = (Bool)true;
         this.mediaEngine.AutoPlay = (Bool)true;
     }
 }
Пример #14
0
        public virtual void Initialize(DeviceManager devices)
        {
            // Startup MediaManager
            MediaManager.Startup();

            // Create a DXGI Device Manager
            dxgiDeviceManager = new DXGIDeviceManager();
            dxgiDeviceManager.ResetDevice(devices.DeviceDirect3D);

            // Setup Media Engine attributes
            var attributes = new MediaEngineAttributes
            {
                DxgiManager       = dxgiDeviceManager,
                VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm
            };

            using (var factory = new MediaEngineClassFactory())
                using (var mediaEngine = new MediaEngine(factory, attributes, MediaEngineCreateflags.None))
                    mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();

            // Register for playback notification from MediaEngine
            mediaEngineEx.PlaybackEvent += MediaEngineExOnPlaybackEvent;
        }
Пример #15
0
        /// <inheritdoc />
        protected override void OnInitialize(IServiceRegistry registry)
        {
            _graphicsDevice = registry.GetService <IGraphicsDevice>();
            _spriteBatch    = ToDispose(new SpriteBatch(_graphicsDevice));
            MediaManager.Startup();
            DeviceMultithread multithread = _graphicsDevice.Device.QueryInterface <DeviceMultithread>();

            multithread.SetMultithreadProtected(true);
            _dxgiDeviceManager = ToDispose(new DXGIDeviceManager());
            _dxgiDeviceManager.ResetDevice(_graphicsDevice.Device);

            MediaEngineAttributes attributes = new MediaEngineAttributes
            {
                DxgiManager = _dxgiDeviceManager, VideoOutputFormat = (int)Format.B8G8R8A8_UNorm
            };

            using (MediaEngineClassFactory factory = new MediaEngineClassFactory())
            {
                _mediaEngine = ToDispose(
                    new MediaEngine(
                        factory, attributes, MediaEngineCreateFlags.WaitForStableState, OnMediaEngineEvent));
            }
            _mediaEngineEx = ToDispose(_mediaEngine.QueryInterface <MediaEngineEx>());
        }
Пример #16
0
        private void RunVideo_Click(object sender, EventArgs e)
        {
            try
            {
                if (Program.openFileDialog == null)
                {
                    throw new NullReferenceException();
                }

                // Initialize MediaFoundation
                MediaManager.Startup();
                renderForm               = new SharpDX.Windows.RenderForm();
                renderForm.WindowState   = FormWindowState.Minimized;
                renderForm.ShowInTaskbar = false;

                Program.device = Program.CreateDeviceForVideo(out Program.dxgiManager);

                // Creates the MediaEngineClassFactory
                var mediaEngineFactory = new MediaEngineClassFactory();

                //Assign our dxgi manager, and set format to bgra
                MediaEngineAttributes attr = new MediaEngineAttributes();
                attr.VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm;
                attr.DxgiManager       = Program.dxgiManager;

                // Creates MediaEngine for AudioOnly
                mediaEngine = new MediaEngine(mediaEngineFactory, attr, MediaEngineCreateFlags.None);

                // Register our PlayBackEvent
                mediaEngine.PlaybackEvent += Program.OnPlaybackCallback;

                // Query for MediaEngineEx interface
                Program.mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();

                // Opens the file
                var fileStream = Program.openFileDialog.OpenFile();

                // Create a ByteStream object from it
                var stream = new ByteStream(fileStream);

                // Creates an URL to the file
                var url = new Uri(Program.openFileDialog.FileName, UriKind.RelativeOrAbsolute);

                // Set the source stream
                Program.mediaEngineEx.SetSourceFromByteStream(stream, url.AbsoluteUri);

                // Wait for MediaEngine to be ready
                if (!Program.eventReadyToPlay.WaitOne(1000))
                {
                    Console.WriteLine("Unexpected error: Unable to play this file");
                }

                //Create our swapchain
                Program.swapChain = Program.CreateSwapChain(Program.device, Program.workerw);

                //Get DXGI surface to be used by our media engine
                var texture = Texture2D.FromSwapChain <Texture2D>(Program.swapChain, 0);
                var surface = texture.QueryInterface <SharpDX.DXGI.Surface>();

                //Get our video size
                int w, h;
                //mediaEngine.GetNativeVideoSize(out w, out h);
                // Play the music
                Program.mediaEngineEx.Play();
                Program.mediaEngineEx.Loop  = true;
                Program.mediaEngineEx.Muted = true;
                //mediaEngineEx.Volume = 0.01;
                long ts;
                //Get display size
                int displayHeight = 0;
                int displayWidth  = 0;
                SharpDX.DXGI.Factory dxgiFactory = new Factory();
                foreach (var dxgiAdapter in dxgiFactory.Adapters)
                {
                    foreach (var output in dxgiAdapter.Outputs)
                    {
                        foreach (var format in Enum.GetValues(typeof(Format)))
                        {
                            var displayModes = output.GetDisplayModeList((Format)format,
                                                                         DisplayModeEnumerationFlags.Interlaced
                                                                         | DisplayModeEnumerationFlags.Scaling);

                            foreach (var displayMode in displayModes)
                            {
                                //Assign last mode from list - max resolution
                                displayWidth  = displayMode.Width;
                                displayHeight = displayMode.Height;
                                Rational displayRefresh = displayMode.RefreshRate;
                            }
                        }
                    }
                }

                RenderLoop.Run(renderForm, () =>
                {
                    //Transfer frame if a new one is available
                    if (mediaEngine.OnVideoStreamTick(out ts))
                    {
                        mediaEngine.TransferVideoFrame(surface, null,
                                                       new SharpDX.Rectangle(0, 0, displayWidth, displayHeight), null);
                    }
                    Program.swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
                }, true);
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show("Ошибка открытия файла: " + ex.Message, "Ошибка");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка: " + ex.Message, "Ошибка");
            }
        }
Пример #17
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The args.</param>

        public static void Run()
        {
            // Select a File to play
            var openFileDialog = new OpenFileDialog {
                Title = "Select a file",
            };
            var result = openFileDialog.ShowDialog();

            if (result == DialogResult.Cancel)
            {
                return;
            }

            // Initialize MediaFoundation
            MediaManager.Startup();

            var renderForm = new SharpDX.Windows.RenderForm();

            device = CreateDeviceForVideo(out dxgiManager);

            // Creates the MediaEngineClassFactory
            var mediaEngineFactory = new MediaEngineClassFactory();

            //Assign our dxgi manager, and set format to bgra
            MediaEngineAttributes attr = new MediaEngineAttributes();

            attr.VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            attr.DxgiManager       = dxgiManager;

            // Creates MediaEngine for AudioOnly
            var mediaEngine = new MediaEngine(mediaEngineFactory, attr, MediaEngineCreateFlags.None);

            // Register our PlayBackEvent
            mediaEngine.PlaybackEvent += OnPlaybackCallback;

            // Query for MediaEngineEx interface
            mediaEngineEx = mediaEngine.QueryInterface <MediaEngineEx>();

            // Opens the file
            var fileStream = openFileDialog.OpenFile();

            // Create a ByteStream object from it
            var stream = new ByteStream(fileStream);

            // Creates an URL to the file
            var url = new Uri(openFileDialog.FileName, UriKind.RelativeOrAbsolute);

            // Set the source stream
            mediaEngineEx.SetSourceFromByteStream(stream, url.AbsoluteUri);

            // Wait for MediaEngine to be ready
            if (!eventReadyToPlay.WaitOne(1000))
            {
                Console.WriteLine("Unexpected error: Unable to play this file");
            }

            //Create our swapchain
            swapChain = CreateSwapChain(device, renderForm.Handle);

            //Get DXGI surface to be used by our media engine
            var texture = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var surface = texture.QueryInterface <SharpDX.DXGI.Surface>();

            //Get our video size
            int w, h;

            mediaEngine.GetNativeVideoSize(out w, out h);

            // Play the music
            mediaEngineEx.Play();

            long ts;

            RenderLoop.Run(renderForm, () =>
            {
                //Transfer frame if a new one is available
                if (mediaEngine.OnVideoStreamTick(out ts))
                {
                    mediaEngine.TransferVideoFrame(surface, null, new SharpDX.Rectangle(0, 0, w, h), null);
                }

                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });

            mediaEngine.Shutdown();
            swapChain.Dispose();
            device.Dispose();
        }