Imported Upstream version 0.13.2+dsfg1

This commit is contained in:
Sebastian Ramacher 2016-02-24 00:16:51 +01:00
commit fb3990e9e5
2036 changed files with 287360 additions and 0 deletions

View file

@ -0,0 +1,48 @@
project(linux-v4l2)
if(DISABLE_V4L2)
message(STATUS "v4l2 plugin disabled")
return()
endif()
find_package(Libv4l2)
find_package(LibUDev QUIET)
if(NOT LIBV4L2_FOUND AND ENABLE_V4L2)
message(FATAL_ERROR "libv4l2 not found bit plugin set as enabled")
elseif(NOT LIBV4L2_FOUND)
message(STATUS "libv4l2 not found, disabling v4l2 plugin")
return()
endif()
if(NOT UDEV_FOUND OR DISABLE_UDEV)
message(STATUS "udev disabled for v4l2 plugin")
else()
set(linux-v4l2-udev_SOURCES
v4l2-udev.c
)
add_definitions(-DHAVE_UDEV)
endif()
include_directories(
SYSTEM "${CMAKE_SOURCE_DIR}/libobs"
${LIBV4L2_INCLUDE_DIRS}
)
set(linux-v4l2_SOURCES
linux-v4l2.c
v4l2-input.c
v4l2-helpers.c
${linux-v4l2-udev_SOURCES}
)
add_library(linux-v4l2 MODULE
${linux-v4l2_SOURCES}
)
target_link_libraries(linux-v4l2
libobs
${LIBV4L2_LIBRARIES}
${UDEV_LIBRARIES}
)
install_obs_plugin_with_data(linux-v4l2 data)

View file

@ -0,0 +1,5 @@
V4L2Input="جهاز التقاط الفيديو (V4L2)"
Device="الجهاز"
Resolution="الأبعاد"
FrameRate="الإطار"

View file

@ -0,0 +1,5 @@
V4L2Input="Видео входно устройство (V4L2)"
Device="Устройство"
Resolution="Резолюция"
FrameRate="Кадри в секунда"

View file

@ -0,0 +1,11 @@
V4L2Input="Dispositiu de captura de vídeo (V4L2)"
Device="Dispositiu"
Input="Entrada"
VideoFormat="Forma de vídeo"
VideoStandard="Estàndard de vídeo"
DVTiming="Cronometratge DV"
Resolution="Resolució"
FrameRate="Fotogrames per segon"
LeaveUnchanged="No ho canviïs"
UseBuffering="Usa memòria intermèdia"

View file

@ -0,0 +1,11 @@
V4L2Input="Zařízení pro záznam (V4L2)"
Device="Zařízení"
Input="Vstup"
VideoFormat="Formát videa"
VideoStandard="Standard videa"
DVTiming="Časování DV"
Resolution="Rozlišení"
FrameRate="Frekvence snímkování"
LeaveUnchanged="Ponechat nezměněné"
UseBuffering="Použít vyrovnávací paměť"

View file

@ -0,0 +1,11 @@
V4L2Input="Video optagelses enhed (V4L2)"
Device="Enhed"
Input="Input"
VideoFormat="Video format"
VideoStandard="Video standard"
DVTiming="DV timing"
Resolution="Opløsning"
FrameRate="Framerate"
LeaveUnchanged="Efterlad uændret"
UseBuffering="Brug buffering"

View file

@ -0,0 +1,11 @@
V4L2Input="Videoaufnahmegerät (V4L2)"
Device="Gerät"
Input="Eingabe"
VideoFormat="Videoformat"
VideoStandard="Videostandard"
DVTiming="DV-Timing"
Resolution="Auflösung"
FrameRate="Bildrate"
LeaveUnchanged="Unverändert lassen"
UseBuffering="Buffering benutzen"

View file

@ -0,0 +1,11 @@
V4L2Input="Συσκευή Λήψης Βίντεο (V4L2)"
Device="Συσκευή"
Input="Είσοδος"
VideoFormat="Μορφή Βίντεο"
VideoStandard="Πρότυπο βίντεο"
DVTiming="Χρονισμός DV"
Resolution="Ανάλυση"
FrameRate="Ρυθμός καρέ"
LeaveUnchanged="Αφήστε αμετάβλητο"
UseBuffering="Χρήση ενδιάμεσης μνήμης"

View file

@ -0,0 +1,10 @@
V4L2Input="Video Capture Device (V4L2)"
Device="Device"
Input="Input"
VideoFormat="Video Format"
VideoStandard="Video Standard"
DVTiming="DV Timing"
Resolution="Resolution"
FrameRate="Frame Rate"
LeaveUnchanged="Leave Unchanged"
UseBuffering="Use Buffering"

View file

@ -0,0 +1,11 @@
V4L2Input="Dispositivo de captura de video (V4L2)"
Device="Dispositivo"
Input="Entrada"
VideoFormat="Formato de vídeo"
VideoStandard="Estándar de vídeo"
DVTiming="Sincronización de Video Digital"
Resolution="Resolución"
FrameRate="Frecuencia de imágenes"
LeaveUnchanged="Dejar sin cambios"
UseBuffering="Utilizar el almacenamiento en búfer"

View file

@ -0,0 +1,11 @@
V4L2Input="Bideo Harpen Gailua (V4L2)"
Device="Gailua"
Input="Sarrera"
VideoFormat="Bideo Heuskarria"
VideoStandard="Bideo Estandarra"
DVTiming="DV Denborapena"
Resolution="Bereizmena"
FrameRate="Frame Neurria"
LeaveUnchanged="Utzi Aldatugabe"
UseBuffering="Erabili Bufferreratzea"

View file

@ -0,0 +1,11 @@
V4L2Input="Videokaappauslaite (V4L2)"
Device="Laite"
Input="Sisääntulo"
VideoFormat="Videoformaatti"
VideoStandard="Videostandardi"
DVTiming="DV ajoitus"
Resolution="Tarkkuus"
FrameRate="Kuvanopeus"
LeaveUnchanged="Jätä ennalleen"
UseBuffering="Käytä puskurointia"

View file

@ -0,0 +1,11 @@
V4L2Input="Périphérique de capture vidéo (V4L2)"
Device="Périphérique"
Input="Entrée"
VideoFormat="Format vidéo"
VideoStandard="Standard vidéo"
DVTiming="Timing DV"
Resolution="Résolution"
FrameRate="Fréquence d'image"
LeaveUnchanged="Annuler les modifications"
UseBuffering="Utiliser la mise en mémoire tampon"

View file

@ -0,0 +1,11 @@
V4L2Input="Dispositivo de captura de vídeo (V4L2)"
Device="Dispositivo"
Input="Entrada"
VideoFormat="Formato de vídeo"
VideoStandard="Vídeo estándar"
DVTiming="Axuste DV"
Resolution="Resolución"
FrameRate="Velocidade de fotogramas"
LeaveUnchanged="Deixar sen cambios"
UseBuffering="Utilizar o almacenamento no búfer"

View file

@ -0,0 +1,11 @@
V4L2Input="Ulazni video uređaj (V4L2)"
Device="Uređaj"
Input="Ulaz"
VideoFormat="Video format"
VideoStandard="Video standard"
DVTiming="DV vreme"
Resolution="Rezolucija"
FrameRate="FPS"
LeaveUnchanged="Ostavi nepromenjeno"
UseBuffering="Koristi baferovanje"

View file

@ -0,0 +1,11 @@
V4L2Input="Videorögzítő Eszköz (V4L2)"
Device="Eszköz"
Input="Bemenet"
VideoFormat="Videó Formátum"
VideoStandard="Video Szabvány"
DVTiming="DV Időzítés"
Resolution="Felbontás"
FrameRate="Képkockasebesség"
LeaveUnchanged="Változatlanul Hagyni"
UseBuffering="Pufferelés Használata"

View file

