Media capture api windows

Media Capture and Streams API (Media Stream)

The Media Capture and Streams API, often called the Media Streams API or MediaStream API, is an API related to WebRTC which provides support for streaming audio and video data. It provides the interfaces and methods for working with the streams and their constituent tracks, the constraints associated with data formats, the success and error callbacks when using the data asynchronously, and the events that are fired during the process.

Concepts and usage

The API is based on the manipulation of a MediaStream object representing a flux of audio- or video-related data. See an example in Get the video.

A MediaStream consists of zero or more MediaStreamTrack objects, representing various audio or video tracks. Each MediaStreamTrack may have one or more channels. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like left or right in a stereo audio track.

MediaStream objects have a single input and a single output. A MediaStream object generated by getUserMedia() is called local, and has as its source input one of the user’s cameras or microphones. A non-local MediaStream may be representing to a media element, like or , a stream originating over the network, and obtained via the WebRTC RTCPeerConnection API, or a stream created using the Web Audio API MediaStreamAudioSourceNode .

The output of the MediaStream object is linked to a consumer. It can be a media elements, like or , the WebRTC RTCPeerConnection API or a Web Audio API MediaStreamAudioSourceNode .

Interfaces

In these reference articles, you’ll find the fundamental information you’ll need to know about each of the interfaces that make up the Media Capture and Streams API.

Early versions of the Media Capture and Streams API specification included separate AudioStreamTrack and VideoStreamTrack interfaces—each based upon MediaStreamTrack —which represented streams of those types. These no longer exist, and you should update any existing code to instead use MediaStreamTrack directly.

Events

Guides and tutorials

The articles below provide additional guidance and how-to information that will help you learn to use the API, and how to perform specific tasks that you may wish to handle.

Видеозапись экрана Screen capture to video

В этой статье описывается кодирование кадров, записанных на экране, с помощью API-интерфейсов Windows. Graphics. Capture в видеофайл. This article describes how to encode frames captured from the screen with the Windows.Graphics.Capture APIs to a video file. Дополнительные сведения о снимках экрана с изображениями см. в разделе скриен Capture. For information on screen capturing still images, see Screeen capture. Простой пример комплексного приложения, в котором используются основные понятия и методы, см. в статье симплерекордер. For a simple end-to-end sample app that utilizes the concepts and techniques shown in this article, see SimpleRecorder.

Обзор процесса видеозаписи Overview of the video capture process

В этой статье представлено пошаговое руководство по примеру приложения, записывающего содержимое окна в видеофайл. This article provides a walkthrough of an example app that records the contents of a window to a video file. Хотя может показаться, что для реализации этого сценария требуется много кода, Высокоуровневая структура приложения для записи экрана довольно проста. While it may seem like there is a lot of code required to implement this scenario, the high-level structure of a screen recorder app is fairly simple. Процесс снимка экрана использует три основные функции UWP: The screen capture process uses three primary UWP features:

  • Интерфейсы API Windows. графикскаптуре выполняют фактическую работу с пикселями с экрана. The Windows.GraphicsCapture APIs do the work of actually grabbing the pixels from the screen. Класс графикскаптуреитем представляет собой записываемое окно или отображаемое изображение. The GraphicsCaptureItem class represents the window or display being captured. Графикскаптуресессион используется для запуска и завершения операции записи. GraphicsCaptureSession is used to start and stop the capture operation. Класс Direct3D11CaptureFramePool поддерживает буфер кадров, в которые копируются содержимое экрана. The Direct3D11CaptureFramePool class maintains a buffer of frames into which the screen contents are copied.
  • Класс медиастреамсаурце получает захваченные кадры и создает поток видео. The MediaStreamSource class receives the captured frames and generates a video stream.
  • Класс Медиатранскодер получает поток, созданный медиастреамсаурце , и кодирует его в видеофайл. The MediaTranscoder class receives the stream produced by the MediaStreamSource and encodes it into a video file.

