Obs virtual camera как пользоваться
Перейти к содержимому

Obs virtual camera как пользоваться

  • автор:

How does OBS virtual camera plugin work on Windows?

The purpose of this article is to break down the work of OBS virtual camera for Windows operating system.

Windows media back-ends

In development of any standardized media application for Windows one faces the choice of media back-end. Most often, there are three options available: Video for Windows, DirectShow, and Media Foundation, but DirectShow normally wins over the other options. Why?

Why DirectShow?

Video for Windows is the oldest one. It is limited and not extensible. The real choice has always been between the old DirectShow and the new Media Foundation. Usually, the most recent technology is a go-to option, but not in the current circumstances. Media Foundation lacks a method to add virtual camera that could be discovered naturally, in the same way as other (non-virtual) devices. Windows 11 API allows this, but it is available only for the aforementioned operating system and is not as widespread as the alternative ones.

Thus, DirectShow is the only remaining option. See discussion details here.

OBS API Overview

Plugins could be made for four types of modules: sources, outputs, encoders, and services. Sources are used to render video and audio. Encoders are obviously encoders of video and audio data, implemented specifically for OBS. Outputs allow to output rendered video and audio in the forms of raw or encoded data. Services are just custom implementations for streaming services which are used in conjunction with outputs for that particular service.

For any plugin, to implement a corresponding object, you need to define a particular structure and fill it out with information and callbacks related to your plugin. You can find more information here.

DirectShow Overview

Brief summary of component object model

COM is a binary-interface standard for software components developed by Microsoft. This means that COM could potentially be implemented on any platform.

It has a very extensive, almost bloated documentation.

What matters here is that COM objects are using interfaces to connect between each other and binary standardized interfaces only. This means that many components can interact, while being located in different processes or even on different machines.

The fact that COM has servers and clients is another notable point. Servers contain COM objects, which will be loaded and given to clients on-demand. On Windows, servers are usually executables (EXE) or dynamic-link libraries (DLL). These files can be placed anywhere on the host system, that’s why COM has concepts of a registry and a Service Control Manager (SCM). SCM locates components on local and remote hosts and connects servers to clients. And the registry exists to track where components are deployed, both on local and remote systems.

On Windows OS, the role of COM registry is usually fulfilled by the Windows registry. And before any freshly acquired component could be used, its server must be registered. On Windows, registration involves invocation of regsvr32 utility with server name, e.g.

Brief summary of DirectShow

DirectShow is a multimedia framework and API. It is based on COM and if one wants to use DS, he must know at least the basics of working with Component Object Model. There are several important things one needs to know about it.

DirectShow was designed for C++ only. It is based upon the concept of data processing graph creation, “filters” are its basic building blocks, implemented as COM objects. Each filter performs some kind of operation: generates, transforms or consumes video, audio and other things. Filters are chained into pipelines to perform complex data processing.

Each filter has one or more “pins” — objects that are responsible for connection between filters. When an output pin is connected to an input pin, they negotiate media types, connection parameters and if they could be connected at all.

Baseclasses

Base class library is a sample provided with Windows SDK (or at least it was provided not long ago). It contains implementation of common DirectShow filter functionality. Baseclasses could be ignored entirely, but it’s not recommended. DirectShow exposes interfaces that could be implemented “from scratch”, with enough work, but not every project needs this fine control over filter behavior. Not to mention the astounding difficulty of such a task.

Step-by-step description of how data is handled in virtual camera

Virtual camera plugin in question is this one. To be more specific, this particular commit.

Preparations

The first thing to note is that the virtual camera project has several artifacts instead of one. OBS plugin must be copied in the OBS plugin folder. DirectShow server must be copied into the appropriate location (readme recommends obs-studio install folder) and registered. Otherwise, the virtual camera plugin will not work.

OBS Side

The first thing that happens to every OBS plugin is initialization via obs_module_load function. It registers two OBS plugin objects: one output here and one source (which is named “filter”) here.