@ -0,0 +1,11 @@
V4L2Input="Dispositivo di acquisizione video (V4L2)"
Device="Dispositivo"
Input="Input"
VideoFormat="Formato Video"
VideoStandard="Video Standard"
DVTiming="DV Timing"
Resolution="Risoluzione"
FrameRate="Frame Rate"
LeaveUnchanged="Lascia invariato"
UseBuffering="Usa Buffer"

View file

@ -0,0 +1,11 @@
V4L2Input="映像キャプチャ デバイス (V4L2)"
Device="デバイス"
Input="入力"
VideoFormat="映像フォーマット"
VideoStandard="ビデオ標準"
DVTiming="デジタルビデオタイミング"
Resolution="解像度"
FrameRate="フレームレート"
LeaveUnchanged="変更せずに戻る"
UseBuffering="バッファリングを使用する"

View file

@ -0,0 +1,11 @@
V4L2Input="비디오 캡쳐 장치(V4L2)"
Device="장치"
Input="입력"
VideoFormat="비디오 형식"
VideoStandard="비디오 표준"
DVTiming="디지털 비디오 타이밍"
Resolution="해상도"
FrameRate="프레임 레이트"
LeaveUnchanged="저장하지 않고 두기"
UseBuffering="버퍼링 사용"

View file

@ -0,0 +1,11 @@
V4L2Input="Videopptaksenhet (V4L2)"
Device="Enhet"
Input="Inndata"
VideoFormat="Videoformat"
VideoStandard="Videostandard"
DVTiming="Digital Video tidsjustering"
Resolution="Oppløsning"
FrameRate="Bildefrekvens"
LeaveUnchanged="La stå uendret"
UseBuffering="Bruk bufring"

View file

@ -0,0 +1,11 @@
V4L2Input="Video-capture apparaat (V4L2)"
Device="Apparaat"
Input="Invoer"
VideoFormat="Video-indeling"
VideoStandard="Videostandaard"
DVTiming="DV-Timing"
Resolution="Resolutie"
FrameRate="Frame Rate"
LeaveUnchanged="Ongewijzigd Laten"
UseBuffering="Buffering Gebruiken"

View file

@ -0,0 +1,11 @@
V4L2Input="Urządzenie przechwytujące obraz (V4L2)"
Device="Urządzenie"
Input="Wejście"
VideoFormat="Format wideo"
VideoStandard="Standard wideo"
DVTiming="Synchronizacja czasowa video"
Resolution="Rozdzielczość"
FrameRate="Klatki na sekundę"
LeaveUnchanged="Pozostaw bez zmian"
UseBuffering="Użyj buforowania"

View file

@ -0,0 +1,11 @@
V4L2Input="Dispositivo de Captura de Vídeo (V4L2)"
Device="Dispositivo"
Input="Entrada"
VideoFormat="Formato de Vídeo"
VideoStandard="Padrão de vídeo"
DVTiming="Sincronismo DV"
Resolution="Resolução"
FrameRate="Taxa de quadros"
LeaveUnchanged="Deixar inalterado"
UseBuffering="Utilizar Buffering"

View file

@ -0,0 +1,11 @@
V4L2Input="Dispositivo de captura de vídeo (V4L2)"
Device="Dispositivo"
Input="Entrada"
VideoFormat="Formato de vídeo"
VideoStandard="Padrão de vídeo"
DVTiming="Sincronismo DV"
Resolution="Resolução"
FrameRate="Taxa de quadros"
LeaveUnchanged="Deixar inalterado"
UseBuffering="Utilizar Buffering"

View file

@ -0,0 +1,11 @@
V4L2Input="Dispozitiv de Captură Video (V4L2)"
Device="Dispozitiv"
Input="Intrare"
VideoFormat="Format Video"
VideoStandard="Standard Video"
DVTiming="Sincronizare DV"
Resolution="Rezoluţie"
FrameRate="Rata de cadru"
LeaveUnchanged="Lasă neschimbat"
UseBuffering="Utilizaţi Tampon/Buffer"

View file

@ -0,0 +1,11 @@
V4L2Input="Устройство захвата видео (V4L2)"
Device="Устройство"
Input="Ввод"
VideoFormat="Формат видео"
VideoStandard="Стандарт видео"
DVTiming="Тайминг цифрового видео"
Resolution="Разрешение"
FrameRate="Частота кадров"
LeaveUnchanged="Оставить без изменений"
UseBuffering="Использовать буферизацию"

View file

@ -0,0 +1,11 @@
V4L2Input="Zariadenie na záznam videa (V4L2)"
Device="Zariadenie"
Input="Vstup"
VideoFormat="Formát videa"
VideoStandard="Video štandard"
DVTiming="DV časovanie"
Resolution="Rozlíšenie"
FrameRate="Frekvencia snímok"
LeaveUnchanged="Ponechať bez zmeny"
UseBuffering="Použiť vyrovnávaciu pamäť"

View file

@ -0,0 +1,11 @@
V4L2Input="Video zajemalne naprave (V4L2)"
Device="Naprava"
Input="Vhod"
VideoFormat="Video Format"
VideoStandard="Video Standard"
DVTiming="DV Timing"
Resolution="Resolucija"
FrameRate="Slike na sekundo"
LeaveUnchanged="Pusti nespremenjeno"
UseBuffering="Uporabi medpomnilnik"

View file

@ -0,0 +1,11 @@
V4L2Input="Ulazni video uređaj (V4L2)"
Device="Uređaj"
Input="Ulaz"
VideoFormat="Video format"
VideoStandard="Video standard"
DVTiming="DV vreme"
Resolution="Rezolucija"
FrameRate="FPS"
LeaveUnchanged="Ostavi nepromenjeno"
UseBuffering="Koristi baferovanje"

View file

@ -0,0 +1,11 @@
V4L2Input="Улазни видео уређај (V4L2)"
Device="Уређај"
Input="Улаз"
VideoFormat="Видео формат"
VideoStandard="Видео стандард"
DVTiming="DV време"
Resolution="Резолуција"
FrameRate="FPS"
LeaveUnchanged="Остави непромењено"
UseBuffering="Користи баферовање"

View file

@ -0,0 +1,11 @@
V4L2Input="Videoinmatningssenhet (V4L2)"
Device="Enhet"
Input="Inmatning"
VideoFormat="Videoformat"
VideoStandard="Videostandard"
DVTiming="DV Tajming"
Resolution="Upplösning"
FrameRate="Bildhastighet"
LeaveUnchanged="Lämna oförändrat"
UseBuffering="Använd buffer"

View file

@ -0,0 +1 @@

View file

@ -0,0 +1,11 @@
V4L2Input="Video Yakalama Aygıtı (V4L2)"
Device="Aygıt"
Input="Giriş"
VideoFormat="Video Formatı"
VideoStandard="Video Standartı"
DVTiming="Dijital Video Zamanlaması"
Resolution="Çözünürlük"
FrameRate="Kare Hızı"
LeaveUnchanged="Değişmeden Bırak"
UseBuffering="Arabelleği Kullan"

View file

@ -0,0 +1,2 @@
FrameRate="Частота кадрів"

View file

@ -0,0 +1,11 @@
V4L2Input="视频捕获设备(V4L2)"
Device="设备"
Input="输入"
VideoFormat="视频格式"
VideoStandard="视频标准"
DVTiming="DV计时"
Resolution="分辨率"
FrameRate="帧率"
LeaveUnchanged="保持不变"
UseBuffering="使用缓冲"

View file

@ -0,0 +1,10 @@
V4L2Input="截取影像裝置V4L2"
Device="裝置"
Input="輸入"
VideoFormat="影像格式"
VideoStandard="影像標準"
Resolution="解析度"
FrameRate="影格率"
LeaveUnchanged="不改變並離開"
UseBuffering="使用緩衝"

View file