Пример кода, приведенный в этой статье, можно разделить на несколько различных задач: The example code shown in this article can be categorized into a few different tasks:

  • Инициализация . сюда входит настройка классов UWP, описанных выше, инициализация интерфейсов графических устройств, выбор окна для записи и Настройка параметров кодировки, таких как разрешение и частота кадров. Initialization — This includes configuring the UWP classes described above, initializing the graphics device interfaces, picking a window to capture, and setting up the encoding parameters such as resolution and frame rate.
  • Обработчики событий и потоки — основной драйвер основного цикла захвата — это медиастреамсаурце , который периодически запрашивает кадры через событие самплерекуестед . Event handlers and threading — The primary driver of the main capture loop is the MediaStreamSource which requests frames periodically through the SampleRequested event. В этом примере используются события для координации запросов новых кадров между различными компонентами примера. This example uses events to coordinate the requests for new frames between the different components of the example. Синхронизация важна для того, чтобы фреймы были записаны и закодированы одновременно. Synchronization is important to allow frames to be captured and encoded simultaneously.
  • Копирование кадров — кадры копируются из буфера кадров захвата в отдельную поверхность Direct3D, которую можно передать в медиастреамсаурце , чтобы ресурс не перезаписывался при кодировании. Copying frames — Frames are copied from the capture frame buffer into a separate Direct3D surface that can be passed to the MediaStreamSource so that the resource isn’t overwritten while being encoded. API-интерфейсы Direct3D используются для быстрого выполнения этой операции копирования. Direct3D APIs are used to perform this copy operation quickly.

Сведения о API Direct3D About the Direct3D APIs

Как упоминалось выше, копирование каждого захваченного кадра, вероятно, является наиболее сложной частью реализации, приведенной в этой статье. As stated above, the copying of each captured frame is probably the most complex part of the implementation shown in this article. На низком уровне эта операция выполняется с помощью Direct3D. At a low level, this operation is done using Direct3D. В этом примере мы используем библиотеку шарпдкс для выполнения операций Direct3D из C#. For this example, we are using the SharpDX library to perform the Direct3D operations from C#. Эта библиотека более официально не поддерживается, но она была выбрана потому, что ее производительность в низкоуровневых операциях копирования хорошо подходит для этого сценария. This library is no longer officially supported, but it was chosen because it’s performance at low-level copy operations is well-suited for this scenario. Мы попытались обеспечить дискретность операций Direct3D, чтобы упростить замену собственного кода или других библиотек для выполнения этих задач. We have tried to keep the Direct3D operations as discrete as possible to make it easier for you to substitute your own code or other libraries for these tasks.

Читайте также:  Как проверить совместимость системы с windows 10

Настройка проекта Setting up your project

Пример кода в этом пошаговом руководстве был создан с помощью шаблона проекта пустое приложение (универсальные приложения Windows) в Visual Studio 2019. The example code in this walkthrough was created using the Blank App (Universal Windows) C# project template in Visual Studio 2019. Чтобы использовать API-интерфейсы Windows. Graphics. Capture в приложении, необходимо включить функцию захвата графики в файл Package. appxmanifest для вашего проекта. In order to use the Windows.Graphics.Capture APIs in your app, you must include the Graphics Capture capability in the Package.appxmanifest file for your project. В этом примере созданные видеофайлы сохраняются в библиотеке видео на устройстве. This example saves generated video files to the Videos Library on the device. Для доступа к этой папке необходимо включить возможности библиотеки видео . To access this folder you must include the Videos Library capability.

Чтобы установить пакет NuGet Шарпдкс, в Visual Studio выберите Управление пакетами NuGet. To install the SharpDX Nuget package, in Visual Studio select Manage Nuget Packages. На вкладке Обзор найдите пакет «Шарпдкс. Direct3D11» и нажмите кнопку установить. In the Browse tab search for the «SharpDX.Direct3D11» package and click Install.

Обратите внимание, что для уменьшения размера кодов в этой статье код в приведенном ниже примере пропускает явные ссылки на пространства имен и объявление переменных-членов класса MainPage, имена которых начинаются с символа подчеркивания ««. Note that in order to reduce the size of the code listings in this article, the code in the walkthrough below omits explicit namespace references and the declaration of MainPage class member variables which are named with a leading underscore, ««.

Настройка кодировки Setup for encoding

Метод сетупенкодинг , описанный в этом разделе, инициализирует некоторые из основных объектов, которые будут использоваться для записи и кодирования видеокадров, и настраивает параметры кодирования для записанного видео. The SetupEncoding method described in this section initializes some of the main objects that will be used to capture and encode video frames and sets up the encoding parameters for captured video. Этот метод может вызываться программно или в ответ на взаимодействие с пользователем, как нажатие кнопки. This method could be called programmatically or in response to a user interaction like a button click. Ниже приведен пример кода для сетупенкодинг после описания шагов инициализации. The code listing for SetupEncoding is shown below after the descriptions of the initialization steps.

