├── OpenWrt-15.05 ├── package │ └── uvc2http │ │ ├── files │ │ ├── uvc2http.config │ │ └── uvc2http.init │ │ └── Makefile └── target │ └── linux │ └── generic │ └── patches-3.18 │ └── 850-uvc-quirk-compression-rate.patch ├── CMakeLists.txt ├── README.md ├── Tracer.h ├── StreamFunc.h ├── Config.h ├── Buffer.h ├── MjpegUtils.h ├── Tracer.cpp ├── UvcGrabber.h ├── StreamFunc.cpp ├── AppMain.cpp ├── HttpServer.h ├── DaemonMain.cpp ├── MjpegUtils.cpp ├── Config.cpp ├── UvcGrabber.cpp ├── LICENSE └── HttpServer.cpp /OpenWrt-15.05/package/uvc2http/files/uvc2http.config: -------------------------------------------------------------------------------- 1 | config uvc2http 'core' 2 | option device '/dev/video0' 3 | option buffers '4' 4 | option width '1280' 5 | option height '720' 6 | option fps '30' 7 | option port '8081' 8 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8) 2 | 3 | project(Uvc2Http) 4 | 5 | # _GLIBCXX_USE_C99 is defined to use snprintf. 6 | # -fpermissive is used to allow simple initialization for structures 7 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_GLIBCXX_USE_C99 -std=c++11 -static-libstdc++ -fpermissive -Wall -fno-exceptions") 8 | 9 | add_library(uvc2http_lib STATIC Tracer.cpp StreamFunc.cpp Config.cpp HttpServer.cpp UvcGrabber.cpp MjpegUtils.cpp) 10 | 11 | add_executable(uvc2http AppMain.cpp) 12 | target_link_libraries(uvc2http uvc2http_lib) 13 | 14 | add_executable(uvc2http_daemon DaemonMain.cpp) 15 | target_link_libraries(uvc2http_daemon uvc2http_lib) 16 | 17 | install(TARGETS uvc2http uvc2http_daemon RUNTIME DESTINATION bin) 18 | -------------------------------------------------------------------------------- /OpenWrt-15.05/package/uvc2http/files/uvc2http.init: -------------------------------------------------------------------------------- 1 | #!/bin/sh /etc/rc.common 2 | # Copyright (C) 2009-2015 OpenWrt.org 3 | 4 | START=90 5 | STOP=10 6 | 7 | USE_PROCD=1 8 | PROG=/usr/bin/uvc2http 9 | 10 | start_instance() { 11 | procd_open_instance 12 | 13 | procd_set_param command "$PROG" 14 | 15 | config_get device "$1" 'device' '/dev/video0' 16 | procd_append_param command --device $device 17 | 18 | config_get buffers "$1" 'buffers' '4' 19 | procd_append_param command --buffers $buffers 20 | 21 | config_get width "$1" 'width' '640' 22 | procd_append_param command --width $width 23 | 24 | config_get height "$1" 'height' '480' 25 | procd_append_param command --height $height 26 | 27 | config_get fps "$1" 'fps' '15' 28 | procd_append_param command --fps $fps 29 | 30 | config_get port "$1" 'port' '8081' 31 | procd_append_param command --port $port 32 | 33 | procd_close_instance 34 | } 35 | 36 | start_service() { 37 | config_load 'uvc2http' 38 | config_foreach start_instance 'uvc2http' 39 | } 40 | -------------------------------------------------------------------------------- /OpenWrt-15.05/package/uvc2http/Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2015 OpenWrt.org 3 | # 4 | # This is free software, licensed under the GNU General Public License v2. 5 | # See /LICENSE for more information. 6 | # 7 | # This is free software, licensed under the GNU General Public License v2. 8 | # 9 | include $(TOPDIR)/rules.mk 10 | 11 | PKG_NAME:=uvc2http 12 | PKG_VERSION:=0.01 13 | PKG_RELEASE:=1 14 | PKG_MAINTAINER:=Oleg 15 | 16 | PKG_SOURCE_PROTO:=git 17 | PKG_SOURCE_URL:=https://github.com/Legich55555/uvc2http.git 18 | PKG_SOURCE_VERSION:=518a089136156bda72d77c5469a628fe157daa1f 19 | PKG_SOURCE:=$(PKG_NAME)-$(PKG_SOURCE_VERSION).tar.gz 20 | PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_SOURCE_VERSION) 21 | PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_SOURCE_VERSION) 22 | 23 | PKG_LICENSE:=GPL-2.0 24 | PKG_LICENSE_FILES:=LICENSE 25 | 26 | include $(INCLUDE_DIR)/package.mk 27 | include $(INCLUDE_DIR)/cmake.mk 28 | 29 | define Package/uvc2http 30 | SECTION:=multimedia 31 | CATEGORY:=Multimedia 32 | TITLE:=UVC to HTTP streamer 33 | DEPENDS:=+libv4l 34 | endef 35 | 36 | define Build/Compile 37 | $(MAKE) -C $(PKG_BUILD_DIR) 38 | $(STRIP) $(PKG_BUILD_DIR)/$(PKG_NAME) 39 | endef 40 | 41 | define Package/uvc2http/install 42 | $(INSTALL_DIR) $(1)/usr/bin 43 | $(INSTALL_BIN) $(PKG_BUILD_DIR)/uvc2http $(1)/usr/bin/ 44 | $(INSTALL_DIR) $(1)/etc/config 45 | $(CP) ./files/uvc2http.config $(1)/etc/config/uvc2http 46 | $(INSTALL_DIR) $(1)/etc/init.d 47 | $(INSTALL_BIN) ./files/uvc2http.init $(1)/etc/init.d/uvc2http 48 | endef 49 | 50 | $(eval $(call BuildPackage,uvc2http)) 51 | 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # uvc2http 2 | A Linux tool for video streaming from USB cameras. 3 | 4 | Uvc_streamer is an alternative for mjpg_streamer. It is targeted for small 5 | Linux devices (like routers with OpenWrt). 6 | 7 | Requirements: 8 | * USB video camera with MJPG capture mode support (tested with Logitech 9 | B910); 10 | * Linux system with installed driver "uvcvideo" (tested with router 11 | TP-Link MR3020 + OpenWrt 15.05); 12 | * C++11 compiler (tested with GCC 4.8.3). 13 | 14 | Usage: 15 | * Build and run. By default it uses following settings: 16 | - camera "/dev/video0"; 17 | - capturing mode 640x480x15; 18 | - listening at TCP port 8081. 19 | 20 | Configuration: 21 | * Put your configuration to file "Config.cpp" and rebuild. A few parameters 22 | can be specified via CLI: 23 | --device DEVICE camera device name 24 | --buffers NUMBER capture buffers number 25 | --width WIDTH frame width 26 | --height HEIGHT frame height 27 | --fps FPS capture fps 28 | --port PORT HTTP server port 29 | For example: uvc2http --device /dev/video0 --buffers 4 --width 1280 --height 720 --fps 30 --port 8080 30 | * Note: 31 | - Real capture framerate can depend on lighting conditions (exposition settings). 32 | - Streameing can influence framerate on clients. 33 | 34 | Expected results: 35 | * On a router TP-Link MR3020 it produces up to 20 frames at resolution 1280x720. 36 | * On a PC with 4 core CPU frame rate is limited only by camera restrictions. 37 | 38 | Differences from mjpg_streamer 39 | * Uses only 1 thread; 40 | * No memory copying; 41 | * Small memory consumption; 42 | * Small CPU utilization. 43 | 44 | 45 | -------------------------------------------------------------------------------- /Tracer.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #ifndef TRACER_H 23 | #define TRACER_H 24 | 25 | namespace Tracer { 26 | void Log(const char* format, ...); 27 | void LogErrNo(const char* format, ...); 28 | } 29 | 30 | #endif // TRACER_H -------------------------------------------------------------------------------- /OpenWrt-15.05/target/linux/generic/patches-3.18/850-uvc-quirk-compression-rate.patch: -------------------------------------------------------------------------------- 1 | --- a/drivers/media/usb/uvc/uvc_video.c 2 | +++ b/drivers/media/usb/uvc/uvc_video.c 3 | @@ -113,6 +113,14 @@ static void uvc_fixup_video_ctrl(struct 4 | if (frame == NULL) 5 | return; 6 | 7 | + if ((format->flags & UVC_FMT_FLAG_COMPRESSED) && 8 | + (stream->dev->quirks & UVC_QUIRK_COMPRESSION_RATE)) { 9 | + /* It is expected that MJPEG compressed image at least 5 times less than uncompressed one */ 10 | + ctrl->dwMaxVideoFrameSize = ((u32)(frame->wWidth) * frame->wHeight * 2U) / 5U; 11 | + 12 | + uvc_printk(KERN_ERR, "dwMaxVideoFrameSize fixed to %d.\n", ctrl->dwMaxVideoFrameSize); 13 | + } 14 | + 15 | if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) || 16 | (ctrl->dwMaxVideoFrameSize == 0 && 17 | stream->dev->uvc_version < 0x0110)) 18 | --- a/drivers/media/usb/uvc/uvcvideo.h 19 | +++ b/drivers/media/usb/uvc/uvcvideo.h 20 | @@ -148,6 +148,7 @@ 21 | #define UVC_QUIRK_PROBE_DEF 0x00000100 22 | #define UVC_QUIRK_RESTRICT_FRAME_RATE 0x00000200 23 | #define UVC_QUIRK_RESTORE_CTRLS_ON_INIT 0x00000400 24 | +#define UVC_QUIRK_COMPRESSION_RATE 0x00000800 25 | 26 | /* Format flags */ 27 | #define UVC_FMT_FLAG_COMPRESSED 0x00000001 28 | --- a/drivers/media/usb/uvc/uvc_driver.c 29 | +++ b/drivers/media/usb/uvc/uvc_driver.c 30 | @@ -2184,6 +2184,16 @@ static struct usb_device_id uvc_ids[] = 31 | .bInterfaceSubClass = 1, 32 | .bInterfaceProtocol = 0, 33 | .driver_info = UVC_QUIRK_RESTORE_CTRLS_ON_INIT }, 34 | + /* Logitech B910 HD Webcam */ 35 | + { .match_flags = USB_DEVICE_ID_MATCH_DEVICE 36 | + | USB_DEVICE_ID_MATCH_INT_INFO, 37 | + .idVendor = 0x046d, 38 | + .idProduct = 0x0823, 39 | + .bInterfaceClass = USB_CLASS_VIDEO, 40 | + .bInterfaceSubClass = 1, 41 | + .bInterfaceProtocol = 0, 42 | + .driver_info = UVC_QUIRK_RESTORE_CTRLS_ON_INIT 43 | + | UVC_QUIRK_COMPRESSION_RATE }, 44 | /* Chicony CNF7129 (Asus EEE 100HE) */ 45 | { .match_flags = USB_DEVICE_ID_MATCH_DEVICE 46 | | USB_DEVICE_ID_MATCH_INT_INFO, 47 | -------------------------------------------------------------------------------- /StreamFunc.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #ifndef STREAMERFUNC_H 23 | #define STREAMERFUNC_H 24 | 25 | #include "Config.h" 26 | 27 | namespace UvcStreamer { 28 | /// @brief Type for a function which should be call to check if streaming should be stopped. 29 | typedef bool (*ShouldExit)(void); 30 | 31 | /// @brief StreamFunc does all streaming tasks. 32 | int StreamFunc(const UvcStreamerCfg& config, ShouldExit shouldExit); 33 | } 34 | 35 | #endif // STREAMERFUNC_H 36 | -------------------------------------------------------------------------------- /Config.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #ifndef CONFIG_H 23 | #define CONFIG_H 24 | 25 | #include 26 | #include 27 | 28 | #include "UvcGrabber.h" 29 | 30 | 31 | struct HttpServerCfg { 32 | std::string ServicePort; 33 | }; 34 | 35 | struct UvcStreamerCfg { 36 | UvcGrabber::Config GrabberCfg; 37 | HttpServerCfg ServerCfg; 38 | bool IsValid; 39 | }; 40 | 41 | UvcStreamerCfg GetConfig(int argc, char **argv); 42 | 43 | void PrintUsage(); 44 | 45 | #endif -------------------------------------------------------------------------------- /Buffer.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #ifndef BUFFER_H 23 | #define BUFFER_H 24 | 25 | #include 26 | #include 27 | #include 28 | 29 | struct Buffer { 30 | const uint8_t* Data; 31 | uint32_t Size; 32 | }; 33 | 34 | struct VideoBuffer { 35 | const uint8_t* Data; // Mmapped address of a v4l2 buffer. 36 | uint32_t Size; // Current size of data in buffer. 37 | uint32_t Length; // Buffer length (used for unmapping). 38 | uint32_t Idx; 39 | v4l2_buffer V4l2Buffer; 40 | }; 41 | 42 | #endif -------------------------------------------------------------------------------- /MjpegUtils.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #ifndef MJPEGUTILS_H 23 | #define MJPEGUTILS_H 24 | 25 | #include 26 | #include 27 | 28 | #include "UvcGrabber.h" 29 | #include "Buffer.h" 30 | 31 | struct VideoBuffer; 32 | 33 | struct MjpegFrame { 34 | const void* Header; 35 | uint32_t HeaderSize; 36 | 37 | const void* HaffmanTable; 38 | uint32_t HaffmanTableSize; 39 | 40 | const void* Data; 41 | uint32_t DataSize; 42 | 43 | const VideoBuffer* SourceBuffer; 44 | }; 45 | 46 | std::unique_ptr CreateMjpegFrame(const VideoBuffer* videoBuffer); 47 | 48 | std::vector CreateMjpegFrameBufferSet(const VideoBuffer* videoBuffer); 49 | 50 | 51 | #endif // MJPEGUTILS_H -------------------------------------------------------------------------------- /Tracer.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #include "Tracer.h" 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | namespace Tracer { 31 | static const char* TraceName = "UvcStreamer"; 32 | 33 | namespace { 34 | bool IsStdErrReady() { 35 | return fileno(stderr) != -1; 36 | } 37 | 38 | void LogVArgs( const char* format, va_list args) { 39 | 40 | if (IsStdErrReady()) { 41 | std::vfprintf(stderr, format, args); 42 | } 43 | else { 44 | static bool isSysLogInitialized = false; 45 | if (!isSysLogInitialized) { 46 | ::openlog(Tracer::TraceName, LOG_ODELAY, LOG_USER | LOG_ERR); 47 | isSysLogInitialized = true; 48 | } 49 | 50 | ::vsyslog(LOG_ERR, format, args); 51 | } 52 | } 53 | } 54 | 55 | 56 | void Log(const char* format, ...) { 57 | va_list args; 58 | va_start(args, format); 59 | LogVArgs(format, args); 60 | va_end(args); 61 | } 62 | 63 | void LogErrNo(const char* format, ...) { 64 | va_list args; 65 | va_start(args, format); 66 | LogVArgs(format, args); 67 | va_end(args); 68 | 69 | const char* errnoDescription = strerror(errno); 70 | Log("%s\n", errnoDescription); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /UvcGrabber.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #ifndef UVCGRABBER_H 23 | #define UVCGRABBER_H 24 | 25 | #include 26 | #include 27 | 28 | struct VideoBuffer; 29 | 30 | 31 | /* 32 | * @brief UvcGrabber captures data from UVC camera device. 33 | * 34 | * */ 35 | class UvcGrabber 36 | { 37 | public: 38 | 39 | typedef bool(*SetupCameraFunc)(int); 40 | 41 | struct Config { 42 | std::string CameraDeviceName; 43 | uint32_t FrameWidth; 44 | uint32_t FrameHeight; 45 | uint32_t FrameRate; 46 | uint32_t BuffersNumber; 47 | 48 | // Function which is called for app specific camera configuration. 49 | SetupCameraFunc SetupCamera; 50 | }; 51 | 52 | explicit UvcGrabber(const Config& config); 53 | ~UvcGrabber(); 54 | 55 | // @brief Initializes video capture. Returns true if initialization was successfull. 56 | bool Init(); 57 | 58 | // @brief ReInitializes video capture. Returns true if initialization was successfull. 59 | bool ReInit(); 60 | 61 | // @brief Shutdowns video capture and free all used resources. 62 | void Shutdown(); 63 | 64 | // @brief Return true if fatal error happened during dequeuing/requeing of frames 65 | // Expected recovery steps: requeu all dequed frames, call Shutdown() and then Init(). 66 | bool IsBroken() const { return _isBroken; } 67 | 68 | // @brief Return true if camera was successfully initialized. 69 | bool IsCameraReady() const { return _cameraFd != -1; } 70 | 71 | const VideoBuffer* DequeuFrame(); 72 | 73 | void RequeueFrame(const VideoBuffer* buffer); 74 | 75 | UvcGrabber() = delete; 76 | UvcGrabber(const UvcGrabber& other) = delete; 77 | UvcGrabber& operator=(const UvcGrabber& other) = delete; 78 | 79 | private: 80 | 81 | Config _config; 82 | std::vector _videoBuffers; 83 | int _cameraFd; 84 | bool _isBroken; 85 | }; 86 | 87 | #endif // UVCGRABBER_H 88 | -------------------------------------------------------------------------------- /StreamFunc.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #include "StreamFunc.h" 23 | 24 | #include 25 | #include 26 | 27 | #include "Tracer.h" 28 | #include "UvcGrabber.h" 29 | #include "HttpServer.h" 30 | #include "MjpegUtils.h" 31 | 32 | namespace UvcStreamer { 33 | 34 | int StreamFunc(const UvcStreamerCfg& config, ShouldExit shouldExit) { 35 | 36 | HttpServer httpServer; 37 | if (!httpServer.Init(config.ServerCfg.ServicePort.c_str())) { 38 | Tracer::Log("Failed to initialize HTTP server.\n"); 39 | return -2; 40 | } 41 | 42 | // Init and configure UVC video camera 43 | UvcGrabber uvcGrabber(config.GrabberCfg); 44 | if (!uvcGrabber.Init()) { 45 | Tracer::Log("Failed to initialize UvcGrabber (is there a UVC camera?). The app will try to initialize later.\n"); 46 | } 47 | 48 | static const long Kilo = 1000; 49 | 50 | while (!shouldExit()) { 51 | 52 | if (uvcGrabber.IsCameraReady() && !uvcGrabber.IsBroken()) { 53 | const VideoBuffer* videoBuffer = uvcGrabber.DequeuFrame(); 54 | if (videoBuffer != nullptr) { 55 | if (!httpServer.QueueBuffer(videoBuffer)) { 56 | uvcGrabber.RequeueFrame(videoBuffer); 57 | } 58 | } 59 | 60 | static const long MaxServeTimeMicroSec = (Kilo * Kilo) / config.GrabberCfg.FrameRate / 2; 61 | httpServer.ServeRequests(MaxServeTimeMicroSec); 62 | 63 | // It is safe to sleep for 1 ms. There is no significant 64 | // difference (in terms of CPU utilization) in comparison with 65 | // sleeping for a rest of time. 66 | const timespec SleepTime {0, Kilo * Kilo}; 67 | ::nanosleep(&SleepTime, nullptr); 68 | 69 | const VideoBuffer* releasedBuffer = httpServer.DequeueBuffer(); 70 | while (releasedBuffer != nullptr) { 71 | uvcGrabber.RequeueFrame(releasedBuffer); 72 | 73 | releasedBuffer = httpServer.DequeueBuffer(); 74 | } 75 | } 76 | else { 77 | std::vector buffers = httpServer.DequeueAllBuffers(); 78 | for (auto buffer : buffers) { 79 | uvcGrabber.RequeueFrame(buffer); 80 | } 81 | 82 | // Repeat recovery attempts every second. 83 | const timespec RecoveryDelay {1, 0}; 84 | ::nanosleep(&RecoveryDelay, nullptr); 85 | 86 | uvcGrabber.ReInit(); 87 | } 88 | } 89 | 90 | return 0; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /AppMain.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | #include "Tracer.h" 29 | #include "Config.h" 30 | #include "StreamFunc.h" 31 | 32 | namespace { 33 | 34 | volatile bool IsSigIntRaisedFlag = false; 35 | 36 | void sigIntHandler(int sig) { 37 | IsSigIntRaisedFlag = true; 38 | } 39 | 40 | bool IsSigIntRaised(void) { 41 | return IsSigIntRaisedFlag; 42 | } 43 | 44 | // This function disables auto focus and sets focus distance to ~1.2 meter (good choice for RC toys cameras). 45 | bool SetupCamera(int cameraFd) { 46 | { 47 | // Disable auto focus 48 | 49 | v4l2_ext_controls ext_ctrls = {0}; 50 | v4l2_ext_control ext_ctrl = {0}; 51 | ext_ctrl.id = 10094860; 52 | ext_ctrl.value64 = 0; 53 | 54 | ext_ctrls.ctrl_class = V4L2_CTRL_CLASS_USER; 55 | ext_ctrls.count = 1; 56 | ext_ctrls.controls = &ext_ctrl; 57 | int ioctlResult = ioctl(cameraFd, VIDIOC_S_EXT_CTRLS, &ext_ctrls); 58 | if (ioctlResult != 0) { 59 | return false; 60 | } 61 | } 62 | 63 | { 64 | // Set focus range ~1.2 meter 65 | 66 | const int focusValue = 80; 67 | 68 | v4l2_ext_controls ext_ctrls = {0}; 69 | v4l2_ext_control ext_ctrl = {0}; 70 | ext_ctrl.id = 10094858; 71 | ext_ctrl.value64 = focusValue; 72 | 73 | ext_ctrls.ctrl_class = V4L2_CTRL_CLASS_USER; 74 | ext_ctrls.count = 1; 75 | ext_ctrls.controls = &ext_ctrl; 76 | int ioctlResult = ioctl(cameraFd, VIDIOC_S_EXT_CTRLS, &ext_ctrls); 77 | if (ioctlResult != 0) { 78 | return false; 79 | } 80 | } 81 | 82 | return true; 83 | } 84 | } 85 | 86 | int main(int argc, char **argv) { 87 | 88 | UvcStreamerCfg config = GetConfig(argc, argv); 89 | if (!config.IsValid) { 90 | PrintUsage(); 91 | return -1; 92 | } 93 | 94 | config.GrabberCfg.SetupCamera = SetupCamera; 95 | 96 | // Ignore SIGPIPE (OS sends it in case of transmitting to a closed TCP socket) 97 | if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { 98 | Tracer::Log("Failed to setup SIGPIPE handler.\n"); 99 | } 100 | 101 | // Register handler for CTRL+C 102 | if (signal(SIGINT, sigIntHandler) == SIG_ERR) { 103 | Tracer::Log("Failed to setup SIGINT handler.\n"); 104 | } 105 | 106 | // Register handler for termination 107 | if (signal(SIGTERM, sigIntHandler) == SIG_ERR) { 108 | Tracer::Log("Failed to setup SIGTERM handler.\n"); 109 | } 110 | 111 | Tracer::Log("Starting streaming..."); 112 | int res = UvcStreamer::StreamFunc(config, IsSigIntRaised); 113 | Tracer::Log("Streaming stopped with code %d", res); 114 | 115 | return res; 116 | } 117 | -------------------------------------------------------------------------------- /HttpServer.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #ifndef HTTPSERVER_H 23 | #define HTTPSERVER_H 24 | 25 | #include 26 | #include 27 | #include 28 | 29 | #include "Buffer.h" 30 | 31 | /* 32 | * @brief HttpServer implements minimal HTTP server for sending MJPEG frames. 33 | * 34 | * */ 35 | class HttpServer 36 | { 37 | public: 38 | HttpServer(); 39 | ~HttpServer(); 40 | 41 | bool Init(const char* servicePort); 42 | 43 | /* 44 | * @brief Adds a buffer to a queue "to be sent". 45 | * Returns true if buffer was successfully queued. 46 | */ 47 | bool QueueBuffer(const VideoBuffer* videoBuffer); 48 | 49 | /* 50 | * @brief Dequeues a buffer. 51 | * Finds a buffer which has already been sent to all clients and 52 | * returns it otherwise returns nullptr. 53 | */ 54 | const VideoBuffer* DequeueBuffer(); 55 | 56 | /* 57 | * @brief Dequeues all buffers. 58 | * If a client connection is slow then it is dropped. 59 | */ 60 | std::vector DequeueAllBuffers(); 61 | 62 | /* 63 | * @brief Accepts a new requests, sends images to active peers. 64 | */ 65 | void ServeRequests(long maxServeTimeMicroSec); 66 | 67 | /* 68 | * @brief Returns true if there are data for client (headers or MJPEG data). 69 | */ 70 | bool HasDataToSend() const; 71 | 72 | /* 73 | * @brief Shutdowns all connections and frees all resources. 74 | */ 75 | void Shutdown(); 76 | 77 | std::size_t GetClientsNumber() const { return _beingServedClients.size() + _waitingClients.size(); } 78 | 79 | HttpServer(const HttpServer& other) = delete; 80 | HttpServer& operator=(const HttpServer& other) = delete; 81 | 82 | private: 83 | 84 | struct RequestInfo 85 | { 86 | std::vector RequestData; 87 | }; 88 | 89 | struct ResponseInfo 90 | { 91 | uint32_t HeaderBytesSent = 0U; 92 | 93 | static const uint32_t InvalidBufferIdx = 0xFFFFFFFF; 94 | 95 | uint32_t DataBufferIdx = InvalidBufferIdx; 96 | uint32_t DataBufferBytesSent = 0U; 97 | timeval Timestamp = {0}; 98 | uint32_t VideoBufferIdx = InvalidBufferIdx; 99 | }; 100 | 101 | struct QueueItem { 102 | std::vector Header; 103 | std::vector Data; 104 | const VideoBuffer* SourceData; 105 | uint32_t UsageCounter; 106 | uint32_t SentCounter; 107 | }; 108 | 109 | void ReadAndParseRequests(); 110 | void SendData(long timeoutMicroSec); 111 | QueueItem* SelectBufferForSending(const timeval& lastBufferTimestamp); 112 | QueueItem* GetBuffer(uint32_t videoBufferIdx); 113 | 114 | std::map _waitingClients; 115 | std::vector _listeningFds; 116 | std::map _beingServedClients; 117 | std::list _incomeQueue; 118 | }; 119 | 120 | #endif // HTTPSERVER_H 121 | -------------------------------------------------------------------------------- /DaemonMain.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include "Tracer.h" 33 | #include "Config.h" 34 | #include "StreamFunc.h" 35 | 36 | namespace { 37 | 38 | volatile bool IsSigIntRaisedFlag = false; 39 | 40 | void sigIntHandler(int sig) { 41 | IsSigIntRaisedFlag = true; 42 | } 43 | 44 | bool IsSigIntRaised(void) { 45 | return IsSigIntRaisedFlag; 46 | } 47 | } 48 | 49 | bool SetupCamera(int cameraFd) { 50 | // In some cases you may need to disable auto exposure 51 | // v4l2_control control = {0}; 52 | // control.id = V4L2_CID_EXPOSURE_AUTO; 53 | // control.value = V4L2_EXPOSURE_MANUAL; 54 | // int ioctlResult = ioctl(cameraFd, VIDIOC_S_CTRL, &control); 55 | // if (ioctlResult != 0) { 56 | // Tracer::Log("Failed Ioctl(VIDIOC_S_CTRL + V4L2_CID_EXPOSURE_AUTO), error: %d\n", ioctlResult); 57 | // return false; 58 | // } 59 | // 60 | // control.id = V4L2_CID_EXPOSURE_ABSOLUTE; 61 | // control.value = 100; 62 | // ioctlResult = ioctl(cameraFd, VIDIOC_S_CTRL, &control); 63 | // if (ioctlResult != 0) { 64 | // Tracer::Log("Failed Ioctl(VIDIOC_S_CTRL + V4L2_CID_EXPOSURE_ABSOLUTE), error: %d\n", ioctlResult); 65 | // return false; 66 | // } 67 | 68 | { 69 | // Disable auto focus 70 | 71 | v4l2_ext_controls ext_ctrls = {0}; 72 | v4l2_ext_control ext_ctrl = {0}; 73 | ext_ctrl.id = 10094860; 74 | ext_ctrl.value64 = 0; 75 | 76 | ext_ctrls.ctrl_class = V4L2_CTRL_CLASS_USER; 77 | ext_ctrls.count = 1; 78 | ext_ctrls.controls = &ext_ctrl; 79 | int ioctlResult = ioctl(cameraFd, VIDIOC_S_EXT_CTRLS, &ext_ctrls); 80 | if (ioctlResult != 0) { 81 | return false; 82 | } 83 | } 84 | 85 | { 86 | // Set focus range ~1.5 meter 87 | 88 | const int focusValue = 80; 89 | 90 | v4l2_ext_controls ext_ctrls = {0}; 91 | v4l2_ext_control ext_ctrl = {0}; 92 | ext_ctrl.id = 10094858; 93 | ext_ctrl.value64 = focusValue; 94 | 95 | ext_ctrls.ctrl_class = V4L2_CTRL_CLASS_USER; 96 | ext_ctrls.count = 1; 97 | ext_ctrls.controls = &ext_ctrl; 98 | int ioctlResult = ioctl(cameraFd, VIDIOC_S_EXT_CTRLS, &ext_ctrls); 99 | if (ioctlResult != 0) { 100 | return false; 101 | } 102 | } 103 | 104 | return true; 105 | } 106 | 107 | int main(int argc, char **argv) { 108 | 109 | UvcStreamerCfg config = GetConfig(argc, argv); 110 | if (!config.IsValid) { 111 | return -1; 112 | } 113 | 114 | config.GrabberCfg.SetupCamera = SetupCamera; 115 | 116 | int pid = fork(); 117 | if (-1 == pid) 118 | { 119 | Tracer::Log("fork() failed"); 120 | return -1; 121 | } 122 | 123 | if (0 == pid) 124 | { 125 | umask(0); 126 | 127 | setsid(); 128 | 129 | chdir("/"); 130 | 131 | ::fclose(stderr); 132 | ::fclose(stdout); 133 | ::fclose(stdin); 134 | 135 | // Ignore SIGPIPE (OS sends it in case of transmitting to a closed TCP socket) 136 | if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { 137 | Tracer::Log("Failed to setup SIGPIPE handler.\n"); 138 | } 139 | 140 | // Ignore SIGCLD as we cannot handle it 141 | if (signal(SIGCLD, SIG_IGN) == SIG_ERR) { 142 | Tracer::Log("Failed to setup SIGCLD handler.\n"); 143 | } 144 | 145 | // Register handler for CTRL+C 146 | if (signal(SIGINT, sigIntHandler) == SIG_ERR) { 147 | Tracer::Log("Failed to setup SIGINT handler.\n"); 148 | } 149 | 150 | // Register handler for termination 151 | if (signal(SIGTERM, sigIntHandler) == SIG_ERR) { 152 | Tracer::Log("Failed to setup SIGTERM handler.\n"); 153 | } 154 | 155 | Tracer::Log("Starting streaming..."); 156 | int res = UvcStreamer::StreamFunc(config, IsSigIntRaised); 157 | Tracer::Log("Streaming stopped with code %d", res); 158 | 159 | return res; 160 | } 161 | 162 | return 0; 163 | } 164 | -------------------------------------------------------------------------------- /MjpegUtils.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #include "MjpegUtils.h" 23 | 24 | #include "Buffer.h" 25 | 26 | const static uint8_t HaffmanTable[] = { 27 | 0xff, 0xc4, 0x01, 0xa2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 28 | 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 29 | 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 30 | 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 31 | 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 32 | 0x0a, 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 33 | 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 34 | 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 35 | 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 36 | 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 37 | 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 38 | 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 39 | 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 40 | 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 41 | 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 42 | 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 43 | 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 44 | 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 45 | 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 46 | 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 47 | 0xfa, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 48 | 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 49 | 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 50 | 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 51 | 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 52 | 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 53 | 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 54 | 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 55 | 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 56 | 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 57 | 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 58 | 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 59 | 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 60 | 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 61 | 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa 62 | }; 63 | 64 | std::unique_ptr CreateMjpegFrame(const VideoBuffer* videoBuffer) 65 | { 66 | const uint8_t baselineDctMarkerPart1 = 0xFF; 67 | const uint8_t baselineDctMarkerPart2 = 0xC0; 68 | 69 | const uint8_t* currPtr = videoBuffer->Data; 70 | while ((baselineDctMarkerPart2 != currPtr[1] || baselineDctMarkerPart1 != currPtr[0]) && 71 | currPtr < (videoBuffer->Data + videoBuffer->Size)) { 72 | ++currPtr; 73 | } 74 | 75 | if (currPtr >= videoBuffer->Data + videoBuffer->Size) { 76 | return std::unique_ptr(); 77 | } 78 | 79 | const uint32_t headerSize = currPtr - videoBuffer->Data; 80 | 81 | std::unique_ptr result(new MjpegFrame); 82 | result->Header = videoBuffer->Data; 83 | result->HeaderSize = headerSize; 84 | result->HaffmanTable = HaffmanTable; 85 | result->HaffmanTableSize = sizeof(HaffmanTable); 86 | result->Data = currPtr; 87 | result->DataSize = videoBuffer->Size - headerSize; 88 | result->SourceBuffer = videoBuffer; 89 | 90 | return result; 91 | } 92 | 93 | std::vector CreateMjpegFrameBufferSet(const VideoBuffer* videoBuffer) 94 | { 95 | const uint8_t baselineDctMarkerPart1 = 0xFF; 96 | const uint8_t baselineDctMarkerPart2 = 0xC0; 97 | 98 | const uint8_t* currPtr = videoBuffer->Data; 99 | while ((baselineDctMarkerPart2 != currPtr[1] || baselineDctMarkerPart1 != currPtr[0]) && 100 | currPtr < (videoBuffer->Data + videoBuffer->Size)) { 101 | ++currPtr; 102 | } 103 | 104 | if (currPtr >= videoBuffer->Data + videoBuffer->Size) { 105 | return std::vector(); 106 | } 107 | 108 | const uint32_t headerSize = currPtr - videoBuffer->Data; 109 | 110 | std::vector result(3); 111 | result[0].Data = videoBuffer->Data; 112 | result[0].Size = headerSize; 113 | result[1].Data = HaffmanTable; 114 | result[1].Size = sizeof(HaffmanTable); 115 | result[2].Data = currPtr; 116 | result[2].Size = videoBuffer->Size - headerSize; 117 | 118 | return std::move(result); 119 | } 120 | -------------------------------------------------------------------------------- /Config.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #include "Config.h" 23 | #include 24 | #include 25 | #include "Tracer.h" 26 | 27 | namespace { 28 | const uint32_t InvalidUInt32OptValue = 0xFFFFFFFF; 29 | 30 | uint32_t GetUInt32OptValue(char* arg) { 31 | static const int ConversionBase = 10; 32 | char* rest; 33 | 34 | int result = strtol(arg, &rest, ConversionBase); 35 | 36 | if (0 != *rest || result <= 0) { 37 | return InvalidUInt32OptValue; 38 | } 39 | 40 | return static_cast(result); 41 | } 42 | } 43 | 44 | UvcStreamerCfg GetConfig(int argc, char **argv) { 45 | UvcStreamerCfg config; 46 | 47 | config.GrabberCfg.CameraDeviceName = "/dev/video0"; 48 | config.GrabberCfg.FrameWidth = 640U; 49 | config.GrabberCfg.FrameHeight = 480U; 50 | config.GrabberCfg.FrameRate = 15U; 51 | config.GrabberCfg.BuffersNumber = 4U; 52 | config.GrabberCfg.SetupCamera = nullptr; 53 | 54 | config.ServerCfg.ServicePort = "8081"; 55 | 56 | static option options[] = { 57 | {"d", required_argument, 0, 0}, // Camera device name 58 | {"device", required_argument, 0, 0}, // Camera device name 59 | {"b", required_argument, 0, 0}, // Capture buffers number 60 | {"buffers", required_argument, 0, 0}, // Capture buffers number 61 | {"w", required_argument, 0, 0}, // Width 62 | {"width", required_argument, 0, 0}, // Width 63 | {"h", required_argument, 0, 0}, // Height 64 | {"height", required_argument, 0, 0}, // Height 65 | {"f", required_argument, 0, 0}, // Frame rate 66 | {"fps", required_argument, 0, 0}, // Frame rate 67 | {"p", required_argument, 0, 0}, // TCP port 68 | {"port", required_argument, 0, 0}, // TCP port 69 | {0, 0, 0, 0} 70 | }; 71 | 72 | bool foundError = false; 73 | 74 | while (!foundError) { 75 | int optionIdx; 76 | int optionCharacter = getopt_long_only(argc, argv, "", options, &optionIdx); 77 | 78 | // There are no more options to parse. 79 | if (-1 == optionCharacter) 80 | { 81 | break; 82 | } 83 | 84 | 85 | // Unexpected option 86 | if (optionCharacter != '?') { 87 | switch (optionIdx) { 88 | // d, device 89 | case 0: 90 | case 1: 91 | config.GrabberCfg.CameraDeviceName = optarg; 92 | break; 93 | 94 | // b, buffers 95 | case 2: 96 | case 3: 97 | { 98 | const uint32_t optVal = GetUInt32OptValue(optarg); 99 | if (optVal != InvalidUInt32OptValue) { 100 | config.GrabberCfg.BuffersNumber = optVal; 101 | } 102 | else { 103 | Tracer::Log("Invalid value '%s' for buffers number.\n", optarg); 104 | foundError = true; 105 | } 106 | } 107 | 108 | break; 109 | 110 | // w, width 111 | case 4: 112 | case 5: 113 | { 114 | const uint32_t optVal = GetUInt32OptValue(optarg); 115 | if (optVal != InvalidUInt32OptValue) { 116 | config.GrabberCfg.FrameWidth = optVal; 117 | } 118 | else { 119 | Tracer::Log("Invalid value '%s' for frame width.\n", optarg); 120 | foundError = true; 121 | } 122 | } 123 | 124 | break; 125 | 126 | // h, height 127 | case 6: 128 | case 7: 129 | { 130 | const uint32_t optVal = GetUInt32OptValue(optarg); 131 | if (optVal != InvalidUInt32OptValue) { 132 | config.GrabberCfg.FrameHeight = optVal; 133 | } 134 | else { 135 | Tracer::Log("Invalid value '%s' for frame height.\n", optarg); 136 | foundError = true; 137 | } 138 | } 139 | 140 | break; 141 | 142 | // f, fps 143 | case 8: 144 | case 9: 145 | { 146 | const uint32_t optVal = GetUInt32OptValue(optarg); 147 | if (optVal != InvalidUInt32OptValue) { 148 | config.GrabberCfg.FrameRate = optVal; 149 | } 150 | else { 151 | Tracer::Log("Invalid value '%s' for frame rate.\n", optarg); 152 | foundError = true; 153 | } 154 | } 155 | 156 | break; 157 | 158 | case 10: 159 | case 11: 160 | { 161 | const uint32_t optVal = GetUInt32OptValue(optarg); 162 | if (optVal != InvalidUInt32OptValue) { 163 | config.ServerCfg.ServicePort = optarg; 164 | } 165 | else { 166 | Tracer::Log("Invalid value '%s' for port.\n", optarg); 167 | foundError = true; 168 | } 169 | } 170 | 171 | break; 172 | 173 | default: 174 | foundError = true; 175 | } 176 | } 177 | else { 178 | Tracer::Log("Unexpected parameter '%c'\n", optionCharacter); 179 | foundError = true; 180 | } 181 | } 182 | 183 | config.IsValid = !foundError; 184 | 185 | return config; 186 | } 187 | 188 | void PrintUsage() { 189 | printf("Usage: uvc2http -d /dev/video0 -b 4 -w 640 -h 480 -f 30 -p 8080\n"); 190 | } 191 | 192 | -------------------------------------------------------------------------------- /UvcGrabber.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #include "UvcGrabber.h" 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include 35 | 36 | #include "Tracer.h" 37 | #include "Buffer.h" 38 | 39 | static const uint32_t IoctlMaxTries = 5U; 40 | 41 | namespace 42 | { 43 | // @brief Executes ioctl and if it fails then try to repeat. 44 | // Exceptions: EINTR, EAGAIN and ETIMEDOUT 45 | int Ioctl(int fd, int request, unsigned triesNumber, void *arg); 46 | 47 | // @brief Configures camera according to a given configuration except V4L buffers. 48 | bool SetupCamera(int cameraFd, const UvcGrabber::Config& config); 49 | 50 | // @brief Allocates and maps V4L buffers for a given camera file descriptor. 51 | std::vector SetupBuffers(int cameraFd, uint32_t buffersNumber); 52 | 53 | // @brief Free V4L buffers allocated by SetupBuffers and remove them from videoBuffers. 54 | void FreeBuffers(int cameraFd, std::vector& videoBuffers); 55 | } 56 | 57 | UvcGrabber::UvcGrabber(const UvcGrabber::Config& config) 58 | : _config(config), 59 | _cameraFd(-1), 60 | _isBroken(false) 61 | { 62 | } 63 | 64 | UvcGrabber::~UvcGrabber() 65 | { 66 | Shutdown(); 67 | } 68 | 69 | bool UvcGrabber::Init() 70 | { 71 | if (_isBroken) { 72 | return false; 73 | } 74 | 75 | int cameraFd = open(_config.CameraDeviceName.c_str(), O_RDWR | O_NONBLOCK); 76 | if (-1 == cameraFd) { 77 | Tracer::LogErrNo("Failed open().\n"); 78 | return false; 79 | } 80 | 81 | if (!SetupCamera(cameraFd, _config)) { 82 | ::close(cameraFd); 83 | return false; 84 | } 85 | 86 | std::vector videoBuffers = SetupBuffers(cameraFd, _config.BuffersNumber); 87 | if (videoBuffers.empty()) { 88 | Tracer::Log("Failed SetupBuffers().\n"); 89 | ::close(cameraFd); 90 | return false; 91 | } 92 | 93 | int type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 94 | int ioctlResult = Ioctl(cameraFd, VIDIOC_STREAMON, IoctlMaxTries, &type); 95 | if (ioctlResult != 0) { 96 | Tracer::Log("Failed Ioctl(VIDIOC_STREAMON).\n"); 97 | FreeBuffers(cameraFd, videoBuffers); 98 | ::close(cameraFd); 99 | return false; 100 | } 101 | 102 | _cameraFd = cameraFd; 103 | _videoBuffers.swap(videoBuffers); 104 | 105 | return true; 106 | } 107 | 108 | bool UvcGrabber::ReInit() 109 | { 110 | Shutdown(); 111 | 112 | return Init(); 113 | } 114 | 115 | void UvcGrabber::Shutdown() 116 | { 117 | if (_cameraFd != -1) { 118 | int type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 119 | int ioctlResult = Ioctl(_cameraFd, VIDIOC_STREAMOFF, IoctlMaxTries, &type); 120 | if (ioctlResult != 0) { 121 | Tracer::Log("Failed Ioctl(VIDIOC_STREAMOFF).\n"); 122 | } 123 | 124 | FreeBuffers(_cameraFd, _videoBuffers); 125 | ::close(_cameraFd); 126 | 127 | _cameraFd = -1; 128 | } 129 | 130 | _isBroken = false; 131 | } 132 | 133 | const VideoBuffer* UvcGrabber::DequeuFrame() 134 | { 135 | if (_isBroken) { 136 | Tracer::Log("Invalid call for DequeuFrame.\n"); 137 | return nullptr; 138 | } 139 | 140 | v4l2_buffer v4l2Buffer = {0}; 141 | v4l2Buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 142 | v4l2Buffer.memory = V4L2_MEMORY_MMAP; 143 | 144 | int ioctlResult = Ioctl(_cameraFd, VIDIOC_DQBUF, IoctlMaxTries, &v4l2Buffer); 145 | if (ioctlResult != 0) { 146 | if (errno != EAGAIN && errno != EINTR && errno != ETIMEDOUT) { 147 | Tracer::Log("Failed Ioctl(VIDIOC_DQBUF) %d.\n", errno); 148 | _isBroken = true; 149 | } 150 | 151 | return nullptr; 152 | } 153 | 154 | if (v4l2Buffer.index >= _videoBuffers.size()) { 155 | Tracer::Log("Unexpected buffer index.\n"); 156 | 157 | ioctlResult = Ioctl(_cameraFd, VIDIOC_QBUF, IoctlMaxTries, &v4l2Buffer); 158 | if (ioctlResult != 0) { 159 | Tracer::Log("Failed Ioctl(VIDIOC_QBUF).\n"); 160 | } 161 | 162 | _isBroken = true; 163 | 164 | return nullptr; 165 | } 166 | 167 | _videoBuffers[v4l2Buffer.index].Size = v4l2Buffer.bytesused; 168 | _videoBuffers[v4l2Buffer.index].V4l2Buffer = v4l2Buffer; 169 | 170 | return &(_videoBuffers[v4l2Buffer.index]); 171 | } 172 | 173 | void UvcGrabber::RequeueFrame(const VideoBuffer* videoBuffer) 174 | { 175 | if (videoBuffer->V4l2Buffer.index >= _videoBuffers.size()) { 176 | Tracer::Log("Unexpected buffer index.\n"); 177 | return; 178 | } 179 | 180 | VideoBuffer& origVideoBuffer = _videoBuffers[videoBuffer->Idx]; 181 | 182 | int ioctlResult = Ioctl(_cameraFd, VIDIOC_QBUF, IoctlMaxTries, &(origVideoBuffer.V4l2Buffer)); 183 | if (ioctlResult < 0) { 184 | Tracer::Log("Failed Ioctl(VIDIOC_QBUF).\n"); 185 | _isBroken = true; 186 | } 187 | } 188 | 189 | namespace 190 | { 191 | // @brief Executes ioctl and if it fails then try to repeat. 192 | // Exceptions: EINTR, EAGAIN and ETIMEDOUT 193 | int Ioctl(int fd, int request, unsigned triesNumber, void *arg) 194 | { 195 | int result = -1; 196 | for (unsigned i = 0; i < triesNumber; i++) 197 | { 198 | result = ioctl(fd, request, arg); 199 | if (0 == result || !(errno == EINTR || errno == EAGAIN || errno == ETIMEDOUT)) { 200 | break; 201 | } 202 | } 203 | 204 | return result; 205 | } 206 | 207 | void FreeBuffers(int cameraFd, std::vector& videoBuffers) 208 | { 209 | // Unmap buffers 210 | for (size_t bufferIdx = 0; bufferIdx < videoBuffers.size(); ++bufferIdx) { 211 | if (0 != munmap(const_cast(videoBuffers[bufferIdx].Data), videoBuffers[bufferIdx].Length)) { 212 | Tracer::Log("Failed munmap().\n"); 213 | } 214 | } 215 | 216 | // Change buffers number to 0 217 | v4l2_requestbuffers requestBuffers = {0}; 218 | requestBuffers.count = 0; 219 | requestBuffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 220 | requestBuffers.memory = V4L2_MEMORY_MMAP; 221 | int ioctlResult = Ioctl(cameraFd, VIDIOC_REQBUFS, IoctlMaxTries, &requestBuffers); 222 | if (ioctlResult < 0) { 223 | Tracer::Log("Failed Ioctl(VIDIOC_REQBUFS).\n"); 224 | } 225 | 226 | videoBuffers.resize(0); 227 | } 228 | 229 | std::vector SetupBuffers(int cameraFd, uint32_t buffersNumber) 230 | { 231 | std::vector videoBuffers(0); 232 | videoBuffers.reserve(buffersNumber); 233 | 234 | { 235 | v4l2_requestbuffers requestBuffers = {0}; 236 | requestBuffers.count = buffersNumber; 237 | requestBuffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 238 | requestBuffers.memory = V4L2_MEMORY_MMAP; 239 | int ioctlResult = Ioctl(cameraFd, VIDIOC_REQBUFS, IoctlMaxTries, &requestBuffers); 240 | if (ioctlResult < 0) { 241 | Tracer::Log("Failed Ioctl(VIDIOC_REQBUFS).\n"); 242 | return videoBuffers; 243 | } 244 | } 245 | 246 | for (size_t bufferIdx = 0; bufferIdx < buffersNumber; ++bufferIdx) { 247 | v4l2_buffer buffer = {0}; 248 | buffer.index = bufferIdx; 249 | buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 250 | buffer.memory = V4L2_MEMORY_MMAP; 251 | 252 | int ioctlResult = Ioctl(cameraFd, VIDIOC_QUERYBUF, IoctlMaxTries, &buffer); 253 | if (ioctlResult != 0) { 254 | Tracer::Log("Failed Ioctl(VIDIOC_QUERYBUF).\n"); 255 | break; 256 | } 257 | 258 | ioctlResult = Ioctl(cameraFd, VIDIOC_QBUF, IoctlMaxTries, &buffer); 259 | if (ioctlResult != 0) { 260 | Tracer::Log("Failed Ioctl(VIDIOC_QBUF).\n"); 261 | break; 262 | } 263 | 264 | void* bufferAddress = mmap(0, buffer.length, PROT_READ | PROT_WRITE, MAP_SHARED, cameraFd, buffer.m.offset); 265 | if (bufferAddress == MAP_FAILED) { 266 | Tracer::Log("Failed mmap().\n"); 267 | break; 268 | } 269 | 270 | videoBuffers.push_back(VideoBuffer {0}); 271 | 272 | videoBuffers[bufferIdx].Data = static_cast(bufferAddress); 273 | videoBuffers[bufferIdx].Idx = bufferIdx; 274 | videoBuffers[bufferIdx].Length = buffer.length; 275 | } 276 | 277 | // If number of buffers is less than reqiested than unmap and free buffers. 278 | if (videoBuffers.size() != buffersNumber) { 279 | FreeBuffers(cameraFd, videoBuffers); 280 | } 281 | 282 | return videoBuffers; 283 | } 284 | 285 | bool SetupCamera(int cameraFd, const UvcGrabber::Config& config) 286 | { 287 | v4l2_capability cameraCaps = {0}; 288 | int ioctlResult = Ioctl(cameraFd, VIDIOC_QUERYCAP, IoctlMaxTries, &cameraCaps); 289 | if (ioctlResult < 0) { 290 | Tracer::Log("Ioctl(VIDIOC_QUERYCAP) failed.\n"); 291 | return false; 292 | } 293 | 294 | if (!(cameraCaps.capabilities & V4L2_CAP_VIDEO_CAPTURE)) { 295 | Tracer::Log("Error: device does not support video capture.\n"); 296 | return false; 297 | } 298 | 299 | if (!(cameraCaps.capabilities & V4L2_CAP_STREAMING)) { 300 | Tracer::Log("Error: device does not support streaming\n"); 301 | return false; 302 | } 303 | 304 | v4l2_format streamFormat = {0}; 305 | streamFormat.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 306 | streamFormat.fmt.pix.width = config.FrameWidth; 307 | streamFormat.fmt.pix.height = config.FrameHeight; 308 | streamFormat.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG; 309 | streamFormat.fmt.pix.field = V4L2_FIELD_ANY; 310 | ioctlResult = Ioctl(cameraFd, VIDIOC_S_FMT, IoctlMaxTries, &streamFormat); 311 | if (ioctlResult < 0) { 312 | Tracer::Log("Failed Ioctl(VIDIOC_S_FMT + V4L2_BUF_TYPE_VIDEO_CAPTURE).\n"); 313 | return false; 314 | } 315 | 316 | // TODO: Check if output format is same as input. 317 | { 318 | v4l2_streamparm streamParm = {0}; 319 | streamParm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 320 | ioctlResult = Ioctl(cameraFd, VIDIOC_G_PARM, IoctlMaxTries, &streamParm); 321 | if (ioctlResult < 0) { 322 | Tracer::Log("Failed Ioctl(VIDIOC_G_PARM + V4L2_BUF_TYPE_VIDEO_CAPTURE), error: %d\n", ioctlResult); 323 | return false; 324 | } 325 | } 326 | 327 | { 328 | v4l2_streamparm streamParm = {0}; 329 | streamParm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; 330 | streamParm.parm.capture.timeperframe.numerator = 1; 331 | streamParm.parm.capture.timeperframe.denominator = config.FrameRate; 332 | ioctlResult = Ioctl(cameraFd, VIDIOC_S_PARM, IoctlMaxTries, &streamParm); 333 | if (ioctlResult < 0) { 334 | Tracer::Log("Failed Ioctl(VIDIOC_S_PARM + V4L2_BUF_TYPE_VIDEO_CAPTURE), error: %d\n", ioctlResult); 335 | return false; 336 | } 337 | } 338 | 339 | if (config.SetupCamera != nullptr && !config.SetupCamera(cameraFd)) { 340 | Tracer::Log("Failed custom SetupCamera\n"); 341 | return false; 342 | } 343 | 344 | return true; 345 | } 346 | } 347 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /HttpServer.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | # # 3 | # This file is part of uvc2http. # 4 | # # 5 | # Copyright (C) 2015 Oleg Efremov # 6 | # # 7 | # Uvc_streamer is free software; you can redistribute it and/or modify # 8 | # it under the terms of the GNU General Public License as published by # 9 | # the Free Software Foundation; version 2 of the License. # 10 | # # 11 | # This program is distributed in the hope that it will be useful, # 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of # 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 14 | # GNU General Public License for more details. # 15 | # # 16 | # You should have received a copy of the GNU General Public License # 17 | # along with this program; if not, write to the Free Software # 18 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # 19 | # # 20 | *******************************************************************************/ 21 | 22 | #include "HttpServer.h" 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "MjpegUtils.h" 35 | #include "Tracer.h" 36 | 37 | namespace { 38 | 39 | const static size_t MaxServersNum = 8U; 40 | const static size_t MaxClientsNum = 20U; 41 | 42 | const size_t ClientReadBufferSize = 2048U; 43 | std::vector ClientReadBuffer(ClientReadBufferSize); 44 | 45 | static const uint8_t HttpBoundaryValue[] = "\r\n--BoundaryDoNotCross\r\n"; 46 | 47 | static const char HttpHeader[] = 48 | "HTTP/1.0 200 OK\r\n" \ 49 | "Connection: close\r\n" \ 50 | "Server: uvc-streamer/0.01\r\n" \ 51 | "Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0\r\n" \ 52 | "Pragma: no-cache\r\n" \ 53 | "Expires: Thu, 1 Jan 1970 00:00:01 GMT\r\n" 54 | "Content-Type: multipart/x-mixed-replace; boundary=BoundaryDoNotCross\r\n" \ 55 | "\r\n" \ 56 | "--BoundaryDoNotCross\r\n"; 57 | 58 | static const uint32_t HeaderSize = sizeof(HttpHeader) - 1; 59 | 60 | bool SetupListeningSocket(int socketFd, const addrinfo* addrInfo, int maxPendingConnections); 61 | int CreateListeningSocket(const addrinfo* addrInfo); 62 | } 63 | 64 | HttpServer::HttpServer() 65 | : _listeningFds(0) 66 | { 67 | _listeningFds.reserve(MaxServersNum); 68 | } 69 | 70 | HttpServer::~HttpServer() 71 | { 72 | Shutdown(); 73 | } 74 | 75 | bool HttpServer::Init(const char* servicePort) 76 | { 77 | addrinfo addrHints = {0}; 78 | addrHints.ai_family = PF_INET; // Only IPv4 79 | addrHints.ai_flags = AI_PASSIVE; 80 | addrHints.ai_socktype = SOCK_STREAM; 81 | 82 | int result = 0; 83 | 84 | addrinfo* addrInfoHead; 85 | if ((result = ::getaddrinfo(nullptr, servicePort, &addrHints, &addrInfoHead)) != 0) { 86 | Tracer::LogErrNo(::gai_strerror(result)); 87 | return false; 88 | } 89 | 90 | addrinfo* currAddrInfo = addrInfoHead; 91 | while (currAddrInfo != nullptr) { 92 | int currAddrFd = CreateListeningSocket(currAddrInfo); 93 | if (currAddrFd != -1) { 94 | _listeningFds.push_back(currAddrFd); 95 | } 96 | else { 97 | Tracer::Log("Failed to create a listening socket.\n"); 98 | } 99 | 100 | currAddrInfo = currAddrInfo->ai_next; 101 | } 102 | 103 | ::freeaddrinfo(addrInfoHead); 104 | 105 | return !_listeningFds.empty(); 106 | } 107 | 108 | void HttpServer::ServeRequests(long maxServeTimeMicroSec) 109 | { 110 | // Send data to connected clients 111 | 112 | if (!_beingServedClients.empty()) { 113 | SendData(maxServeTimeMicroSec); 114 | } 115 | 116 | // If there is only one client then we have to send all grabbed data to it. 117 | while (_beingServedClients.size() == 1 && 118 | _beingServedClients.cbegin()->second.VideoBufferIdx != ResponseInfo::InvalidBufferIdx) { 119 | 120 | SendData(maxServeTimeMicroSec); 121 | } 122 | 123 | 124 | // Check for new connections. 125 | 126 | // Count and accept only for every 100th call. 127 | static uint32_t listenCount = 0; 128 | listenCount %= 1000; 129 | listenCount += 1; 130 | if ((listenCount % 100) == 0) { 131 | return; 132 | } 133 | 134 | fd_set selectfds; 135 | FD_ZERO(&selectfds); 136 | 137 | int maxFd = 0; 138 | 139 | for (size_t i = 0; i < _listeningFds.size(); ++i) { 140 | if (_listeningFds[i] != -1) { 141 | FD_SET(_listeningFds[i], &selectfds); 142 | 143 | if (_listeningFds[i] > maxFd) { 144 | maxFd = _listeningFds[i]; 145 | } 146 | } 147 | } 148 | 149 | timeval selectTimeSpec = { 0 }; 150 | int result = ::select(maxFd + 1, &selectfds, nullptr, nullptr, &selectTimeSpec); 151 | if (result < 0 && errno != EINTR) { 152 | Tracer::LogErrNo("select()."); 153 | return; 154 | } 155 | 156 | for (size_t i = 0; i < _listeningFds.size(); ++i) { 157 | if (_listeningFds[i] != -1 && FD_ISSET(_listeningFds[i], &selectfds)) { 158 | 159 | sockaddr_storage sockAddr = {0}; 160 | socklen_t sockAddrSize = sizeof(sockAddr); 161 | 162 | int clientFd = ::accept(_listeningFds[i], reinterpret_cast(&sockAddr), &sockAddrSize); 163 | if (-1 != clientFd) { 164 | if (GetClientsNumber() < MaxClientsNum) { 165 | result = ::fcntl(clientFd, F_SETFL, O_NONBLOCK); 166 | if (-1 == result) { 167 | Tracer::LogErrNo("fcntl() F_SETFL, O_NONBLOCK."); 168 | ::close(clientFd); 169 | } 170 | else { 171 | _waitingClients[clientFd] = RequestInfo(); 172 | } 173 | } 174 | else { 175 | Tracer::Log("Client dropped because of MaxClientsNum.\n"); 176 | ::close(clientFd); 177 | } 178 | } 179 | else { 180 | Tracer::LogErrNo("accept()."); 181 | } 182 | } 183 | } 184 | 185 | ReadAndParseRequests(); 186 | } 187 | 188 | bool HttpServer::HasDataToSend() const 189 | { 190 | for (auto clientIt : _beingServedClients) { 191 | 192 | const ResponseInfo& responseInfo = clientIt.second; 193 | 194 | if (responseInfo.HeaderBytesSent < HeaderSize || 195 | responseInfo.DataBufferIdx != ResponseInfo::InvalidBufferIdx) { 196 | return true; 197 | } 198 | } 199 | 200 | return false; 201 | } 202 | 203 | void HttpServer::ReadAndParseRequests() 204 | { 205 | fd_set selectFds; 206 | FD_ZERO(&selectFds); 207 | 208 | int maxFd = 0; 209 | 210 | for (auto clientFdIt : _waitingClients) { 211 | int clientFd = clientFdIt.first; 212 | 213 | FD_SET(clientFd, &selectFds); 214 | 215 | if (clientFd > maxFd) { 216 | maxFd = clientFd; 217 | } 218 | } 219 | 220 | if (0 == maxFd) { 221 | return; 222 | } 223 | 224 | timeval selectTimeSpec = {0}; 225 | int result = ::select(maxFd + 1, &selectFds, nullptr, nullptr, &selectTimeSpec); 226 | if (result < 0 && errno != EINTR && errno != EBADF) { 227 | Tracer::LogErrNo("select()."); 228 | 229 | // Something wrong happened with waiting clients. Drop all of them. 230 | 231 | for (auto clientFdIt : _waitingClients) { 232 | result = ::close(clientFdIt.first); 233 | if (result < 0) { 234 | Tracer::LogErrNo("close()."); 235 | } 236 | } 237 | 238 | _waitingClients.clear(); 239 | return; 240 | } 241 | 242 | std::list brokenClientFds; 243 | std::list parsedClientFds; 244 | 245 | for (auto clientFdIt : _waitingClients) { 246 | int clientFd = clientFdIt.first; 247 | RequestInfo& requestInfo = clientFdIt.second; 248 | 249 | if (FD_ISSET(clientFd, &selectFds)) { 250 | ssize_t readResult = ::read(clientFd, ClientReadBuffer.data(), ClientReadBuffer.size()); 251 | if (readResult > 0) { 252 | requestInfo.RequestData.insert(requestInfo.RequestData.end(), ClientReadBuffer.data(), ClientReadBuffer.data() + readResult); 253 | 254 | for (auto ch : ClientReadBuffer) { 255 | if (ch == '\n') { 256 | parsedClientFds.push_back(clientFd); 257 | break; 258 | } 259 | } 260 | } 261 | else if (EAGAIN == readResult || EWOULDBLOCK == readResult) { 262 | } 263 | else { 264 | // Something wrong with a client. Close it. 265 | _waitingClients.erase(clientFd); 266 | brokenClientFds.push_back(clientFd); 267 | } 268 | } 269 | } 270 | 271 | for (auto brokenClientFd : brokenClientFds) { 272 | if (::close(brokenClientFd) != 0) { 273 | Tracer::LogErrNo("close()."); 274 | } 275 | } 276 | 277 | for (auto parsedClientFd : parsedClientFds) { 278 | _waitingClients.erase(parsedClientFd); 279 | _beingServedClients[parsedClientFd] = ResponseInfo(); 280 | } 281 | } 282 | 283 | void HttpServer::SendData(long timeoutMicroSec) 284 | { 285 | fd_set selectFds; 286 | FD_ZERO(&selectFds); 287 | 288 | int maxFd = 0; 289 | 290 | for (auto clientFdIt : _beingServedClients) { 291 | int clientFd = clientFdIt.first; 292 | 293 | FD_SET(clientFd, &selectFds); 294 | 295 | if (clientFd > maxFd) { 296 | maxFd = clientFd; 297 | } 298 | } 299 | 300 | if (0 == maxFd) { 301 | return; 302 | } 303 | 304 | timeval selectTimeSpec = {0, timeoutMicroSec}; 305 | 306 | int result = ::select(maxFd + 1, nullptr, &selectFds, nullptr, &selectTimeSpec); 307 | if (result < 0 && errno != EINTR) { 308 | Tracer::LogErrNo("select()."); 309 | return; 310 | } 311 | 312 | if (0 == result) { 313 | return; 314 | } 315 | 316 | std::list brokenClientFds; 317 | 318 | for (std::pair& beingServedClientsIt : _beingServedClients) { 319 | int clientFd = beingServedClientsIt.first; 320 | 321 | if (FD_ISSET(clientFd, &selectFds)) { 322 | ResponseInfo& responseInfo = beingServedClientsIt.second; 323 | 324 | bool shouldBreak = false; 325 | 326 | while (!shouldBreak) { 327 | if (responseInfo.HeaderBytesSent < HeaderSize) { 328 | int writeResult = ::write(clientFd, HttpHeader + responseInfo.HeaderBytesSent, HeaderSize - responseInfo.HeaderBytesSent); 329 | if (writeResult > 0) { 330 | responseInfo.HeaderBytesSent += writeResult; 331 | } 332 | else if (-1 == writeResult && (errno == EAGAIN || errno == EWOULDBLOCK)) { 333 | // Stop sending data to the current client as it is busy. 334 | shouldBreak = true; 335 | } 336 | else { 337 | // Stop sending data to the current client as something went wrong. 338 | shouldBreak = true; 339 | Tracer::LogErrNo("write()."); 340 | brokenClientFds.push_back(clientFd); 341 | } 342 | } 343 | else if (ResponseInfo::InvalidBufferIdx == responseInfo.VideoBufferIdx) { 344 | HttpServer::QueueItem* queueItem = SelectBufferForSending(responseInfo.Timestamp); 345 | if (queueItem != nullptr) { 346 | queueItem->UsageCounter += 1; 347 | queueItem->SentCounter += 1; 348 | 349 | responseInfo.DataBufferBytesSent = 0; 350 | responseInfo.DataBufferIdx = 0; 351 | responseInfo.Timestamp = queueItem->SourceData->V4l2Buffer.timestamp; 352 | responseInfo.VideoBufferIdx = queueItem->SourceData->Idx; 353 | } 354 | else { 355 | // Stop sending data to the current client as there is no data for sending. 356 | shouldBreak = true; 357 | } 358 | } 359 | else { 360 | HttpServer::QueueItem* queueItem = GetBuffer(responseInfo.VideoBufferIdx); 361 | 362 | if (nullptr == queueItem) { 363 | // Stop sending data to the current client as unexpected problem is detected. 364 | shouldBreak = true; 365 | } 366 | else { 367 | const Buffer& buffer = queueItem->Data[responseInfo.DataBufferIdx]; 368 | int writeResult = ::write(clientFd, buffer.Data + responseInfo.DataBufferBytesSent, 369 | buffer.Size - responseInfo.DataBufferBytesSent); 370 | if (writeResult > 0) { 371 | responseInfo.DataBufferBytesSent += writeResult; 372 | if (responseInfo.DataBufferBytesSent == buffer.Size) { 373 | if (responseInfo.DataBufferIdx + 1 >= queueItem->Data.size()) { 374 | // The item was sent so we need to find a new item 375 | responseInfo.VideoBufferIdx = ResponseInfo::InvalidBufferIdx; 376 | 377 | // Release the item. 378 | queueItem->UsageCounter -= 1; 379 | } 380 | else { 381 | // Switch to next buffer 382 | responseInfo.DataBufferIdx += 1; 383 | responseInfo.DataBufferBytesSent = 0; 384 | } 385 | } 386 | } 387 | else if (-1 == writeResult && (errno == EAGAIN || errno == EWOULDBLOCK)) { 388 | shouldBreak = true; 389 | } 390 | else { 391 | // Stop sending data to the current client as something went wrong. 392 | shouldBreak = true; 393 | Tracer::LogErrNo("write()."); 394 | brokenClientFds.push_back(clientFd); 395 | 396 | queueItem->UsageCounter -= 1; 397 | } 398 | } 399 | } 400 | } 401 | } 402 | } 403 | 404 | for (auto clientFd : brokenClientFds) { 405 | _beingServedClients.erase(clientFd); 406 | 407 | if (-1 == ::close(clientFd)) { 408 | Tracer::LogErrNo("close()."); 409 | } 410 | } 411 | } 412 | 413 | HttpServer::QueueItem* HttpServer::SelectBufferForSending(const timeval& lastBufferTimestamp) 414 | { 415 | for (auto it = _incomeQueue.rbegin(); it != _incomeQueue.rend(); it++) { 416 | const timeval& itemTimestamp = it->SourceData->V4l2Buffer.timestamp; 417 | if (itemTimestamp.tv_sec > lastBufferTimestamp.tv_sec || 418 | (itemTimestamp.tv_sec == lastBufferTimestamp.tv_sec && itemTimestamp.tv_usec > lastBufferTimestamp.tv_usec)) { 419 | return &(*it); 420 | } 421 | } 422 | 423 | return nullptr; 424 | } 425 | 426 | HttpServer::QueueItem* HttpServer::GetBuffer(uint32_t videoBufferIdx) 427 | { 428 | for (QueueItem& queueItem : _incomeQueue) { 429 | if (queueItem.SourceData->Idx == videoBufferIdx) { 430 | return &queueItem; 431 | } 432 | } 433 | 434 | return nullptr; 435 | } 436 | 437 | bool HttpServer::QueueBuffer(const VideoBuffer* videoBuffer) 438 | { 439 | std::vector mjpegFrameData = CreateMjpegFrameBufferSet(videoBuffer); 440 | if (mjpegFrameData.empty()) { 441 | return false; 442 | } 443 | 444 | uint32_t frameSize = 0; 445 | for (const Buffer& buff : mjpegFrameData) { 446 | frameSize += buff.Size; 447 | } 448 | 449 | static const char frameHeaderTemplate[] = 450 | "Content-Type: image/jpeg\r\n" \ 451 | "Content-Length: %d\r\n" \ 452 | "X-Timestamp: %ld.%06ld\r\n" \ 453 | "\r\n"; 454 | 455 | std::vector frameHeaderBuff(sizeof(frameHeaderTemplate) + 100, 0); 456 | int result = std::snprintf(reinterpret_cast(frameHeaderBuff.data()), 457 | frameHeaderBuff.size() - 1, frameHeaderTemplate, 458 | frameSize, videoBuffer->V4l2Buffer.timestamp.tv_sec, 459 | videoBuffer->V4l2Buffer.timestamp.tv_usec); 460 | if (result <= 0) { 461 | Tracer::Log("Failed to create HTTP header for MJPEG frame: snprintf.\n"); 462 | return false; 463 | } 464 | 465 | uint32_t headerSize = static_cast(result); 466 | if (headerSize > frameHeaderBuff.size()) { 467 | Tracer::Log("Failed to create HTTP header for MJPEG frame. buffer is \n"); 468 | return false; 469 | } 470 | 471 | QueueItem newFrame; 472 | newFrame.Header.swap(frameHeaderBuff); 473 | 474 | newFrame.Data.reserve(mjpegFrameData.size() + 2); 475 | newFrame.Data.push_back(Buffer {newFrame.Header.data(), headerSize}); 476 | newFrame.Data.insert(newFrame.Data.end(), mjpegFrameData.begin(), mjpegFrameData.end()); 477 | newFrame.Data.push_back(Buffer {HttpBoundaryValue, sizeof(HttpBoundaryValue) - 1}); 478 | newFrame.SourceData = videoBuffer; 479 | newFrame.UsageCounter = 0; 480 | newFrame.SentCounter = 0; 481 | 482 | _incomeQueue.push_back(std::move(newFrame)); 483 | 484 | return true; 485 | } 486 | 487 | const VideoBuffer* HttpServer::DequeueBuffer() 488 | { 489 | auto currIt = _incomeQueue.begin(); 490 | while (currIt != _incomeQueue.end()) { 491 | auto nextIt = currIt; 492 | ++nextIt; 493 | 494 | if (nextIt != _incomeQueue.end() && 0 == currIt->UsageCounter) { 495 | const VideoBuffer* dequeuedBuffer = currIt->SourceData; 496 | 497 | // This code is for debugging slow clients 498 | // if (!_beingServedClients.empty()) { 499 | // if (0 == currIt->SentCounter) { 500 | // Tracer::Log("HttpServer missed frame %d %ld.%06ld\n", 501 | // dequeuedBuffer->V4l2Buffer.sequence, 502 | // dequeuedBuffer->V4l2Buffer.timestamp.tv_sec, 503 | // dequeuedBuffer->V4l2Buffer.timestamp.tv_usec); 504 | // } 505 | // 506 | // static timeval lastSentTs = dequeuedBuffer->V4l2Buffer.timestamp; 507 | // 508 | // long int delta = 0; 509 | // long int seconds = dequeuedBuffer->V4l2Buffer.timestamp.tv_sec - lastSentTs.tv_sec; 510 | // 511 | // if (seconds > 0) { 512 | // delta = seconds * 1000000; 513 | // delta -= lastSentTs.tv_usec; 514 | // delta += dequeuedBuffer->V4l2Buffer.timestamp.tv_usec; 515 | // } 516 | // else { 517 | // delta = dequeuedBuffer->V4l2Buffer.timestamp.tv_usec - lastSentTs.tv_usec; 518 | // } 519 | // 520 | // if (delta > 40000) { 521 | // Tracer::Log("Latency detected for frame %d: %ld\n", dequeuedBuffer->V4l2Buffer.sequence, delta); 522 | // } 523 | // 524 | // lastSentTs = dequeuedBuffer->V4l2Buffer.timestamp; 525 | // } 526 | 527 | _incomeQueue.erase(currIt); 528 | return dequeuedBuffer; 529 | } 530 | 531 | currIt = nextIt; 532 | } 533 | 534 | return nullptr; 535 | } 536 | 537 | std::vector HttpServer::DequeueAllBuffers() 538 | { 539 | std::vector result; 540 | result.reserve(_incomeQueue.size()); 541 | for (auto item : _incomeQueue) { 542 | result.push_back(item.SourceData); 543 | } 544 | 545 | // We have to wait till all currenty being transmitted buffers are sent. 546 | 547 | static const unsigned int SleepTimeInUSec = 5000; 548 | static const unsigned int MaxTotalSleepTimeInUs = 500000U; 549 | static const unsigned int MaxAttempts = MaxTotalSleepTimeInUs / SleepTimeInUSec; 550 | 551 | auto isUnused = [](const QueueItem& queueItem) -> bool { 552 | return 0 == queueItem.UsageCounter; 553 | }; 554 | 555 | for (unsigned int attempt = 0; attempt < MaxAttempts && !_incomeQueue.empty(); ++attempt) { 556 | // Remove all unused VideoBuffers from _incomeQueue. 557 | _incomeQueue.remove_if(isUnused); 558 | 559 | // Send already being transmitted VideoBuffer-s 560 | SendData(SleepTimeInUSec); 561 | } 562 | 563 | if (!_incomeQueue.empty()) { 564 | std::list brokenClientFds; 565 | for (auto client : _beingServedClients) { 566 | ResponseInfo& responseInfo = client.second; 567 | if (responseInfo.VideoBufferIdx != ResponseInfo::InvalidBufferIdx) { 568 | HttpServer::QueueItem* queueItem = GetBuffer(responseInfo.VideoBufferIdx); 569 | 570 | if (queueItem != nullptr) { 571 | responseInfo.VideoBufferIdx = ResponseInfo::InvalidBufferIdx; 572 | queueItem->UsageCounter -= 1; 573 | } 574 | 575 | brokenClientFds.push_back(client.first); 576 | } 577 | } 578 | 579 | for (auto clientFd : brokenClientFds) { 580 | _beingServedClients.erase(clientFd); 581 | 582 | if (-1 == ::close(clientFd)) { 583 | Tracer::LogErrNo("close()."); 584 | } 585 | 586 | Tracer::Log("Closed slow client."); 587 | } 588 | } 589 | 590 | _incomeQueue.remove_if(isUnused); 591 | 592 | return result; 593 | } 594 | 595 | void HttpServer::Shutdown() 596 | { 597 | DequeueAllBuffers(); 598 | 599 | for (auto client : _beingServedClients) { 600 | if (-1 == ::close(client.first)) { 601 | Tracer::LogErrNo("close()."); 602 | } 603 | } 604 | _beingServedClients.clear(); 605 | 606 | for (auto client : _waitingClients) { 607 | if (-1 == ::close(client.first)) { 608 | Tracer::LogErrNo("close()."); 609 | } 610 | } 611 | 612 | for (auto fd : _listeningFds) { 613 | if (-1 == ::close(fd)) { 614 | Tracer::LogErrNo("close()."); 615 | } 616 | } 617 | 618 | _listeningFds.clear(); 619 | } 620 | 621 | namespace { 622 | 623 | bool SetupListeningSocket(int socketFd, const addrinfo* addrInfo, int maxPendingConnections) 624 | { 625 | // Ignore "socket already in use" errors 626 | int reuseAddrValue = 1; 627 | if (::setsockopt(socketFd, SOL_SOCKET, SO_REUSEADDR, &reuseAddrValue, sizeof(reuseAddrValue)) != 0) { 628 | Tracer::LogErrNo("setsockopt(SO_REUSEADDR)."); 629 | return false; 630 | } 631 | 632 | // Switch to non-blocking mode 633 | if (::fcntl(socketFd, F_SETFL, O_NONBLOCK) < 0) { 634 | Tracer::LogErrNo("fcntl(F_SETFL, O_NONBLOCK)."); 635 | return false; 636 | } 637 | 638 | if (::bind(socketFd, addrInfo->ai_addr, addrInfo->ai_addrlen) != 0) { 639 | Tracer::LogErrNo("bind()."); 640 | return false; 641 | } 642 | 643 | if (::listen(socketFd, maxPendingConnections) != 0) { 644 | Tracer::LogErrNo("listen()."); 645 | return false; 646 | } 647 | 648 | return true; 649 | } 650 | 651 | int CreateListeningSocket(const addrinfo* addrInfo) 652 | { 653 | static const int MaxPendingConnections = 4; 654 | 655 | int socketFd = ::socket(addrInfo->ai_family, addrInfo->ai_socktype, 0); 656 | if (-1 == socketFd) { 657 | Tracer::LogErrNo("Failed to create a socket."); 658 | return -1; 659 | } 660 | 661 | if (!SetupListeningSocket(socketFd, addrInfo, MaxPendingConnections)) { 662 | ::close(socketFd); 663 | Tracer::Log("Failed to configure a listening socket."); 664 | return -1; 665 | } 666 | 667 | return socketFd; 668 | } 669 | } 670 | --------------------------------------------------------------------------------