@ -0,0 +1,28 @@
/*
Copyright (C) 2014 by Leonhard Oelke <leonhard@in-verted.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <obs-module.h>
OBS_DECLARE_MODULE()
OBS_MODULE_USE_DEFAULT_LOCALE("linux-v4l2", "en-US")
extern struct obs_source_info v4l2_input;
bool obs_module_load(void)
{
obs_register_source(&v4l2_input);
return true;
}

View file

@ -0,0 +1,282 @@
/*
Copyright (C) 2014 by Leonhard Oelke <leonhard@in-verted.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/mman.h>
#include <util/bmem.h>
#include "v4l2-helpers.h"
#define blog(level, msg, ...) blog(level, "v4l2-helpers: " msg, ##__VA_ARGS__)
int_fast32_t v4l2_start_capture(int_fast32_t dev, struct v4l2_buffer_data *buf)
{
enum v4l2_buf_type type;
struct v4l2_buffer enq;
memset(&enq, 0, sizeof(enq));
enq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
enq.memory = V4L2_MEMORY_MMAP;
for (enq.index = 0; enq.index < buf->count; ++enq.index) {
if (v4l2_ioctl(dev, VIDIOC_QBUF, &enq) < 0) {
blog(LOG_ERROR, "unable to queue buffer");
return -1;
}
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (v4l2_ioctl(dev, VIDIOC_STREAMON, &type) < 0) {
blog(LOG_ERROR, "unable to start stream");
return -1;
}
return 0;
}
int_fast32_t v4l2_stop_capture(int_fast32_t dev)
{
enum v4l2_buf_type type;
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (v4l2_ioctl(dev, VIDIOC_STREAMOFF, &type) < 0) {
blog(LOG_ERROR, "unable to stop stream");
return -1;
}
return 0;
}
int_fast32_t v4l2_create_mmap(int_fast32_t dev, struct v4l2_buffer_data *buf)
{
struct v4l2_requestbuffers req;
struct v4l2_buffer map;
memset(&req, 0, sizeof(req));
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (v4l2_ioctl(dev, VIDIOC_REQBUFS, &req) < 0) {
blog(LOG_ERROR, "Request for buffers failed !");
return -1;
}
if (req.count < 2) {
blog(LOG_ERROR, "Device returned less than 2 buffers");
return -1;
}
buf->count = req.count;
buf->info = bzalloc(req.count * sizeof(struct v4l2_mmap_info));
memset(&map, 0, sizeof(map));
map.type = req.type;
map.memory = req.memory;
for (map.index = 0; map.index < req.count; ++map.index) {
if (v4l2_ioctl(dev, VIDIOC_QUERYBUF, &map) < 0) {
blog(LOG_ERROR, "Failed to query buffer details");
return -1;
}
buf->info[map.index].length = map.length;
buf->info[map.index].start = v4l2_mmap(NULL, map.length,
PROT_READ | PROT_WRITE, MAP_SHARED,
dev, map.m.offset);
if (buf->info[map.index].start == MAP_FAILED) {
blog(LOG_ERROR, "mmap for buffer failed");
return -1;
}
}
return 0;
}
int_fast32_t v4l2_destroy_mmap(struct v4l2_buffer_data *buf)
{
for(uint_fast32_t i = 0; i < buf->count; ++i) {
if (buf->info[i].start != MAP_FAILED && buf->info[i].start != 0)
v4l2_munmap(buf->info[i].start, buf->info[i].length);
}
if (buf->count) {
bfree(buf->info);
buf->count = 0;
}
return 0;
}
int_fast32_t v4l2_set_input(int_fast32_t dev, int *input)
{
if (!dev || !input)
return -1;
return (*input == -1)
? v4l2_ioctl(dev, VIDIOC_G_INPUT, input)
: v4l2_ioctl(dev, VIDIOC_S_INPUT, input);
}
int_fast32_t v4l2_get_input_caps(int_fast32_t dev, int input, uint32_t *caps)
{
if (!dev || !caps)
return -1;
if (input == -1) {
if (v4l2_ioctl(dev, VIDIOC_G_INPUT, &input) < 0)
return -1;
}
struct v4l2_input in;
memset(&in, 0, sizeof(in));
in.index = input;
if (v4l2_ioctl(dev, VIDIOC_ENUMINPUT, &in) < 0)
return -1;
*caps = in.capabilities;
return 0;
}
int_fast32_t v4l2_set_format(int_fast32_t dev, int *resolution,
int *pixelformat, int *bytesperline)
{
bool set = false;
int width, height;
struct v4l2_format fmt;
if (!dev || !resolution || !pixelformat || !bytesperline)
return -1;
/* We need to set the type in order to query the settings */
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (v4l2_ioctl(dev, VIDIOC_G_FMT, &fmt) < 0)
return -1;
if (*resolution != -1) {
v4l2_unpack_tuple(&width, &height, *resolution);
fmt.fmt.pix.width = width;
fmt.fmt.pix.height = height;
set = true;
}
if (*pixelformat != -1) {
fmt.fmt.pix.pixelformat = *pixelformat;
set = true;
}
if (set && (v4l2_ioctl(dev, VIDIOC_S_FMT, &fmt) < 0))
return -1;
*resolution = v4l2_pack_tuple(fmt.fmt.pix.width, fmt.fmt.pix.height);
*pixelformat = fmt.fmt.pix.pixelformat;
*bytesperline = fmt.fmt.pix.bytesperline;
return 0;
}
int_fast32_t v4l2_set_framerate(int_fast32_t dev, int *framerate)
{
bool set = false;
int num, denom;
struct v4l2_streamparm par;
if (!dev || !framerate)
return -1;
/* We need to set the type in order to query the stream settings */
par.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (v4l2_ioctl(dev, VIDIOC_G_PARM, &par) < 0)
return -1;
if (*framerate != -1) {
v4l2_unpack_tuple(&num, &denom, *framerate);
par.parm.capture.timeperframe.numerator = num;
par.parm.capture.timeperframe.denominator = denom;
set = true;
}
if (set && (v4l2_ioctl(dev, VIDIOC_S_PARM, &par) < 0))
return -1;
*framerate = v4l2_pack_tuple(par.parm.capture.timeperframe.numerator,
par.parm.capture.timeperframe.denominator);
return 0;
}
int_fast32_t v4l2_set_standard(int_fast32_t dev, int *standard)
{
if (!dev || !standard)
return -1;
if (*standard == -1) {
if (v4l2_ioctl(dev, VIDIOC_G_STD, standard) < 0)
return -1;
} else {
if (v4l2_ioctl(dev, VIDIOC_S_STD, standard) < 0)
return -1;
}
return 0;
}
int_fast32_t v4l2_enum_dv_timing(int_fast32_t dev, struct v4l2_dv_timings *dvt,
int index)
{
#if !defined(VIDIOC_ENUM_DV_TIMINGS) || !defined(V4L2_IN_CAP_DV_TIMINGS)
UNUSED_PARAMETER(dev);
UNUSED_PARAMETER(dvt);
UNUSED_PARAMETER(index);
return -1;
#else
if (!dev || !dvt)
return -1;
struct v4l2_enum_dv_timings iter;
memset(&iter, 0, sizeof(iter));
iter.index = index;
if (v4l2_ioctl(dev, VIDIOC_ENUM_DV_TIMINGS, &iter) < 0)
return -1;
memcpy(dvt, &iter.timings, sizeof(struct v4l2_dv_timings));
return 0;
#endif
}
int_fast32_t v4l2_set_dv_timing(int_fast32_t dev, int *timing)
{
if (!dev || !timing)
return -1;
if (*timing == -1)
return 0;
struct v4l2_dv_timings dvt;
if (v4l2_enum_dv_timing(dev, &dvt, *timing) < 0)
return -1;
if (v4l2_ioctl(dev, VIDIOC_S_DV_TIMINGS, &dvt) < 0)
return -1;
return 0;
}

View file