Проверьте поддержку записи. Check for capture support. Прежде чем начать процесс записи, необходимо вызвать графикскаптуресессион. support , чтобы убедиться, что на текущем устройстве поддерживается функция захвата экрана. Before beginning the capture process, you need to call GraphicsCaptureSession.IsSupported to make sure that the screen capture feature is supported on the current device.

Инициализация интерфейсов Direct3D. Initialize Direct3D interfaces. Этот пример использует Direct3D для копирования пикселов, записанных с экрана, в текстуру, закодированную в виде видеокадра. This sample uses Direct3D to copy the pixels captured from the screen into a texture that is encoded as a video frame. Вспомогательные методы, используемые для инициализации интерфейсов Direct3D, CreateD3DDevice и креатешарпдксдевице, показаны Далее в этой статье. The helper methods used to initialize the Direct3D interfaces, CreateD3DDevice and CreateSharpDXDevice, are shown later in this article.

Инициализация Графикскаптуреитем. Initialize a GraphicsCaptureItem. Графикскаптуреитем представляет элемент на экране, который будет захвачен как окно или весь экран. A GraphicsCaptureItem represents an item on the screen that is going to be captured, either a window or the entire screen. Разрешить пользователю выбирать элемент для захвата путем создания графикскаптурепиккер и вызова пикксинглеитемасинк. Allow the user to pick an item to capture by creating a GraphicsCapturePicker and calling PickSingleItemAsync.

Создайте текстуру композиции. Create a composition texture. Создайте ресурс текстуры и связанное представление целевого объекта прорисовки, которое будет использоваться для копирования каждого кадра видео. Create a texture resource and an associated render target view that will be used to copy each video frame. Эту текстуру нельзя создать, пока не будет создана графикскаптуреитем и мы понимаем ее размеры. This texture can’t be created until the GraphicsCaptureItem has been created and we know its dimensions. См. Описание ваитфорневфраме , чтобы увидеть, как используется эта текстура композиции. See the description of the WaitForNewFrame to see how this composition texture is used. Вспомогательный метод для создания этой текстуры также показан далее в этой статье. The helper method for creating this texture is also shown later in this article.

Создайте Медиаенкодингпрофиле и Видеостреамдескриптор. Create a MediaEncodingProfile and VideoStreamDescriptor. Экземпляр класса медиастреамсаурце принимает изображения, записанные с экрана, и кодирует их в поток видео. An instance of the MediaStreamSource class will take images captured from the screen and encode them into a video stream. Затем поток видео будет перекодирован в видеофайл с помощью класса Медиатранскодер . Then, the video stream will be transcoded into a video file by the MediaTranscoder class. Видеостреамдекриптор предоставляет параметры кодирования, такие как разрешение и частоту кадров, для медиастреамсаурце. A VideoStreamDecriptor provides encoding parameters, such as resolution and frame rate, for the MediaStreamSource. Параметры кодировки видеофайла для Медиатранскодер указываются с помощью медиаенкодингпрофиле. The video file encoding parameters for the MediaTranscoder are specified with a MediaEncodingProfile. Обратите внимание, что размер, используемый для кодирования видео, не должен совпадать с размером захваченного окна, но для упрощения этого примера параметры кодирования жестко запрограммированы для использования фактических измерений элемента захвата. Note that the size used for video encoding doesn’t have to be the same as the size of the window being captured, but to keep this example simple, the encoding settings are hard-coded to use the capture item’s actual dimensions.

Создайте объекты Медиастреамсаурце и Медиатранскодер. Create the MediaStreamSource and MediaTranscoder objects. Как упоминалось выше, объект медиастреамсаурце кодирует отдельные кадры в поток видео. As mentioned above, the MediaStreamSource object encodes individual frames into a video stream. Вызовите конструктор для этого класса, передав медиаенкодингпрофиле , созданный на предыдущем шаге. Call the constructor for this class, passing in the MediaEncodingProfile created in the previous step. Установите значение времени буфера равным нулю и Зарегистрируйте обработчики для начальных и самплерекуестед событий, которые будут показаны Далее в этой статье. Set the buffer time to zero and register handlers for the Starting and SampleRequested events, which will be shown later in this article. Затем создайте новый экземпляр класса Медиатранскодер и включите аппаратное ускорение. Next, construct a new instance of the MediaTranscoder class and enable hardware acceleration.

Создание выходного файла Последний шаг в этом методе — создание файла, в который будет перекодироваться видео. Create an output file The final step in this method is to create a file to which the video will be transcoded. В этом примере мы просто создадим файл с уникальным именем в папке библиотеки videos на устройстве. For this example, we will just create a uniquely named file in the Videos Library folder on the device. Обратите внимание, что для доступа к этой папке приложение должно указать функцию «библиотека видео» в манифесте приложения. Note that in order to access this folder, your app must specify the «Videos Library» capability in the app manifest. После создания файла откройте его для чтения и записи и передайте полученный поток в метод енкодеасинк , который будет показан далее. Once the file has been created, open it for read and write, and pass the resulting stream into the EncodeAsync method which will be shown next.

Начать кодирование Start encoding

Теперь, когда основные объекты инициализированы, метод енкодеасинк реализуется для запуска операции записи. Now that the main objects have been initialized the EncodeAsync method is implemented to kick off the capture operation. Этот метод сначала проверяет, что мы еще не записывали, и если нет, он вызывает вспомогательный метод старткаптуре , чтобы начать запись кадров с экрана. This method first checks to make sure we aren’t already recording, and if not, it calls the helper method StartCapture to begin capturing frames from the screen. Этот метод показан далее в этой статье. This method is shown later in this article. Затем вызывается препаремедиастреамсаурцетранскодеасинк для получения Медиатранскодер , готового к перекодированию видеопотока, созданного объектом медиастреамсаурце , в поток выходных файлов с использованием профиля кодирования, созданного в предыдущем разделе. Next, PrepareMediaStreamSourceTranscodeAsync is called to get the MediaTranscoder ready to transcode the video stream produced by the MediaStreamSource object to the output file stream, using the encoding profile we created in the previous section. После подготовки перекодирования вызовите транскодеасинк , чтобы начать перекодировку. Once the transcoder has been prepared, call TranscodeAsync to start transcoding. Дополнительные сведения об использовании Медиатранскодерсм. в разделе перекодировать файлы мультимедиа. For more information on using the MediaTranscoder, see Transcode media files.

Читайте также:  Диск с заблокирован полностью как разблокировать windows 10

Обработку событий Медиастреамсаурце Handle MediaStreamSource events

Объект медиастреамсаурце принимает кадры, записанные на экране, и преобразует их в поток видео, который можно сохранить в файл с помощью Медиатранскодер. The MediaStreamSource object takes frames that we capture from the screen and transforms them into a video stream that can be saved to a file using the MediaTranscoder. Мы передаем кадры в медиастреамсаурце через обработчики для событий объекта. We pass the frames to the MediaStreamSource via handlers for the object’s events.

Событие самплерекуестед возникает при готовности медиастреамсаурце для нового видеокадра. The SampleRequested event is raised when the MediaStreamSource is ready for a new video frame. Убедившись в том, что запись выполняется, вызывается вспомогательный метод ваитфорневфраме для получения нового кадра, захваченного с экрана. After making sure we are currently recording, the helper method WaitForNewFrame is called to get a new frame captured from the screen. Этот метод, показанный далее в этой статье, возвращает объект ID3D11Surface , содержащий захваченный кадр. This method, shown later in this article, returns a ID3D11Surface object containing the captured frame. В этом примере мы заключим интерфейс IDirect3DSurface в вспомогательный класс, который также хранит системное время, в которое был захвачен кадр. For this example, we wrap the IDirect3DSurface interface in a helper class that also stores the system time at which the frame was captured. Как кадр, так и системное время передаются в фабричный метод медиастреамсампле. CreateFromDirect3D11Surface , а результирующий медиастреамсампле устанавливается в свойство медиастреамсаурцесамплерекуест. Sample объекта медиастреамсаурцесамплерекуестедевентаргс. Both the frame and the system time are passed into the MediaStreamSample.CreateFromDirect3D11Surface factory method and the resulting MediaStreamSample is set to the MediaStreamSourceSampleRequest.Sample property of the MediaStreamSourceSampleRequestedEventArgs. Именно так захваченный кадр предоставляется медиастреамсаурце. This is how the captured frame is provided to the MediaStreamSource.

В обработчике для начального события мы вызываем ваитфорневфраме, но передайте системное время, которое кадр был захвачен в метод Медиастреамсаурцестартингрекуест. сетактуалстартпоситион , который медиастреамсаурце использует для правильной кодировки времени последующих кадров. In the handler for the Starting event, we call WaitForNewFrame, but only pass the system time the frame was captured to the MediaStreamSourceStartingRequest.SetActualStartPosition method, which the MediaStreamSource uses to properly encode the timing of the subsequent frames.

Начать запись Start capturing

Метод старткаптуре , показанный на этом шаге, вызывается из вспомогательного метода енкодеасинк , показанного на предыдущем шаге. The StartCapture method shown in this step is called from the EncodeAsync helper method shown in a previous step. Во-первых, этот метод инициализирует набор объектов событий, которые используются для управления потоком операции записи. First, this method initializes up a set of event objects that are used to control the flow of the capture operation.

  • _multithread является вспомогательным классом, который служит оболочкой для многопоточного объекта библиотеки шарпдкс, который будет использоваться, чтобы гарантировать, что другие потоки не обращаются к текстуре шарпдкс во время копирования. _multithread is a helper class wrapping the SharpDX library’s Multithread object that will be used to make sure that no other threads access the SharpDX texture while it’s being copied.
  • _frameEvent используется для сигнализации о том, что новый кадр записан и может быть передан в медиастреамсаурце_frameEvent is used to signal that a new frame has been captured and can be passed to the MediaStreamSource
  • _closedEvent сигнализирует о том, что запись остановлена и что нам не нужно ждать каких бы то ни было новых кадров. _closedEvent signals that recording has stopped and that we shouldn’t wait for any new frames.

Событие Frame и закрытое событие добавляются в массив, поэтому мы можем ожидать один из них в цикле записи. The frame event and closed event are added to an array so we can wait for either one of them in the capture loop.

Остальная часть метода старткаптуре настраивает API Windows. Graphics. Capture, которые будут выполнять фактическую запись экрана. The rest of the StartCapture method sets up the Windows.Graphics.Capture APIs that will do the actual screen capturing. Во-первых, событие регистрируется для события каптуреитем. Closed . First, an event is registered for the CaptureItem.Closed event. Далее создается Direct3D11CaptureFramePool , позволяющий поочередно буферизовать несколько захваченных кадров. Next, a Direct3D11CaptureFramePool is created, which allows multiple captured frames to be buffered at a time. Метод креатефрисреадед используется для создания пула кадров таким образом, чтобы событие фрамеарривед вызывалось в собственном рабочем потоке пула, а не в основном потоке приложения. The CreateFreeThreaded method is used to create the frame pool so that the FrameArrived event is called on the pool’s own worker thread rather than on the app’s main thread. Затем регистрируется обработчик для события фрамеарривед . Next, a handler is registered for the FrameArrived event. Наконец, создается графикскаптуресессион для выбранного каптуреитем , а запись кадров инициируется вызовом старткаптуре. Finally, a GraphicsCaptureSession is created for the selected CaptureItem and the capture of frames is initiated by calling StartCapture.

Обработку событий захвата графики Handle graphics capture events

На предыдущем этапе мы зарегистрировали два обработчика для событий захвата графики и настроили некоторые события, помогающие управлять потоком цикла захвата. In the previous step we registered two handlers for graphics capture events and set up some events to help manage the flow of the capture loop.

Событие фрамеарривед возникает, когда для Direct3D11CaptureFramePool доступен новый захваченный кадр. The FrameArrived event is raised when the Direct3D11CaptureFramePool has a new captured frame available. В обработчике этого события вызовите трижетнекстфраме для отправителя, чтобы получить следующий захваченный кадр. In the handler for this event, call TryGetNextFrame on the sender to get the next captured frame. После извлечения кадра мы устанавливаем _frameEvent , чтобы наш цикл записи знал, что доступен новый фрейм. After the frame is retrieved, we set the _frameEvent so that our capture loop knows there is a new frame available.