The main interest is the output (because virtual camera deals with the sequence “obs output → queue → directshow source”). When output starts (with virtual_output_start) a queue is created. Then, during virtual camera work, frames are pushed to the queue.

Once started, the plugin will set a callback, which in turn will be pushing videodata down the queue indefinitely, until stopped.

Queue

Since the OBS plugin and the DirectShow filter reside in different processes, they need some form of interprocess communication to transfer frame data from former to latter. This is where the queue comes into play.

Queue manages a file mapping, accessing it for writing on the OBS side and accessing it for reading on the DirectShow side. Moreover, it creates mapping with INVALID_HANDLE_VALUE, effectively mapping a file that does not exist, i.e. creating a shared memory region for two processes. That memory is still backed by the system paging file though.

More information about file mappings can be found here.

DirectShow Side

The DirectShow side is represented by the DirectShow filter CVCam and its pin CVCamStream. The latter is indeed a pin, because it inherits CSourceStream from baseclasses. And CSourceStream (as shown here) inherits CBasePin, which in turn implements IPin interface along with many other things.

This kind of complexity is precisely the reason why coding a new DirectShow filter without baseclasses is an awful pain. Without them, one would need to implement all those things by himself, relying solely on DirectShow interfaces.

The main point of interest in the DirectShow side is CVCamStream::FillBuffer. Because when graph setup is complete and all media types are set upon, this function does actual work pushing virtual camera frames down the graph.

FillBuffer gets any COM object implementing IMediaSample interface and fills it with frame data. First, it opens the queue, if it was not opened already. Before doing anything with the data, the function synchronizes the queue by waiting (if it’s too far ahead on schedule), or skipping frames (if it’s too far behind). Then, if it is time to get a frame, FillBuffer pulls it from the queue. Alternatively, if there are no frames available, the function will wait for 5 milliseconds then check again. As a minor note, FillBuffer also takes care of OBS to DirectShow timestamp conversion.

Summary

Although the inner workings of virtual camera plugin are relatively simple, they may be difficult to grasp at first glance. Many things here are done behind the scenes, just because base class library is thought out this way. We hope that this short description will be of help to anyone who wants to understand the inner workings of OBS virtual camera plugin on Windows or to implement an analogue.

Read more articles on Machine Learning from our Deelvin Machine Learning Blog.

Что такое плагин OBS VirtualCam, установка и инструкция

Применение OBS VirtualCam считается отличным методом проявления творческого потенциала в применении веб-камеры с целью совершения видеовстреч разностороннего формата. Если вы до сегодня еще ни разу не слышали про OBS VirtualCam, данное руководство поможет вам справиться со всеми трудностями последующей установки плагина.

Что такое плагин OBS VirtualCam

OBS VirtualCam является дополнительной функцией, которая внедряется непосредственно внутрь вашего плагина OBS. Программа устанавливается с целью создания виртуальной камеры, которая идеально подходит для вашей работы на любом сайте. Таким образом отпадает потребность в скачивании дополнительного софта наподобие Logitech capture или сплиттеров, которые будут нагружать устройство.

Софт OBS VirtualCam отличается от встроенной виртуальной WEB-камеры стандартного образца несколькими дополнительными возможностями:

  • Способность вывода определенной сцены или источника как виртуальной WEB камеры;
  • Способность вывода четырех виртуальных WEB камер.

Пользователь сможет выводить основную WEB камеру из OBS Studio 27.2.4 в любое нужно для вас приложение по типу Skype, Discord или Zoom. С этой возможностью раскрывается возможность параллельного применения множества дополнительных функций. Стоит отметить, что VirtualCam способен бесперебойно совмещать свою деятельность с неограниченным количеством сайтов.

Скачать

Установка плагина OBS VirtualCam