@ -0,0 +1,303 @@
/*
Copyright (C) 2014 by Leonhard Oelke <leonhard@in-verted.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <linux/videodev2.h>
#include <libv4l2.h>
#include <obs-module.h>
#include <media-io/video-io.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Data structure for mapped buffers
*/
struct v4l2_mmap_info {
/** length of the mapped buffer */
size_t length;
/** start address of the mapped buffer */
void *start;
};
/**
* Data structure for buffer info
*/
struct v4l2_buffer_data {
/** number of mapped buffers */
uint_fast32_t count;
/** memory info for mapped buffers */
struct v4l2_mmap_info *info;
};
/**
* Convert v4l2 pixel format to obs video format
*
* @param format v4l2 format id
*
* @return obs video_format id
*/
static inline enum video_format v4l2_to_obs_video_format(uint_fast32_t format)
{
switch (format) {
case V4L2_PIX_FMT_YVYU: return VIDEO_FORMAT_YVYU;
case V4L2_PIX_FMT_YUYV: return VIDEO_FORMAT_YUY2;
case V4L2_PIX_FMT_UYVY: return VIDEO_FORMAT_UYVY;
case V4L2_PIX_FMT_NV12: return VIDEO_FORMAT_NV12;
case V4L2_PIX_FMT_YUV420: return VIDEO_FORMAT_I420;
case V4L2_PIX_FMT_YVU420: return VIDEO_FORMAT_I420;
#ifdef V4L2_PIX_FMT_XBGR32
case V4L2_PIX_FMT_XBGR32: return VIDEO_FORMAT_BGRX;
#endif
#ifdef V4L2_PIX_FMT_ABGR32
case V4L2_PIX_FMT_ABGR32: return VIDEO_FORMAT_BGRA;
#endif
default: return VIDEO_FORMAT_NONE;
}
}
/**
* Fixed framesizes for devices that don't support enumerating discrete values.
*
* The framesizes in this array are packed, the width encoded in the high word
* and the height in the low word.
* The array is terminated with a zero.
*/
static const int v4l2_framesizes[] =
{
/* 4:3 */
160<<16 | 120,
320<<16 | 240,
480<<16 | 320,
640<<16 | 480,
800<<16 | 600,
1024<<16 | 768,
1280<<16 | 960,
1440<<16 | 1050,
1440<<16 | 1080,
1600<<16 | 1200,
/* 16:9 */
640<<16 | 360,
960<<16 | 540,
1280<<16 | 720,
1600<<16 | 900,
1920<<16 | 1080,
1920<<16 | 1200,
/* tv */
432<<16 | 520,
480<<16 | 320,
480<<16 | 530,
486<<16 | 440,
576<<16 | 310,
576<<16 | 520,
576<<16 | 570,
720<<16 | 576,
1024<<16 | 576,
0
};
/**
* Fixed framerates for devices that don't support enumerating discrete values.
*
* The framerates in this array are packed, the numerator encoded in the high
* word and the denominator in the low word.
* The array is terminated with a zero.
*/
static const int v4l2_framerates[] =
{
1<<16 | 60,
1<<16 | 50,
1<<16 | 30,
1<<16 | 25,
1<<16 | 20,
1<<16 | 15,
1<<16 | 10,
1<<16 | 5,
0
};
/**
* Pack two integer values into one
*
* Obviously the input integers have to be truncated in order to fit into
* one. The effective 16bits left are still enough to handle resolutions and
* framerates just fine.
*
* @param a integer one
* @param b integer two
*
* @return the packed integer
*/
static inline int v4l2_pack_tuple(int a, int b)
{
return (a << 16) | (b & 0xffff);
}
/**
* Unpack two integer values from one
*
* @see v4l2_pack_tuple
*
* @param a pointer to integer a
* @param b pointer to integer b
* @param packed the packed integer
*/
static void v4l2_unpack_tuple(int *a, int *b, int packed)
{
*a = packed >> 16;
*b = packed & 0xffff;
}
/**
* Start the video capture on the device.
*
* This enqueues the memory mapped buffers and instructs the device to start
* the video stream.
*
* @param dev handle for the v4l2 device
* @param buf buffer data
*
* @return negative on failure
*/
int_fast32_t v4l2_start_capture(int_fast32_t dev, struct v4l2_buffer_data *buf);
/**
* Stop the video capture on the device.
*
* @param dev handle for the v4l2 device
*
* @return negative on failure
*/
int_fast32_t v4l2_stop_capture(int_fast32_t dev);
/**
* Create memory mapping for buffers
*
* This tries to map at least 2, preferably 4, buffers to application memory.
*
* @param dev handle for the v4l2 device
* @param buf buffer data
*
* @return negative on failure
*/
int_fast32_t v4l2_create_mmap(int_fast32_t dev, struct v4l2_buffer_data *buf);
/**
* Destroy the memory mapping for buffers
*
* @param buf buffer data
*
* @return negative on failure
*/
int_fast32_t v4l2_destroy_mmap(struct v4l2_buffer_data *buf);
/**
* Set the video input on the device.
*
* If the action succeeds input is set to the currently selected input.
*
* @param dev handle for the v4l2 device
* @param input index of the input or -1 to leave it as is
*
* @return negative on failure
*/
int_fast32_t v4l2_set_input(int_fast32_t dev, int *input);
/**
* Get capabilities for an input.
*
* @param dev handle for the v4l2 device
* @param input index of the input or -1 to use the currently selected
* @param caps capabilities for the input
*
* @return negative on failure
*/
int_fast32_t v4l2_get_input_caps(int_fast32_t dev, int input, uint32_t *caps);
/**
* Set the video format on the device.
*
* If the action succeeds resolution, pixelformat and bytesperline are set
* to the used values.
*
* @param dev handle for the v4l2 device
* @param resolution packed value of the resolution or -1 to leave as is
* @param pixelformat index of the pixelformat or -1 to leave as is
* @param bytesperline this will be set accordingly on success
*
* @return negative on failure
*/
int_fast32_t v4l2_set_format(int_fast32_t dev, int *resolution,
int *pixelformat, int *bytesperline);
/**
* Set the framerate on the device.
*
* If the action succeeds framerate is set to the used value.
*
* @param dev handle to the v4l2 device
* @param framerate packed value of the framerate or -1 to leave as is
*
* @return negative on failure
*/
int_fast32_t v4l2_set_framerate(int_fast32_t dev, int *framerate);
/**
* Set a video standard on the device.
*
* If the action succeeds standard is set to the used video standard id.
*
* @param dev handle to the v4l2 device
* @param standard id of the standard to use or -1 to leave as is
*
* @return negative on failure
*/
int_fast32_t v4l2_set_standard(int_fast32_t dev, int *standard);
/**
* Get the dv timing for an input with a specified index
*
* @param dev handle to the v4l2 device
* @param dvt pointer to the timing structure to fill
* @param index index of the dv timing to fetch
*
* @return negative on failure
*/
int_fast32_t v4l2_enum_dv_timing(int_fast32_t dev, struct v4l2_dv_timings *dvt,
int index);
/**
* Set a dv timing on the device
*
* Currently standard will not be changed on success or error.
*
* @param dev handle to the v4l2 device
* @param timing index of the timing to use or -1 to leave as is
*
* @return negative on failure
*/
int_fast32_t v4l2_set_dv_timing(int_fast32_t dev, int *timing);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,990 @@
/*
Copyright (C) 2014 by Leonhard Oelke <leonhard@in-verted.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <inttypes.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <linux/videodev2.h>
#include <libv4l2.h>
#include <util/threading.h>
#include <util/bmem.h>
#include <util/dstr.h>
#include <util/platform.h>
#include <obs-module.h>
#include "v4l2-helpers.h"
#if HAVE_UDEV
#include "v4l2-udev.h"
#endif
/* The new dv timing api was introduced in Linux 3.4
* Currently we simply disable dv timings when this is not defined */
#if !defined(VIDIOC_ENUM_DV_TIMINGS) || !defined(V4L2_IN_CAP_DV_TIMINGS)
#define V4L2_IN_CAP_DV_TIMINGS 0
#endif
#define V4L2_DATA(voidptr) struct v4l2_data *data = voidptr;
#define timeval2ns(tv) \
(((uint64_t) tv.tv_sec * 1000000000) + ((uint64_t) tv.tv_usec * 1000))
#define V4L2_FOURCC_STR(code) \
(char[5]) { \
(code >> 24) & 0xFF, \
(code >> 16) & 0xFF, \
(code >> 8) & 0xFF, \
code & 0xFF, \
0 \
}
#define blog(level, msg, ...) blog(level, "v4l2-input: " msg, ##__VA_ARGS__)
/**
* Data structure for the v4l2 source
*/
struct v4l2_data {
/* settings */
char *device_id;
int input;
int pixfmt;
int standard;
int dv_timing;
int resolution;
int framerate;
/* internal data */
obs_source_t *source;
pthread_t thread;
os_event_t *event;
int_fast32_t dev;
int width;
int height;
int linesize;
struct v4l2_buffer_data buffers;
};
/* forward declarations */
static void v4l2_init(struct v4l2_data *data);
static void v4l2_terminate(struct v4l2_data *data);
/**
* Prepare the output frame structure for obs and compute plane offsets
*
* Basically all data apart from memory pointers and the timestamp is known
* before the capture starts. This function prepares the obs_source_frame
* struct with all the data that is already known.
*
* v4l2 uses a continuous memory segment for all planes so we simply compute
* offsets to add to the start address in order to give obs the correct data
* pointers for the individual planes.
*/
static void v4l2_prep_obs_frame(struct v4l2_data *data,
struct obs_source_frame *frame, size_t *plane_offsets)
{
memset(frame, 0, sizeof(struct obs_source_frame));
memset(plane_offsets, 0, sizeof(size_t) * MAX_AV_PLANES);
frame->width = data->width;
frame->height = data->height;
frame->format = v4l2_to_obs_video_format(data->pixfmt);
video_format_get_parameters(VIDEO_CS_DEFAULT, VIDEO_RANGE_PARTIAL,
frame->color_matrix, frame->color_range_min,
frame->color_range_max);
switch(data->pixfmt) {
case V4L2_PIX_FMT_NV12:
frame->linesize[0] = data->linesize;
frame->linesize[1] = data->linesize / 2;
plane_offsets[1] = data->linesize * data->height;
break;
case V4L2_PIX_FMT_YVU420:
frame->linesize[0] = data->linesize;
frame->linesize[1] = data->linesize / 2;
frame->linesize[2] = data->linesize / 2;
plane_offsets[1] = data->linesize * data->height * 5 / 4;
plane_offsets[2] = data->linesize * data->height;
break;
case V4L2_PIX_FMT_YUV420:
frame->linesize[0] = data->linesize;
frame->linesize[1] = data->linesize / 2;
frame->linesize[2] = data->linesize / 2;
plane_offsets[1] = data->linesize * data->height;
plane_offsets[2] = data->linesize * data->height * 5 / 4;
break;
default:
frame->linesize[0] = data->linesize;
break;
}
}
/*
* Worker thread to get video data
*/
static void *v4l2_thread(void *vptr)
{
V4L2_DATA(vptr);
int r;
fd_set fds;
uint8_t *start;
uint64_t frames;
uint64_t first_ts;
struct timeval tv;
struct v4l2_buffer buf;
struct obs_source_frame out;
size_t plane_offsets[MAX_AV_PLANES];
if (v4l2_start_capture(data->dev, &data->buffers) < 0)
goto exit;
frames = 0;
first_ts = 0;
v4l2_prep_obs_frame(data, &out, plane_offsets);
while (os_event_try(data->event) == EAGAIN) {
FD_ZERO(&fds);
FD_SET(data->dev, &fds);
tv.tv_sec = 1;
tv.tv_usec = 0;
r = select(data->dev + 1, &fds, NULL, NULL, &tv);
if (r < 0) {
if (errno == EINTR)
continue;
blog(LOG_DEBUG, "select failed");
break;
} else if (r == 0) {
blog(LOG_DEBUG, "select timeout");
continue;
}
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if (v4l2_ioctl(data->dev, VIDIOC_DQBUF, &buf) < 0) {
if (errno == EAGAIN)
continue;
blog(LOG_DEBUG, "failed to dequeue buffer");
break;
}
out.timestamp = timeval2ns(buf.timestamp);
if (!frames)
first_ts = out.timestamp;
out.timestamp -= first_ts;
start = (uint8_t *) data->buffers.info[buf.index].start;
for (uint_fast32_t i = 0; i < MAX_AV_PLANES; ++i)
out.data[i] = start + plane_offsets[i];
obs_source_output_video(data->source, &out);
if (v4l2_ioctl(data->dev, VIDIOC_QBUF, &buf) < 0) {
blog(LOG_DEBUG, "failed to enqueue buffer");
break;
}
frames++;
}
blog(LOG_INFO, "Stopped capture after %"PRIu64" frames", frames);
exit:
v4l2_stop_capture(data->dev);
return NULL;
}
static const char* v4l2_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("V4L2Input");
}
static void v4l2_defaults(obs_data_t *settings)
{
obs_data_set_default_int(settings, "input", -1);
obs_data_set_default_int(settings, "pixelformat", -1);
obs_data_set_default_int(settings, "standard", -1);
obs_data_set_default_int(settings, "dv_timing", -1);
obs_data_set_default_int(settings, "resolution", -1);
obs_data_set_default_int(settings, "framerate", -1);
obs_data_set_default_bool(settings, "buffering", true);
}
/**
* Enable/Disable all properties for the source.
*
* @note A property that should be ignored can be specified
*
* @param props the source properties
* @param ignore ignore this property
* @param enable enable/disable all properties
*/
static void v4l2_props_set_enabled(obs_properties_t *props,
obs_property_t *ignore, bool enable)
{
if (!props)
return;
for (obs_property_t *prop = obs_properties_first(props); prop != NULL;
obs_property_next(&prop)) {
if (prop == ignore)
continue;
obs_property_set_enabled(prop, enable);
}
}
/*
* List available devices
*/
static void v4l2_device_list(obs_property_t *prop, obs_data_t *settings)
{
DIR *dirp;
struct dirent *dp;
struct dstr device;
bool cur_device_found;
size_t cur_device_index;
const char *cur_device_name;
#ifdef __FreeBSD__
dirp = opendir("/dev");
#else
dirp = opendir("/sys/class/video4linux");
#endif
if (!dirp)
return;
cur_device_found = false;
cur_device_name = obs_data_get_string(settings, "device_id");
obs_property_list_clear(prop);
dstr_init_copy(&device, "/dev/");
while ((dp = readdir(dirp)) != NULL) {
int fd;
uint32_t caps;
struct v4l2_capability video_cap;
#ifdef __FreeBSD__
if (strstr(dp->d_name, "video") == NULL)
continue;
#endif
if (dp->d_type == DT_DIR)
continue;
dstr_resize(&device, 5);
dstr_cat(&device, dp->d_name);
if ((fd = v4l2_open(device.array, O_RDWR | O_NONBLOCK)) == -1) {
blog(LOG_INFO, "Unable to open %s", device.array);
continue;
}
if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &video_cap) == -1) {
blog(LOG_INFO, "Failed to query capabilities for %s",
device.array);
v4l2_close(fd);
continue;
}
#ifndef V4L2_CAP_DEVICE_CAPS
caps = video_cap.capabilities;
#else
/* ... since Linux 3.3 */
caps = (video_cap.capabilities & V4L2_CAP_DEVICE_CAPS)
? video_cap.device_caps
: video_cap.capabilities;
#endif
if (!(caps & V4L2_CAP_VIDEO_CAPTURE)) {
blog(LOG_INFO, "%s seems to not support video capture",
device.array);
v4l2_close(fd);
continue;
}
obs_property_list_add_string(prop, (char *) video_cap.card,
device.array);
blog(LOG_INFO, "Found device '%s' at %s", video_cap.card,
device.array);
/* check if this is the currently used device */
if (cur_device_name && !strcmp(cur_device_name, device.array))
cur_device_found = true;
v4l2_close(fd);
}
/* add currently selected device if not present, but disable it ... */
if (!cur_device_found && cur_device_name && strlen(cur_device_name)) {
cur_device_index = obs_property_list_add_string(prop,
cur_device_name, cur_device_name);
obs_property_list_item_disable(prop, cur_device_index, true);
}
closedir(dirp);
dstr_free(&device);
}
/*
* List inputs for device
*/
static void v4l2_input_list(int_fast32_t dev, obs_property_t *prop)
{
struct v4l2_input in;
memset(&in, 0, sizeof(in));
obs_property_list_clear(prop);
while (v4l2_ioctl(dev, VIDIOC_ENUMINPUT, &in) == 0) {
obs_property_list_add_int(prop, (char *) in.name, in.index);
blog(LOG_INFO, "Found input '%s' (Index %d)", in.name,
in.index);
in.index++;
}
}
/*
* List formats for device
*/
static void v4l2_format_list(int dev, obs_property_t *prop)
{
struct v4l2_fmtdesc fmt;
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.index = 0;
struct dstr buffer;
dstr_init(&buffer);
obs_property_list_clear(prop);
while (v4l2_ioctl(dev, VIDIOC_ENUM_FMT, &fmt) == 0) {
dstr_copy(&buffer, (char *) fmt.description);
if (fmt.flags & V4L2_FMT_FLAG_EMULATED)
dstr_cat(&buffer, " (Emulated)");
if (v4l2_to_obs_video_format(fmt.pixelformat)
!= VIDEO_FORMAT_NONE) {
obs_property_list_add_int(prop, buffer.array,
fmt.pixelformat);
blog(LOG_INFO, "Pixelformat: %s (available)",
buffer.array);
} else {
blog(LOG_INFO, "Pixelformat: %s (unavailable)",
buffer.array);
}
fmt.index++;
}
dstr_free(&buffer);
}
/*
* List video standards for the device
*/
static void v4l2_standard_list(int dev, obs_property_t *prop)
{
struct v4l2_standard std;
std.index = 0;
obs_property_list_clear(prop);
obs_property_list_add_int(prop, obs_module_text("LeaveUnchanged"), -1);
while (v4l2_ioctl(dev, VIDIOC_ENUMSTD, &std) == 0) {
obs_property_list_add_int(prop, (char *) std.name, std.id);
std.index++;
}
}
/*
* List dv timings for the device
*/
static void v4l2_dv_timing_list(int dev, obs_property_t *prop)
{
struct v4l2_dv_timings dvt;
struct dstr buf;
int index = 0;
dstr_init(&buf);
obs_property_list_clear(prop);
obs_property_list_add_int(prop, obs_module_text("LeaveUnchanged"), -1);
while (v4l2_enum_dv_timing(dev, &dvt, index) == 0) {
/* i do not pretend to understand, this is from qv4l2 ... */
double h = (double) dvt.bt.height + dvt.bt.vfrontporch +
dvt.bt.vsync + dvt.bt.vbackporch +
dvt.bt.il_vfrontporch + dvt.bt.il_vsync +
dvt.bt.il_vbackporch;
double w = (double) dvt.bt.width + dvt.bt.hfrontporch +
dvt.bt.hsync + dvt.bt.hbackporch;
double i = (dvt.bt.interlaced) ? 2.0f : 1.0f;
double rate = (double) dvt.bt.pixelclock / (w * (h / i));
dstr_printf(&buf, "%ux%u%c %.2f",
dvt.bt.width, dvt.bt.height,
(dvt.bt.interlaced) ? 'i' : 'p', rate);
obs_property_list_add_int(prop, buf.array, index);
index++;
}
dstr_free(&buf);
}
/*
* List resolutions for device and format
*/
static void v4l2_resolution_list(int dev, uint_fast32_t pixelformat,
obs_property_t *prop)
{
struct v4l2_frmsizeenum frmsize;
frmsize.pixel_format = pixelformat;
frmsize.index = 0;
struct dstr buffer;
dstr_init(&buffer);
obs_property_list_clear(prop);
obs_property_list_add_int(prop, obs_module_text("LeaveUnchanged"), -1);
v4l2_ioctl(dev, VIDIOC_ENUM_FRAMESIZES, &frmsize);
switch(frmsize.type) {
case V4L2_FRMSIZE_TYPE_DISCRETE:
while (v4l2_ioctl(dev, VIDIOC_ENUM_FRAMESIZES, &frmsize) == 0) {
dstr_printf(&buffer, "%dx%d", frmsize.discrete.width,
frmsize.discrete.height);
obs_property_list_add_int(prop, buffer.array,
v4l2_pack_tuple(frmsize.discrete.width,
frmsize.discrete.height));
frmsize.index++;
}
break;
default:
blog(LOG_INFO, "Stepwise and Continuous framesizes "
"are currently hardcoded");
for (const int *packed = v4l2_framesizes; *packed; ++packed) {
int width;
int height;
v4l2_unpack_tuple(&width, &height, *packed);
dstr_printf(&buffer, "%dx%d", width, height);
obs_property_list_add_int(prop, buffer.array, *packed);
}
break;
}
dstr_free(&buffer);
}
/*
* List framerates for device and resolution
*/
static void v4l2_framerate_list(int dev, uint_fast32_t pixelformat,
uint_fast32_t width, uint_fast32_t height, obs_property_t *prop)
{
struct v4l2_frmivalenum frmival;
frmival.pixel_format = pixelformat;
frmival.width = width;
frmival.height = height;
frmival.index = 0;
struct dstr buffer;
dstr_init(&buffer);
obs_property_list_clear(prop);
obs_property_list_add_int(prop, obs_module_text("LeaveUnchanged"), -1);
v4l2_ioctl(dev, VIDIOC_ENUM_FRAMEINTERVALS, &frmival);
switch(frmival.type) {
case V4L2_FRMIVAL_TYPE_DISCRETE:
while (v4l2_ioctl(dev, VIDIOC_ENUM_FRAMEINTERVALS,
&frmival) == 0) {
float fps = (float) frmival.discrete.denominator /
frmival.discrete.numerator;
int pack = v4l2_pack_tuple(frmival.discrete.numerator,
frmival.discrete.denominator);
dstr_printf(&buffer, "%.2f", fps);
obs_property_list_add_int(prop, buffer.array, pack);
frmival.index++;
}
break;
default:
blog(LOG_INFO, "Stepwise and Continuous framerates "
"are currently hardcoded");
for (const int *packed = v4l2_framerates; *packed; ++packed) {
int num;
int denom;
v4l2_unpack_tuple(&num, &denom, *packed);
float fps = (float) denom / num;
dstr_printf(&buffer, "%.2f", fps);
obs_property_list_add_int(prop, buffer.array, *packed);
}
break;
}
dstr_free(&buffer);
}
/*
* Device selected callback
*/
static bool device_selected(obs_properties_t *props, obs_property_t *p,
obs_data_t *settings)
{
int dev = v4l2_open(obs_data_get_string(settings, "device_id"),
O_RDWR | O_NONBLOCK);
v4l2_props_set_enabled(props, p, (dev == -1) ? false : true);
if (dev == -1)
return false;
obs_property_t *prop = obs_properties_get(props, "input");
v4l2_input_list(dev, prop);
v4l2_close(dev);
obs_property_modified(prop, settings);
return true;
}
/*
* Input selected callback
*/
static bool input_selected(obs_properties_t *props, obs_property_t *p,
obs_data_t *settings)
{
UNUSED_PARAMETER(p);
int dev = v4l2_open(obs_data_get_string(settings, "device_id"),
O_RDWR | O_NONBLOCK);
if (dev == -1)
return false;
obs_property_t *prop = obs_properties_get(props, "pixelformat");
v4l2_format_list(dev, prop);
v4l2_close(dev);
obs_property_modified(prop, settings);
return true;
}
/*
* Format selected callback
*/
static bool format_selected(obs_properties_t *props, obs_property_t *p,
obs_data_t *settings)
{
UNUSED_PARAMETER(p);
int dev = v4l2_open(obs_data_get_string(settings, "device_id"),
O_RDWR | O_NONBLOCK);
if (dev == -1)
return false;
int input = (int) obs_data_get_int(settings, "input");
uint32_t caps = 0;
if (v4l2_get_input_caps(dev, input, &caps) < 0)
return false;
caps &= V4L2_IN_CAP_STD | V4L2_IN_CAP_DV_TIMINGS;
obs_property_t *resolution = obs_properties_get(props, "resolution");
obs_property_t *framerate = obs_properties_get(props, "framerate");
obs_property_t *standard = obs_properties_get(props, "standard");
obs_property_t *dv_timing = obs_properties_get(props, "dv_timing");
obs_property_set_visible(resolution, (!caps) ? true : false);
obs_property_set_visible(framerate, (!caps) ? true : false);
obs_property_set_visible(standard,
(caps & V4L2_IN_CAP_STD) ? true : false);
obs_property_set_visible(dv_timing,
(caps & V4L2_IN_CAP_DV_TIMINGS) ? true : false);
if (!caps) {
v4l2_resolution_list(dev, obs_data_get_int(
settings, "pixelformat"), resolution);
}
if (caps & V4L2_IN_CAP_STD)
v4l2_standard_list(dev, standard);
if (caps & V4L2_IN_CAP_DV_TIMINGS)
v4l2_dv_timing_list(dev, dv_timing);
v4l2_close(dev);
if (!caps)
obs_property_modified(resolution, settings);
if (caps & V4L2_IN_CAP_STD)
obs_property_modified(standard, settings);
if (caps & V4L2_IN_CAP_DV_TIMINGS)
obs_property_modified(dv_timing, settings);
return true;
}
/*
* Resolution selected callback
*/
static bool resolution_selected(obs_properties_t *props, obs_property_t *p,
obs_data_t *settings)
{
UNUSED_PARAMETER(p);
int width, height;
int dev = v4l2_open(obs_data_get_string(settings, "device_id"),
O_RDWR | O_NONBLOCK);
if (dev == -1)
return false;
obs_property_t *prop = obs_properties_get(props, "framerate");
v4l2_unpack_tuple(&width, &height, obs_data_get_int(settings,
"resolution"));
v4l2_framerate_list(dev, obs_data_get_int(settings, "pixelformat"),
width, height, prop);
v4l2_close(dev);
obs_property_modified(prop, settings);
return true;
}
#if HAVE_UDEV
/**
* Device added callback
*
* If everything went fine we can start capturing again when the device is
* reconnected
*/
static void device_added(void *vptr, calldata_t *calldata)
{
V4L2_DATA(vptr);
obs_source_update_properties(data->source);
const char *dev;
calldata_get_string(calldata, "device", &dev);
if (strcmp(data->device_id, dev))
return;
blog(LOG_INFO, "Device %s reconnected", dev);
v4l2_init(data);
}
/**
* Device removed callback
*
* We stop recording here so we don't block the device node
*/
static void device_removed(void *vptr, calldata_t *calldata)
{
V4L2_DATA(vptr);
obs_source_update_properties(data->source);
const char *dev;
calldata_get_string(calldata, "device", &dev);
if (strcmp(data->device_id, dev))
return;
blog(LOG_INFO, "Device %s disconnected", dev);
v4l2_terminate(data);
}
#endif
static obs_properties_t *v4l2_properties(void *vptr)
{
V4L2_DATA(vptr);
obs_properties_t *props = obs_properties_create();
obs_property_t *device_list = obs_properties_add_list(props,
"device_id", obs_module_text("Device"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
obs_property_t *input_list = obs_properties_add_list(props,
"input", obs_module_text("Input"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_property_t *format_list = obs_properties_add_list(props,
"pixelformat", obs_module_text("VideoFormat"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_property_t *standard_list = obs_properties_add_list(props,
"standard", obs_module_text("VideoStandard"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_property_set_visible(standard_list, false);
obs_property_t *dv_timing_list = obs_properties_add_list(props,
"dv_timing", obs_module_text("DVTiming"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_property_set_visible(dv_timing_list, false);
obs_property_t *resolution_list = obs_properties_add_list(props,
"resolution", obs_module_text("Resolution"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_properties_add_list(props,
"framerate", obs_module_text("FrameRate"),
OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
obs_properties_add_bool(props,
"buffering", obs_module_text("UseBuffering"));
obs_data_t *settings = obs_source_get_settings(data->source);
v4l2_device_list(device_list, settings);
obs_data_release(settings);
obs_property_set_modified_callback(device_list, device_selected);
obs_property_set_modified_callback(input_list, input_selected);
obs_property_set_modified_callback(format_list, format_selected);
obs_property_set_modified_callback(resolution_list,
resolution_selected);
return props;
}
static void v4l2_terminate(struct v4l2_data *data)
{
if (data->thread) {
os_event_signal(data->event);
pthread_join(data->thread, NULL);
os_event_destroy(data->event);
data->thread = 0;
}
v4l2_destroy_mmap(&data->buffers);
if (data->dev != -1) {
v4l2_close(data->dev);
data->dev = -1;
}
}
static void v4l2_destroy(void *vptr)
{
V4L2_DATA(vptr);
if (!data)
return;
v4l2_terminate(data);
if (data->device_id)
bfree(data->device_id);
#if HAVE_UDEV
signal_handler_t *sh = v4l2_get_udev_signalhandler();
signal_handler_disconnect(sh, "device_added", device_added, data);
signal_handler_disconnect(sh, "device_removed", device_removed, data);
v4l2_unref_udev();
#endif
bfree(data);
}
/**
* Initialize the v4l2 device
*
* This function:
* - tries to open the device
* - sets pixelformat and requested resolution
* - sets the requested framerate
* - maps the buffers
* - starts the capture thread
*/
static void v4l2_init(struct v4l2_data *data)
{
uint32_t input_caps;
int fps_num, fps_denom;
blog(LOG_INFO, "Start capture from %s", data->device_id);
data->dev = v4l2_open(data->device_id, O_RDWR | O_NONBLOCK);
if (data->dev == -1) {
blog(LOG_ERROR, "Unable to open device");
goto fail;
}
/* set input */
if (v4l2_set_input(data->dev, &data->input) < 0) {
blog(LOG_ERROR, "Unable to set input %d", data->input);
goto fail;
}
blog(LOG_INFO, "Input: %d", data->input);
if (v4l2_get_input_caps(data->dev, -1, &input_caps) < 0) {
blog(LOG_ERROR, "Unable to get input capabilities");
goto fail;
}
/* set video standard if supported */
if (input_caps & V4L2_IN_CAP_STD) {
if (v4l2_set_standard(data->dev, &data->standard) < 0) {
blog(LOG_ERROR, "Unable to set video standard");
goto fail;
}
data->resolution = -1;
data->framerate = -1;
}
/* set dv timing if supported */
if (input_caps & V4L2_IN_CAP_DV_TIMINGS) {
if (v4l2_set_dv_timing(data->dev, &data->dv_timing) < 0) {
blog(LOG_ERROR, "Unable to set dv timing");
goto fail;
}
data->resolution = -1;
data->framerate = -1;
}
/* set pixel format and resolution */
if (v4l2_set_format(data->dev, &data->resolution, &data->pixfmt,
&data->linesize) < 0) {
blog(LOG_ERROR, "Unable to set format");
goto fail;
}
if (v4l2_to_obs_video_format(data->pixfmt) == VIDEO_FORMAT_NONE) {
blog(LOG_ERROR, "Selected video format not supported");
goto fail;
}
v4l2_unpack_tuple(&data->width, &data->height, data->resolution);
blog(LOG_INFO, "Resolution: %dx%d", data->width, data->height);
blog(LOG_INFO, "Pixelformat: %s", V4L2_FOURCC_STR(data->pixfmt));
blog(LOG_INFO, "Linesize: %d Bytes", data->linesize);
/* set framerate */
if (v4l2_set_framerate(data->dev, &data->framerate) < 0) {
blog(LOG_ERROR, "Unable to set framerate");
goto fail;
}
v4l2_unpack_tuple(&fps_num, &fps_denom, data->framerate);
blog(LOG_INFO, "Framerate: %.2f fps", (float) fps_denom / fps_num);
/* map buffers */
if (v4l2_create_mmap(data->dev, &data->buffers) < 0) {
blog(LOG_ERROR, "Failed to map buffers");
goto fail;
}
/* start the capture thread */
if (os_event_init(&data->event, OS_EVENT_TYPE_MANUAL) != 0)
goto fail;
if (pthread_create(&data->thread, NULL, v4l2_thread, data) != 0)
goto fail;
return;
fail:
blog(LOG_ERROR, "Initialization failed");
v4l2_terminate(data);
}
/** Update source flags depending on the settings */
static void v4l2_update_source_flags(struct v4l2_data *data,
obs_data_t *settings)
{
uint32_t flags = obs_source_get_flags(data->source);
flags = (obs_data_get_bool(settings, "buffering"))
? flags & ~OBS_SOURCE_FLAG_UNBUFFERED
: flags | OBS_SOURCE_FLAG_UNBUFFERED;
obs_source_set_flags(data->source, flags);
}
/**
* Update the settings for the v4l2 source
*
* Since there are very few settings that can be changed without restarting the
* stream we don't bother to even try. Whenever this is called the currently
* active stream (if exists) is stopped, the settings are updated and finally
* the new stream is started.
*/
static void v4l2_update(void *vptr, obs_data_t *settings)
{
V4L2_DATA(vptr);
v4l2_terminate(data);
if (data->device_id)
bfree(data->device_id);
data->device_id = bstrdup(obs_data_get_string(settings, "device_id"));
data->input = obs_data_get_int(settings, "input");
data->pixfmt = obs_data_get_int(settings, "pixelformat");
data->standard = obs_data_get_int(settings, "standard");
data->dv_timing = obs_data_get_int(settings, "dv_timing");
data->resolution = obs_data_get_int(settings, "resolution");
data->framerate = obs_data_get_int(settings, "framerate");
v4l2_update_source_flags(data, settings);
v4l2_init(data);
}
static void *v4l2_create(obs_data_t *settings, obs_source_t *source)
{
struct v4l2_data *data = bzalloc(sizeof(struct v4l2_data));
data->dev = -1;
data->source = source;
/* Bitch about build problems ... */
#ifndef V4L2_CAP_DEVICE_CAPS
blog(LOG_WARNING, "Plugin built without device caps support!");
#endif
#if !defined(VIDIOC_ENUM_DV_TIMINGS) || !defined(V4L2_IN_CAP_DV_TIMINGS)
blog(LOG_WARNING, "Plugin built without dv-timing support!");
#endif
v4l2_update(data, settings);
#if HAVE_UDEV
v4l2_init_udev();
signal_handler_t *sh = v4l2_get_udev_signalhandler();
signal_handler_connect(sh, "device_added", &device_added, data);
signal_handler_connect(sh, "device_removed", &device_removed, data);
#endif
return data;
}
struct obs_source_info v4l2_input = {
.id = "v4l2_input",
.type = OBS_SOURCE_TYPE_INPUT,
.output_flags = OBS_SOURCE_ASYNC_VIDEO |
OBS_SOURCE_DO_NOT_DUPLICATE,
.get_name = v4l2_getname,
.create = v4l2_create,
.destroy = v4l2_destroy,
.update = v4l2_update,
.get_defaults = v4l2_defaults,
.get_properties = v4l2_properties
};

View file

@ -0,0 +1,199 @@
/*
Copyright (C) 2014 by Leonhard Oelke <leonhard@in-verted.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <libudev.h>
#include <util/threading.h>
#include <util/darray.h>
#include <obs.h>
#include "v4l2-udev.h"
/** udev action enum */
enum udev_action {
UDEV_ACTION_ADDED,
UDEV_ACTION_REMOVED,
UDEV_ACTION_UNKNOWN
};
static const char *udev_signals[] = {
"void device_added(string device)",
"void device_removed(string device)",
NULL
};
/* global data */
static uint_fast32_t udev_refs = 0;
static pthread_mutex_t udev_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_t udev_thread;
static os_event_t *udev_event;
static signal_handler_t *udev_signalhandler = NULL;
/**
* udev gives us the device action as string, so we convert it here ...
*
* @param action the udev action as string
* @return the udev action as enum value
*/
static enum udev_action udev_action_to_enum(const char *action)
{
if (!action)
return UDEV_ACTION_UNKNOWN;
if (!strncmp("add", action, 3))
return UDEV_ACTION_ADDED;
if (!strncmp("remove", action, 6))
return UDEV_ACTION_REMOVED;
return UDEV_ACTION_UNKNOWN;
}
/**
* Call all registered callbacks with the event
*
* @param dev udev device that had an event occuring
*/
static inline void udev_signal_event(struct udev_device *dev)
{
const char *node;
enum udev_action action;
struct calldata data;
pthread_mutex_lock(&udev_mutex);
node = udev_device_get_devnode(dev);
action = udev_action_to_enum(udev_device_get_action(dev));
calldata_init(&data);
calldata_set_string(&data, "device", node);
switch (action) {
case UDEV_ACTION_ADDED:
signal_handler_signal(udev_signalhandler,
"device_added", &data);
break;
case UDEV_ACTION_REMOVED:
signal_handler_signal(udev_signalhandler,
"device_removed", &data);
break;
default:
break;
}
calldata_free(&data);
pthread_mutex_unlock(&udev_mutex);
}
/**
* Event listener thread
*/
static void *udev_event_thread(void *vptr)
{
UNUSED_PARAMETER(vptr);
int fd;
fd_set fds;
struct timeval tv;
struct udev *udev;
struct udev_monitor *mon;
struct udev_device *dev;
/* set up udev monitoring */
udev = udev_new();
mon = udev_monitor_new_from_netlink(udev, "udev");
udev_monitor_filter_add_match_subsystem_devtype(
mon, "video4linux", NULL);
if (udev_monitor_enable_receiving(mon) < 0)
return NULL;
/* set up fds */
fd = udev_monitor_get_fd(mon);
while (os_event_try(udev_event) == EAGAIN) {
FD_ZERO(&fds);
FD_SET(fd, &fds);
tv.tv_sec = 1;
tv.tv_usec = 0;
if (select(fd + 1, &fds, NULL, NULL, &tv) <= 0)
continue;
dev = udev_monitor_receive_device(mon);
if (!dev)
continue;
udev_signal_event(dev);
udev_device_unref(dev);
}
udev_monitor_unref(mon);
udev_unref(udev);
return NULL;
}
void v4l2_init_udev(void)
{
pthread_mutex_lock(&udev_mutex);
/* set up udev */
if (udev_refs == 0) {
if (os_event_init(&udev_event, OS_EVENT_TYPE_MANUAL) != 0)
goto fail;
if (pthread_create(&udev_thread, NULL, udev_event_thread,
NULL) != 0)
goto fail;
udev_signalhandler = signal_handler_create();
if (!udev_signalhandler)
goto fail;
signal_handler_add_array(udev_signalhandler, udev_signals);
}
udev_refs++;
fail:
pthread_mutex_unlock(&udev_mutex);
}
void v4l2_unref_udev(void)
{
pthread_mutex_lock(&udev_mutex);
/* unref udev monitor */
if (udev_refs && --udev_refs == 0) {
os_event_signal(udev_event);
pthread_join(udev_thread, NULL);
os_event_destroy(udev_event);
if (udev_signalhandler)
signal_handler_destroy(udev_signalhandler);
udev_signalhandler = NULL;
}
pthread_mutex_unlock(&udev_mutex);
}
signal_handler_t *v4l2_get_udev_signalhandler(void)
{
return udev_signalhandler;
}

View file

@ -0,0 +1,47 @@
/*
Copyright (C) 2014 by Leonhard Oelke <leonhard@in-verted.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <inttypes.h>
#include <callback/signal.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Initialize udev system to watch for device events
*/
void v4l2_init_udev(void);
/**
* Unref the udev system
*/
void v4l2_unref_udev(void);
/**
* Get signal handler
*
* @return signal handler for udev events
*/
signal_handler_t *v4l2_get_udev_signalhandler(void);
#ifdef __cplusplus
}
#endif