В закрытом обработчике событий мы сигналим _closedEvent , чтобы цикл записи знал, когда следует останавливаться. In the Closed event handler, we signal the _closedEvent so that the capture loop will know when to stop.

Ожидание новых кадров Wait for new frames

Вспомогательный метод ваитфорневфраме , описанный в этом разделе, заключается в том, где происходит тяжелая тяжелая работа цикла записи. The WaitForNewFrame helper method described in this section is where the heavy-lifting of the capture loop occurs. Помните, что этот метод вызывается из обработчика событий онмедиастреамсаурцесамплерекуестед каждый раз, когда медиастреамсаурце готов к добавлению нового кадра в видеопоток. Remember, this method is called from the OnMediaStreamSourceSampleRequested event handler whenever the MediaStreamSource is ready for a new frame to be added to the video stream. На высоком уровне эта функция просто копирует каждый видеокадр, захваченный экраном, из одной поверхности Direct3D в другую, чтобы его можно было передать в медиастреамсаурце для кодирования во время записи нового кадра. At a high-level, this function simply copies each screen-captured video frame from one Direct3D surface to another so that it can be passed into the MediaStreamSource for encoding while a new frame is being captured. В этом примере используется библиотека Шарпдкс для выполнения фактической операции копирования. This example uses the SharpDX library to perform the actual copy operation.

Читайте также:  Музыкальный эквалайзер для windows

Перед ожиданием нового кадра метод уничтожает любой предыдущий кадр, хранящийся в переменной класса, _currentFrameи сбрасывает _frameEvent. Before waiting for a new frame, the method disposes of any previous frame stored in the class variable, _currentFrame, and resets the _frameEvent. Затем метод ожидает получения сигнала для _frameEvent или _closedEvent . Then the method waits for either the _frameEvent or the _closedEvent to be signaled. Если задано событие Closed, приложение вызывает вспомогательный метод для очистки ресурсов записи. If the closed event is set, then the app calls a helper method to cleanup the capture resources. Этот метод показан далее в этой статье. This method is shown later in this article.

Если задано событие Frame, то мы понимаем, что был вызван обработчик событий фрамеарривед , определенный на предыдущем шаге, и начнем процесс копирования записанных данных кадра в поверхность Direct3D 11, которая будет передаваться в медиастреамсаурце. If the frame event is set, then we know that the FrameArrived event handler defined in the previous step has been called, and we begin the process of copying the captured frame data into a Direct3D 11 surface that will be passed to the MediaStreamSource.

В этом примере используется вспомогательный класс сурфацевисинфо, который просто позволяет передать видеокадр и системное время кадра, как и в случае с одним объектом, медиастреамсаурце . This example uses a helper class, SurfaceWithInfo, which simply allows us to pass the video frame and the system time of the frame — both required by the MediaStreamSource — as a single object. Первым шагом процесса копирования кадров является создание экземпляра этого класса и установка системного времени. The first step of the frame copy process is to instantiate this class and set the system time.

Следующие шаги являются частью этого примера, который используется исключительно в библиотеке Шарпдкс. The next steps are the part of this example that relies specifically on the SharpDX library. Вспомогательные функции, используемые здесь, определены в конце этой статьи. The helper functions used here are defined at the end of this article. Сначала мы используем мултисреадлокк , чтобы другие потоки не обращаются к буферу кадров видео во время создания копии. First we use the MultiThreadLock to make sure no other threads access the video frame buffer while we are making the copy. Затем мы вызываем вспомогательный метод CreateSharpDXTexture2D для создания объекта шарпдкс Texture2D из видеокадра. Next, we call the helper method CreateSharpDXTexture2D to create a SharpDX Texture2D object from the video frame. Это будет исходная текстура для операции копирования. This will be the source texture for the copy operation.

Далее мы копируем из объекта Texture2D , созданного на предыдущем шаге, в текстуру композиции, созданную ранее в процессе. Next, we copy from the Texture2D object created in the previous step into the composition texture we created earlier in the process. Эта текстура композиции выступает в качестве буфера подкачки, чтобы процесс кодирования мог работать с пикселами во время записи следующего кадра. This composition texture acts as a swap buffer so that the encoding process can operate on the pixels while the next frame is being captured. Чтобы выполнить копирование, мы очищаете представление целевого объекта прорисовки, связанное с текстурой композиции, затем определим область в пределах текстуры, которую нужно скопировать — всю текстуру в этом случае, а затем вызываем кописубресаурцерегион для фактического копирования пикселов в текстуру композиции. To perform the copy, we clear the render target view associated with the composition texture, then we define the region within the texture we want to copy — the entire texture in this case, and then we call CopySubresourceRegion to actually copy the pixels to the composition texture.