Полную установку плагина OBS VirtualCam трудно назвать затруднительной процедурой. Давайте более детально рассмотрим порядок ваших действий:

  • Изначально потребуется установить последнюю версию программы OBS Studio.
  • Далее устанавливаем специальный модуль для использования WEB камеры, поскольку функция виртуальной камеры до сих пор не встроена программное обеспечения.
  • Производим настройку источников и различных сцены, которые вы планируете использовать для дальнейших звонков в Zoom или для подобных собраний на любой другой платформе.
  • После завершения настроек остается только активировать виртуальную камеру. Для этого перейдите в раздел «Управление» в правом нижнем углу окна OBS и нажмите «Запустить виртуальную камеру».

После выполнения данного руководства уже можно приступить к непосредственной работе. Программа позволяет вашему компьютеру использовать OBS в качестве видео источника в другом приложении. Просто выберите OBS в качестве веб-камеры в настройках видео программного обеспечения.

Инструкция по применению OBS VirtualCam

Поскольку все больше людей предпочитают работать у себя дома, можно наблюдать как стремительно увеличивается количество вопросов относительно инструкции по применению OBS Studio в качестве виртуальной камеры.

Чтобы настроить параметры виртуальной камеры, щелкните значок шестеренки на панели управления. Далее следуем строго в соответствии с инструкцией:

• Установите плагин OBS VirtualCam.
• Перезагрузите ваш компьютер.
• Настройте OBS с применением дополнительного цветного ключа.
• В OBS Studio выберите вкладку «Инструменты», расположенную в верхнем меню, затем перейдите во вкладку «VirtualCam».
• Нажмите кнопку «Пуск». При желании можно установить флажок «Автозапуск», если вы желаете, чтобы VirtualCam запускался всякий раз, когда вы работаете с OBS Studio.

Настройка завершена. Теперь вы можете наблюдать «OBS-Camera» в качестве опции веб-камеры.

В настоящие время в жизни людей складывается тенденция учащенного использования удаленной коммуникации через сторонние методы связи. Улучшите воспроизведение онлайн медиаконтента, транслируемого через OBS Studio. Интегрируйте плагин и наслаждайтесь результатом.

Virtual Camera Guide

Discord and Skype using the virtual camera

The Virtual Camera is a feature of OBS Studio that allows you to share your OBS Studio scene with any applications that can make use of a webcam, such as Zoom, Skype, Discord, etc. This feature is particularly useful for applications that cannot capture the screen directly.

Using the virtual camera

To start the virtual camera, click Start Virtual Camera in the Controls dock. To stop the virtual camera, click the same button again (which will be labelled Stop Virtual Camera).

To adjust settings for the virtual camera, click on the ⚙ Gear icon in the Controls dock.