Мы создадим копию описания текстуры, которая будет использоваться при создании целевой текстуры, но описание будет изменено, установив для биндфлагс значение рендертаржет , чтобы Новая текстура была доступна для записи. We create a copy of the texture description to use when we create our target texture, but the description is modified, setting the BindFlags to RenderTarget so that the new texture has write access. Установка значения None для параметра кпуакцессфлагс позволяет системе оптимизировать операцию копирования. Setting the CpuAccessFlags to None allows the system to optimize the copy operation. Описание текстуры используется для создания нового ресурса текстуры, а ресурс текстуры композиции копируется в этот новый ресурс с помощью вызова копиресаурце. The texture description is used to create a new texture resource and the composition texture resource is copied into this new resource with a call to CopyResource. Наконец, вызывается CreateDirect3DSurfaceFromSharpDXTexture для создания объекта IDirect3DSurface , возвращаемого этим методом. Finally, CreateDirect3DSurfaceFromSharpDXTexture is called to create the IDirect3DSurface object that is returned from this method.

Отмена записи и очистка ресурсов Stop capture and clean up resources

Метод « Завершение » позволяет прерывать операцию записи. The Stop method provides a way to stop the capture operation. Приложение может вызывать это программно или в ответ на взаимодействие с пользователем, например нажатием кнопки. Your app may call this programmatically or in response to a user interaction, like a button click. Этот метод просто задает _closedEvent. This method simply sets the _closedEvent. Метод ваитфорневфраме , определенный на предыдущих шагах, выполняет поиск этого события и, если он задан, завершает операцию записи. The WaitForNewFrame method defined in the previous steps looks for this event and, if set, shuts down the capture operation.

Метод Cleanup используется для правильного удаления ресурсов, созданных во время операции копирования. The Cleanup method is used to properly dispose of the resources that were created during the copy operation. В том числе: This includes:

  • Объект Direct3D11CaptureFramePool , используемый сеансом отслеживания The Direct3D11CaptureFramePool object used by the capture session
  • Графикскаптуресессион и графикскаптуреитем The GraphicsCaptureSession and GraphicsCaptureItem
  • Устройства Direct3D и Шарпдкс The Direct3D and SharpDX devices
  • Шарпдкс текстура и представление целевого объекта прорисовки, используемые в операции копирования. The SharpDX texture and render target view used in the copy operation.
  • Direct3D11CaptureFrame , используемый для хранения текущего кадра. The Direct3D11CaptureFrame used for storing the current frame.

Вспомогательные классы-оболочки Helper wrapper classes

Следующие вспомогательные классы были определены для помощи с примером кода в этой статье. The following helper classes were defined to help with the example code in this article.

Вспомогательный класс мултисреадлокк создает оболочку для многопоточного класса шарпдкс, который гарантирует, что другие потоки не обращаются к ресурсам текстуры при копировании. The MultithreadLock helper class wraps the SharpDX Multithread class that makes sure that other threads don’t access the texture resources while being copied.

Сурфацевисинфо используется для связывания IDirect3DSurface с системрелативетиме , представляющим захваченный кадр, и временем его записи соответственно. SurfaceWithInfo is used to associate an IDirect3DSurface with a SystemRelativeTime representing the a captured frame and the time it was captured, respectively.

API-интерфейсы модуля поддержки Direct3D и Шарпдкс Direct3D and SharpDX helper APIs

Следующие вспомогательные API определяются для абстракции создания ресурсов Direct3D и Шарпдкс. The following helper APIs are defined to abstract out the creation of Direct3D and SharpDX resources. Подробное описание этих технологий выходит за рамки этой статьи, но здесь приведен код, позволяющий реализовать пример кода, показанный в этом пошаговом руководстве. A detailed explanation of these technologies is outside the scope of this article but the code is provided here to allow you to implement the example code shown in the walkthrough.

Оцените статью