From the Virtual Camera settings window, you can adjust the following settings:

  • Internal
    • Program Output: the virtual camera will show what OBS Studio normally outputs
    • Preview Output: if using Studio Mode, the virtual camera will show the Preview. This means anybody watching the video feed will see you changing scenes, making edits, etc.

    Show a single source in the virtual camera

    In a future update, you will be able to select a single source for the virtual camera to show. Until then, you can show a single source by creating an extra scene containing the source.

    1. Add a new scene. In this tutorial, it will be called Virtual Camera.
    1. Add an existing source:
    • click on the + Add Source button
    • select the type of the source you want to show
    • click on Add Existing
    • select the source

    (Alternatively, you can copy the source and paste a reference to it)

    1. Your Virtual Camera should contain a single source. You can resize the source to fit the source to the size of the scene.

    The quickest method to fit a source to the scene is to right-click on the source and choose:

    Настроить виртуальную камеру с помощью OBS

    Вы можете выбрать или войти в любую легальную папку назначения.

    4. Выберите компоненты.

    Если вам нужно использовать только виртуальную камеру, нет необходимости устанавливать плагины, которые не выбраны на рисунке ниже.

    5. Установка

    Если вы устанавливаете OBS впервые, он может быть установлен автоматически во время установки.Intel RealSense SDK. Даже если установка не удалась, это практически не повлияет на использование виртуальной камеры в OBS.

    6. Готово

    Если вы хотите продолжить установку виртуальной камеры, вам не нужно сейчас запускать OBS Studio.
    отменить выбор "Запустить OBS Studio"Флажок

    Скачать OBS-VirtualCam

    Вы можетеВот(Baidu Netdisk)Загрузите OBS-VirtualCam, код извлечения 5qyx 。

    Установить OBS-VirtualCam

    1. Примите лицензионное соглашение.

    вВнимательно прочтите лицензионное соглашениеЗатем выберите Я принимаю соглашение. Вы должны принять соглашение для установки.

    2. Выберите дополнительные задачи.

    Выбрать здесь2. Установите плагин и зарегистрируйте только одну виртуальную камеру. Может удовлетворить общие потребности.

    3. Установка

    Когда появится следующее приглашение, регистрация успешна. Нажмите наисполняйте Завершите программу установки.

    Запустить OBS

    пожалуйстаЗапустить OBS Studio. Вы можете найти ярлык на рабочем столе или в меню «Пуск» либо найти OBS Studio в поиске.

    Проверьте, появляется ли VirtualCam

    Если вы видитеВиртуальная камераПлагин (выделен на рисунке), доказывает, что ваша установка верна. В противном случае удалите и переустановите OBS и VirtualCam.

    Здесь также должны появиться другие установленные вами плагины.

    Измените настройки OBS (необязательно)

    ВФайл-Настройки , Вы можете изменить язык и тему OBS.

    Обратите внимание на разрешение, битрейт и т. Д., Которые следует установить при использовании виртуальной камеры.

    Вы можете настроить сочетания клавиш для быстрого переключения сцен.

    Вы можете открыть студийный режим в элементе управления в правом нижнем углу (по умолчанию) для удобного просмотра превью и окон программы.

    Используйте OBS и виртуальную камеру

    Добавить сцену

    Щелкните «+» или щелкните правой кнопкой мыши, чтобы создать несколько сцен.

    Добавить источники в сцену

    Вы можете добавить несколько источников для каждой сцены, а затем организовать расположение этих источников.


    Щелкните и перетащите эти источники, чтобы организовать их расположение.

    Ниже двапример


    Вы можете переименовывать и устанавливать цвета для этих сцен, источников и т. д.

    Установить эффект перехода

    Когда есть несколько сцен, вы можете установить эффект перехода для перехода.

    Прямой переключательНет плавного перехода, аисчезатьЕго можно настроить на переключение в течение определенного времени (например, 300 миллисекунд), чтобы сделать изображение более естественным.

    Запустить VirtualCam

    ВИнструменты-Виртуальная камера ВыбратьАвтоматический запуск(Это рекомендуется делать только), а затем выберите целевую виртуальную камеру (поскольку выше упоминалось, что установлена ​​только одна виртуальная камера, поэтому есть только один вариант. Если вы выберете регистрацию 4 во время установки, вы можете указать, какую виртуальную камеру запускать), затем щелкнитезапускать

    Если вы обнаружите, что изображение перевернуто при использовании программного обеспечения для видео, выберите второй вариант,горизонтальный флип

    Запустите видео программное обеспечение

    В программном обеспечении для видео при выборе камеры выберитеOBS-Camera

    Если вам нужно переключить сцены

    Вы можете найти кнопку для переключения сцен в центре интерфейса студии.

    Вывод справа — это контент, который выводится в данный момент, а слева — пресс.Эффекты переходаЭкран, на который нужно переключиться после кнопки. После нажатия кнопки два экрана поменяются местами друг с другом.

    исполняйте

    Enjoy it!

    Для получения дополнительных вопросов об использовании OBS посетитеЗдесь (Помощь | OBS)Просмотреть справку OBS

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *