├── .dockerignore ├── .gitattributes ├── .gitignore ├── .vscode ├── c_cpp_properties.json ├── settings.json └── tasks.json ├── Dockerfile.build ├── LICENSE.md ├── LICENSE ├── LICENSE.Raspberry_UserLand_Software ├── LICENSE.WebRTC ├── LICENSE.WebRTC_THIRD_PARTY ├── LICENSE.avahi ├── LICENSE.libwebsockets ├── LICENSE.rpi-webrtc-streamer ├── OWNERS.WebRTC └── PATENTS.WebRTC ├── README.md ├── README_TelegramBot.md ├── README_audio.md ├── README_building.md ├── README_motion.md ├── README_rws_setup.md ├── etc └── template │ ├── media_config.conf │ ├── motion_config.conf │ ├── telegramBot.conf │ └── webrtc_streamer.conf ├── lib └── libwebsockets-3.1.0.zip ├── misc ├── .clang-format ├── AndroidApp_ClinetCerts.patch ├── icons8-raspberry-pi-520.png ├── motion_detection_example.avi ├── telegram-icon-6264.png ├── telegram_botfather.png ├── webrtc_arm_build_args.gn ├── webrtc_armv6_build_args.gn ├── webrtc_streamer_architecture.png └── webrtc_x64_build_args.gn ├── mk ├── config_libwebsockets.sh ├── cross_arm_build.mk ├── cross_mmal.mk ├── libavahi_arm.mk ├── libwebsocket_arm_build.mk ├── libwebsocket_native_gcc.mk ├── native_gcc.mk ├── validate_variables.mk └── webrtc_library_gn.py ├── scripts └── rws.service ├── src ├── Makefile ├── app_channel.cc ├── app_channel.h ├── app_clientinfo.cc ├── app_clientinfo.h ├── app_ws_client.cc ├── app_ws_client.h ├── compat │ ├── optionsfile.cc │ ├── optionsfile.h │ ├── status.cc │ ├── status_payload_printer.cc │ └── statusor.cc ├── config_defs.h ├── config_media.cc ├── config_media.h ├── config_motion.cc ├── config_motion.h ├── config_streamer.cc ├── config_streamer.h ├── def │ ├── config_media.def │ ├── config_motion.def │ └── config_streamer.def ├── direct_socket.cc ├── direct_socket.h ├── file_log_sink.cc ├── file_log_sink.h ├── file_writer_handle.cc ├── file_writer_handle.h ├── frame_queue.cc ├── frame_queue.h ├── log_rotating_stream.cc ├── log_rotating_stream.h ├── main.cc ├── mdns_publish.c ├── mdns_publish.h ├── mmal_common.h ├── mmal_still.c ├── mmal_still.h ├── mmal_still_capture.cc ├── mmal_still_capture.h ├── mmal_util.c ├── mmal_video.c ├── mmal_video.h ├── mmal_video_reset.c ├── mmal_wrapper.cc ├── mmal_wrapper.h ├── raspi_decoder.cc ├── raspi_decoder.h ├── raspi_decoder_dummy.cc ├── raspi_decoder_dummy.h ├── raspi_encoder.cc ├── raspi_encoder.h ├── raspi_encoder_impl.cc ├── raspi_encoder_impl.h ├── raspi_httpnoti.cc ├── raspi_httpnoti.h ├── raspi_motion.cc ├── raspi_motion.h ├── raspi_motionblob.cc ├── raspi_motionblob.h ├── raspi_motionblobid.h ├── raspi_motionfile.cc ├── raspi_motionfile.h ├── raspi_motionvector.cc ├── raspi_motionvector.h ├── raspi_quality_config.cc ├── raspi_quality_config.h ├── raspicamcontrol.c ├── raspicamcontrol.h ├── raspicli.c ├── raspicli.h ├── raspipreview.c ├── raspipreview.h ├── session_config.cc ├── session_config.h ├── streamer.cc ├── streamer.h ├── streamer_signaling.cc ├── streamer_signaling.h ├── utils.cc ├── utils.h ├── utils_pc_config.cc ├── utils_pc_config.h ├── utils_pc_strings.cc ├── utils_pc_strings.h ├── utils_url.h ├── websocket_handler.h ├── websocket_server.cc ├── websocket_server.h ├── websocket_server_callback.cc ├── websocket_server_internal.h ├── websocket_server_util.c ├── wstreamer_types.cc └── wstreamer_types.h ├── tools ├── ffmpeg_armv6 ├── ffmpeg_neon └── telegramBot.py └── web-root └── np2 ├── css └── main.css ├── images └── webrtc-icon-192x192.png ├── index.html └── js ├── config_media.mjs ├── config_params.mjs ├── constants.mjs ├── peerconnection_client.mjs ├── snackbar.mjs ├── streamer_connection_rws.mjs ├── streamer_controller.mjs └── streamer_transaction.mjs /.dockerignore: -------------------------------------------------------------------------------- 1 | backup/* 2 | imv_examples/* 3 | lib/libsockets 4 | tools/* 5 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | web-root/* linguist-vendored 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.o 3 | *.dwo 4 | 5 | # Precompiled Headers 6 | *.gch 7 | *.pch 8 | ipch 9 | 10 | # Compiled Static libraries 11 | *.a 12 | *.lib 13 | 14 | # Executables 15 | webrtc-streamer 16 | lib/libwebsockets/ 17 | 18 | # Configuration 19 | etc/app_channel.conf 20 | etc/webrtc-streamer.conf 21 | 22 | # Tempoary backup 23 | backup 24 | src/OLD 25 | imv_examples 26 | src/.vscode 27 | .ccls-cache 28 | -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Linux", 5 | "cStandard": "c11", 6 | "cppStandard": "c++17", 7 | "intelliSenseMode": "gcc-x64", 8 | "compileCommands": "${workspaceFolder}/compile_commands.json", 9 | "compilerPath": "/opt/rpi_rootfs/tools/arm-linux-gnueabihf/bin/arm-linux-gnueabihf-g++" 10 | } 11 | ], 12 | "version": 4 13 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.exclude": { 3 | "**/.ccls-cache/**": true, 4 | "**/.DS_Store": false, 5 | "**/*.dwo": true, 6 | "**/*.o": true, 7 | "**/webrtc/out/**": true, 8 | "${workspaceFolder}/backup/**": true, 9 | "${workspaceFolder}/log/**": true, 10 | "${workspaceFolder}/src/OLD/**": true 11 | }, 12 | "C_Cpp.clang_format_path": "/usr/bin/clang-format-9", 13 | "C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: Google, IndentWidth: 4 }", 14 | "git.ignoreLimitWarning": true, 15 | "C_Cpp.default.cppStandard": "c++17", 16 | "C_Cpp.default.cStandard": "c11", 17 | "files.associations": { 18 | "*.tcc": "cpp", 19 | "string": "cpp" 20 | }, 21 | "C_Cpp.default.compileCommands": "${workspaceFolder}/compile_commands.json", 22 | "editor.formatOnSave": true, 23 | "C_Cpp.default.intelliSenseMode": "gcc-x64", 24 | "search.exclude": { 25 | "**/webrtc/**/*.c": true, 26 | "**/webrtc/**/*.cc": true 27 | }, 28 | "files.watcherExclude": { 29 | "**/webrtc/src/**.cc": true 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "shell", 8 | "label": "Builing with make", 9 | "command": "make", 10 | "args": [ 11 | "all", 12 | ], 13 | "options": { 14 | "cwd": "${workspaceRoot}/src" 15 | }, 16 | "problemMatcher": [ 17 | "$gcc" 18 | ], 19 | "group": { 20 | "kind": "build", 21 | "isDefault": true 22 | } 23 | }, 24 | { 25 | "type": "shell", 26 | "label": "Clean with make", 27 | "command": "make", 28 | "args": [ 29 | "clean", 30 | ], 31 | "options": { 32 | "cwd": "${workspaceRoot}/src" 33 | }, 34 | "problemMatcher": [ 35 | "$gcc" 36 | ], 37 | "group": { 38 | "kind": "build", 39 | "isDefault": true 40 | } 41 | } 42 | ] 43 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | #### WebRTC 2 | 3 | Refer to LICENSE.WebRTC, PATERNS.WebRTC, OWNERS.WebRTC in LICENSE directory 4 | 5 | #### H.264 bitstream 6 | 7 | Refer to LICENSE_h264bitstream in LICENSE directory 8 | 9 | #### rpi-webrtc-streamer 10 | 11 | Refer to LICENSE_rpi-webrtc-streamer in LICENSE directory -------------------------------------------------------------------------------- /LICENSE/LICENSE.Raspberry_UserLand_Software: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012, Broadcom Europe Ltd 2 | Copyright (c) 2015, Raspberry Pi (Trading) Ltd 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright 10 | notice, this list of conditions and the following disclaimer in the 11 | documentation and/or other materials provided with the distribution. 12 | * Neither the name of the copyright holder nor the 13 | names of its contributors may be used to endorse or promote products 14 | derived from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | -------------------------------------------------------------------------------- /LICENSE/LICENSE.WebRTC: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011, The WebRTC project authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in 12 | the documentation and/or other materials provided with the 13 | distribution. 14 | 15 | * Neither the name of Google nor the names of its contributors may 16 | be used to endorse or promote products derived from this software 17 | without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 20 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 23 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /LICENSE/LICENSE.rpi-webrtc-streamer: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016, Lyu,KeunChang rpi-webrtc-streamer 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 22 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | -------------------------------------------------------------------------------- /LICENSE/OWNERS.WebRTC: -------------------------------------------------------------------------------- 1 | henrika@webrtc.org 2 | kwiberg@webrtc.org 3 | mflodman@webrtc.org 4 | niklas.enbom@webrtc.org 5 | tina.legrand@webrtc.org 6 | tommi@webrtc.org 7 | 8 | per-file *.isolate=kjellander@webrtc.org 9 | 10 | # These are for the common case of adding or renaming files. If you're doing 11 | # structural changes, please get a review from a reviewer in this file. 12 | per-file *.gyp=* 13 | per-file *.gypi=* 14 | 15 | per-file BUILD.gn=kjellander@webrtc.org 16 | 17 | per-file *video*.h=pbos@webrtc.org 18 | -------------------------------------------------------------------------------- /LICENSE/PATENTS.WebRTC: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the WebRTC code package. 5 | 6 | Google hereby grants to you a perpetual, worldwide, non-exclusive, 7 | no-charge, irrevocable (except as stated in this section) patent 8 | license to make, have made, use, offer to sell, sell, import, 9 | transfer, and otherwise run, modify and propagate the contents of this 10 | implementation of the WebRTC code package, where such license applies 11 | only to those patent claims, both currently owned by Google and 12 | acquired in the future, licensable by Google that are necessarily 13 | infringed by this implementation of the WebRTC code package. This 14 | grant does not include claims that would be infringed only as a 15 | consequence of further modification of this implementation. If you or 16 | your agent or exclusive licensee institute or order or agree to the 17 | institution of patent litigation against any entity (including a 18 | cross-claim or counterclaim in a lawsuit) alleging that this 19 | implementation of the WebRTC code package or any code incorporated 20 | within this implementation of the WebRTC code package constitutes 21 | direct or contributory patent infringement, or inducement of patent 22 | infringement, then any patent rights granted to you under this License 23 | for this implementation of the WebRTC code package shall terminate as 24 | of the date such litigation is filed. 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # WebRTC streamer for Raspberry PI 3 | 4 | ## General 5 | Notice: This is a work in progress, 6 | 7 | This repo's objective is providing something like Web Cam server on the most popular Raspberry PI hardware. By integrating [WebRTC](https://webrtc.org/native-code/) and Raspberry PI, we can stream the Raspberry camera feed to browser or native client which talks WebRTC. 8 | 9 | Generally, the components of WebRTC service are classified into Signaling Server and WebRTC client. However, RWS(Rpi-WebRTC-Streamer) is built to operate on one piece of Raspberry PI hardware and includes some of Signaling Server functionality. In other words, the Browser or Client supporting WebRTC directly connects to RWS and receives WebRTC streaming service. 10 | 11 | ### Streaming camera feed 12 | To get the camera feed from Raspberry PI, i.e. H.264 video stream, RWS use MMAL(Multi-Media Abstraction Layer) library can be found on [ARM side libraries for interfacing to Raspberry Pi GPU](https://github.com/raspberrypi/userland). it provides lower level API to multi-media components running on Broadcom VideoCore. For convenience, this streamer directly integrated [raspivid](https://github.com/raspberrypi/userland/tree/master/host_applications/linux/apps/raspicam) 13 | with encoding parameter changing in H.264 stream and passing video frame through WebRTC native code package. 14 | 15 | ### Motion Detection 16 | Motion Detection feature provided by Rpi-WebRTC-Streamer uses Inline Motion Vector which is generated during video encoding. And use this to get the approximate Motion Detection function while using minimal CPU resources. 17 | 18 | Please refer to [README_motion document](../master/README_motion.md). 19 | 20 | ### Messenger Notification 21 | The motion detection event message can be transmitted to the user through the telegram messenger. It can send motion detection message and detected video clip to Telegram Messenger client so that it can be used as a private security bot. 22 | For more information, Please refer to [README_TelegramBot document](../master/README_TelegramBot.md). 23 | 24 | 25 | ## Rpi WebRTC Streamer 26 | ### Demo Video 27 | 28 | 30 | 31 | ## Hardware Requirement 32 | ### Raspberry PI 33 | - Raspberry PI 2/3 34 | - Raspberry Pi Zero/Zero W (ZeroW tested) 35 | 36 | ### Video Camera 37 | - RPI Camera board V1/V2 38 | - Arducam 5 Megapixels 1080p Sensor OV5647 Mini Camera Video Module 39 | 40 | ### Audio hardware 41 | Please refer to the [README_audio.md](https://github.com/kclyu/rpi-webrtc-streamer/blob/master/README_audio.md) 42 | 43 | ## Running RWS on Raspberry PI 44 | Please refer to [README_rws_setup.md document](../master/README_rws_setup.md). 45 | 46 | ## Download Docker image for Testing 47 | In Raspberry PI, you can run the image directly after the pull from the docker hub as shown below. 48 | 49 | ``` 50 | docker pull kclyu/rpi-webrtc-streamer 51 | docker container run --device=/dev/vcsm --device=/dev/vchiq --net=host --mount type=bind,source=/var/run/dbus,target=/var/run/dbus --rm -d kclyu/rpi-webrtc-streamer # note1 52 | ``` 53 | _Note1: docker image is currently for armv7l (Raspberry PI2 and above)._ 54 | ## Download Deb package for Testing 55 | To download RWS deb package, please refer to the following URL. RWS is currently in development and testing, so please use it with consideration. 56 | 57 | Please refer to [Rpi-Webrtc-Streamer-deb Repo](https://github.com/kclyu/rpi-webrtc-streamer-deb). 58 | 59 | ## Cross Compile on Ubuntu Linux 60 | 61 | Please refer to [README_building.md document](../master/README_building.md). 62 | -------------------------------------------------------------------------------- /README_audio.md: -------------------------------------------------------------------------------- 1 | 2 | # Raspberry PI Audio Setup for RWS 3 | 4 | ## General 5 | In RWS, PulseAudio is disabled and uses ALSA. To use audio, use a USB audio dongle or USB microphone that has been confirmed to work with Raspberry PI. This document is based on the device whose operation has been verified and will be added if any device operation is confirmed. 6 | 7 | ## Want to buy Audio Device? 8 | The Raspberry PI forum audio articles have a large number of posts , but there are not many latest updates of USB audio device for new hardware. One thing I would like to ask you first is to try to purchase a audio device that has been confirmed to be a hardware device that runs on Raspberry PI before purchasing a device for Audio Setup. 9 | 10 | For example, USB 3.0 hub (power hub) or dongle does not work with Raspberry PI and some USB 2.0 dongle may or may not work. 11 | 12 | See [USB Sound Cards](http://elinux.org/RPi_VerifiedPeripherals#USB_Sound_Cards), which is confirmed to work with Raspberry PI). 13 | 14 | ## Audio Device Setup 15 | The linux audio part of the WebRTC native code package first searches all available audio device lists in the OS. However, the audio device you want to use should be set to search first. 16 | 17 | #### 1. Disable raspberry audio 18 | ``` 19 | sudo vi /boot/config.txt 20 | #dtparam=audio=on ## comment out 21 | ``` 22 | #### 2. Reorder USB audio device index 23 | ``` 24 | sudo vi /lib/modprobe.d/aliases.conf 25 | #options snd-usb-audio index=-2 # comment out 26 | ``` 27 | #### 3. change asoundrc 28 | ``` 29 | vi ~/.asoundrc 30 | defaults.pcm.card 0; 31 | defaults.ctl.card 0; 32 | ``` 33 | 34 | 35 | ## USB audio dongle 36 | An example of using USB audio dongle is [A presence robot with Chromium, WebRTC, Raspberry Pi 3 and EasyRTC](https://planb.nicecupoftea.org/2016/10/24/a-presence-robot-with-chromium-webrtc-raspberry-pi-3-and-easyrtc/) 37 | 38 | ## Working Audio Device List for WebRTC audio 39 | - USB microphone - Cosy USB microphone MK1343UB 40 | 41 | ## Do you have any working configuration on Audio? 42 | It is not easy to buy as many hardware as possible for the test, and there is not really much time to test it. If you have successfully set up your audio with your Raspberry PI and have verified audio transmission from RWS, please share it. I think it will help a lot of others. 43 | 44 | Please add the comment to the issue as shown below. 45 | 46 | - Device Type: (USB dongle | USB microphone | Raspberry PI audio hat | etc) 47 | - Device Name: (Device Model) 48 | - Command Output: 49 | - lsusb 50 | - cat / proc / asound / cards 51 | 52 | 53 | ## Testing Required 54 | 55 | - Raspberry PI Audio Hat 56 | - USB audio dongle 57 | 58 | 59 | ## Audio Setup - Version History 60 | 61 | * 2017/05/21 : Initial Version 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /etc/template/media_config.conf: -------------------------------------------------------------------------------- 1 | max_bitrate=3500000 2 | # specify screen resolution ratio ( true: using 4:3, false: using 16:9) 3 | resolution_4_3_enable=true 4 | 5 | # The roi value consists of 4 values, and each value is x,y,width,height 6 | # video_roi=x,y,width,height 7 | # Each value is set to a value normalized to a value of 0.0 ~ 1.0 for the size of 8 | # the video resolution. The width and height values must have a size of 0.2 9 | # (at least 20% of the total) or more. If this config does not in use, 10 | # delete the video_roi setting value and use as the default value. 11 | # 12 | # video_roi=0,0,0,1.0,1.0 13 | # 14 | 15 | # rotate video , valid value is [0|90|180|270] 16 | video_rotation=0 17 | video_hflip=false 18 | video_vflip=false 19 | # specify using dynamic resolution changing based on the bandwidth estimation 20 | # (If set to true, dynamic resolution feature is enabled; if set to false, 21 | # fixed_resolution will be used.) 22 | use_dynamic_video_resolution=true 23 | use_dynamic_video_fps=true 24 | fixed_video_resolution=640x480 25 | fixed_video_fps=30 26 | # list of 4:3 ratio screen resolution 27 | video_resolution_list_4_3=320x240,400x300,512x384,640x480,1024x768,1152x864,1296x972,1640x1232 28 | # list of 16:9 ratio screen resolution 29 | video_resolution_list_16_9=384x216,512x288,640x360,768x432,896x504,1024x576,1152x648,1280x720,1408x864,1920x1080 30 | # enable/disable below audio processing feature 31 | # when set to true, audio related features are enabled. 32 | # After enable, each feature can be set to enable/disable. 33 | # when set to false, all audio features are ignored. 34 | audio_processing_enable=false 35 | # echo cancelllation 36 | audio_echo_cancellaton=true 37 | audio_auto_gain_control=true 38 | audio_high_passfilter=true 39 | audio_noise_suppression=true 40 | audio_experimental_agc=false 41 | audio_experimental_ns=false 42 | # sharpness (-100 to 100) 43 | video_sharpness=0 44 | # contrast (-100 to 100) 45 | video_contrast=0 46 | # brightness (0 to 100) 47 | video_brightness=50 48 | # saturation (-100 to 100) 49 | video_saturation=0 50 | # exposure compensation (-10 to 10) 51 | video_ev=0 52 | video_exposure_mode=auto 53 | video_flicker_mode=auto 54 | video_awb_mode=auto 55 | video_drc_mode=high 56 | video_enable_annotate_text=false 57 | video_annotate_text_size_ratio=3 58 | video_annotate_text=%Y-%m-%d.%X 59 | -------------------------------------------------------------------------------- /etc/template/motion_config.conf: -------------------------------------------------------------------------------- 1 | motion_detection_enable=false 2 | motion_width=1024 3 | motion_height=768 4 | motion_fps=30 5 | motion_bitrate=3500 6 | motion_clear_percent=5 7 | motion_annotate_text=Raspi Motion %Y-%m-%d.%X 8 | motion_clear_wait_period=5000 9 | motion_directory=/home/pi/Videos 10 | motion_file_prefix=motion 11 | motion_file_size_limit=6000 12 | motion_save_imv_file=false 13 | blob_cancel_threshold=1 14 | blob_tracking_threshold=10 15 | motion_file_total_size_limit=2000 16 | -------------------------------------------------------------------------------- /etc/template/telegramBot.conf: -------------------------------------------------------------------------------- 1 | # auth_token : Auth_token generated from Telegram BotFather 2 | auth_token: xxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 3 | 4 | # the directory where Rpi-WebRTC-Streamer stores h.264 files 5 | motion_h264_path: /home/pi/Videos 6 | 7 | # Set the interval to invoke process to check for new files added. 8 | checking_interval: 5 9 | 10 | # the file to store the telegram chat_id to use when sending the message. 11 | # the below example is default value 12 | # 13 | chat_id_filename: /opt/rws/etc/run/telegrambot.pickle 14 | 15 | # specify the location of the file to store the admin id. 16 | # 17 | admin_list_filename: /opt/rws/etc/run/telegrambotadmin.pickle 18 | 19 | # specifies whether the h.264 file generated by rws is converted to an mp4 file 20 | # and included in the telegram message. if you set the default value to true 21 | # and set it to false, only the name of the newly created file will be transferred 22 | # to the message without the mp4 file. 23 | # default value is true 24 | mp4_upload_enable: true 25 | 26 | # specifies the system command to use when converting to mp4 file. 27 | # the specified command string must have $input_file and $output_file, 28 | # and it is a template to replace internally. 29 | # 30 | # there are two ffmpeg_neon and ffmpeg_armv6 files in the tools directory, 31 | # and ffmpeg_neon should be used on pi2 or higher hardware. 32 | # and ffmpeg_armv6 should be used on ZeroW or PI1 33 | # 34 | #converting_command: '/opt/rws/tools/ffmpeg_armv6 -y -i $input_file $output_file' 35 | # 36 | # When you convert h.264 video to mp4, the size will be smaller than h.264 original 37 | # file and it is advantageous when you send the file to Messenger like Telegram or 38 | # upload it to Cloud Storage like GoogleDrive 39 | # 40 | # However, conversion to mp4 is very slow on hardware such as PI 1 or PI Zero W 41 | # with an ARMv6 family of CPUs, so it can hardly be used. 42 | # In this case, you should use '-vcodec copy' to convert the file to a level 43 | # that simply changes the container, as shown below. 44 | # 45 | converting_command: '/opt/rws/tools/ffmpeg_armv6 -y -vcodec copy -i $input_file $output_file' 46 | 47 | # 48 | # When telegram message upload, specify the value of upload timeout seconds. 49 | # If network upload is slow, you should increase the timeout value. 50 | upload_timeout: 120 51 | 52 | # Keep the message waiting for a period of time after transmission. 53 | # No new messages are sent during this period. 54 | # The default value is 120. 55 | # When set to 0, new motion detection messages will continue to be transmitted 56 | # without waiting time. 57 | noti_cooling_period: 120 58 | 59 | 60 | # Always disable sound alert when sending messages. 61 | # The Telegram Client receives new messages but without a sound alert. 62 | # 63 | sound_alerts_in_schedule: False 64 | 65 | # specifies the hour of day 66 | noti_schedule_hour: '[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]' 67 | # specifies the day of week. 0 is Monday, ... 6 is Sunday 68 | noti_schedule_day: '[0,1,2,3,4,5,6]' 69 | -------------------------------------------------------------------------------- /etc/template/webrtc_streamer.conf: -------------------------------------------------------------------------------- 1 | websocket_enable=true 2 | websocket_port=8889 3 | media_config=etc/media_config.conf 4 | motion_config=etc/motion_config.conf 5 | direct_socket_enable=true 6 | direct_socket_port=8888 7 | disable_log_buffering=false 8 | web_root=/opt/rws/web-root 9 | libwebsocket_debug=false 10 | rws_ws_url=/rws/ws 11 | 12 | # 13 | # Using audio is disabled by default. To use audio, set audio_enable = true. 14 | # video is enabled by default. 15 | audio_enable=false 16 | video_enable=true 17 | 18 | # 19 | # The settings related to ice_server are separated by urls, 20 | # as shown below. If you only use stun, you only need to set urls. 21 | # 22 | # * : default value 23 | # ice_transports_type= none | relay | nohost | *all 24 | # bundle_policy= *balanced | max-bundle | max-compat 25 | # rtcp_mux_policy= *require | negotiate 26 | # 27 | # ice_server_urls_?=stun:stun.l.google.com:19302 28 | # ice_server_username_?= 29 | # ice_server_password_?= 30 | # ice_server_hostname_?= 31 | # ice_server_tls_cert_policy_?= secure or insecure 32 | # ice_server_tls_alpn_protocols_?= # List of protocols to be used in the TLS ALPN extension. 33 | # ice_server_tls_elliptic_curves_?= # List of elliptic curves to be used in the TLS elliptic curves extension. 34 | # 35 | ice_server_urls_0=stun:stun.l.google.com:19302,stun:stun1.l.google.com:19302,stun:stun2.l.google.com:19302,stun:stun3.l.google.com:19302,stun:stun4.l.google.com:19302 36 | -------------------------------------------------------------------------------- /lib/libwebsockets-3.1.0.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kclyu/rpi-webrtc-streamer/e109e418aa9023009b3b59c95eec2de4721125be/lib/libwebsockets-3.1.0.zip -------------------------------------------------------------------------------- /misc/.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | # BasedOnStyle: Google 4 | AccessModifierOffset: -1 5 | AlignAfterOpenBracket: Align 6 | AlignConsecutiveMacros: false 7 | AlignConsecutiveAssignments: false 8 | AlignConsecutiveDeclarations: false 9 | AlignEscapedNewlines: Left 10 | AlignOperands: true 11 | AlignTrailingComments: true 12 | AllowAllArgumentsOnNextLine: true 13 | AllowAllConstructorInitializersOnNextLine: true 14 | AllowAllParametersOfDeclarationOnNextLine: true 15 | AllowShortBlocksOnASingleLine: false 16 | AllowShortCaseLabelsOnASingleLine: false 17 | AllowShortFunctionsOnASingleLine: All 18 | AllowShortLambdasOnASingleLine: All 19 | AllowShortIfStatementsOnASingleLine: WithoutElse 20 | AllowShortLoopsOnASingleLine: true 21 | AlwaysBreakAfterDefinitionReturnType: None 22 | AlwaysBreakAfterReturnType: None 23 | AlwaysBreakBeforeMultilineStrings: true 24 | AlwaysBreakTemplateDeclarations: Yes 25 | BinPackArguments: true 26 | BinPackParameters: true 27 | BraceWrapping: 28 | AfterCaseLabel: false 29 | AfterClass: false 30 | AfterControlStatement: false 31 | AfterEnum: false 32 | AfterFunction: false 33 | AfterNamespace: false 34 | AfterObjCDeclaration: false 35 | AfterStruct: false 36 | AfterUnion: false 37 | AfterExternBlock: false 38 | BeforeCatch: false 39 | BeforeElse: false 40 | IndentBraces: false 41 | SplitEmptyFunction: true 42 | SplitEmptyRecord: true 43 | SplitEmptyNamespace: true 44 | BreakBeforeBinaryOperators: None 45 | BreakBeforeBraces: Attach 46 | BreakBeforeInheritanceComma: false 47 | BreakInheritanceList: BeforeColon 48 | BreakBeforeTernaryOperators: true 49 | BreakConstructorInitializersBeforeComma: false 50 | BreakConstructorInitializers: BeforeColon 51 | BreakAfterJavaFieldAnnotations: false 52 | BreakStringLiterals: true 53 | ColumnLimit: 80 54 | CommentPragmas: '^ IWYU pragma:' 55 | CompactNamespaces: false 56 | ConstructorInitializerAllOnOneLineOrOnePerLine: true 57 | ConstructorInitializerIndentWidth: 4 58 | ContinuationIndentWidth: 4 59 | Cpp11BracedListStyle: true 60 | DerivePointerAlignment: true 61 | DisableFormat: false 62 | ExperimentalAutoDetectBinPacking: false 63 | FixNamespaceComments: true 64 | ForEachMacros: 65 | - foreach 66 | - Q_FOREACH 67 | - BOOST_FOREACH 68 | IncludeBlocks: Regroup 69 | IncludeCategories: 70 | - Regex: '^' 71 | Priority: 2 72 | - Regex: '^<.*\.h>' 73 | Priority: 1 74 | - Regex: '^<.*' 75 | Priority: 2 76 | - Regex: '.*' 77 | Priority: 3 78 | IncludeIsMainRegex: '([-_](test|unittest))?$' 79 | IndentCaseLabels: true 80 | IndentPPDirectives: None 81 | IndentWidth: 4 82 | IndentWrappedFunctionNames: false 83 | JavaScriptQuotes: Leave 84 | JavaScriptWrapImports: true 85 | KeepEmptyLinesAtTheStartOfBlocks: false 86 | MacroBlockBegin: '' 87 | MacroBlockEnd: '' 88 | MaxEmptyLinesToKeep: 1 89 | NamespaceIndentation: None 90 | ObjCBinPackProtocolList: Never 91 | ObjCBlockIndentWidth: 2 92 | ObjCSpaceAfterProperty: false 93 | ObjCSpaceBeforeProtocolList: true 94 | PenaltyBreakAssignment: 2 95 | PenaltyBreakBeforeFirstCallParameter: 1 96 | PenaltyBreakComment: 300 97 | PenaltyBreakFirstLessLess: 120 98 | PenaltyBreakString: 1000 99 | PenaltyBreakTemplateDeclaration: 10 100 | PenaltyExcessCharacter: 1000000 101 | PenaltyReturnTypeOnItsOwnLine: 200 102 | PointerAlignment: Left 103 | RawStringFormats: 104 | - Language: Cpp 105 | Delimiters: 106 | - cc 107 | - CC 108 | - cpp 109 | - Cpp 110 | - CPP 111 | - 'c++' 112 | - 'C++' 113 | CanonicalDelimiter: '' 114 | BasedOnStyle: google 115 | - Language: TextProto 116 | Delimiters: 117 | - pb 118 | - PB 119 | - proto 120 | - PROTO 121 | EnclosingFunctions: 122 | - EqualsProto 123 | - EquivToProto 124 | - PARSE_PARTIAL_TEXT_PROTO 125 | - PARSE_TEST_PROTO 126 | - PARSE_TEXT_PROTO 127 | - ParseTextOrDie 128 | - ParseTextProtoOrDie 129 | CanonicalDelimiter: '' 130 | BasedOnStyle: google 131 | ReflowComments: true 132 | SortIncludes: true 133 | SortUsingDeclarations: true 134 | SpaceAfterCStyleCast: false 135 | SpaceAfterLogicalNot: false 136 | SpaceAfterTemplateKeyword: true 137 | SpaceBeforeAssignmentOperators: true 138 | SpaceBeforeCpp11BracedList: false 139 | SpaceBeforeCtorInitializerColon: true 140 | SpaceBeforeInheritanceColon: true 141 | SpaceBeforeParens: ControlStatements 142 | SpaceBeforeRangeBasedForLoopColon: true 143 | SpaceInEmptyParentheses: false 144 | SpacesBeforeTrailingComments: 2 145 | SpacesInAngles: false 146 | SpacesInContainerLiterals: true 147 | SpacesInCStyleCastParentheses: false 148 | SpacesInParentheses: false 149 | SpacesInSquareBrackets: false 150 | Standard: Cpp11 151 | StatementMacros: 152 | - Q_UNUSED 153 | - QT_REQUIRE_VERSION 154 | TabWidth: 4 155 | UseTab: Never 156 | ... 157 | 158 | -------------------------------------------------------------------------------- /misc/icons8-raspberry-pi-520.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kclyu/rpi-webrtc-streamer/e109e418aa9023009b3b59c95eec2de4721125be/misc/icons8-raspberry-pi-520.png -------------------------------------------------------------------------------- /misc/motion_detection_example.avi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kclyu/rpi-webrtc-streamer/e109e418aa9023009b3b59c95eec2de4721125be/misc/motion_detection_example.avi -------------------------------------------------------------------------------- /misc/telegram-icon-6264.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kclyu/rpi-webrtc-streamer/e109e418aa9023009b3b59c95eec2de4721125be/misc/telegram-icon-6264.png -------------------------------------------------------------------------------- /misc/telegram_botfather.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kclyu/rpi-webrtc-streamer/e109e418aa9023009b3b59c95eec2de4721125be/misc/telegram_botfather.png -------------------------------------------------------------------------------- /misc/webrtc_arm_build_args.gn: -------------------------------------------------------------------------------- 1 | # Build arguments go here. Examples: 2 | # is_component_build = true 3 | # is_debug = false 4 | # See "gn args --list" for available build arguments. 5 | 6 | # 7 | # 8 | # The following two flags are used for debugging. 9 | # 10 | #is_official_build=false 11 | #is_debug=true 12 | 13 | # For package building, we need to chage is_official_build to true and is_debug to false. 14 | # 15 | is_official_build=true 16 | is_debug=false 17 | 18 | is_component_build=false 19 | enable_iterator_debugging=false 20 | 21 | host_toolchain="//build/toolchain/linux:arm" 22 | is_clang=false 23 | use_sysroot=true 24 | target_sysroot="/opt/rpi_rootfs/rootfs" 25 | gold_path = "/opt/rpi_rootfs/tools/arm-linux-gnueabihf/bin" 26 | 27 | # target CPU optimization for PI2 28 | target_os="linux" 29 | target_cpu="arm" 30 | arm_arch="armv7-a" 31 | arm_fpu="neon" 32 | arm_float_abi="hard" 33 | arm_use_neon=true 34 | arm_tune="cortex-a7" 35 | rtc_build_with_neon=true 36 | 37 | # 38 | # build option for third party package of WebRTC native code 39 | rtc_use_pipewire=false 40 | libyuv_disable_jpeg=true 41 | use_system_libjpeg=true 42 | # disabled 43 | libcxx_natvis_include=false 44 | libyuv_include_tests=false 45 | rtc_enable_protobuf=false 46 | 47 | # 48 | # codec config options 49 | rtc_use_h264=true 50 | rtc_include_pulse_audio=false 51 | # do not use libaom(AV1 codec) 52 | enable_libaom=false 53 | 54 | # 55 | # WebRTC native package code build options which related to 56 | # target system envirionment 57 | # 58 | rtc_use_x11=false 59 | rtc_use_gtk=false 60 | use_ozone=true 61 | use_aura=false 62 | use_partition_alloc=false 63 | use_allocator_shim=false 64 | use_custom_libcxx=false 65 | is_chrome_branded=true 66 | rtc_include_tests=false 67 | treat_warnings_as_errors=false 68 | 69 | -------------------------------------------------------------------------------- /misc/webrtc_armv6_build_args.gn: -------------------------------------------------------------------------------- 1 | # Build arguments go here. Examples: 2 | # is_component_build = true 3 | # is_debug = false 4 | # See "gn args --list" for available build arguments. 5 | 6 | # 7 | # 8 | # The following two flags are used for debugging. 9 | # 10 | #is_official_build=false 11 | #is_debug=true 12 | 13 | # For package building, we need to chage is_official_build to true and is_debug to false. 14 | # 15 | is_official_build=true 16 | is_debug=false 17 | 18 | is_component_build=false 19 | enable_iterator_debugging=false 20 | 21 | host_toolchain="//build/toolchain/linux:arm" 22 | is_clang=false 23 | use_sysroot=true 24 | target_sysroot="/opt/rpi_rootfs/rootfs" 25 | gold_path = "/opt/rpi_rootfs/tools/arm-linux-gnueabihf/bin" 26 | 27 | # taget CPU optimization for PI ZeroW 28 | target_os="linux" 29 | target_cpu="arm" 30 | arm_version=6 31 | arm_arch="armv6" 32 | arm_float_abi="hard" 33 | arm_use_neon=false 34 | arm_use_thumb=false 35 | arm_fpu="vfp" 36 | arm_optionally_use_neon=false 37 | arm_tune="arm1176jz-s" 38 | rtc_build_with_neon=false 39 | 40 | # 41 | # build option for third party package of WebRTC native code 42 | rtc_use_pipewire=false 43 | libyuv_disable_jpeg=true 44 | use_system_libjpeg=true 45 | # disabled 46 | libcxx_natvis_include=false 47 | libyuv_include_tests=false 48 | rtc_enable_protobuf=false 49 | ffmpeg_use_atomics_fallback=false 50 | 51 | # 52 | # codec config options 53 | rtc_use_h264=true 54 | rtc_include_pulse_audio=false 55 | rtc_libvpx_build_vp9=false 56 | # do not use libaom(AV1 codec) 57 | enable_libaom=false 58 | 59 | # 60 | # WebRTC native package code build options which related to 61 | # target system envirionment 62 | # 63 | rtc_use_x11=false 64 | rtc_use_gtk=false 65 | use_ozone=true 66 | use_aura=false 67 | use_partition_alloc=false 68 | use_allocator_shim=false 69 | use_custom_libcxx=false 70 | is_chrome_branded=true 71 | rtc_include_tests=false 72 | treat_warnings_as_errors=false 73 | 74 | -------------------------------------------------------------------------------- /misc/webrtc_streamer_architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kclyu/rpi-webrtc-streamer/e109e418aa9023009b3b59c95eec2de4721125be/misc/webrtc_streamer_architecture.png -------------------------------------------------------------------------------- /misc/webrtc_x64_build_args.gn: -------------------------------------------------------------------------------- 1 | # Build arguments go here. Examples: 2 | # is_component_build = true 3 | # is_debug = false 4 | # See "gn args --list" for available build arguments. 5 | 6 | #is_official_build=true 7 | #is_debug=false # Relese Version 8 | is_component_build=false 9 | enable_iterator_debugging=false 10 | 11 | host_toolchain="//build/toolchain/linux:x64" 12 | target_os="linux" 13 | is_clang=false 14 | use_sysroot=false 15 | 16 | # 17 | # 18 | use_ozone=true 19 | is_desktop_linux=false 20 | 21 | # 22 | # 23 | is_chrome_branded=true 24 | rtc_use_h264=true 25 | use_openh264=true 26 | rtc_libvpx_build_vp9=false # do not build VP9 27 | rtc_include_tests=false 28 | rtc_include_pulse_audio=false 29 | rtc_enable_protobuf=false 30 | treat_warnings_as_errors=false 31 | 32 | -------------------------------------------------------------------------------- /mk/config_libwebsockets.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # this script will accept RPI_ROOTFS path a argument 3 | # e.g: ./config_libwebsocket.sh /opt/rpi_rootfs 4 | # if argument does not exist, the default rpi_rootfs path will be used 5 | if [ "$#" -lt 1 ]; then 6 | RPI_ROOTFS_CMAKE=${HOME}/Workspace/rpi_rootfs/PI.cmake 7 | else 8 | RPI_ROOTFS_CMAKE=$1/PI.cmake 9 | fi 10 | 11 | RWS_LIBRARY_DIR=../lib 12 | 13 | LIBWEBSOCKETS_BASENAME=libwebsockets-3.1.0 14 | LIBWEBSOCKET_DIR=${RWS_LIBRARY_DIR}/libwebsockets 15 | LIBWEBSOCKET_BUILD_DIR=${RWS_LIBRARY_DIR}/libwebsockets/arm_build 16 | LIBWEBSOCKETS_LIBRARY=${LIBWEBSOCKET_BUILD_DIR}/lib/libwebsockets.a 17 | 18 | ## 19 | ## Check whether rpi_rootfs repo exist 20 | if [ ! -e ${RPI_ROOTFS_CMAKE} ] 21 | then 22 | echo "rpi_rootfs does not exists" 23 | echo "You need to configure rpi_rootfs repo to build" 24 | echo "Please check https://github.com/kclyu/rpi_rootfs" 25 | exit -1 26 | fi 27 | 28 | if [ -e ${RWS_LIBRARY_DIR}/${LIBWEBSOCKETS_BASENAME}.zip ] 29 | then 30 | # checking libwebsockets library build directory exist 31 | if [ ! -d ${LIBWEBSOCKET_DIR} ] 32 | then 33 | echo "extracting libwebsocket library in lib" 34 | cd ${RWS_LIBRARY_DIR} && unzip ${LIBWEBSOCKETS_BASENAME}.zip && \ 35 | mv ${LIBWEBSOCKETS_BASENAME} ${LIBWEBSOCKET_DIR} 36 | fi 37 | 38 | # checking libwebsockets library archive file 39 | if [ ! -f ${LIBWEBSOCKETS_LIBRARY} ] 40 | then 41 | echo "start building libwebsockets library" 42 | mkdir -p ${LIBWEBSOCKET_BUILD_DIR} 43 | cd ${LIBWEBSOCKET_BUILD_DIR} && \ 44 | cmake .. -DCMAKE_TOOLCHAIN_FILE=${RPI_ROOTFS_CMAKE} \ 45 | -DCMAKE_BUILD_TYPE=Debug -DLWS_WITH_SSL=OFF -DLWS_WITH_SHARED=OFF \ 46 | -DLWS_WITH_LIBEV=0 && make 47 | else 48 | echo "libwebsockets.a already exist" 49 | fi 50 | else 51 | echo "Zipfile ${RWS_LIBRARY_DIR}/${LIBWEBSOCKETS_BASENAME}.zip not found" 52 | fi 53 | exit 0 54 | 55 | -------------------------------------------------------------------------------- /mk/cross_arm_build.mk: -------------------------------------------------------------------------------- 1 | 2 | ifdef RPI_ROOTFS 3 | SYSROOT=$(RPI_ROOTFS)/rootfs 4 | else 5 | SYSROOT=/opt/rpi_rootfs/rootfs 6 | endif 7 | 8 | # validate sysroot path 9 | ifeq ("$(wildcard $(SYSROOT))","") 10 | $(error sysroot is is not configurd, please configure the sysroot/rootfs in Rpi_RootFS) 11 | endif 12 | 13 | CC=arm-linux-gnueabihf-gcc 14 | CXX=arm-linux-gnueabihf-g++ 15 | AR=arm-linux-gnueabihf-ar 16 | LD=arm-linux-gnueabihf-ld 17 | AS=arm-linux-gnueabihf-as 18 | RANLIB=arm-linux-gnueabihf-ranlib 19 | 20 | # 21 | # WebRTC source tree and object directory 22 | # 23 | ifndef WEBRTC_ROOT 24 | WEBRTC_ROOT=$(HOME)/Workspace/webrtc 25 | endif 26 | 27 | WEBRTC_OUTPUT=out/$(TARGET_ARCH_BUILD) 28 | WEBRTC_LIBPATH=$(WEBRTC_ROOT)/src/$(WEBRTC_COUTPUT) 29 | 30 | ## WebRTC library build script 31 | # GN Build 32 | WEBRTC_NINJA_EXTACTOR=../mk/webrtc_library_gn.py $(WEBRTC_ROOT) $(WEBRTC_OUTPUT) 33 | 34 | WEBRTC_CFLAGS=$(shell $(WEBRTC_NINJA_EXTACTOR) cflags) 35 | WEBRTC_CCFLAGS=$(shell $(WEBRTC_NINJA_EXTACTOR) ccflags) 36 | WEBRTC_DEFINES=$(shell $(WEBRTC_NINJA_EXTACTOR) defines) 37 | 38 | WEBRTC_FLAGS_INCLUDES = -I$(WEBRTC_ROOT)/src 39 | WEBRTC_FLAGS_INCLUDES += $(shell $(WEBRTC_NINJA_EXTACTOR) includes) 40 | 41 | WEBRTC_BUILD_LIBS=$(shell $(WEBRTC_NINJA_EXTACTOR) libs) 42 | WEBRTC_SYSLIBS = $(shell $(WEBRTC_NINJA_EXTACTOR) syslibs) 43 | WEBRTC_LDFLAGS = $(shell $(WEBRTC_NINJA_EXTACTOR) ldflags) 44 | 45 | ifdef VERBOSE 46 | $(info WEBRTC_CFLAGS is "$(WEBRTC_CFLAGS)") 47 | $(info WEBRTC_CCFLAGS is "$(WEBRTC_CCFLAGS)") 48 | $(info WEBRTC_FLAGS_INCLUDES is "$(WEBRTC_FLAGS_INCLUDES)") 49 | $(info WEBRTC_SYSLIBS is "$(WEBRTC_SYSLIBS)") 50 | $(info WEBRTC_LDFLAGS is "$(WEBRTC_LDFLAGS)") 51 | $(info WEBRTC_BUILD_LIBS is "$(WEBRTC_BUILD_LIBS)") 52 | endif 53 | 54 | 55 | -------------------------------------------------------------------------------- /mk/cross_mmal.mk: -------------------------------------------------------------------------------- 1 | 2 | # 3 | # Variables for MMAL(raspivid) compilation 4 | # 5 | PI_INCLUDE=$(SYSROOT)/opt/vc/include 6 | MMAL_CFLAGS+=-D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS -DTARGET_POSIX \ 7 | -D_LINUX -fPIC -DPIC -D_REENTRANT -D_LARGEFILE64_SOURCE \ 8 | -D_FILE_OFFSET_BITS=64 -U_FORTIFY_SOURCE -Wall -g -DHAVE_LIBOPENMAX=2 \ 9 | -DOMX -DOMX_SKIP64BIT -ftree-vectorize -pipe -DUSE_EXTERNAL_OMX \ 10 | -DHAVE_LIBBCM_HOST -DUSE_EXTERNAL_LIBBCM_HOST -DUSE_VCHIQ_ARM 11 | 12 | MMAL_INCLUDES+=-I$(PI_INCLUDE)/interface/vcos/pthreads \ 13 | -I$(PI_INCLUDE)/interface/vmcs_host/linux \ 14 | -I$(PI_INCLUDE)/interface/vmcs_host \ 15 | -I$(PI_INCLUDE)/interface/vchiq_arm \ 16 | -I$(PI_INCLUDE) -I$(PI_INCLUDE)/interface/mmal 17 | 18 | MMAL_LDFLAGS+=-Wl,--no-as-needed -L$(SYSROOT)/opt/vc/lib/ -lmmal_core -lmmal \ 19 | -lmmal_util -lvcos -lbcm_host -lmmal_vc_client -lmmal_components \ 20 | -lvchiq_arm 21 | 22 | -------------------------------------------------------------------------------- /mk/libavahi_arm.mk: -------------------------------------------------------------------------------- 1 | # 2 | # Avahi library compiler and linker flags definiton 3 | # 4 | AVAHI_INCLUDES=-I$(SYSROOT)/usr/include 5 | 6 | # LD FLAGS 7 | AVAHI_LIBS=-L$(SYSROOT)/usr/lib -lavahi-client -lavahi-common 8 | -------------------------------------------------------------------------------- /mk/libwebsocket_arm_build.mk: -------------------------------------------------------------------------------- 1 | # 2 | # libwebsocket compiler and linker definiton 3 | # 4 | # 5 | LIBWEBSOCKETS_ROOT=$(HOME)/Workspace/rpi-webrtc-streamer/lib/libwebsockets 6 | 7 | # CC FLAGS 8 | LWS_C_FLAGS=-Wall -fvisibility=hidden -pthread 9 | LWS_INCLUDES=-I$(LIBWEBSOCKETS_ROOT)/arm_build \ 10 | -I$(LIBWEBSOCKETS_ROOT)/arm_build/include \ 11 | -I$(LIBWEBSOCKETS_ROOT) 12 | 13 | # LD FLAGS 14 | LWS_LIBS=$(LIBWEBSOCKETS_ROOT)/arm_build/lib/libwebsockets.a 15 | LWS_SYS_LIBS=-lz -lssl -lcrypto -lm 16 | -------------------------------------------------------------------------------- /mk/libwebsocket_native_gcc.mk: -------------------------------------------------------------------------------- 1 | # 2 | # libwebsocket compiler and linker definiton 3 | # 4 | # 5 | LIBWEBSOCKETS_ROOT=$(HOME)/Workspace/rpi-webrtc-streamer/lib/libwebsockets 6 | 7 | 8 | # CC FLAGS 9 | #LWS_C_FLAGS=-Wall -Werror -fvisibility=hidden -pthread 10 | LWS_C_FLAGS=-Wall -fvisibility=hidden -pthread 11 | LWS_INCLUDES=-I$(LIBWEBSOCKETS_ROOT)/linux_build 12 | 13 | # LD FLAGS 14 | LWS_LIBS=$(LIBWEBSOCKETS_ROOT)/linux_build/lib/libwebsockets.a 15 | LWS_SYS_LIBS=-lz -lssl -lcrypto -lm 16 | -------------------------------------------------------------------------------- /mk/native_gcc.mk: -------------------------------------------------------------------------------- 1 | # 2 | # WebRTC source tree and object directory 3 | # 4 | WEBRTC_ROOT=$(HOME)/Workspace/webrtc 5 | WEBRTC_OUTPUT=x64_build 6 | WEBRTC_LIBPATH=$(WEBRTC_ROOT)/src/$(WEBRTC_COUTPUT) 7 | 8 | ## WebRTC library build script 9 | # GN Build 10 | WEBRTC_NINJA_EXTACTOR=./scripts/webrtc_library_gn.py $(WEBRTC_ROOT) $(WEBRTC_OUTPUT) 11 | 12 | WEBRTC_CFLAGS=$(shell $(WEBRTC_NINJA_EXTACTOR) cflags) 13 | WEBRTC_CCFLAGS=$(shell $(WEBRTC_NINJA_EXTACTOR) ccflags) 14 | WEBRTC_DEFINES=$(shell $(WEBRTC_NINJA_EXTACTOR) defines) 15 | 16 | WEBRTC_FLAGS_INCLUDES = -I$(WEBRTC_ROOT)/src 17 | WEBRTC_FLAGS_INCLUDES += $(shell $(WEBRTC_NINJA_EXTACTOR) includes) 18 | 19 | WEBRTC_BUILD_LIBS=$(shell $(WEBRTC_NINJA_EXTACTOR) libs) 20 | WEBRTC_SYSLIBS = $(shell $(WEBRTC_NINJA_EXTACTOR) syslibs) 21 | WEBRTC_LDFLAGS = $(shell $(WEBRTC_NINJA_EXTACTOR) ldflags) 22 | 23 | ifdef VERBOSE 24 | $(info WEBRTC_CFLAGS is "$(WEBRTC_CFLAGS)") 25 | $(info WEBRTC_CCFLAGS is "$(WEBRTC_CCFLAGS)") 26 | $(info WEBRTC_FLAGS_INCLUDES is "$(WEBRTC_FLAGS_INCLUDES)") 27 | $(info WEBRTC_SYSLIBS is "$(WEBRTC_SYSLIBS)") 28 | $(info WEBRTC_LDFLAGS is "$(WEBRTC_LDFLAGS)") 29 | $(info WEBRTC_BUILD_LIBS is "$(WEBRTC_BUILD_LIBS)") 30 | endif 31 | -------------------------------------------------------------------------------- /mk/validate_variables.mk: -------------------------------------------------------------------------------- 1 | # 2 | # ARCH can only be used in either arm or armv6. 3 | # arm : above armv6 4 | # armv6 : armv6 (raspberry pi zero) 5 | ARCH=arm 6 | ifeq ($(ARCH),arm) 7 | TARGET_ARCH_BUILD=arm_build 8 | else ifeq ($(ARCH),armv6) 9 | TARGET_ARCH_BUILD=armv6_build 10 | else 11 | $(error Unknown ARCH $(ARCH) type argument) 12 | endif 13 | 14 | # 15 | # Checking RPI_ROOTFS variable 16 | # 17 | ifndef RPI_ROOTFS 18 | # default RPI_ROOTFS variable 19 | RPI_ROOTFS=/opt/rpi_rootfs 20 | endif 21 | ifeq ("$(wildcard $(RPI_ROOTFS))","") 22 | define RPI_ROOTFS_ERROR_MESG 23 | Rpi_RootFS is not configured, please configure rpi_rootfs 24 | You need to configure rpi_rootfs repo to build,Please check https://github.com/kclyu/rpi_rootfs 25 | endef 26 | $(error $(RPI_ROOTFS_ERROR_MESG)) 27 | endif 28 | 29 | # 30 | # Checking WEBRTC_ROOT variable 31 | # 32 | ifndef WEBRTC_ROOT 33 | # default WEBRTC_ROOT variable 34 | WEBRTC_ROOT=$(HOME)/Workspace/webrtc 35 | endif 36 | ifeq ("$(wildcard $(WEBRTC_ROOT)/src)","") 37 | define WEBRTC_ROOT_ERROR_MESG 38 | WebRTC native source code package is not configured, please configure it before try RWS building 39 | endef 40 | $(error $(WEBRTC_ROOT_ERROR_MESG)) 41 | endif 42 | 43 | -------------------------------------------------------------------------------- /scripts/rws.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Rpi WebRTC Streamer 3 | After=syslog.target 4 | 5 | [Service] 6 | Type=simple 7 | PIDFile=/var/run/webrtc-streamer.pid 8 | ExecStart=/opt/rws/webrtc-streamer --log /opt/rws/log 9 | StandardOutput=journal 10 | StandardError=journal 11 | Restart=always 12 | RestartSec=5 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /src/Makefile: -------------------------------------------------------------------------------- 1 | 2 | # including make scripts supports RWS building 3 | include ../mk/validate_variables.mk # validating required variable to build 4 | include ../mk/cross_arm_build.mk 5 | include ../mk/cross_mmal.mk 6 | include ../mk/libwebsocket_arm_build.mk 7 | include ../mk/libavahi_arm.mk 8 | 9 | # 10 | # including compat as source directory 11 | # 12 | RWS_INSTALL_DIR=\"/opt/rws\" 13 | RWS_VERSION=\"$(shell git describe --abbrev=16 --dirty --always --tags)\" 14 | WEBRTC_GIT=$(shell (cd $(WEBRTC_ROOT)/src/; git describe --abbrev=16 --dirty --always --tags)) 15 | WEBRTC_CRPOSITION=$(shell (cd $(WEBRTC_ROOT)/src/;\ 16 | git log -1 | gawk 'match($$0,/Cr-Commit-Position/){print $$0}' | sed 's/ //g')) 17 | 18 | CCFLAGS += -DINSTALL_DIR=$(RWS_INSTALL_DIR) $(LWS_C_FLAGS) $(WEBRTC_CCFLAGS) 19 | CFLAGS += -DINSTALL_DIR=$(RWS_INSTALL_DIR) $(WEBRTC_CFLAGS) 20 | 21 | INCLUDES += $(LWS_INCLUDES) $(WEBRTC_DEFINES) $(WEBRTC_FLAGS_INCLUDES) \ 22 | $(H264BITSTREAM_INCLUDES) $(MMAL_INCLUDES) $(AVAHI_INCLUDES) \ 23 | -I$(SYSROOT)/usr/include/arm-linux-gnueabihf 24 | 25 | # adding abseil-cpp include path in this makefile 26 | INCLUDES += -I$(WEBRTC_ROOT)/src/third_party/abseil-cpp/ 27 | 28 | # for Raspbian Strech 29 | BUILD_LIBS += $(WEBRTC_BUILD_LIBS) $(LWS_LIBS) $(AVAHI_LIBS) 30 | SYSLIBS += $(LWS_SYS_LIBS) $(WEBRTC_SYSLIBS) 31 | LDFLAGS += $(WEBRTC_LDFLAGS) $(MMAL_LDFLAGS) 32 | 33 | # Adding Version Information 34 | CCFLAGS += -D__RWS_VERSION__=$(RWS_VERSION) \ 35 | -D__WEBRTC_VERSION__="\"$(WEBRTC_GIT),$(WEBRTC_CRPOSITION)\"" 36 | 37 | # 38 | # Debugging purpose only 39 | # 40 | ifdef VERBOSE 41 | $(info LWS_C_FLAGS is "$(LWS_C_FLAGS)") 42 | $(info WEBRTC_CCFLAGS is "$(WEBRTC_CCFLAGS)") 43 | $(info MMAL_CFLAGS is "$(MMAL_CFLAGS)") 44 | $(info RWS_INSTALL_DIR is "$(RWS_INSTALL_DIR)") 45 | $(info CFLAGS is "$(CFLAGS)") 46 | $(info CCFLAGS is "$(CCFLAGS)") 47 | $(info INCLUDES is "$(INCLUDES)") 48 | $(info SYSLIBS is "$(SYSLIBS)") 49 | $(info LDFLAGS is "$(LDFLAGS)") 50 | $(info BUILD_LIBS is "$(BUILD_LIBS)") 51 | endif 52 | 53 | # 54 | # Raspberry PI testing host 55 | ifndef RPI_HOST_URL 56 | RPI_HOST_URL=pi@10.0.0.11:~/Workspace/client 57 | endif 58 | 59 | # TARGET 60 | # 61 | TARGET = ../webrtc-streamer 62 | TARGET_LWS_LIBS = $(LWS_LIBS) 63 | 64 | # 65 | # source from WebRTC native library for compat 66 | # 67 | COMPAT.CC = compat/optionsfile.cc compat/status.cc compat/status_payload_printer.cc \ 68 | compat/statusor.cc 69 | # 70 | # source & object list definition 71 | # 72 | SOURCES.CC = websocket_server.cc websocket_server_callback.cc app_clientinfo.cc \ 73 | app_channel.cc direct_socket.cc raspi_decoder_dummy.cc raspi_decoder.cc \ 74 | raspi_encoder.cc raspi_encoder_impl.cc mmal_wrapper.cc utils.cc main.cc \ 75 | streamer_signaling.cc streamer.cc raspi_quality_config.cc app_ws_client.cc \ 76 | file_log_sink.cc raspi_motion.cc raspi_motionvector.cc config_streamer.cc \ 77 | raspi_motionblob.cc raspi_motionfile.cc config_media.cc config_motion.cc \ 78 | utils_pc_config.cc utils_pc_strings.cc session_config.cc frame_queue.cc \ 79 | file_writer_handle.cc log_rotating_stream.cc wstreamer_types.cc mmal_still_capture.cc \ 80 | 81 | SOURCES.C = websocket_server_util.c mmal_video.c mmal_video_reset.c mmal_util.c \ 82 | raspicli.c raspicamcontrol.c mmal_still.c raspipreview.c mdns_publish.c 83 | 84 | OBJECTS.CC = $(SOURCES.CC:.cc=.o) $(COMPAT.CC:.cc=.o) 85 | OBJECTS.C = $(SOURCES.C:.c=.o) 86 | OBJECTS = $(OBJECTS.CC) $(OBJECTS.C) 87 | 88 | all: $(TARGET_LWS_LIBS) $(TARGET) 89 | 90 | # 91 | # Makefile rules... 92 | # 93 | .c.o : $(OBJECTS.C) 94 | $(CC) -I. $(CFLAGS) $(INCLUDES) $(MMAL_CFLAGS) -D__MMAL_ENCODER_DEBUG__ -c $< -o $@ 95 | 96 | .cc.o : $(OBJECTS.CC) 97 | $(CXX) -I. $(CFLAGS) $(CCFLAGS) $(MMAL_CFLAGS) $(INCLUDES) -c $< -o $@ 98 | 99 | $(TARGET): $(OBJECTS) 100 | $(CXX) $(LDFLAGS) -o $(TARGET) -Wl,--start-group $(OBJECTS) $(BUILD_LIBS) -Wl,--end-group $(SYSLIBS) 101 | 102 | clean: 103 | rm -f *.o *.dwo compat/*.o compat/*.dwo $(TARGET) 104 | 105 | distclean: clean 106 | rm -fr ../lib/libwebsockets 107 | 108 | $(TARGET_LWS_LIBS) : 109 | ../mk/config_libwebsockets.sh $(RPI_ROOTFS) 110 | 111 | # 112 | # helper rules 113 | # 114 | rcp: $(TARGET) 115 | rsync -v -u -r --stats $(TARGET) *.cc *.h *.dwo compat $(RPI_HOST_URL) 116 | 117 | rcp_full: $(TARGET) 118 | rsync -v -u -r --stats $(TARGET) ../LICENSE ../tools ../etc ../etc/template ../web-root \ 119 | ../scripts $(RPI_HOST_URL) 120 | 121 | web: $(TARGET) 122 | rsync -v -u -r -L --stats ../web-root $(RPI_HOST_URL) 123 | 124 | # 125 | # You need to install clang-format-9 126 | format: 127 | find . -maxdepth 2 -iname \*.h -o -iname \*.cc -o -iname \*.c \ 128 | | xargs clang-format-9 -style=file -i -fallback-style=none 129 | 130 | # 131 | # You need to configure ccls and bear(2.4.3 >= version) to generate compile_commands.json 132 | ccls: 133 | make clean 134 | bear --use-cc arm-linux-gnueabihf-gcc --use-c++ arm-linux-gnueabihf-g++ make 135 | rm -f ../compile_commands.json 136 | mv compile_commands.json ../ 137 | 138 | -------------------------------------------------------------------------------- /src/app_channel.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #include "app_channel.h" 31 | 32 | #include 33 | 34 | #include 35 | #include 36 | 37 | #include "absl/strings/str_format.h" 38 | #include "config_media.h" 39 | #include "utils.h" 40 | #include "websocket_server.h" 41 | 42 | namespace { 43 | 44 | constexpr char kDefaultHttpWebMount[] = "/"; 45 | constexpr char kMotionFileLink[] = "motion"; 46 | constexpr char kStillFileLink[] = "still"; 47 | 48 | } // namespace 49 | 50 | //////////////////////////////////////////////////////////////////////////////// 51 | // 52 | // Application Channel 53 | // 54 | //////////////////////////////////////////////////////////////////////////////// 55 | AppChannel::AppChannel() : is_inited_(false) {} 56 | 57 | bool AppChannel::AppInitialize(StreamerProxy* proxy, 58 | ConfigStreamer& config_streamer, 59 | ConfigMotion& config_motion) { 60 | std::string websocket_url_path; 61 | std::string http_mount_origin; 62 | int port_num; 63 | 64 | // LibWebSocket debug log 65 | if (config_streamer.GetLwsDebugEnable()) { 66 | RTC_LOG(INFO) << "enabling debug logging message of websocket library"; 67 | LogLevel(LibWebSocketServer::DEBUG_LEVEL_ALL); 68 | }; 69 | 70 | // need to initialize the motion mount after WebRoot initialization. 71 | http_mount_origin = config_streamer.GetWebRootPath(); 72 | RTC_LOG(INFO) << "Using http file mapping : " << http_mount_origin; 73 | AddHttpWebMount(kDefaultHttpWebMount, http_mount_origin); 74 | 75 | if (config_motion.GetDetectionEnable()) { 76 | std::string motion_file_link = 77 | absl::StrFormat("%s/%s", http_mount_origin, kMotionFileLink); 78 | utils::DeleteFile(motion_file_link); 79 | utils::SymLink(config_motion.GetDirectory(), motion_file_link); 80 | RTC_LOG(INFO) << "Using motion video mapping : " 81 | << config_motion.GetDirectory() 82 | << ", link: " << motion_file_link; 83 | } 84 | if (ConfigMediaSingleton::Instance()->GetStillEnable()) { 85 | std::string still_file_link = 86 | absl::StrFormat("%s/%s", http_mount_origin, kStillFileLink); 87 | utils::DeleteFile(still_file_link); 88 | utils::SymLink(ConfigMediaSingleton::Instance()->GetStillDirectory(), 89 | still_file_link); 90 | RTC_LOG(INFO) << "Using still image mapping : " 91 | << ConfigMediaSingleton::Instance()->GetStillDirectory() 92 | << ", link: " << still_file_link; 93 | } 94 | 95 | port_num = config_streamer.GetWebSocketPort(); 96 | RTC_LOG(INFO) << "WebSocket port num : " << port_num; 97 | if (Init(port_num) == false) return false; 98 | 99 | ws_client_.reset(new AppWsClient(proxy)); 100 | 101 | websocket_url_path = config_streamer.GetRwsWsUrlPath(); 102 | RTC_LOG(INFO) << "Using RWS WS client url : " << websocket_url_path; 103 | ws_client_->RegisterWebSocketMessage(this); 104 | ws_client_->RegisterConfigStreamer(&config_streamer); 105 | AddWebSocketHandler(websocket_url_path, SINGLE_INSTANCE, ws_client_.get()); 106 | 107 | is_inited_ = true; 108 | return true; 109 | } 110 | 111 | AppChannel::~AppChannel() {} 112 | -------------------------------------------------------------------------------- /src/app_channel.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef APP_CHANNEL_H_ 31 | #define APP_CHANNEL_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "app_ws_client.h" 37 | #include "config_motion.h" 38 | #include "config_streamer.h" 39 | #include "websocket_server.h" 40 | 41 | class AppChannel : public LibWebSocketServer { 42 | public: 43 | explicit AppChannel(); 44 | ~AppChannel(); 45 | bool AppInitialize(StreamerProxy* proxy, ConfigStreamer& config_streamer, 46 | ConfigMotion& config_motion); 47 | 48 | private: 49 | bool is_inited_; 50 | std::unique_ptr ws_client_; 51 | }; 52 | 53 | #endif // APP_CHANNEL_H_ 54 | -------------------------------------------------------------------------------- /src/app_clientinfo.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #include "app_clientinfo.h" 31 | 32 | #include 33 | #include 34 | #include 35 | 36 | #include 37 | #include 38 | 39 | #include "rtc_base/checks.h" 40 | #include "rtc_base/logging.h" 41 | 42 | namespace { 43 | 44 | const uint32_t kClientIDLength = 8; 45 | const uint32_t kRoomIDLength = 9; 46 | const uint32_t kMaxClientID = 99999999; 47 | const uint32_t kMaxRoomID = 999999999; 48 | const uint64_t kWaitTimeout = 1000; 49 | 50 | } // namespace 51 | 52 | //////////////////////////////////////////////////////////////////////////////// 53 | // 54 | // AppClientInfo 55 | // 56 | //////////////////////////////////////////////////////////////////////////////// 57 | AppClientInfo::AppClientInfo() : state_(ClientState::CLIENT_DISCONNECTED) {} 58 | 59 | bool AppClientInfo::Register(int sockid, int room_id, int client_id) { 60 | webrtc::MutexLock lock(&mutex_); 61 | RTC_LOG(LS_VERBOSE) << __FUNCTION__ << "WS id: " << sockid << ", Roomid " 62 | << room_id << ",Client id: " << client_id; 63 | RTC_DCHECK(sockid > 0 && room_id > 0 && client_id > 0) 64 | << "id must be greater then 0"; 65 | switch (state_) { 66 | case ClientState::CLIENT_REGISTERED: 67 | if (room_id_ == room_id && client_id_ == client_id) { 68 | RTC_LOG(LS_WARNING) << "Doing register second times"; 69 | return true; 70 | } 71 | return false; // already registered by another client 72 | // All other state can be changed to CONNECTED 73 | case ClientState::CLIENT_DISCONNECTED: 74 | room_id_ = room_id; 75 | client_id_ = client_id; 76 | break; 77 | default: 78 | break; 79 | } 80 | sockid_ = sockid; 81 | 82 | // this type of request generated by testing page of browser 83 | if (room_id_ != 0 || client_id_ != 0) { 84 | RTC_LOG(LS_WARNING) 85 | << "internal id (room,client) does not cleared correctly" 86 | << " or, invalid/unknown state transition"; 87 | } 88 | room_id_ = room_id; 89 | client_id_ = client_id; 90 | 91 | state_ = CLIENT_REGISTERED; 92 | return true; 93 | } 94 | 95 | bool AppClientInfo::Disconnect(int sockid) { 96 | webrtc::MutexLock lock(&mutex_); 97 | RTC_LOG(INFO) << __FUNCTION__ << ": sockid id " << sockid; 98 | if (sockid_ != sockid) { 99 | RTC_LOG(INFO) << "sockid does not match."; 100 | return false; 101 | }; 102 | switch (state_) { 103 | case ClientState::CLIENT_REGISTERED: 104 | state_ = ClientState::CLIENT_DISCONNECTED; 105 | return true; 106 | default: 107 | break; 108 | } 109 | return true; 110 | } 111 | 112 | bool AppClientInfo::GetSockId(int client_id, int& sockid) { 113 | RTC_LOG(LS_VERBOSE) << __FUNCTION__ << ":Client id: " << client_id; 114 | RTC_DCHECK(client_id_ == client_id); 115 | if (client_id_ == client_id) { 116 | sockid = sockid_; 117 | return true; 118 | } 119 | return false; 120 | } 121 | 122 | bool AppClientInfo::IsRegistered(int sockid) { 123 | return state_ == ClientState::CLIENT_REGISTERED && sockid_ == sockid; 124 | } 125 | 126 | void AppClientInfo::Reset() { 127 | RTC_LOG(LS_VERBOSE) << __FUNCTION__; 128 | client_id_ = room_id_ = sockid_ = 0; 129 | state_ = CLIENT_DISCONNECTED; 130 | } 131 | -------------------------------------------------------------------------------- /src/app_clientinfo.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ 28 | 29 | #ifndef APP_CLIENTINFO_H_ 30 | #define APP_CLIENTINFO_H_ 31 | 32 | #include 33 | #include 34 | #include 35 | 36 | #include "rtc_base/checks.h" 37 | #include "rtc_base/strings/json.h" 38 | #include "rtc_base/synchronization/mutex.h" 39 | 40 | // AppClient does not have room concept and only one clinet connection.. 41 | // so room_id and client_id will be held within AppClientInfo 42 | class AppClientInfo { 43 | enum ClientState { 44 | CLIENT_DISCONNECTED = 0, 45 | CLIENT_REGISTERED, 46 | CLIENT_DISCONNECT_WAIT 47 | }; 48 | 49 | public: 50 | explicit AppClientInfo(); 51 | ~AppClientInfo(){}; 52 | 53 | bool Register(int sockid, int room_id, int client_id); 54 | bool Disconnect(int sockid); 55 | bool GetSockId(int client_id, int& sockid); 56 | bool IsRegistered(int sockid); 57 | void Reset(); 58 | 59 | private: 60 | webrtc::Mutex mutex_; 61 | // Status transition 62 | ClientState state_; 63 | int client_id_; 64 | int room_id_; 65 | int sockid_; 66 | }; 67 | 68 | #endif // APP_CLIENTINFO_H_ 69 | -------------------------------------------------------------------------------- /src/app_ws_client.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef APP_WS_CLIENT_H_ 31 | #define APP_WS_CLIENT_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "api/media_stream_interface.h" 37 | #include "api/peer_connection_interface.h" 38 | #include "app_clientinfo.h" 39 | #include "compat/optionsfile.h" 40 | #include "config_media.h" 41 | #include "config_streamer.h" 42 | #include "rtc_base/message_handler.h" 43 | #include "session_config.h" 44 | #include "streamer_signaling.h" 45 | #include "utils.h" 46 | #include "websocket_server.h" 47 | 48 | class AppWsClient : public rtc::MessageHandler, 49 | public WebSocketHandler, 50 | public SignalingChannelHelper { 51 | public: 52 | enum EventType { EventNotice, EventError }; 53 | 54 | explicit AppWsClient(StreamerProxy* proxy); 55 | ~AppWsClient(); 56 | 57 | // register WebSocket Server for SendMessage 58 | void RegisterWebSocketMessage(WebSocketMessage* server_instance); 59 | void RegisterConfigStreamer(ConfigStreamer* config_streamer); 60 | 61 | // WebSocket Handler 62 | void OnConnect(int sockid) override; 63 | bool OnMessage(int sockid, const std::string& message) override; 64 | void OnDisconnect(int sockid) override; 65 | void OnError(int sockid, const std::string& message) override; 66 | 67 | // SignalingInbound interface 68 | bool SendMessageToPeer(const int peer_id, 69 | const std::string& message) override; 70 | void ReportEvent(const int peer_id, bool drop_connection, 71 | const std::string& message) override; 72 | 73 | private: 74 | // message handler interface 75 | void OnMessage(rtc::Message* msg) override; 76 | 77 | void SendResponse(int sockid, bool success, const std::string& type, 78 | const std::string& transaction, const std::string& data, 79 | const std::string& error_mesg); 80 | void SendEvent(int sockid, EventType is_event, 81 | const std::string& event_mesg); 82 | 83 | std::string ws_url_; 84 | AppClientInfo app_client_; 85 | SessionConfig session_config_; 86 | WebSocketMessage* websocket_message_; 87 | 88 | // WebSocket chunked frames 89 | std::string chunked_frames_; 90 | int num_chunked_frames_; 91 | std::string deviceid_; 92 | bool deviceid_inited_; 93 | ConfigMedia* config_media_; 94 | ConfigStreamer* config_streamer_; 95 | }; 96 | 97 | #endif // APP_WS_CLIENT_H_ 98 | -------------------------------------------------------------------------------- /src/compat/optionsfile.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2008 The WebRTC Project Authors. All rights reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. An additional intellectual property rights grant can be found 7 | * in the file PATENTS. All contributing project authors may 8 | * be found in the AUTHORS file in the root of the source tree. 9 | */ 10 | 11 | #ifndef RTC_BASE_OPTIONSFILE_H_ 12 | #define RTC_BASE_OPTIONSFILE_H_ 13 | 14 | #include 15 | #include 16 | 17 | namespace rtc { 18 | 19 | // Implements storage of simple options in a text file on disk. This is 20 | // cross-platform, but it is intended mostly for Linux where there is no 21 | // first-class options storage system. 22 | class OptionsFile { 23 | public: 24 | OptionsFile(const std::string& path); 25 | ~OptionsFile(); 26 | 27 | // Loads the file from disk, overwriting the in-memory values. 28 | bool Load(bool verbose = false); 29 | // Saves the contents in memory, overwriting the on-disk values. 30 | bool Save(); 31 | 32 | bool GetStringValue(const std::string& option, std::string* out_val) const; 33 | bool GetIntValue(const std::string& option, int* out_val) const; 34 | bool SetStringValue(const std::string& option, const std::string& val); 35 | bool SetIntValue(const std::string& option, int val); 36 | bool RemoveValue(const std::string& option); 37 | 38 | private: 39 | typedef std::map OptionsMap; 40 | 41 | static bool IsLegalName(const std::string& name); 42 | static bool IsLegalValue(const std::string& value); 43 | 44 | std::string path_; 45 | OptionsMap options_; 46 | }; 47 | 48 | } // namespace rtc 49 | 50 | #endif // RTC_BASE_OPTIONSFILE_H_ 51 | -------------------------------------------------------------------------------- /src/compat/status_payload_printer.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Abseil Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | #include "absl/status/status_payload_printer.h" 15 | 16 | #include 17 | 18 | #include "absl/base/attributes.h" 19 | #include "absl/base/internal/atomic_hook.h" 20 | 21 | namespace absl { 22 | ABSL_NAMESPACE_BEGIN 23 | namespace status_internal { 24 | 25 | ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES 26 | static absl::base_internal::AtomicHook storage; 27 | 28 | void SetStatusPayloadPrinter(StatusPayloadPrinter printer) { 29 | storage.Store(printer); 30 | } 31 | 32 | StatusPayloadPrinter GetStatusPayloadPrinter() { 33 | return storage.Load(); 34 | } 35 | 36 | } // namespace status_internal 37 | ABSL_NAMESPACE_END 38 | } // namespace absl 39 | -------------------------------------------------------------------------------- /src/compat/statusor.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Abseil Authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | #include "absl/status/statusor.h" 15 | 16 | #include 17 | #include 18 | 19 | #include "absl/base/internal/raw_logging.h" 20 | #include "absl/status/status.h" 21 | #include "absl/strings/str_cat.h" 22 | 23 | namespace absl { 24 | ABSL_NAMESPACE_BEGIN 25 | 26 | BadStatusOrAccess::BadStatusOrAccess(absl::Status status) 27 | : status_(std::move(status)) {} 28 | 29 | BadStatusOrAccess::~BadStatusOrAccess() = default; 30 | const char* BadStatusOrAccess::what() const noexcept { 31 | return "Bad StatusOr access"; 32 | } 33 | 34 | const absl::Status& BadStatusOrAccess::status() const { return status_; } 35 | 36 | namespace internal_statusor { 37 | 38 | void Helper::HandleInvalidStatusCtorArg(absl::Status* status) { 39 | const char* kMessage = 40 | "An OK status is not a valid constructor argument to StatusOr"; 41 | #ifdef NDEBUG 42 | ABSL_INTERNAL_LOG(ERROR, kMessage); 43 | #else 44 | ABSL_INTERNAL_LOG(FATAL, kMessage); 45 | #endif 46 | // In optimized builds, we will fall back to InternalError. 47 | *status = absl::InternalError(kMessage); 48 | } 49 | 50 | void Helper::Crash(const absl::Status& status) { 51 | ABSL_INTERNAL_LOG( 52 | FATAL, 53 | absl::StrCat("Attempting to fetch value instead of handling error ", 54 | status.ToString())); 55 | } 56 | 57 | void ThrowBadStatusOrAccess(absl::Status status) { 58 | #ifdef ABSL_HAVE_EXCEPTIONS 59 | throw absl::BadStatusOrAccess(std::move(status)); 60 | #else 61 | ABSL_INTERNAL_LOG( 62 | FATAL, 63 | absl::StrCat("Attempting to fetch value instead of handling error ", 64 | status.ToString())); 65 | std::abort(); 66 | #endif 67 | } 68 | 69 | } // namespace internal_statusor 70 | ABSL_NAMESPACE_END 71 | } // namespace absl 72 | -------------------------------------------------------------------------------- /src/config_defs.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2021, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef CONFIG_DEFS_H_ 31 | #define CONFIG_DEFS_H_ 32 | 33 | /////////////////////////////////////////////////////////////////////////////// 34 | // 35 | // macro to validator function 36 | // 37 | /////////////////////////////////////////////////////////////////////////////// 38 | #define DECLARE_METHOD_VALIDATOR(class_name, config_var, config_type) \ 39 | bool class_name ::validate_value__##config_var(config_type config_var, \ 40 | config_type default_value) 41 | 42 | #define DECLARE_FUNCTION_VALIDATOR(config_var, config_type) \ 43 | bool validate_value__##config_var(config_type config_var, \ 44 | config_type default_value) 45 | 46 | #endif // CONFIG_DEFS_H_ 47 | -------------------------------------------------------------------------------- /src/config_motion.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2021, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef CONFIG_MOTION_H_ 31 | #define CONFIG_MOTION_H_ 32 | 33 | #include 34 | 35 | #include "compat/optionsfile.h" 36 | 37 | class ConfigMotion { 38 | public: 39 | explicit ConfigMotion(const std::string& config_file, bool verbose = false); 40 | ~ConfigMotion(); 41 | 42 | // Load Config 43 | bool Load(); 44 | 45 | // define expasion macros for Getter 46 | // type Get##name(); 47 | 48 | // define expasion macros for Getter 49 | // type GetName(); 50 | #define _CR(name, config_var, config_remote_access, config_type, \ 51 | config_default) \ 52 | config_type Get##name(void) const; \ 53 | config_type config_var; \ 54 | bool isloaded__##config_var; \ 55 | bool validate_value__##config_var(config_type value, \ 56 | config_type default_value); 57 | #define _CR_B _CR 58 | #define _CR_I _CR 59 | #define _CR_F _CR 60 | 61 | #include "def/config_motion.def" 62 | 63 | void DumpConfig(void); 64 | 65 | private: 66 | bool config_loaded_; 67 | std::string config_file_; 68 | bool dump_config_; 69 | std::unique_ptr options_file_; 70 | std::string config_dir_basename_; 71 | }; 72 | 73 | #endif // CONFIG_MOTION_H_ 74 | -------------------------------------------------------------------------------- /src/config_streamer.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef CONFIG_STREAMER_H_ 31 | #define CONFIG_STREAMER_H_ 32 | 33 | #include "compat/optionsfile.h" 34 | #include "rtc_base/checks.h" 35 | #include "utils_pc_config.h" 36 | 37 | class ConfigStreamer { 38 | public: 39 | explicit ConfigStreamer(const std::string& config_file, 40 | bool verbose = false); 41 | ~ConfigStreamer(); 42 | 43 | // Load Config 44 | bool Load(); 45 | 46 | // define expasion macros for Getter 47 | // type Get##name(); 48 | 49 | // define expasion macros for Getter 50 | // type GetName(); 51 | #define _CR(name, config_var, config_remote_access, config_type, \ 52 | config_default) \ 53 | config_type Get##name(void) const; \ 54 | config_type config_var; \ 55 | bool isloaded__##config_var; \ 56 | bool validate_value__##config_var(config_type value, \ 57 | config_type default_value); 58 | #define _CR_B _CR 59 | #define _CR_I _CR 60 | 61 | #include "def/config_streamer.def" 62 | 63 | bool GetJsonRtcConfig(std::string& json_rtcconfig); 64 | bool GetRtcConfig(utils::RTCConfiguration& config); 65 | 66 | bool GetLogPath(std::string& log_dir); 67 | 68 | std::string GetMediaConfigFile(); 69 | std::string GetMotionConfigFile(); 70 | 71 | void DumpConfig(void); 72 | 73 | private: 74 | bool config_loaded_; 75 | std::string config_file_; 76 | bool dump_config_; 77 | std::unique_ptr options_file_; 78 | std::string config_dir_basename_; 79 | }; 80 | 81 | #endif // CONFIG_STREAMER_H_ 82 | -------------------------------------------------------------------------------- /src/def/config_media.def: -------------------------------------------------------------------------------- 1 | 2 | // Configuration Row Macro 3 | // 4 | // CR : String 5 | // CR_I : Integer Type 6 | // CR_B : Boolean Type 7 | // CR_L : List Type ( string but need speical list parsing function ) 8 | // 9 | // Configuration Rearod Argument 10 | // 11 | // Argument Index: 12 | // 0 : confiugration item name 13 | // 1 : string to be used as config name in config file 14 | // 2 : whether the json message can be modified from remote. 15 | // 3 : define cpp type of configuration value 16 | // 4 : default value 17 | // 18 | 19 | #define MEDIA_CONFIG_ROW_LIST \ 20 | _CR_I( CameraSelect, camera_select, false, int, 0 ) \ 21 | _CR( VideoRoi, video_roi, false, std::string, \ 22 | "0,0,1.0,1.0" ) \ 23 | _CR_I( MaxBitrate, max_bitrate, false, int, 3500000 ) \ 24 | _CR_B( Resolution4_3, resolution_4_3_enable, false, bool, true ) \ 25 | _CR_I( VideoRotation, video_rotation, true, int, 0) \ 26 | _CR_B( VideoVFlip, video_vflip, true, bool, false ) \ 27 | _CR_B( VideoHFlip, video_hflip, true, bool, false ) \ 28 | _CR_L( VideoResolutionList43, video_resolution_list_4_3, false, std::string, \ 29 | "320x240,400x300,512x384,640x480,1024x768,1152x864,1296x972,1640x1232" ) \ 30 | _CR_L( VideoResolutionList169, video_resolution_list_16_9, false, std::string, \ 31 | "384x216,512x288,640x360,768x432,896x504,1024x576,1152x648,1280x720,1408x864,1920x1080" ) \ 32 | _CR_B( VideoDynamicResolution, use_dynamic_video_resolution, false, bool, true ) \ 33 | _CR_B( VideoDynamicFps, use_dynamic_video_fps, false, bool, true) \ 34 | _CR( FixedVideoResolution, fixed_video_resolution, false, std::string, \ 35 | "640x480") \ 36 | _CR_I( FixedVideoFps, fixed_video_fps, false, int, 30) \ 37 | _CR_B( AudioProcessing, audio_processing_enable, false, bool, false ) \ 38 | _CR_B( AudioEchoCancel, audio_echo_cancellation, false, bool, true ) \ 39 | _CR_B( AudioAutoGainControl, audio_auto_gain_control, false, bool, true ) \ 40 | _CR_B( AudioNoiseSuppression, audio_noise_suppression, false, bool, true ) \ 41 | _CR_B( AudioHighPassFilter, audio_highpass_filter, false, bool, true ) \ 42 | _CR_B( AudioJitterBufferEnable, audio_jitter_buffer_enable, false, bool, false ) \ 43 | _CR_I( AudioJitterBufferMaxPackets, audio_jitter_buffer_max_packets, false, int, 75 ) \ 44 | _CR_B( AudioJitterBufferFastAccel, audio_jitter_buffer_fast_accel, false, bool, true ) \ 45 | _CR_I( AudioJitterBufferMinDelayMs, audio_jitter_buffer_min_delay_ms, false, int, 20 ) \ 46 | _CR_B( AudioJitterBufferEnableRtx, audio_jitter_buffer_enable_rtx_handling, false, bool, false ) \ 47 | _CR_B( AudioExperimentalAgc, audio_experimental_agc, false, bool, false ) \ 48 | _CR_B( AudioExperimentalNs, audio_experimental_ns, false, bool, false ) \ 49 | _CR_I( VideoSharpness, video_sharpness, true, int, 0 ) \ 50 | _CR_I( VideoContrast, video_contrast, true, int, 0 ) \ 51 | _CR_I( VideoBrightness, video_brightness, true, int, 50 ) \ 52 | _CR_I( VideoSaturation, video_saturation, true, int, 0 ) \ 53 | _CR_I( VideoEV, video_ev, true, int, 2 ) \ 54 | _CR( VideoExposureMode, video_exposure_mode, true, std::string, "auto" ) \ 55 | _CR( VideoFlickerMode, video_flicker_mode, true, std::string, "auto" ) \ 56 | _CR( VideoAwbMode, video_awb_mode, true, std::string, "auto" ) \ 57 | _CR( VideoDrcMode, video_drc_mode, true, std::string, "off" ) \ 58 | _CR_B( VideoStabilisation, video_stabilisation, false, bool, false ) \ 59 | _CR_B( VideoEnableAnnotateText, video_enable_annotate_text, true, bool, false ) \ 60 | _CR( VideoAnnotateText, video_annotate_text, true, std::string,"" ) \ 61 | _CR_I( VideoAnnotateTextSizeRatio, video_annotate_text_size_ratio, true, int, 3 ) \ 62 | _CR_B( StillEnable, still_capture_enable, false, bool, false) \ 63 | _CR_I( StillCameraNum, still_camera_num, false, int, 0) \ 64 | _CR_I( StillWidth, still_width, false, int, 640) \ 65 | _CR_I( StillHeight, still_height, false, int, 480) \ 66 | _CR_I( StillMaxAge, still_max_age, false, int, 300) \ 67 | _CR_I( StillQuality, still_quality, false, int, 85) \ 68 | _CR_I( StillInterval, still_capture_interval, false, int, 300) \ 69 | _CR_B( StilFileAppendDataTime, still_append_datatime, false, bool, false) \ 70 | _CR( StillDirectory, still_directory, false, std::string, "/opt/rws/still_captured") \ 71 | _CR( StillFilePrefix, still_file_prefix, false, std::string, "still_capture") \ 72 | _CR( StillFileExtension, still_file_extension, false, std::string, "jpg") 73 | 74 | // DO actual macro expansion 75 | MEDIA_CONFIG_ROW_LIST 76 | 77 | // Removing configuraiton row definition macros 78 | #undef _CR 79 | #undef _CR_L 80 | #undef _CR_B 81 | #undef _CR_I 82 | #undef MEDIA_CONFIG_ROW_LIST 83 | 84 | 85 | -------------------------------------------------------------------------------- /src/def/config_motion.def: -------------------------------------------------------------------------------- 1 | 2 | // Configuration Row Macro 3 | // 4 | // CR : String 5 | // CR_I : Integer Type 6 | // CR_B : Boolean Type 7 | // CR_F : Float Type 8 | // 9 | // Configuration Rearod Argument 10 | // 11 | // Argument Index: 12 | // 0 : confiugration item name 13 | // 1 : string to be used as config name in config file 14 | // 2 : whether the json message can be modified from remote. 15 | // 3 : define cpp type of configuration value 16 | // 4 : default value 17 | // 18 | 19 | #define MOTION_CONFIG_ROW_LIST \ 20 | _CR_B(DetectionEnable, motion_detection_enable, false, bool, false) \ 21 | _CR_I(Width, motion_width, false, int, 1024) \ 22 | _CR_I(Height, motion_height, false, int, 768) \ 23 | _CR_I(Fps, motion_fps, false, int, 30) \ 24 | _CR_I(Bitrate, motion_bitrate, false, int, 3500) \ 25 | _CR_I(ClearPercent, motion_clear_percent, false, int, 5) \ 26 | _CR_I(ClearWaitPeriod, motion_clear_wait_period, false, int, 5000) \ 27 | _CR(Directory, motion_directory, false, std::string, "/opt/rws/motion_captured") \ 28 | _CR(FilePrefix, motion_file_prefix, false, std::string, "motion") \ 29 | _CR_I(FileSizeLimit, motion_file_size_limit, false, int, 6000) \ 30 | _CR_B(SaveImvFile, motion_save_imv_file, false, bool, false) \ 31 | _CR_B(EnableAnnotateText, motion_enable_annotate_text, false, bool, true) \ 32 | _CR(AnnotateText, motion_annotate_text, false, std::string, "") \ 33 | _CR_I(AnnotateTextSize, motion_annotate_text_size, false, int, 32) \ 34 | _CR_F(BlobCancelThreshold, blob_cancel_threshold, false, float, 0.5 ) \ 35 | _CR_I(BlobTrackingThreshold, blob_tracking_threshold, false, int, 15) \ 36 | _CR_I(TotalFileSizeLimit, motion_file_total_size_limit, false, int, 4000) 37 | 38 | // DO actual macro expansion 39 | MOTION_CONFIG_ROW_LIST 40 | 41 | 42 | // Removing configuraiton row definition macros 43 | #undef _CR 44 | #undef _CR_B 45 | #undef _CR_I 46 | #undef _CR_F 47 | 48 | #undef MOTION_CONFIG_ROW_LIST 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/def/config_streamer.def: -------------------------------------------------------------------------------- 1 | 2 | // Configuration Row Macro 3 | // 4 | // CR : String 5 | // CR_I : Integer Type 6 | // CR_B : Boolean Type 7 | // CR_L : List Type ( string but need speical list parsing function ) 8 | // 9 | // Configuration Rearod Argument 10 | // 11 | // Argument Index: 12 | // 0 : confiugration item name 13 | // 1 : string to be used as config name in config file 14 | // 2 : whether the json message can be modified from remote. 15 | // 3 : define cpp type of configuration value 16 | // 4 : default value 17 | // 18 | 19 | #define STREAMER_CONFIG_ROW_LIST \ 20 | _CR_B(WebSocketEnable, websocket_enable, false, bool, true) \ 21 | _CR_I(WebSocketPort, websocket_port, false, int, 8889) \ 22 | _CR_I(DirectSocketPort, direct_socket_port, false, int, 8888) \ 23 | _CR_B(DirectSocketEnable, direct_socket_enable, false, bool, false) \ 24 | _CR(MediaConfig, media_config, false, std::string, "etc/media_config.conf") \ 25 | _CR(MotionConfig, motion_config, false, std::string, "etc/motion_config.conf") \ 26 | _CR(FieldTrials, fieldtrials, false, std::string, "") \ 27 | _CR_B(DisableLogBuffering, disable_log_buffering, false, bool, true) \ 28 | _CR_B(LwsDebugEnable, libwebsocket_debug, false, bool, false) \ 29 | _CR_B(AudioEnable, audio_enable, false, bool, false) \ 30 | _CR_B(VideoEnable, video_enable, false, bool, true) \ 31 | _CR_B(SrtpEnable, srtp_enable, false, bool, true) \ 32 | _CR(WebRootPath, web_root, false, std::string, INSTALL_DIR "/web-root") \ 33 | _CR(RwsWsUrlPath, rws_ws_url, false, std::string, "/rws/ws") 34 | 35 | // DO actual macro expansion 36 | STREAMER_CONFIG_ROW_LIST 37 | 38 | // Removing configuraiton row definition macros 39 | #undef _CR 40 | #undef _CR_B 41 | #undef _CR_I 42 | 43 | #undef STREAMER_CONFIG_ROW_LIST 44 | 45 | 46 | -------------------------------------------------------------------------------- /src/direct_socket.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef DIRECT_SOCKET_H_ 31 | #define DIRECT_SOCKET_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "rtc_base/net_helpers.h" 37 | #include "rtc_base/physical_socket_server.h" 38 | #include "rtc_base/third_party/sigslot/sigslot.h" 39 | #include "streamer_signaling.h" 40 | 41 | #define FORCE_CONNECTION_DROP_VALID_DURATION 3000 42 | #define FORCE_CONNECTION_DROP_TRYCOUNT_THRESHOLD 3 43 | 44 | #define DIRECTSOCKET_FAKE_PEERID 100 45 | #define DIRECTSOCKET_FAKE_NAME_PREFIX "DS" 46 | 47 | class DirectSocketServer : public SignalingChannelHelper, 48 | public rtc::MessageHandler, 49 | public sigslot::has_slots<> { 50 | public: 51 | DirectSocketServer(StreamerProxy* proxy); 52 | ~DirectSocketServer(); 53 | 54 | bool Listen(const rtc::SocketAddress& address); 55 | void StopListening(void); 56 | 57 | void SetSignalingInbound(SignalingInbound* inbound) override; 58 | bool SendMessageToPeer(const int peer_id, 59 | const std::string& message) override; 60 | void ReportEvent(const int peer_id, bool drop_connection, 61 | const std::string& message) override; 62 | 63 | private: 64 | void OnAccept(rtc::AsyncSocket* socket); 65 | void OnClose(rtc::AsyncSocket* socket, int err); 66 | void OnRead(rtc::AsyncSocket* socket); 67 | 68 | // message handler interface 69 | void OnMessage(rtc::Message* msg) override; 70 | 71 | std::unique_ptr listener_; 72 | std::unique_ptr direct_socket_; 73 | 74 | // local id and name 75 | int socket_peer_id_; 76 | std::string socket_peer_name_; 77 | // read buffer from client 78 | std::string buffered_read_; 79 | 80 | // Forced connection, 81 | // release the preempted connection and establish a new attempted 82 | // connection. 83 | uint64_t last_reject_time_ms_; 84 | int connection_reject_count_; 85 | }; 86 | 87 | #endif // DIRECT_SOCKET_H_ 88 | -------------------------------------------------------------------------------- /src/file_log_sink.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2021, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #include "file_log_sink.h" 31 | 32 | #include 33 | #include 34 | #include 35 | 36 | #include "rtc_base/checks.h" 37 | #include "rtc_base/log_sinks.h" 38 | #include "rtc_base/logging.h" 39 | #include "rtc_base/stream.h" 40 | #include "utils.h" 41 | 42 | namespace utils { 43 | 44 | namespace { 45 | 46 | constexpr int kLogFileSizeLimit = 3 * 1024 * 1024; // 3M bytes; 47 | constexpr char kLogFilenamePrefix[] = "rws.log"; 48 | constexpr size_t kMaxLogFileNums = 10; 49 | 50 | } // namespace 51 | 52 | ////////////////////////////////////////////////////////////////////////////////////////// 53 | // 54 | // File Logger Class 55 | // 56 | ////////////////////////////////////////////////////////////////////////////////////////// 57 | FileLogSink::FileLogSink(const std::string path, 58 | const rtc::LoggingSeverity severity, 59 | bool disable_buffering) 60 | : dir_path_(path), 61 | severity_(severity), 62 | disable_buffering_(disable_buffering) { 63 | stream_.reset(new rtc::LogRotatingStream( 64 | dir_path_, kLogFilenamePrefix, kLogFileSizeLimit, kMaxLogFileNums)); 65 | } 66 | 67 | FileLogSink::~FileLogSink() {} 68 | 69 | bool FileLogSink::Init() { 70 | if (!stream_->Open()) { 71 | std::cerr << "Failed to open log files at path: " << dir_path_ << "\n"; 72 | stream_.reset(); 73 | return false; 74 | } 75 | 76 | if (disable_buffering_ == true) { 77 | // disabling_buffering in FileLogSink 78 | stream_->DisableBuffering(); 79 | }; 80 | 81 | rtc::LogMessage::LogThreads(true); 82 | rtc::LogMessage::LogTimestamps(true); 83 | rtc::LogMessage::AddLogToStream(this, severity_); 84 | return true; 85 | } 86 | 87 | void FileLogSink::OnLogMessage(const std::string& message) { 88 | if (stream_->GetState() != rtc::SS_OPEN) { 89 | std::fprintf(stderr, 90 | "Init() must be called before adding this sink.\n"); 91 | return; 92 | } 93 | stream_->WriteAll(message.c_str(), message.size(), nullptr, nullptr); 94 | } 95 | 96 | void FileLogSink::OnLogMessage(const std::string& message, 97 | rtc::LoggingSeverity sev, const char* tag) { 98 | if (stream_->GetState() != rtc::SS_OPEN) { 99 | std::fprintf(stderr, 100 | "Init() must be called before adding this sink.\n"); 101 | return; 102 | } 103 | stream_->WriteAll(tag, strlen(tag), nullptr, nullptr); 104 | stream_->WriteAll(": ", 2, nullptr, nullptr); 105 | stream_->WriteAll(message.c_str(), message.size(), nullptr, nullptr); 106 | } 107 | 108 | }; // namespace utils 109 | -------------------------------------------------------------------------------- /src/file_log_sink.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2021, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef FILE_LOG_SINK_H_ 31 | #define FILE_LOG_SINK_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "log_rotating_stream.h" 37 | #include "rtc_base/log_sinks.h" 38 | 39 | namespace utils { 40 | 41 | // save the logging messsage to file 42 | class FileLogSink : public rtc::LogSink { 43 | public: 44 | explicit FileLogSink(const std::string path, 45 | const rtc::LoggingSeverity severity, 46 | bool disable_buffering); 47 | bool Init(); 48 | ~FileLogSink(); 49 | 50 | // Writes the message to the current file. It will spill over to the next 51 | // file if needed. 52 | void OnLogMessage(const std::string& message) override; 53 | void OnLogMessage(const std::string& message, rtc::LoggingSeverity sev, 54 | const char* tag) override; 55 | 56 | private: 57 | std::string dir_path_; 58 | rtc::LoggingSeverity severity_; 59 | size_t log_max_file_size_; 60 | std::unique_ptr stream_; 61 | bool disable_buffering_; 62 | RTC_DISALLOW_COPY_AND_ASSIGN(FileLogSink); 63 | }; 64 | 65 | }; // namespace utils 66 | 67 | #endif // FILE_LOG_SINK_H_ 68 | -------------------------------------------------------------------------------- /src/file_writer_handle.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2021, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef FILE_WRITER_HANDLE_H_ 31 | #define FILE_WRITER_HANDLE_H_ 32 | 33 | #include 34 | #include 35 | #include 36 | 37 | #include "rtc_base/constructor_magic.h" 38 | #include "rtc_base/event.h" 39 | #include "rtc_base/platform_thread.h" 40 | #include "rtc_base/synchronization/mutex.h" 41 | #include "rtc_base/system/file_wrapper.h" 42 | #include "rtc_base/thread.h" 43 | 44 | namespace webrtc { 45 | 46 | constexpr double kDefaultBufferIncreaaseFactor = 0.25; 47 | 48 | //////////////////////////////////////////////////////////////////////////////// 49 | // 50 | // FileWriter Buffer 51 | // 52 | //////////////////////////////////////////////////////////////////////////////// 53 | 54 | class FileWriterBuffer { 55 | public: 56 | explicit FileWriterBuffer(size_t buffer_size /* frame buffer size */); 57 | ~FileWriterBuffer(); 58 | 59 | size_t ReadFront(void *buffer, size_t size); 60 | size_t WriteBack(const void *buffer, size_t size); 61 | 62 | size_t size(); 63 | inline size_t buffer_size() const { return buffer_size_; } 64 | void clear(); 65 | 66 | private: 67 | void Resize(double increase_factor = kDefaultBufferIncreaaseFactor); 68 | webrtc::Mutex mutex_; 69 | 70 | size_t buffer_size_; 71 | size_t offset_start_, offset_end_; 72 | std::unique_ptr buffer_; 73 | 74 | RTC_DISALLOW_COPY_AND_ASSIGN(FileWriterBuffer); 75 | }; 76 | 77 | //////////////////////////////////////////////////////////////////////////////// 78 | // 79 | // FileWriter Handle 80 | // 81 | //////////////////////////////////////////////////////////////////////////////// 82 | 83 | class FileWriterHandle : public rtc::Event { 84 | public: 85 | explicit FileWriterHandle(const std::string name, size_t buffer_size); 86 | ~FileWriterHandle(); 87 | 88 | bool Open(const std::string dirname, const std::string prefix, 89 | const std::string extension, const int file_size_limit, 90 | const bool use_temporary_filename = true); 91 | bool Close(); 92 | bool Write(); 93 | void Flush(); 94 | FileWriterBuffer *GetBuffer(); 95 | inline bool is_open() { return file_.is_open(); } 96 | inline size_t FileSize() { return file_written_; } 97 | 98 | // interface for buffer 99 | size_t ReadFront(void *buffer, size_t size); 100 | size_t WriteBack(const void *buffer, size_t size); 101 | void clear(); // remove all of contents in file writer buffer 102 | size_t size(); // file writer buffer size 103 | 104 | private: 105 | bool WriterProcess(); 106 | std::unique_ptr buffer_; 107 | // thread for file writing 108 | rtc::PlatformThread writerThread_; 109 | bool writer_quit_; 110 | webrtc::Mutex writer_lock_; 111 | FileWrapper file_; 112 | std::string filename_; 113 | int file_size_limit_; 114 | int file_written_; 115 | bool use_temporary_filename_; 116 | std::string name_; 117 | 118 | RTC_DISALLOW_COPY_AND_ASSIGN(FileWriterHandle); 119 | }; 120 | 121 | } // namespace webrtc 122 | 123 | #endif // FILE_WRITER_HANDLE_H_ 124 | -------------------------------------------------------------------------------- /src/log_rotating_stream.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Lyu,KeunChang 3 | * 4 | * This is a stripped down version of the original file_rotating_stream module 5 | * from ther WebRTC native source code, 6 | * Original copyright info below 7 | */ 8 | /* 9 | * Copyright 2015 The WebRTC Project Authors. All rights reserved. 10 | * 11 | * Use of this source code is governed by a BSD-style license 12 | * that can be found in the LICENSE file in the root of the source 13 | * tree. An additional intellectual property rights grant can be found 14 | * in the file PATENTS. All contributing project authors may 15 | * be found in the AUTHORS file in the root of the source tree. 16 | */ 17 | 18 | #ifndef LOG_ROTATING_STREAM_H_ 19 | #define LOG_ROTATING_STREAM_H_ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | #include "rtc_base/constructor_magic.h" 26 | #include "rtc_base/stream.h" 27 | #include "rtc_base/system/file_wrapper.h" 28 | 29 | namespace rtc { 30 | 31 | class LogRotatingStream : public StreamInterface { 32 | public: 33 | LogRotatingStream(const std::string& dir_path, 34 | const std::string& file_prefix, size_t max_file_size, 35 | size_t num_files); 36 | 37 | ~LogRotatingStream(); 38 | 39 | // StreamInterface methods. 40 | StreamState GetState() const override; 41 | StreamResult Read(void* buffer, size_t buffer_len, size_t* read, 42 | int* error) override; 43 | StreamResult Write(const void* data, size_t data_len, size_t* written, 44 | int* error) override; 45 | bool Flush() override; 46 | void Close() override; 47 | 48 | // Opens the appropriate file(s). Call this before using the stream. 49 | bool Open(); 50 | 51 | // Disabling buffering causes writes to block until disk is updated. This is 52 | // enabled by default for performance. 53 | bool DisableBuffering(); 54 | 55 | // Returns the path used for the i-th newest file, where the 0th file is the 56 | // newest file. The file may or may not exist, this is just used for 57 | // formatting. Index must be less than GetNumFiles(). 58 | std::string GetFilePath(size_t index) const; 59 | 60 | // Returns the number of files that will used by this stream. 61 | size_t GetNumFiles() const { return file_names_.size(); } 62 | 63 | protected: 64 | size_t GetMaxFileSize() const { return max_file_size_; } 65 | void SetMaxFileSize(size_t size) { max_file_size_ = size; } 66 | size_t GetRotationIndex() const { return rotation_index_; } 67 | void SetRotationIndex(size_t index) { rotation_index_ = index; } 68 | 69 | virtual void OnRotation() {} 70 | 71 | private: 72 | bool OpenCurrentFile(); 73 | void CloseCurrentFile(); 74 | 75 | // Rotates the files by creating a new current file, renaming the 76 | // existing files, and deleting the oldest one. e.g. 77 | // file_0 -> file_1 78 | // file_1 -> file_2 79 | // file_2 -> delete 80 | // create new file_0 81 | void RotateFiles(); 82 | 83 | // Private version of GetFilePath. 84 | std::string GetFilePath(size_t index, size_t num_files) const; 85 | 86 | std::string dir_path_; 87 | const std::string file_prefix_; 88 | 89 | // File we're currently writing to. 90 | webrtc::FileWrapper file_; 91 | // Convenience storage for file names so we don't generate them over and 92 | // over. 93 | std::vector file_names_; 94 | size_t max_file_size_; 95 | size_t current_file_index_; 96 | // The rotation index indicates the index of the file that will be 97 | // deleted first on rotation. Indices lower than this index will be rotated. 98 | size_t rotation_index_; 99 | // Number of bytes written to current file. We need this because with 100 | // buffering the file size read from disk might not be accurate. 101 | size_t current_bytes_written_; 102 | bool disable_buffering_; 103 | 104 | RTC_DISALLOW_COPY_AND_ASSIGN(LogRotatingStream); 105 | }; 106 | 107 | } // namespace rtc 108 | 109 | #endif // LOG_ROTATING_STREAM_H_ 110 | -------------------------------------------------------------------------------- /src/mdns_publish.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef MDNS_PUBLISH_H_ 31 | #define MDNS_PUBLISH_H_ 32 | 33 | #ifdef __cplusplus 34 | extern "C" { 35 | #endif // __cplusplus 36 | 37 | #define MDNS_SUCCESS 0 38 | #define MDNS_FAILED 1 39 | 40 | int mdns_init_clientinfo(int port_number, const char *ws, 41 | const char *device_id); 42 | void mdns_destroy_clientinfo(void); 43 | int mdns_run_loop(int timeout); 44 | 45 | #ifdef __cplusplus 46 | } // extern "C" 47 | #endif // __cplusplus 48 | 49 | #endif /* MDNS_PUBLISH_H_ */ 50 | -------------------------------------------------------------------------------- /src/mmal_common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Includes for broadcom and ilclient headers wrapped in C style. 3 | */ 4 | #ifndef MMAL_COMMON_H_ 5 | #define MMAL_COMMON_H_ 6 | 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif // __cplusplus 10 | 11 | /////////////////////////////////////////////////////////////////////////////// 12 | // 13 | // MMAL related header files 14 | // 15 | /////////////////////////////////////////////////////////////////////////////// 16 | #include 17 | 18 | #include "bcm_host.h" 19 | #include "interface/mmal/mmal.h" 20 | #include "interface/mmal/mmal_buffer.h" 21 | #include "interface/mmal/mmal_logging.h" 22 | #include "interface/mmal/mmal_parameters_camera.h" 23 | #include "interface/mmal/util/mmal_connection.h" 24 | #include "interface/mmal/util/mmal_default_components.h" 25 | #include "interface/mmal/util/mmal_util.h" 26 | #include "interface/mmal/util/mmal_util_params.h" 27 | #include "interface/vcos/vcos.h" 28 | #include "raspicamcontrol.h" 29 | #include "raspicli.h" 30 | #include "raspipreview.h" 31 | 32 | #define RASPI_CAM_FIXED_WIDTH 1296 33 | #define RASPI_CAM_FIXED_HEIGHT 972 34 | 35 | /////////////////////////////////////////////////////////////////////////////// 36 | // 37 | // Log macro definition to stdout 38 | // 39 | /////////////////////////////////////////////////////////////////////////////// 40 | #define DLOG(msg) printf("(%s:%d): %s\n", __FILE__, __LINE__, msg); 41 | 42 | #define DLOG_FORMAT(format, args...) \ 43 | printf("(%s:%d):", __FILE__, __LINE__); \ 44 | printf(format, args); \ 45 | printf("\n"); 46 | 47 | #define DLOG_ERROR(format, args...) \ 48 | fprintf(stderr, "(%s:%d):", __FILE__, __LINE__); \ 49 | fprintf(stderr, format, args); \ 50 | fprintf(stderr, "\n"); 51 | 52 | #define DLOG_ERROR_0(message) \ 53 | fprintf(stderr, "(%s:%d):", __FILE__, __LINE__); \ 54 | fprintf(stderr, message); \ 55 | fprintf(stderr, "\n"); 56 | 57 | #ifdef __MMAL_ENCODER_DEBUG__ 58 | #define DEBUG_LOG(format, args...) \ 59 | printf("(%s:%d):", __FILE__, __LINE__); \ 60 | printf(format, args) 61 | #else 62 | #define DEBUG_LOG(format, args...) 63 | #endif /* __MMAL_ENCODER_DEBUG__ */ 64 | 65 | // Standard port setting for the camera component 66 | #define MMAL_CAMERA_PREVIEW_PORT 0 67 | #define MMAL_CAMERA_VIDEO_PORT 1 68 | #define MMAL_CAMERA_CAPTURE_PORT 2 69 | 70 | // Port configuration for the splitter component 71 | #define SPLITTER_OUTPUT_PORT 0 72 | #define SPLITTER_PREVIEW_PORT 1 73 | 74 | // Video format information 75 | // 0 implies variable 76 | #define VIDEO_FRAME_RATE_NUM 30 77 | #define VIDEO_FRAME_RATE_DEN 1 78 | 79 | /// Video render needs at least 2 buffers. 80 | #define VIDEO_OUTPUT_BUFFERS_NUM 3 81 | #define VIDEO_INTRAFRAME_PERIOD 3 /// 3 seconds 82 | 83 | // Stills format information 84 | // 0 implies variable 85 | #define STILLS_FRAME_RATE_NUM 0 86 | #define STILLS_FRAME_RATE_DEN 1 87 | 88 | #ifdef __cplusplus 89 | } // extern "C" 90 | #endif // __cplusplus 91 | 92 | #endif // MMAL_COMMON_H_ 93 | -------------------------------------------------------------------------------- /src/mmal_still_capture.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2021, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef MMAL_STILL_CAPTURE_H_ 31 | #define MMAL_STILL_CAPTURE_H_ 32 | 33 | #include "absl/status/status.h" 34 | #include "config_media.h" 35 | #include "mmal_still.h" 36 | #include "mutex" 37 | #include "rtc_base/event.h" 38 | #include "rtc_base/synchronization/mutex.h" 39 | #include "rtc_base/system/file_wrapper.h" 40 | #include "system_wrappers/include/clock.h" 41 | #include "wstreamer_types.h" 42 | 43 | namespace webrtc { 44 | 45 | //////////////////////////////////////////////////////////////////////////////// 46 | // 47 | // MMAL Encoder Wrapper 48 | // 49 | //////////////////////////////////////////////////////////////////////////////// 50 | class StillCapture : public rtc::Event { 51 | public: 52 | // Singleton, constructor and destructor are private. 53 | static StillCapture *Instance(); 54 | inline bool IsCapturing() const { return still_capture_active_; } 55 | absl::Status Capture(const wstreamer::StillOptions &options, 56 | std::string *captured_filename = nullptr); 57 | absl::Status GetLatestOrCapture(const wstreamer::StillOptions &options, 58 | std::string *captured_filename = nullptr); 59 | 60 | private: 61 | StillCapture(); 62 | ~StillCapture(); 63 | absl::Status InitStillEncoder(const wstreamer::StillOptions &options); 64 | void InitParams(const wstreamer::StillOptions &options); 65 | bool UninitStillEncoder(); 66 | 67 | // Callback Functions 68 | static void BufferCallback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer); 69 | void OnBufferCallback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer); 70 | 71 | static void createStillCaptureSingleton(); 72 | static StillCapture *mmal_still_capture_; 73 | static std::once_flag singleton_flag_; 74 | 75 | bool still_capture_active_; 76 | 77 | ConfigMedia *config_media_; 78 | MMAL_PORT_T *camera_preview_port_, *camera_video_port_, *camera_still_port_; 79 | MMAL_PORT_T *preview_input_port_; 80 | MMAL_PORT_T *encoder_input_port_, *encoder_output_port_; 81 | RASPISTILL_STATE state_; 82 | FileWrapper file_; 83 | 84 | webrtc::Mutex mutex_; 85 | RTC_DISALLOW_COPY_AND_ASSIGN(StillCapture); 86 | }; 87 | 88 | } // namespace webrtc 89 | 90 | #endif // MMAL_STILL_CAPTURE_H_ 91 | -------------------------------------------------------------------------------- /src/raspi_decoder.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #include "raspi_decoder.h" 31 | 32 | #include 33 | #include 34 | 35 | #include "absl/memory/memory.h" 36 | #include "common_video/h264/h264_bitstream_parser.h" 37 | #include "common_video/h264/h264_common.h" 38 | #include "media/base/codec.h" 39 | #include "modules/video_coding/codecs/h264/include/h264.h" 40 | #include "raspi_decoder_dummy.h" 41 | #include "rtc_base/checks.h" 42 | #include "rtc_base/logging.h" 43 | 44 | namespace webrtc { 45 | 46 | std::unique_ptr RaspiDecoder::Create() { 47 | RTC_LOG(LS_INFO) << "Creating H264DecoderDummy."; 48 | return std::make_unique(); 49 | } 50 | 51 | bool RaspiDecoder::IsSupported() { return true; } 52 | 53 | std::unique_ptr CreateRaspiVideoDecoderFactory() { 54 | RTC_LOG(LS_INFO) << "Creating RaspiVideoDecoderFactory."; 55 | return std::make_unique(); 56 | } 57 | 58 | /////////////////////////////////////////////////////////////////////////////// 59 | // 60 | // Raspi Video Decoder Factory 61 | // 62 | /////////////////////////////////////////////////////////////////////////////// 63 | RaspiVideoDecoderFactory::RaspiVideoDecoderFactory() { 64 | RTC_LOG(INFO) << "Raspi H.264 Video decoder factory."; 65 | for (const SdpVideoFormat& h264_format : SupportedH264Codecs()) 66 | supported_formats_.push_back(h264_format); 67 | } 68 | 69 | std::unique_ptr RaspiVideoDecoderFactory::CreateVideoDecoder( 70 | const SdpVideoFormat& format) { 71 | const cricket::VideoCodec codec(format); 72 | 73 | RTC_LOG(INFO) << "Raspi " << format.name << " video decoder created"; 74 | return RaspiDecoder::Create(); 75 | } 76 | 77 | RaspiVideoDecoderFactory::~RaspiVideoDecoderFactory() { 78 | RTC_LOG(INFO) << "Raspi Video decoder factory destroy"; 79 | } 80 | 81 | std::vector RaspiVideoDecoderFactory::GetSupportedFormats() 82 | const { 83 | return supported_formats_; 84 | } 85 | 86 | } // namespace webrtc 87 | -------------------------------------------------------------------------------- /src/raspi_decoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RASPI_DECODER_H_ 31 | #define RASPI_DECODER_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "api/video_codecs/sdp_video_format.h" 37 | #include "api/video_codecs/video_decoder.h" 38 | #include "api/video_codecs/video_decoder_factory.h" 39 | #include "media/base/codec.h" 40 | #include "modules/video_coding/include/video_codec_interface.h" 41 | 42 | namespace webrtc { 43 | 44 | class RaspiDecoder : public VideoDecoder { 45 | public: 46 | static std::unique_ptr Create(); 47 | static bool IsSupported(); 48 | ~RaspiDecoder() override {} 49 | }; 50 | 51 | std::unique_ptr CreateRaspiVideoDecoderFactory(); 52 | 53 | // 54 | // Implementation of Raspberry video decoder factory 55 | class RaspiVideoDecoderFactory : public VideoDecoderFactory { 56 | public: 57 | RaspiVideoDecoderFactory(); 58 | virtual ~RaspiVideoDecoderFactory() override; 59 | 60 | std::unique_ptr CreateVideoDecoder( 61 | const SdpVideoFormat& format) override; 62 | 63 | // Returns a list of supported codecs in order of preference. 64 | std::vector GetSupportedFormats() const override; 65 | 66 | private: 67 | std::vector supported_formats_; 68 | }; 69 | 70 | } // namespace webrtc 71 | 72 | #endif // RASPI_DECODER_H_ 73 | -------------------------------------------------------------------------------- /src/raspi_decoder_dummy.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. An additional intellectual property rights grant can be found 7 | * in the file PATENTS. All contributing project authors may 8 | * be found in the AUTHORS file in the root of the source tree. 9 | * 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | #include "api/video/i420_buffer.h" 16 | #include "common_video/include/video_frame_buffer.h" 17 | #include "raspi_decoder.h" 18 | #include "rtc_base/checks.h" 19 | #include "rtc_base/logging.h" 20 | #include "rtc_base/time_utils.h" 21 | #include "system_wrappers/include/metrics.h" 22 | 23 | // clang-format off 24 | #include "raspi_decoder_dummy.h" 25 | // clang-format on 26 | 27 | namespace webrtc { 28 | 29 | RaspiDecoderDummy::RaspiDecoderDummy() 30 | : decoded_image_callback_(nullptr), decoder_initialized_(false) {} 31 | 32 | RaspiDecoderDummy::~RaspiDecoderDummy() { Release(); } 33 | 34 | int32_t RaspiDecoderDummy::InitDecode(const VideoCodec* codec_settings, 35 | int32_t number_of_cores) { 36 | if (codec_settings && codec_settings->codecType != kVideoCodecH264) { 37 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; 38 | } 39 | 40 | // Release necessary in case of re-initializing. 41 | int32_t ret = Release(); 42 | if (ret != WEBRTC_VIDEO_CODEC_OK) { 43 | return ret; 44 | } 45 | 46 | decoder_config_ = *codec_settings; 47 | decoder_initialized_ = true; 48 | return WEBRTC_VIDEO_CODEC_OK; 49 | } 50 | 51 | int32_t RaspiDecoderDummy::Release() { 52 | decoder_initialized_ = false; 53 | return WEBRTC_VIDEO_CODEC_OK; 54 | } 55 | 56 | int32_t RaspiDecoderDummy::RegisterDecodeCompleteCallback( 57 | DecodedImageCallback* callback) { 58 | decoded_image_callback_ = callback; 59 | return WEBRTC_VIDEO_CODEC_OK; 60 | } 61 | 62 | int32_t RaspiDecoderDummy::Decode(const EncodedImage& input_image, 63 | bool /*missing_frames*/, 64 | int64_t render_time_ms) { 65 | if (!IsInitialized()) { 66 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; 67 | } 68 | if (!decoded_image_callback_) { 69 | RTC_LOG(LS_WARNING) 70 | << "InitDecode() has been called, but a callback function " 71 | "has not been set with RegisterDecodeCompleteCallback()"; 72 | return WEBRTC_VIDEO_CODEC_UNINITIALIZED; 73 | } 74 | if (!input_image.data() || !input_image.size()) { 75 | return WEBRTC_VIDEO_CODEC_ERR_PARAMETER; 76 | } 77 | 78 | VideoFrame frame( 79 | I420Buffer::Create(decoder_config_.width, decoder_config_.height), 80 | kVideoRotation_0, render_time_ms * rtc::kNumMicrosecsPerMillisec); 81 | frame.set_timestamp(input_image.Timestamp()); 82 | frame.set_ntp_time_ms(input_image.ntp_time_ms_); 83 | 84 | decoded_image_callback_->Decoded(frame); 85 | 86 | return WEBRTC_VIDEO_CODEC_OK; 87 | } 88 | 89 | const char* RaspiDecoderDummy::ImplementationName() const { 90 | return "RaspiDecoderDummy"; 91 | } 92 | 93 | bool RaspiDecoderDummy::IsInitialized() const { return decoder_initialized_; } 94 | 95 | } // namespace webrtc 96 | -------------------------------------------------------------------------------- /src/raspi_decoder_dummy.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. An additional intellectual property rights grant can be found 7 | * in the file PATENTS. All contributing project authors may 8 | * be found in the AUTHORS file in the root of the source tree. 9 | * 10 | */ 11 | 12 | #ifndef RASPI_DECODER_DUMMY_H_ 13 | #define RASPI_DECODER_DUMMY_H_ 14 | 15 | #include 16 | 17 | #include "./raspi_decoder.h" 18 | #include "api/video/video_frame.h" 19 | #include "api/video_codecs/video_codec.h" 20 | 21 | namespace webrtc { 22 | 23 | class RaspiDecoderDummy : public RaspiDecoder { 24 | public: 25 | RaspiDecoderDummy(); 26 | ~RaspiDecoderDummy() override; 27 | 28 | int32_t InitDecode(const VideoCodec* codec_settings, 29 | int32_t number_of_cores) override; 30 | int32_t Release() override; 31 | 32 | int32_t RegisterDecodeCompleteCallback( 33 | DecodedImageCallback* callback) override; 34 | 35 | int32_t Decode(const EncodedImage& input_image, bool /*missing_frames*/, 36 | int64_t render_time_ms = -1) override; 37 | 38 | const char* ImplementationName() const override; 39 | 40 | private: 41 | bool IsInitialized() const; 42 | 43 | VideoCodec decoder_config_; 44 | DecodedImageCallback* decoded_image_callback_; 45 | bool decoder_initialized_; 46 | }; 47 | 48 | } // namespace webrtc 49 | 50 | #endif // RASPI_DECODER_DUMMY_H_ 51 | -------------------------------------------------------------------------------- /src/raspi_encoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RASPI_ENCODER_H_ 31 | #define RASPI_ENCODER_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "api/video_codecs/sdp_video_format.h" 37 | #include "api/video_codecs/video_encoder.h" 38 | #include "api/video_codecs/video_encoder_factory.h" 39 | #include "media/base/codec.h" 40 | #include "modules/video_coding/include/video_codec_interface.h" 41 | 42 | namespace webrtc { 43 | 44 | class RaspiEncoder : public VideoEncoder { 45 | public: 46 | static std::unique_ptr Create( 47 | const cricket::VideoCodec& codec); 48 | static bool IsSupported(); 49 | ~RaspiEncoder() override {} 50 | }; 51 | 52 | std::unique_ptr CreateRaspiVideoEncoderFactory(); 53 | 54 | // 55 | // Implementation of Raspberry video encoder factory 56 | class RaspiVideoEncoderFactory : public VideoEncoderFactory { 57 | public: 58 | RaspiVideoEncoderFactory(); 59 | virtual ~RaspiVideoEncoderFactory() override; 60 | 61 | std::unique_ptr CreateVideoEncoder( 62 | const SdpVideoFormat& format) override; 63 | 64 | // Returns a list of supported codecs in order of preference. 65 | std::vector GetSupportedFormats() const override { 66 | return supported_formats_; 67 | } 68 | std::vector GetImplementations() const override { 69 | return supported_formats_; 70 | } 71 | 72 | CodecInfo QueryVideoEncoder(const SdpVideoFormat& format) const override; 73 | 74 | std::unique_ptr GetEncoderSelector() 75 | const override; 76 | 77 | private: 78 | std::vector supported_formats_; 79 | }; 80 | 81 | } // namespace webrtc 82 | 83 | #endif // RASPI_ENCODER_H_ 84 | -------------------------------------------------------------------------------- /src/raspi_encoder_impl.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RASPI_ENCODER_IMPL_H_ 31 | #define RASPI_ENCODER_IMPL_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "common_video/h264/h264_bitstream_parser.h" 37 | #include "common_video/h264/h264_common.h" 38 | #include "mmal_wrapper.h" 39 | #include "modules/video_coding/include/video_codec_interface.h" 40 | #include "raspi_encoder.h" 41 | #include "raspi_quality_config.h" 42 | #include "rtc_base/platform_thread.h" 43 | #include "rtc_base/synchronization/mutex.h" 44 | #include "system_wrappers/include/clock.h" 45 | 46 | namespace webrtc { 47 | 48 | class RaspiEncoderImpl : public RaspiEncoder { 49 | public: 50 | struct FrameFlowCtl { 51 | enum FLOWCTL_STATE { 52 | FLOW_DISABLED = 0, 53 | FLOW_WAITING_KEYFRAME, 54 | FLOW_KEYFRAME_REQUSTED, 55 | FLOW_ENABLED 56 | }; 57 | explicit FrameFlowCtl(); 58 | virtual ~FrameFlowCtl(){}; 59 | 60 | Clock* const clock_; 61 | MMALEncoderWrapper* mmal_encoder_; 62 | 63 | // Change the value to enable when the Encode function is called 64 | // and wiil be enable when SetRates method called with positive 65 | // bitrate and will be disable when SetRates methold called with 0 66 | // bitrate 67 | FLOWCTL_STATE flow_state_ = FLOW_DISABLED; 68 | int64_t keyframe_wait_start_time_ = 0; 69 | 70 | void Set(); 71 | void Clear(); 72 | bool IsEnabled(); 73 | bool CheckKeyframe(bool keyframe); 74 | }; 75 | 76 | public: 77 | explicit RaspiEncoderImpl(const cricket::VideoCodec& codec); 78 | ~RaspiEncoderImpl() override; 79 | 80 | int32_t InitEncode(const VideoCodec* codec_settings, 81 | const VideoEncoder::Settings& settings) override; 82 | int32_t Release() override; 83 | 84 | int32_t RegisterEncodeCompleteCallback( 85 | EncodedImageCallback* callback) override; 86 | void SetRates(const RateControlParameters& parameters) override; 87 | 88 | // Encode metholds are not used to encode frames. This methold is used only 89 | // as an event for creating a keyframe in the encoder when a keyframe is 90 | // needed. 91 | int32_t Encode(const VideoFrame& frame, 92 | const std::vector* frame_types) override; 93 | 94 | VideoEncoder::EncoderInfo GetEncoderInfo() const override; 95 | 96 | private: 97 | bool IsInitialized() const; 98 | 99 | bool drain_quit_; 100 | bool DrainProcess(); 101 | 102 | // Reports statistics with histograms. 103 | void ReportInit(); 104 | void ReportError(); 105 | 106 | MMALEncoderWrapper* mmal_encoder_; 107 | // media configuration sigleton reference 108 | ConfigMedia* config_media_; 109 | 110 | bool has_reported_init_; 111 | bool has_reported_error_; 112 | 113 | // Encoded frame process thread 114 | rtc::PlatformThread drainThread_; 115 | Mutex drain_lock_; 116 | 117 | EncodedImageCallback* encoded_image_callback_; 118 | std::vector encoded_image_; 119 | 120 | // H264 bitstream parser, used to extract QP from encoded bitstreams. 121 | H264BitstreamParser h264_bitstream_parser_; 122 | 123 | Clock* const clock_; 124 | 125 | VideoCodecMode mode_; 126 | size_t max_payload_size_; 127 | int key_frame_interval_; 128 | 129 | // H.264 specifc parameters 130 | bool frame_dropping_on_; 131 | H264PacketizationMode packetization_mode_; 132 | 133 | // Quality Config 134 | QualityConfig quality_config_; 135 | VideoCodec codec_; 136 | 137 | // Frame Flow Control 138 | FrameFlowCtl frame_flow_; 139 | }; 140 | 141 | } // namespace webrtc 142 | 143 | #endif // RASPI_ENCODER_IMPL_H_ 144 | -------------------------------------------------------------------------------- /src/raspi_httpnoti.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2018, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RASPI_HTTPNOTI_H_ 31 | #define RASPI_HTTPNOTI_H_ 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | #include "rtc_base/net_helpers.h" 39 | #include "rtc_base/physical_socket_server.h" 40 | #include "rtc_base/synchronization/mutex.h" 41 | #include "rtc_base/third_party/sigslot/sigslot.h" 42 | 43 | class RaspiHttpNoti : public sigslot::has_slots<>, public rtc::MessageHandler { 44 | public: 45 | enum State { 46 | HTTPNOTI_INIT_ERROR = 0, 47 | HTTPNOTI_NOT_INITED, 48 | HTTPNOTI_ADDR_RESOLVING, 49 | HTTPNOTI_IFADDR_RESOLVING, 50 | HTTPNOTI_AVAILABLE, 51 | HTTPNOTI_IN_USE, 52 | HTTPNOTI_NOT_AVAILABLE, 53 | }; 54 | explicit RaspiHttpNoti(); 55 | ~RaspiHttpNoti(); 56 | 57 | bool Initialize(const std::string url); 58 | bool IsInited(void); 59 | 60 | void SendMotionNoti(const std::string motion_file); 61 | 62 | void OnMessage(rtc::Message* msg); 63 | 64 | protected: 65 | void ActivateSending(const std::string& noti); 66 | void DeactivateSending(void); 67 | 68 | // Resolve server name 69 | void OnResolveResult(rtc::AsyncResolverInterface* resolver); 70 | 71 | // Resolve ip address of network interface 72 | void DoIfAddrResolveConnect(void); 73 | void OnIfAddrConnect(rtc::AsyncSocket* socket); 74 | void OnIfAddrResolveClose(rtc::AsyncSocket* socket, int err); 75 | 76 | void DoConnect(void); 77 | void Close(); 78 | 79 | rtc::AsyncSocket* CreateClientSocket(int family); 80 | void OnRead(rtc::AsyncSocket* socket); 81 | void OnConnect(rtc::AsyncSocket* socket); 82 | void OnClose(rtc::AsyncSocket* socket, int err); 83 | 84 | // Returns true if the whole response has been read. 85 | bool ReadIntoBuffer(rtc::AsyncSocket* socket, std::string& data, 86 | size_t* content_length); 87 | int GetResponseStatus(const std::string& response); 88 | bool GetHeaderValue(const std::string& data, size_t eoh, 89 | const char* header_pattern, size_t* value); 90 | bool GetHeaderValue(const std::string& data, size_t eoh, 91 | const char* header_pattern, std::string* value); 92 | 93 | std::list noti_message_list_; 94 | std::string response_data_; 95 | 96 | std::string server_; 97 | int port_; 98 | std::string path_; 99 | std::string deviceid_; 100 | std::unique_ptr http_socket_; 101 | rtc::SocketAddress server_address_; 102 | rtc::SocketAddress local_address_; 103 | State state_; 104 | rtc::AsyncResolver* resolver_; 105 | webrtc::Mutex mutex_; 106 | RTC_DISALLOW_COPY_AND_ASSIGN(RaspiHttpNoti); 107 | }; 108 | 109 | #endif // RASPI_HTTPNOTI_H_ 110 | -------------------------------------------------------------------------------- /src/raspi_motion.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RASPI_MOTION_H_ 31 | #define RASPI_MOTION_H_ 32 | 33 | // to print average delays of processing 34 | // #define PRINT_PROCESS_DELAYS 35 | 36 | #include 37 | #include 38 | 39 | #include "api/task_queue/default_task_queue_factory.h" 40 | #include "api/task_queue/queued_task.h" 41 | #include "api/task_queue/task_queue_base.h" 42 | #include "config_motion.h" 43 | #include "mmal_wrapper.h" 44 | #include "raspi_httpnoti.h" 45 | #include "raspi_motionfile.h" 46 | #include "raspi_motionvector.h" 47 | #include "rtc_base/buffer_queue.h" 48 | #include "rtc_base/numerics/moving_average.h" 49 | #include "rtc_base/platform_thread.h" 50 | #include "rtc_base/synchronization/mutex.h" 51 | #include "system_wrappers/include/clock.h" 52 | 53 | class RaspiMotion : public MotionBlobObserver, 54 | public MotionImvObserver, 55 | public rtc::Event { 56 | public: 57 | explicit RaspiMotion(ConfigMotion* config_motion, int width, int height, 58 | int framerate, int bitrate); 59 | explicit RaspiMotion(ConfigMotion* config_motion); 60 | ~RaspiMotion(); 61 | 62 | bool IsEnabled() const; 63 | bool IsActive() const; 64 | 65 | // Motion Capture will use fixed resolution 66 | bool StartCapture(); 67 | void StopCapture(); 68 | 69 | // Motion Observers 70 | void OnMotionTriggered(int active_nums) override; 71 | void OnMotionCleared(int updates) override; 72 | void OnActivePoints(int total_points, int active_points) override; 73 | 74 | enum MOTION_STATE { 75 | CLEARED = 0, 76 | TRIGGERED, 77 | WAIT_CLEAR, 78 | }; 79 | 80 | private: 81 | bool DrainProcess(); 82 | // Encoded frame process thread 83 | rtc::PlatformThread drainThread_; 84 | webrtc::Mutex drain_lock_; 85 | 86 | bool motion_active_; 87 | bool motion_drain_quit_; 88 | 89 | // Motion Capture params 90 | int width_, height_, framerate_, bitrate_; 91 | 92 | webrtc::MMALEncoderWrapper* mmal_encoder_; 93 | webrtc::Clock* const clock_; 94 | 95 | // motion file 96 | std::unique_ptr motion_file_; 97 | 98 | // making buffer queue_capacity based on IntraFrame Period 99 | size_t frame_buffer_size_; // Default Frame buffer size 100 | size_t mv_buffer_size_; // Default Frame buffer size 101 | 102 | // MotionVector Analysis 103 | RaspiMotionVector motion_analysis_; 104 | MOTION_STATE motion_state_; 105 | uint64_t last_average_print_timestamp_; 106 | uint64_t motion_clear_wait_timestamp_; 107 | uint32_t motion_clear_wait_period_; 108 | 109 | rtc::MovingAverage motion_active_average_; 110 | #ifdef PRINT_PROCESS_DELAYS 111 | rtc::MovingAverage imv_process_delay_; 112 | rtc::MovingAverage frame_process_delay_; 113 | rtc::MovingAverage drain_process_delay_; 114 | #endif // PRINT_PROCESS_DELAYS 115 | int motion_active_percent_clear_threshold_; 116 | int motion_active_percent_trigger_threshold_; 117 | bool notification_enable_; 118 | std::string notification_url_; 119 | 120 | ConfigMotion* config_motion_; 121 | std::unique_ptr task_queue_factory_; 122 | rtc::TaskQueue worker_queue_; 123 | 124 | RTC_DISALLOW_COPY_AND_ASSIGN(RaspiMotion); 125 | }; 126 | 127 | struct RaspiMotionHolder { 128 | RaspiMotionHolder(ConfigMotion* config_motion); 129 | ~RaspiMotionHolder(); 130 | bool Start(); 131 | bool Stop(); 132 | bool SetNotificationUrl(bool enable, const std::string url); 133 | 134 | private: 135 | std::unique_ptr raspi_motion_; 136 | ConfigMotion* config_motion_; 137 | }; 138 | 139 | #endif // RASPI_MOTION_H_ 140 | -------------------------------------------------------------------------------- /src/raspi_motionblob.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RASPI_MOTIONBLOB_H_ 31 | #define RASPI_MOTIONBLOB_H_ 32 | 33 | #include 34 | #include 35 | 36 | #define MAX_BLOB_LIST_SIZE 256 37 | 38 | struct MotionBlob { 39 | enum MotionBlobStatus { 40 | UNUSED = 0, 41 | COLLECTING, 42 | ACTIVE, 43 | }; 44 | MotionBlob() 45 | : sx_(0), 46 | sy_(0), 47 | status_(UNUSED), 48 | size_(0), 49 | overlap_size_(0), 50 | update_counter_(0), 51 | blob_(nullptr){}; 52 | uint8_t sx_, sy_; 53 | MotionBlobStatus status_; 54 | int size_; 55 | int overlap_size_; 56 | int update_counter_; 57 | uint8_t bid; 58 | uint8_t *blob_; 59 | }; 60 | 61 | struct BlobPoint { 62 | BlobPoint(uint8_t x, uint8_t y) : x_(x), y_(y){}; 63 | virtual ~BlobPoint() {} 64 | uint8_t x_; 65 | uint8_t y_; 66 | }; 67 | 68 | struct ActiveBlob { 69 | uint8_t id_; 70 | int size_; // percent 71 | uint32_t frame_update_count_; 72 | }; 73 | 74 | class RaspiMotionBlob { 75 | public: 76 | explicit RaspiMotionBlob(int mvx, int mvy, float blob_cancel_threshold, 77 | int blob_tracking_threshold); 78 | ~RaspiMotionBlob(); 79 | 80 | bool UpdateBlob(uint8_t *motion, size_t size); 81 | void GetBlobImage(uint8_t *buffer, size_t buflen); 82 | int GetActiveBlobCount(void); 83 | int GetActiveBlobUpdateCount(void); 84 | 85 | void SetBlobCancelThreshold(int cancel_min); 86 | 87 | // disallow copy and assign 88 | void operator=(const RaspiMotionBlob &) = delete; 89 | RaspiMotionBlob(const RaspiMotionBlob &) = delete; 90 | 91 | private: 92 | bool AccquireBlobId(int *blob_id); 93 | void UnaccquireBlobId(int blob_id); 94 | 95 | size_t SearchConnectedBlob(uint8_t x, uint8_t y, int blob_id); 96 | bool SearchConnectedNeighbor(uint8_t x, uint8_t y, int blob_id, 97 | std::list &connected_list); 98 | 99 | void MergeActiveBlob(std::list &active_blob_list); 100 | void TrackingBlob(std::list &active_blob_list); 101 | 102 | void DumpBlobBuffer(const char *header, uint8_t *buffer); 103 | void DumpList(std::list &connected_list); 104 | void DumpBlobIdList(const char *header); 105 | 106 | uint32_t mvx_, mvy_; 107 | float blob_cancel_threshold_; 108 | uint32_t blob_tracking_threshold_; 109 | 110 | uint8_t *extracted_; 111 | uint8_t *extracted_previous_; 112 | uint8_t *source_; 113 | 114 | MotionBlob blob_list_[MAX_BLOB_LIST_SIZE]; 115 | std::list active_blob_list_; 116 | }; 117 | 118 | #endif // RASPI_MOTIONBLOB_H_ 119 | -------------------------------------------------------------------------------- /src/raspi_motionblobid.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RASPI_MOTIONBLOBID_H_ 31 | #define RASPI_MOTIONBLOBID_H_ 32 | 33 | #include 34 | #include 35 | 36 | struct MotionBlob { 37 | enum MotionBlobStatus { 38 | UNUSED = 0, 39 | COLLECTING, 40 | ACTIVE, 41 | }; 42 | MotionBlob() 43 | : status_(UNUSED), 44 | size_(0), 45 | sx_(0), 46 | sy_(0), 47 | overlap_size_(0), 48 | update_counter_(0){}; 49 | MotionBlobStatus status_; 50 | int size_; 51 | int overlap_size_; 52 | int update_counter_; 53 | uint8_t sx_, sy_; 54 | }; 55 | 56 | class MotionBlobId { 57 | public: 58 | explicit MotionBlobId(); 59 | ~RaspiMotionBlobId(); 60 | 61 | private: 62 | bool CreateBlobId(uint16_t* blob_id); 63 | void FreeBlobId(uint16_t blob_id); 64 | MotionBlob* GetMotionBlob(uint16_t blob_id); 65 | }; 66 | 67 | #endif // RASPI_MOTIONBLOBID_H_ 68 | -------------------------------------------------------------------------------- /src/raspi_motionfile.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RASPI_MOTIONFIE_H_ 31 | #define RASPI_MOTIONFIE_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "api/task_queue/default_task_queue_factory.h" 37 | #include "api/task_queue/queued_task.h" 38 | #include "api/task_queue/task_queue_base.h" 39 | #include "config_motion.h" 40 | #include "file_writer_handle.h" 41 | #include "rtc_base/platform_thread.h" 42 | #include "rtc_base/synchronization/mutex.h" 43 | #include "system_wrappers/include/clock.h" 44 | 45 | class LimitTotalDirSizeTask : public webrtc::QueuedTask { 46 | public: 47 | explicit LimitTotalDirSizeTask(const std::string& base_path, 48 | const std::string& prefix, size_t size_limit) 49 | : base_path_(base_path), prefix_(prefix), size_limit_(size_limit) {} 50 | 51 | private: 52 | bool Run() override; 53 | const std::string base_path_, prefix_; 54 | size_t size_limit_; 55 | }; 56 | 57 | class RaspiMotionFile { 58 | public: 59 | explicit RaspiMotionFile(ConfigMotion* config_motion, 60 | const std::string base_path, 61 | const std::string prefix, int frame_queue_size, 62 | int motion_queue_size); 63 | ~RaspiMotionFile(); 64 | 65 | // Frame queuing 66 | bool FrameQueuing(const void* data, size_t bytes, size_t* bytes_written, 67 | bool is_keyframe); 68 | // Inline Motion Vector queuing 69 | bool ImvQueuing(const void* data, size_t bytes, size_t* bytes_written, 70 | bool is_keyframe); 71 | 72 | bool IsWriterActive(void); 73 | bool StartWriter(void); 74 | bool StopWriter(void); 75 | 76 | private: 77 | std::string base_path_; 78 | std::string prefix_; 79 | bool writer_active_; 80 | 81 | // Frame and MV queue for saving frame and mv 82 | std::unique_ptr frame_writer_handle_; 83 | std::unique_ptr imv_writer_handle_; 84 | 85 | size_t frame_file_size_limit_; 86 | 87 | webrtc::Mutex mutex_; 88 | webrtc::Clock* const clock_; 89 | ConfigMotion* config_motion_; 90 | RTC_DISALLOW_COPY_AND_ASSIGN(RaspiMotionFile); 91 | }; 92 | 93 | #endif // RASPI_MOTIONFIE_H_ 94 | -------------------------------------------------------------------------------- /src/raspi_motionvector.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RASPI_MOTIONVECTOR_H_ 31 | #define RASPI_MOTIONVECTOR_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "raspi_motionblob.h" 37 | 38 | struct MotionVector { 39 | int8_t mx_; 40 | int8_t my_; 41 | uint16_t sad; 42 | }; 43 | 44 | struct MotionBlobObserver { 45 | virtual void OnMotionTriggered(int active_nums) = 0; 46 | virtual void OnMotionCleared(int updates) = 0; 47 | 48 | protected: 49 | virtual ~MotionBlobObserver() {} 50 | }; 51 | 52 | struct MotionImvObserver { 53 | virtual void OnActivePoints(int total_points, int active_points) = 0; 54 | 55 | protected: 56 | virtual ~MotionImvObserver() {} 57 | }; 58 | 59 | class RaspiMotionVector { 60 | public: 61 | explicit RaspiMotionVector(int x, int y, int framerate, 62 | bool use_imv_coordination, 63 | float blob_cancel_threshold, 64 | int blob_tracking_threshold); 65 | ~RaspiMotionVector(); 66 | 67 | bool Analyse(uint8_t *buffer, size_t len); 68 | 69 | void GetIMVImage(uint8_t *buffer, size_t buflen); 70 | void GetMotionImage(uint8_t *buffer, size_t buflen); 71 | // available only when blob is enabled 72 | bool GetBlobImage(uint8_t *buffer, size_t buflen); 73 | 74 | void SetBlobEnable(bool blob_enable); 75 | void SetMotionActiveTreshold(int max, int min); 76 | void RegisterBlobObserver(MotionBlobObserver *observer); 77 | void RegisterImvObserver(MotionImvObserver *observer); 78 | 79 | // disallow copy and assign 80 | void operator=(const RaspiMotionVector &) = delete; 81 | RaspiMotionVector(const RaspiMotionVector &) = delete; 82 | 83 | private: 84 | // bitcount uses the 'Counting bits set, in parallel' algorithm below. 85 | // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 86 | int BitCount(uint32_t motion_value); 87 | 88 | size_t mvx_, mvy_; 89 | size_t valid_mv_frame_size_; 90 | bool blob_enable_; 91 | 92 | uint32_t binary_oper_; 93 | // motion vector processing buffers 94 | uint32_t *candidate_; 95 | uint8_t *motion_; 96 | uint64_t update_counter_; 97 | uint32_t initial_coolingdown_; 98 | bool enable_observer_callback_; 99 | 100 | std::unique_ptr blob_; 101 | uint32_t blob_active_count_; 102 | uint32_t blob_active_updates_; 103 | MotionBlobObserver *blob_observer_; 104 | MotionImvObserver *imv_observer_; 105 | uint32_t motion_trigger_threshold_; 106 | uint32_t motion_clear_threshold_; 107 | float blob_cancel_threshold_; 108 | int blob_tracking_threshold_; 109 | }; 110 | 111 | #endif // RASPI_MOTIONVECTOR_H_ 112 | -------------------------------------------------------------------------------- /src/raspi_quality_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef RPI_QUALITY_CONFIG_H_ 31 | #define RPI_QUALITY_CONFIG_H_ 32 | 33 | #include 34 | #include 35 | 36 | #include "absl/types/optional.h" 37 | #include "config_media.h" 38 | #include "rtc_base/numerics/moving_average.h" 39 | #include "system_wrappers/include/clock.h" 40 | #include "wstreamer_types.h" 41 | 42 | // Currently, Only BWE-based QoS functions are implemented. 43 | class QualityConfig { 44 | public: 45 | explicit QualityConfig(); 46 | ~QualityConfig(); 47 | 48 | void ReportFrameSize(int frame_size); 49 | void ReportFrameRate(int framerate); 50 | void ReportTargetBitrate(int bitrate); // kbps 51 | 52 | wstreamer::VideoEncodingParams& GetBestMatch(int target_bitrate); 53 | wstreamer::VideoEncodingParams& GetBestMatch(); 54 | wstreamer::VideoEncodingParams& GetInitialBestMatch(); 55 | 56 | private: 57 | struct ResolutionConfigEntry { 58 | ResolutionConfigEntry(int width, int height, int max_fps, int min_fps); 59 | int width_, height_, max_fps_, min_fps_; 60 | int average_bandwidth_, max_bandwidth_, min_bandwidth_; 61 | }; 62 | // media configuration sigleton reference 63 | ConfigMedia* config_media_; 64 | 65 | std::list resolution_config_; 66 | int target_framerate_; 67 | int target_bitrate_; 68 | rtc::MovingAverage average_mf_; /* average motion factor */ 69 | wstreamer::VideoEncodingParams current_res_; 70 | bool use_dynamic_resolution_; 71 | bool use_initial_resolution_; 72 | }; 73 | 74 | #endif // RPI_QUALITY_CONFIG_H_ 75 | -------------------------------------------------------------------------------- /src/raspicli.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Lyu,KeunChang 3 | * 4 | * This is a stripped down version of the original RaspiCLI module from the 5 | * raspberry pi userland-master branch, 6 | * Original copyright info below 7 | */ 8 | /* 9 | Copyright (c) 2013, Broadcom Europe Ltd 10 | Copyright (c) 2013, James Hughes 11 | All rights reserved. 12 | 13 | Redistribution and use in source and binary forms, with or without 14 | modification, are permitted provided that the following conditions are met: 15 | * Redistributions of source code must retain the above copyright 16 | notice, this list of conditions and the following disclaimer. 17 | * Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in the 19 | documentation and/or other materials provided with the distribution. 20 | * Neither the name of the copyright holder nor the 21 | names of its contributors may be used to endorse or promote products 22 | derived from this software without specific prior written permission. 23 | 24 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 25 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 26 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 27 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 28 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 29 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 31 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 32 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | */ 35 | 36 | /** 37 | * \file RaspiCLI.c 38 | * Code for handling command line parameters 39 | * 40 | * \date 4th March 2013 41 | * \Author: James Hughes 42 | * 43 | * Description 44 | * 45 | * Some functions/structures for command line parameter parsing 46 | * 47 | */ 48 | #include "raspicli.h" 49 | 50 | #include 51 | #include 52 | #include 53 | #include 54 | 55 | #include "interface/vcos/vcos.h" 56 | 57 | /** 58 | * Convert a string from command line to a comand_id from the list 59 | * 60 | * @param commands Array of command to check 61 | * @param num_command Number of commands in the array 62 | * @param arg String to search for in the list 63 | * @param num_parameters Returns the number of parameters used by the command 64 | * 65 | * @return command ID if found, -1 if not found 66 | * 67 | */ 68 | int raspicli_get_command_id(const COMMAND_LIST *commands, 69 | const int num_commands, const char *arg, 70 | int *num_parameters) { 71 | int command_id = -1; 72 | int j; 73 | 74 | vcos_assert(commands); 75 | vcos_assert(num_parameters); 76 | vcos_assert(arg); 77 | 78 | if (!commands || !num_parameters || !arg) return -1; 79 | 80 | for (j = 0; j < num_commands; j++) { 81 | if (!strcmp(arg, commands[j].command) || 82 | !strcmp(arg, commands[j].abbrev)) { 83 | // match 84 | command_id = commands[j].id; 85 | *num_parameters = commands[j].num_parameters; 86 | break; 87 | } 88 | } 89 | 90 | return command_id; 91 | } 92 | 93 | /** 94 | * Display the list of commands in help format 95 | * 96 | * @param commands Array of command to check 97 | * @param num_command Number of commands in the arry 98 | * 99 | * 100 | */ 101 | void raspicli_display_help(const COMMAND_LIST *commands, 102 | const int num_commands) { 103 | int i; 104 | 105 | vcos_assert(commands); 106 | 107 | if (!commands) return; 108 | 109 | for (i = 0; i < num_commands; i++) { 110 | fprintf(stdout, "-%s, -%s\t: %s\n", commands[i].abbrev, 111 | commands[i].command, commands[i].help); 112 | } 113 | } 114 | 115 | /** 116 | * Function to take a string, a mapping, and return the int equivalent 117 | * @param str Incoming string to match 118 | * @param map Mapping data 119 | * @param num_refs The number of items in the mapping data 120 | * @return The integer match for the string, or -1 if no match 121 | */ 122 | int raspicli_map_xref(const char *str, const XREF_T *map, int num_refs) { 123 | int i; 124 | 125 | for (i = 0; i < num_refs; i++) { 126 | if (!strcasecmp(str, map[i].mode)) { 127 | return map[i].mmal_mode; 128 | } 129 | } 130 | return -1; 131 | } 132 | 133 | /** 134 | * Function to take a mmal enum (as int) and return the string equivalent 135 | * @param en Incoming int to match 136 | * @param map Mapping data 137 | * @param num_refs The number of items in the mapping data 138 | * @return const pointer to string, or NULL if no match 139 | */ 140 | const char *raspicli_unmap_xref(const int en, XREF_T *map, int num_refs) { 141 | int i; 142 | 143 | for (i = 0; i < num_refs; i++) { 144 | if (en == map[i].mmal_mode) { 145 | return map[i].mode; 146 | } 147 | } 148 | return NULL; 149 | } 150 | -------------------------------------------------------------------------------- /src/raspicli.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Lyu,KeunChang 3 | * 4 | * This is a stripped down version of the original RaspiCamControl module from 5 | * the raspberry pi userland-master branch, Original copyright info below 6 | */ 7 | /* 8 | Copyright (c) 2013, Broadcom Europe Ltd 9 | Copyright (c) 2013, James Hughes 10 | All rights reserved. 11 | 12 | Redistribution and use in source and binary forms, with or without 13 | modification, are permitted provided that the following conditions are met: 14 | * Redistributions of source code must retain the above copyright 15 | notice, this list of conditions and the following disclaimer. 16 | * Redistributions in binary form must reproduce the above copyright 17 | notice, this list of conditions and the following disclaimer in the 18 | documentation and/or other materials provided with the distribution. 19 | * Neither the name of the copyright holder nor the 20 | names of its contributors may be used to endorse or promote products 21 | derived from this software without specific prior written permission. 22 | 23 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 24 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 25 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 26 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 27 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 28 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 29 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 30 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 32 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | */ 34 | 35 | #ifndef RASPICLI_H_ 36 | #define RASPICLI_H_ 37 | 38 | typedef struct { 39 | int id; 40 | char *command; 41 | char *abbrev; 42 | char *help; 43 | int num_parameters; 44 | } COMMAND_LIST; 45 | 46 | /// Cross reference structure, mode string against mode id 47 | typedef struct xref_t { 48 | char *mode; 49 | int mmal_mode; 50 | } XREF_T; 51 | 52 | void raspicli_display_help(const COMMAND_LIST *commands, 53 | const int num_commands); 54 | int raspicli_get_command_id(const COMMAND_LIST *commands, 55 | const int num_commands, const char *arg, 56 | int *num_parameters); 57 | 58 | int raspicli_map_xref(const char *str, const XREF_T *map, int num_refs); 59 | const char *raspicli_unmap_xref(const int en, XREF_T *map, int num_refs); 60 | 61 | #endif // RASPICLI_H_ 62 | 63 | -------------------------------------------------------------------------------- /src/raspipreview.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Lyu,KeunChang 3 | * 4 | * This is a stripped down version of the original RaspiCamControl module from 5 | * the raspberry pi userland-master branch, Original copyright info below 6 | */ 7 | /* 8 | Copyright (c) 2013, Broadcom Europe Ltd 9 | Copyright (c) 2013, James Hughes 10 | All rights reserved. 11 | 12 | Redistribution and use in source and binary forms, with or without 13 | modification, are permitted provided that the following conditions are met: 14 | * Redistributions of source code must retain the above copyright 15 | notice, this list of conditions and the following disclaimer. 16 | * Redistributions in binary form must reproduce the above copyright 17 | notice, this list of conditions and the following disclaimer in the 18 | documentation and/or other materials provided with the distribution. 19 | * Neither the name of the copyright holder nor the 20 | names of its contributors may be used to endorse or promote products 21 | derived from this software without specific prior written permission. 22 | 23 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 24 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 25 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 26 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 27 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 28 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 29 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 30 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 32 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | */ 34 | 35 | #ifndef RASPIPREVIEW_H_ 36 | #define RASPIPREVIEW_H_ 37 | 38 | /// Layer that preview window should be displayed on 39 | #define PREVIEW_LAYER 2 40 | 41 | // Frames rates of 0 implies variable, but denominator needs to be 1 to prevent 42 | // div by 0 43 | #define PREVIEW_FRAME_RATE_NUM 0 44 | #define PREVIEW_FRAME_RATE_DEN 1 45 | 46 | #define FULL_RES_PREVIEW_FRAME_RATE_NUM 0 47 | #define FULL_RES_PREVIEW_FRAME_RATE_DEN 1 48 | 49 | #define FULL_FOV_PREVIEW_16x9_X 1280 50 | #define FULL_FOV_PREVIEW_16x9_Y 720 51 | 52 | #define FULL_FOV_PREVIEW_4x3_X 1296 53 | #define FULL_FOV_PREVIEW_4x3_Y 972 54 | 55 | #define FULL_FOV_PREVIEW_FRAME_RATE_NUM 0 56 | #define FULL_FOV_PREVIEW_FRAME_RATE_DEN 1 57 | 58 | typedef struct { 59 | int wantPreview; /// Display a preview 60 | int wantFullScreenPreview; /// 0 is use previewRect, non-zero to use full 61 | /// screen 62 | int opacity; /// Opacity of window - 0 = transparent, 255 = opaque 63 | MMAL_RECT_T 64 | previewWindow; /// Destination rectangle for the preview window. 65 | MMAL_COMPONENT_T * 66 | preview_component; /// Pointer to the created preview display component 67 | } RASPIPREVIEW_PARAMETERS; 68 | 69 | MMAL_STATUS_T raspipreview_create(RASPIPREVIEW_PARAMETERS *state); 70 | void raspipreview_destroy(RASPIPREVIEW_PARAMETERS *state); 71 | void raspipreview_set_defaults(RASPIPREVIEW_PARAMETERS *state); 72 | void raspipreview_dump_parameters(RASPIPREVIEW_PARAMETERS *state); 73 | int raspipreview_parse_cmdline(RASPIPREVIEW_PARAMETERS *params, 74 | const char *arg1, const char *arg2); 75 | void raspipreview_display_help(); 76 | 77 | #endif /* RASPIPREVIEW_H_ */ 78 | -------------------------------------------------------------------------------- /src/session_config.cc: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2020, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #include "session_config.h" 31 | 32 | #include 33 | #include 34 | #include 35 | 36 | #include "rtc_base/checks.h" 37 | #include "rtc_base/logging.h" 38 | #include "rtc_base/strings/json.h" 39 | #include "utils_pc_config.h" 40 | 41 | SessionConfig::SessionConfig() {} 42 | SessionConfig::~SessionConfig() {} 43 | 44 | void SessionConfig::SetRtcConfig(int id, std::string str_rtc_config) { 45 | webrtc::MutexLock lock(&mutex_); 46 | RTC_LOG(INFO) << __FUNCTION__ << ", id : " << id; 47 | for (std::vector::iterator it = session_pc_config_.begin(); 48 | it != session_pc_config_.end(); ++it) { 49 | // update rtc config 50 | if (it->id_ == id) { 51 | it->rtc_config_ = str_rtc_config; 52 | return; 53 | } 54 | } 55 | 56 | RTC_LOG(INFO) << "SessionConfig id " << id 57 | << " not found, adding new config "; 58 | session_pc_config_.push_back(Config(id, str_rtc_config)); 59 | } 60 | 61 | bool SessionConfig::GetConfig(int id, Config &pc_config) { 62 | webrtc::MutexLock lock(&mutex_); 63 | RTC_LOG(INFO) << __FUNCTION__ << ", id : " << id; 64 | for (std::vector::iterator it = session_pc_config_.begin(); 65 | it != session_pc_config_.end(); ++it) { 66 | if (it->id_ == id) { 67 | RTC_LOG(INFO) << "SessionConfig Get id found: " << it->id_ 68 | << ", rtc_config : " << !it->rtc_config_.empty(); 69 | pc_config = *it; 70 | return true; 71 | } 72 | } 73 | RTC_LOG(LS_ERROR) << "SessionRtcConfig id not found : " << id; 74 | return false; 75 | } 76 | 77 | void SessionConfig::Remove(int id) { 78 | webrtc::MutexLock lock(&mutex_); 79 | RTC_LOG(INFO) << __FUNCTION__ << ", id: " << id 80 | << ", size : " << session_pc_config_.size(); 81 | 82 | for (std::vector::iterator it = session_pc_config_.begin(); 83 | it != session_pc_config_.end(); ++it) { 84 | if (it->id_ == id) { 85 | RTC_LOG(INFO) << "SessionRtcConfig Remove found id: " << it->id_; 86 | session_pc_config_.erase(it); 87 | RTC_LOG(INFO) << "SessionConfig size : " 88 | << session_pc_config_.size(); 89 | return; 90 | } 91 | } 92 | RTC_LOG(INFO) << "SessionConfig id not found : " << id 93 | << ", size : " << session_pc_config_.size(); 94 | } 95 | 96 | -------------------------------------------------------------------------------- /src/session_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2020, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef SESSION_CONFIG_H_ 31 | #define SESSION_CONFIG_H_ 32 | 33 | #include 34 | #include 35 | #include 36 | 37 | #include "rtc_base/checks.h" 38 | #include "rtc_base/synchronization/mutex.h" 39 | #include "utils_pc_config.h" 40 | 41 | class SessionConfig { 42 | public: 43 | struct Config { 44 | explicit Config(int id, const std::string &str_rtc_config) 45 | : id_(id), rtc_config_(str_rtc_config) {} 46 | Config() : id_(0) {} 47 | virtual ~Config(){}; 48 | inline const std::string GetRtcConfig(void) const { 49 | return rtc_config_.empty() == false ? rtc_config_ : ""; 50 | } 51 | inline void clear() { rtc_config_.clear(); } 52 | int id_; 53 | std::string rtc_config_; 54 | // TODO: need to implement video/audio config 55 | }; 56 | 57 | SessionConfig(); 58 | ~SessionConfig(); 59 | 60 | // Temporarily save the rtc config set by the manager through 61 | // the websocket interface and make it available for use in the session. 62 | // void Set(int id, utils::RTCConfiguration &pc_config); 63 | void SetRtcConfig(int id, std::string str_rtc_config); 64 | bool GetConfig(int id, Config &pc_config); 65 | void Remove(int id); 66 | 67 | private: 68 | webrtc::Mutex mutex_; 69 | // Session RtcConfig 70 | std::vector session_pc_config_; 71 | }; 72 | 73 | #endif // SESSION_CONFIG_H_ 74 | -------------------------------------------------------------------------------- /src/streamer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2016, rpi-webrtc-streamer Lyu,KeunChang 3 | * 4 | * stream.h 5 | * 6 | * Modified version of src/webrtc/examples/peer/client/peer_connection.h 7 | * in WebRTC source tree 8 | * The origianl copyright info below. 9 | */ 10 | /* 11 | * Copyright 2012 The WebRTC Project Authors. All rights reserved. 12 | * 13 | * Use of this source code is governed by a BSD-style license 14 | * that can be found in the LICENSE file in the root of the source 15 | * tree. An additional intellectual property rights grant can be found 16 | * in the file PATENTS. All contributing project authors may 17 | * be found in the AUTHORS file in the root of the source tree. 18 | */ 19 | 20 | #ifndef STREAMER_H_ 21 | #define STREAMER_H_ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | #include "api/media_stream_interface.h" 29 | #include "api/peer_connection_interface.h" 30 | #include "config_streamer.h" 31 | #include "pc/video_track_source.h" 32 | #include "session_config.h" 33 | #include "streamer_signaling.h" 34 | 35 | class Streamer : public webrtc::PeerConnectionObserver, 36 | public webrtc::CreateSessionDescriptionObserver, 37 | public SignalingInbound { 38 | public: 39 | Streamer(SignalingOutbound* signaling_outbound, ConfigStreamer* config); 40 | void AddObserver(SignalingOutbound* session); 41 | bool connection_active() const; 42 | virtual void Close(); 43 | 44 | protected: 45 | ~Streamer(); 46 | bool InitializePeerConnection(); 47 | bool CreatePeerConnection(); 48 | void DeletePeerConnection(); 49 | void AddTracks(); 50 | 51 | // 52 | // PeerConnectionObserver implementation. 53 | // 54 | void OnSignalingChange( 55 | webrtc::PeerConnectionInterface::SignalingState new_state) override; 56 | void OnDataChannel( 57 | rtc::scoped_refptr channel) override {} 58 | void OnRenegotiationNeeded() override {} 59 | 60 | void OnStandardizedIceConnectionChange( 61 | webrtc::PeerConnectionInterface::IceConnectionState new_state) override; 62 | void OnConnectionChange(webrtc::PeerConnectionInterface::PeerConnectionState 63 | new_state) override; 64 | void OnIceGatheringChange( 65 | webrtc::PeerConnectionInterface::IceGatheringState new_state) override; 66 | void OnIceCandidate( 67 | const webrtc::IceCandidateInterface* candidate) override; 68 | void OnIceConnectionReceivingChange(bool receiving) override {} 69 | 70 | void OnIceCandidateError(const std::string& host_candidate, 71 | const std::string& url, int error_code, 72 | const std::string& error_text) override; 73 | 74 | void OnIceCandidateError(const std::string& address, int port, 75 | const std::string& url, int error_code, 76 | const std::string& error_text) override; 77 | 78 | void OnAddTrack( 79 | rtc::scoped_refptr receiver, 80 | const std::vector>& 81 | streams) override; 82 | void OnRemoveTrack( 83 | rtc::scoped_refptr receiver) override; 84 | 85 | void OnInterestingUsage(int usage_pattern) override; 86 | 87 | // 88 | // CreateSessionDescriptionObserver implementation. 89 | // 90 | virtual void OnSuccess(webrtc::SessionDescriptionInterface* desc) override; 91 | virtual void OnFailure(webrtc::RTCError error) override; 92 | 93 | // 94 | // StreamerSessionObserver implementation. 95 | // 96 | virtual void OnPeerConnected(int peer_id, 97 | const SessionConfig::Config& config) override; 98 | virtual void OnPeerDisconnected(int peer_id) override; 99 | virtual void OnMessageFromPeer(int peer_id, 100 | const std::string& message) override; 101 | virtual void OnMessageSent(int err) override; 102 | 103 | private: 104 | // Send a message to the remote peer. 105 | void SendMessage(const std::string& message /* json format */); 106 | // Send a event message to the remote peer. 107 | void ReportEvent(bool drop_connection, const std::string message); 108 | 109 | // Change the max_bitrate in RtpSender 110 | void UpdateMaxBitrate(); 111 | // audio options 112 | void GetAudioOptions(cricket::AudioOptions& options); 113 | 114 | int peer_id_; 115 | SessionConfig::Config pc_config_; 116 | rtc::scoped_refptr peer_connection_; 117 | rtc::scoped_refptr 118 | peer_connection_factory_; 119 | rtc::scoped_refptr adm_; 120 | 121 | std::unique_ptr worker_thread_; 122 | std::unique_ptr network_thread_; 123 | std::unique_ptr signaling_thread_; 124 | 125 | std::vector> 126 | video_track_sources_; 127 | 128 | SignalingOutbound* signaling_outbound_; 129 | ConfigStreamer* config_streamer_; 130 | webrtc::PeerConnectionInterface::IceConnectionState ice_state_; 131 | webrtc::PeerConnectionInterface::PeerConnectionState peerconnection_state_; 132 | }; 133 | 134 | #endif // STREAMER_H_ 135 | -------------------------------------------------------------------------------- /src/streamer_signaling.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef STREAMER_SIGNALING_H_ 31 | #define STREAMER_SIGNALING_H_ 32 | 33 | #include 34 | 35 | #include "config_motion.h" 36 | #include "raspi_motion.h" 37 | #include "session_config.h" 38 | 39 | struct SignalingInbound { 40 | virtual void OnPeerConnected(int peer_id, 41 | const SessionConfig::Config& config) = 0; 42 | virtual void OnPeerDisconnected(int peer_id) = 0; 43 | virtual void OnMessageFromPeer(int peer_id, const std::string& message) = 0; 44 | virtual void OnMessageSent(int err) = 0; 45 | 46 | protected: 47 | virtual ~SignalingInbound() {} 48 | }; 49 | 50 | struct SignalingOutbound { 51 | virtual void SetSignalingInbound(SignalingInbound* inbound) = 0; 52 | virtual bool SendMessageToPeer(const int peer_id, 53 | const std::string& message) = 0; 54 | virtual void ReportEvent(const int peer_id, bool drop_connection, 55 | const std::string& message) = 0; 56 | 57 | protected: 58 | virtual ~SignalingOutbound() {} 59 | }; 60 | 61 | class StreamerProxy; // forward declaration 62 | class RaspiMotion; // forward declaration 63 | class SignalingChannelHelper : public SignalingOutbound { 64 | public: 65 | void SetSignalingInbound(SignalingInbound* inbound){}; 66 | 67 | protected: 68 | SignalingChannelHelper(StreamerProxy* proxy); 69 | virtual ~SignalingChannelHelper() {} 70 | // Offer will be generated at server side. 71 | bool StartSignalingSession(const int peer_id, 72 | const SessionConfig::Config& config); 73 | // the messsage is offer message from client 74 | bool StartSignalingSession(const int peer_id, 75 | const SessionConfig::Config& config, 76 | const std::string& message); 77 | void StopSignalingSession(); 78 | void MessageFromPeer(const std::string& message); 79 | int GetActivePeerId(); 80 | bool IsSignalingSessionActive(); 81 | 82 | private: 83 | bool streamsession_active_; 84 | SignalingInbound* signaling_inbound_; 85 | StreamerProxy* proxy_; 86 | int peer_id_; 87 | }; 88 | 89 | class StreamerProxy : public SignalingOutbound { 90 | public: 91 | StreamerProxy(RaspiMotionHolder* motion_holder); 92 | ~StreamerProxy() {} 93 | 94 | bool StartStremerSignaling(SignalingOutbound* outbound, int peer_id, 95 | const SessionConfig::Config& config); 96 | bool StartStremerSignaling(SignalingOutbound* outbound, int peer_id, 97 | const SessionConfig::Config& config, 98 | const std::string& message); 99 | void StopStreamerSignaling(SignalingOutbound* outbound, int peer_id); 100 | void MessageFromPeer(int peer_id, const std::string& message); 101 | void MessageSent(int err); 102 | // SignalingOutbound 103 | void SetSignalingInbound(SignalingInbound* inbound) override; 104 | bool SendMessageToPeer(const int peer_id, 105 | const std::string& message) override; 106 | void ReportEvent(const int peer_id, bool drop_connection, 107 | const std::string& message) override; 108 | 109 | private: 110 | SignalingOutbound* active_signaling_outbound_; 111 | SignalingInbound* signaling_inbound_; // inbound signaling channel 112 | RaspiMotionHolder* motion_holder_; 113 | bool motion_enabled_; 114 | int active_peer_id_; 115 | std::string active_peer_name_; 116 | }; 117 | 118 | #endif // STREAMER_SIGNALING_H_ 119 | -------------------------------------------------------------------------------- /src/utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2011 The WebRTC Project Authors. All rights reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. An additional intellectual property rights grant can be found 7 | * in the file PATENTS. All contributing project authors may 8 | * be found in the AUTHORS file in the root of the source tree. 9 | */ 10 | #ifndef STREAMER_UTILS_H_ 11 | #define STREAMER_UTILS_H_ 12 | 13 | #include 14 | #include 15 | 16 | #include 17 | 18 | #include "absl/types/optional.h" 19 | #include "rtc_base/logging.h" 20 | 21 | namespace utils { 22 | 23 | void PrintLicenseInfo(); 24 | std::string GetVersionInfo(); 25 | const char* GetProgramDescription(); 26 | 27 | // utility functions 28 | bool ParseVideoResolution(const std::string resolution, int* width, 29 | int* height); 30 | rtc::LoggingSeverity String2LogSeverity(const std::string severity); 31 | 32 | const std::string GetDateTimeString(void); 33 | 34 | // Getting folder and parent folder from std::string path 35 | std::string GetFolder(std::string path); 36 | std::string GetParentFolder(std::string path); 37 | 38 | // Filesystem access utility helpers 39 | bool IsFolder(const std::string& file); 40 | bool IsFile(const std::string& file); 41 | bool DeleteFile(const std::string& file); 42 | bool MoveFile(const std::string& old_file, const std::string& new_file); 43 | bool SymLink(const std::string& origin, const std::string& symbolic_link); 44 | bool GetFolderWithTailingDelimiter(const std::string& path, 45 | std::string& path_with_delimiter); 46 | absl::optional GetFileSize(const std::string& file); 47 | absl::optional GetFileChangedTime(const std::string& file); 48 | 49 | // Get hardware serial number from /proc/cpu 50 | bool GetHardwareDeviceId(std::string* deviceid); 51 | 52 | }; // namespace utils 53 | 54 | #endif // STREAMER_UTILS_H_ 55 | -------------------------------------------------------------------------------- /src/utils_pc_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2018, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef STREAMER_UTILS_PC_CONFIG_H_ 31 | #define STREAMER_UTILS_PC_CONFIG_H_ 32 | 33 | #pragma once 34 | 35 | #include 36 | 37 | #include 38 | 39 | #include "api/media_stream_interface.h" 40 | #include "api/peer_connection_interface.h" 41 | 42 | namespace utils { 43 | 44 | // typedef aliases for webrtc::PeerConnectionInterface structures 45 | typedef webrtc::PeerConnectionInterface::SignalingState SignalingState; 46 | typedef webrtc::PeerConnectionInterface::IceGatheringState IceGatheringState; 47 | typedef webrtc::PeerConnectionInterface::PeerConnectionState 48 | PeerConnectionState; 49 | typedef webrtc::PeerConnectionInterface::IceConnectionState IceConnectionState; 50 | 51 | typedef webrtc::PeerConnectionInterface::RTCConfiguration RTCConfiguration; 52 | typedef webrtc::PeerConnectionInterface::IceTransportsType IceTransportsType; 53 | typedef webrtc::PeerConnectionInterface::BundlePolicy BundlePolicy; 54 | typedef webrtc::PeerConnectionInterface::RtcpMuxPolicy RtcpMuxPolicy; 55 | typedef webrtc::PeerConnectionInterface::TlsCertPolicy TlsCertPolicy; 56 | typedef webrtc::PeerConnectionInterface::IceServer IceServer; 57 | typedef webrtc::PeerConnectionInterface::IceServers IceServers; 58 | 59 | extern const char kDefaultIceTransportsType[]; 60 | extern const char kDefaultBundlePolicy[]; 61 | extern const char kDefaultRtcpMuxPolicy[]; 62 | 63 | bool RTCConfigFromJson(utils::RTCConfiguration& config, 64 | const std::string& json_string, 65 | std::string& error_message); 66 | 67 | IceTransportsType StrToIceTransportsType(const std::string type); 68 | BundlePolicy StrToBundlePolicy(const std::string bundle_policy); 69 | RtcpMuxPolicy StrToRtcpMuxPolicy(const std::string mux_policy); 70 | 71 | // for ice servers 72 | std::vector StrToIceUrls(const std::string urls); 73 | TlsCertPolicy StrToTlsCertPolicy(const std::string policy); 74 | std::vector StrToVector(const std::string configs); 75 | 76 | std::string maskingPassword(const std::string password); 77 | void PrintRTCConfig(const RTCConfiguration& rtc_config); 78 | bool validateIceServerUrl(const std::string url, std::string& error_message, 79 | bool not_allow_numberic_ipaddress = true); 80 | 81 | }; // namespace utils 82 | 83 | #endif // STREAMER_UTILS_PC_CONFIG_H_ 84 | -------------------------------------------------------------------------------- /src/utils_pc_strings.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2018, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef STREAMER_UTILS_PC_STRINGS_H_ 31 | #define STREAMER_UTILS_PC_STRINGS_H_ 32 | 33 | #pragma once 34 | 35 | #include 36 | 37 | #include 38 | 39 | #include "api/media_stream_interface.h" 40 | #include "api/peer_connection_interface.h" 41 | #include "utils_pc_config.h" 42 | 43 | namespace utils { 44 | 45 | std::string SignalingStateToString( 46 | const webrtc::PeerConnectionInterface::SignalingState state); 47 | 48 | std::string IceGatheringStateToString( 49 | const webrtc::PeerConnectionInterface::IceGatheringState state); 50 | 51 | std::string PeerConnectionStateToString( 52 | const webrtc::PeerConnectionInterface::PeerConnectionState state); 53 | 54 | std::string PeerIceConnectionStateToString( 55 | const webrtc::PeerConnectionInterface::IceConnectionState state); 56 | 57 | // It is not a printer for state, but an Ice related enum printer. 58 | std::string IceTransportsTypeToString(const IceTransportsType type, 59 | bool default_value = false); 60 | std::string BundlePolicyToString(const BundlePolicy type, 61 | bool default_value = false); 62 | std::string RtcpMuxPolicyToString(const RtcpMuxPolicy type, 63 | bool default_value = false); 64 | std::string TlsCertPolicyToString(const TlsCertPolicy type, 65 | bool default_value = false); 66 | 67 | }; // namespace utils 68 | 69 | #endif // STREAMER_UTILS_PC_STRINGS_H_ 70 | -------------------------------------------------------------------------------- /src/utils_url.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2004 The WebRTC Project Authors. All rights reserved. 3 | * 4 | * Use of this source code is governed by a BSD-style license 5 | * that can be found in the LICENSE file in the root of the source 6 | * tree. An additional intellectual property rights grant can be found 7 | * in the file PATENTS. All contributing project authors may 8 | * be found in the AUTHORS file in the root of the source tree. 9 | */ 10 | 11 | #ifndef STREAMER_UTILS_URL_H_ 12 | #define STREAMER_UTILS_URL_H_ 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | #include "rtc_base/checks.h" 20 | #include "rtc_base/httpcommon.h" 21 | #include "rtc_base/stream.h" 22 | #include "rtc_base/stringutils.h" 23 | 24 | namespace rtc { 25 | 26 | static const uint16_t HTTP_DEFAULT_PORT = 80; 27 | static const uint16_t HTTP_SECURE_PORT = 443; 28 | 29 | ////////////////////////////////////////////////////////////////////// 30 | // Url 31 | ////////////////////////////////////////////////////////////////////// 32 | 33 | template 34 | class Url { 35 | public: 36 | typedef typename Traits::string string; 37 | 38 | // TODO: Implement Encode/Decode 39 | static int Encode(const CTYPE* source, CTYPE* destination, size_t len); 40 | static int Encode(const string& source, string& destination); 41 | static int Decode(const CTYPE* source, CTYPE* destination, size_t len); 42 | static int Decode(const string& source, string& destination); 43 | 44 | Url(const string& url) { do_set_url(url.c_str(), url.size()); } 45 | Url(const string& path, const string& host, 46 | uint16_t port = HTTP_DEFAULT_PORT) 47 | : host_(host), port_(port), secure_(HTTP_SECURE_PORT == port) { 48 | set_full_path(path); 49 | } 50 | 51 | bool valid() const { return !host_.empty(); } 52 | void clear() { 53 | host_.clear(); 54 | port_ = HTTP_DEFAULT_PORT; 55 | secure_ = false; 56 | path_.assign(1, static_cast('/')); 57 | query_.clear(); 58 | } 59 | 60 | void set_url(const string& val) { do_set_url(val.c_str(), val.size()); } 61 | string url() const { 62 | string val; 63 | do_get_url(&val); 64 | return val; 65 | } 66 | 67 | void set_address(const string& val) { 68 | do_set_address(val.c_str(), val.size()); 69 | } 70 | string address() const { 71 | string val; 72 | do_get_address(&val); 73 | return val; 74 | } 75 | 76 | void set_full_path(const string& val) { 77 | do_set_full_path(val.c_str(), val.size()); 78 | } 79 | string full_path() const { 80 | string val; 81 | do_get_full_path(&val); 82 | return val; 83 | } 84 | 85 | void set_host(const string& val) { host_ = val; } 86 | const string& host() const { return host_; } 87 | 88 | void set_port(uint16_t val) { port_ = val; } 89 | uint16_t port() const { return port_; } 90 | 91 | void set_secure(bool val) { secure_ = val; } 92 | bool secure() const { return secure_; } 93 | 94 | void set_path(const string& val) { 95 | if (val.empty()) { 96 | path_.assign(1, static_cast('/')); 97 | } else { 98 | RTC_DCHECK(val[0] == static_cast('/')); 99 | path_ = val; 100 | } 101 | } 102 | const string& path() const { return path_; } 103 | 104 | void set_query(const string& val) { 105 | RTC_DCHECK(val.empty() || (val[0] == static_cast('?'))); 106 | query_ = val; 107 | } 108 | const string& query() const { return query_; } 109 | 110 | bool get_attribute(const string& name, string* value) const; 111 | 112 | private: 113 | void do_set_url(const CTYPE* val, size_t len); 114 | void do_set_address(const CTYPE* val, size_t len); 115 | void do_set_full_path(const CTYPE* val, size_t len); 116 | 117 | void do_get_url(string* val) const; 118 | void do_get_address(string* val) const; 119 | void do_get_full_path(string* val) const; 120 | 121 | string host_, path_, query_; 122 | uint16_t port_; 123 | bool secure_; 124 | }; 125 | 126 | } // namespace rtc 127 | 128 | #endif // STREAMER_UTILS_URL_H_ 129 | -------------------------------------------------------------------------------- /src/websocket_handler.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2017, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef WEBSOCKET_HANDLER_H_ 31 | #define WEBSOCKET_HANDLER_H_ 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | 39 | enum WebSocketHandlerType { 40 | SINGLE_INSTANCE, // allow only one handler runtime 41 | MULTIPLE_INSTANCE, // allow multiple handler runtime 42 | }; 43 | 44 | enum FileMappingType { 45 | MAPPING_DEFAULT, 46 | MAPPING_FILE, 47 | MAPPING_DIRECTORY, 48 | }; 49 | 50 | struct FileMapping { 51 | FileMapping(const std::string uri_prefix, FileMappingType type, 52 | const std::string uri_resource_path) 53 | : uri_prefix_(uri_prefix), 54 | type_(type), 55 | uri_resource_path_(uri_resource_path) {} 56 | ~FileMapping() {} 57 | // allowed prefix for input URI 58 | const std::string uri_prefix_; 59 | FileMappingType type_; 60 | // mapping local resource path for uri_prefix 61 | const std::string uri_resource_path_; 62 | }; 63 | 64 | struct WebSocketHandler { 65 | virtual void OnConnect(int sockid) = 0; 66 | virtual bool OnMessage(int sockid, const std::string& message) = 0; 67 | virtual void OnDisconnect(int sockid) = 0; 68 | virtual void OnError(int sockid, const std::string& message) = 0; 69 | 70 | protected: 71 | virtual ~WebSocketHandler() {} 72 | }; 73 | 74 | struct WebSocketMessage { 75 | virtual void SendMessage(int sockid, const std::string& message) = 0; 76 | virtual void Close(int sockid, int reason_code, 77 | const std::string& message) = 0; 78 | 79 | protected: 80 | virtual ~WebSocketMessage() {} 81 | }; 82 | 83 | #endif // WEBSOCKET_HANDLER_H_ 84 | -------------------------------------------------------------------------------- /src/websocket_server_internal.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 22 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #ifndef WEBSOCKET_SERVER_INTERNAL_H_ 31 | #define WEBSOCKET_SERVER_INTERNAL_H_ 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | 43 | #include "libwebsockets.h" 44 | 45 | #ifdef __cplusplus 46 | extern "C" { 47 | #endif // __cplusplus 48 | 49 | void dump_handshake_info(struct lws* wsi); 50 | const char* to_callbackreason_str(int callback_reason, int brief); 51 | const char* to_httpstatus_str(int status); 52 | 53 | #ifdef __cplusplus 54 | }; 55 | #endif // __cplusplus 56 | 57 | #endif // WEBSOCKET_SERVER_INTERNAL_H_ 58 | 59 | -------------------------------------------------------------------------------- /tools/ffmpeg_armv6: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kclyu/rpi-webrtc-streamer/e109e418aa9023009b3b59c95eec2de4721125be/tools/ffmpeg_armv6 -------------------------------------------------------------------------------- /tools/ffmpeg_neon: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kclyu/rpi-webrtc-streamer/e109e418aa9023009b3b59c95eec2de4721125be/tools/ffmpeg_neon -------------------------------------------------------------------------------- /web-root/np2/images/webrtc-icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kclyu/rpi-webrtc-streamer/e109e418aa9023009b3b59c95eec2de4721125be/web-root/np2/images/webrtc-icon-192x192.png -------------------------------------------------------------------------------- /web-root/np2/js/constants.mjs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2021, rpi-webrtc-streamer Lyu,KeunChang 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the copyright holder nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 22 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | const Constants = { 31 | URL_PATH: '/rws/ws', 32 | 33 | // Element Id for Video related buttons 34 | ELEMENT_CONNECT: 'Connect', 35 | ELEMENT_DISCONNECT: 'Disconnect', 36 | ELEMENT_VIDEO: 'remoteVideo', 37 | 38 | // Element Id for media configurations 39 | ELEMENT_CONFIG_RESET: 'resetConfig', 40 | ELEMENT_CONFIG_APPLY: 'applyConfig', 41 | ELEMENT_CONFIG_SECTION: 'media_configurations', 42 | ELEMENT_SHOW_CONFIG: 'showConfig', 43 | ELEMENT_SHOW_BUTTON_TEXT: 'Show Video Settings', 44 | ELEMENT_SHOW_BUTTON_HIDE_TEXT: 'Hide Video Settings', 45 | 46 | // Element Id for snackBar message 47 | ELEMENT_SNACKBAR: 'snackBar', 48 | SNACKBAR_TIMEOUT: 3000, 49 | 50 | WEBSOCKET_CONNECT_TIMEOUT: 1000, 51 | 52 | // WebSocket request result code 53 | REQUEST_SUCCESS: 'SUCCESS', 54 | REQUEST_FAILED: 'FAILED', 55 | 56 | // Interval Values 57 | RECONNECT_INTERVAL: 3000, // 3 seconds 58 | STILL_IMAGE_UPDATE_INTERVAL: 300000, // 5 minutes 59 | 60 | ERROR_CONNECTION_NOT_ESTABLISHED: 'Connection is not established', 61 | ERROR_INVALID_SIGNAING_CHANNEL: 62 | 'Internal Error, Signaling connection is not ready', 63 | ERROR_INVALID_CALL_CONFIGMEDIA: 64 | 'Internal Error, Invalid ConfigMedia method call', 65 | ERROR_SENDING_REGISTER: 'Internal Error, Sending register command failed', 66 | ERROR_INVALID_DEVICEID: 'Internal Error, Invalid Device ID', 67 | ERROR_FAILED_DEVICEID: 'Failed to get Device ID', 68 | ERROR_FAILED_CONFIG_MEDIA: 'Failed to get Config Media', 69 | ERROR_FAILED_ZOOM_COMMAND: 'Failed to send Zoom command', 70 | }; 71 | 72 | export default Constants; 73 | -------------------------------------------------------------------------------- /web-root/np2/js/snackbar.mjs: -------------------------------------------------------------------------------- 1 | import Constants from './constants.mjs'; 2 | 3 | /* 4 | * Simple SnackBar messages 5 | * (from https://www.w3schools.com/howto/howto_js_snackbar.asp) 6 | */ 7 | function SnackBarMessage(message) { 8 | let x = document.getElementById(Constants.ELEMENT_SNACKBAR); 9 | if (x) { 10 | // show snackbar message only when the snackbar element id exist 11 | // changing snackBar 12 | x.className = 'show'; 13 | x.innerText = message; 14 | setTimeout(function () { 15 | x.className = x.className.replace('show', ''); 16 | }, Constants.SNACKBAR_TIMEOUT); 17 | } 18 | } 19 | 20 | export default SnackBarMessage; 21 | -------------------------------------------------------------------------------- /web-root/np2/js/streamer_transaction.mjs: -------------------------------------------------------------------------------- 1 | import Constants from './constants.mjs'; 2 | 3 | // makeid from the below url 4 | // https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript 5 | function makeid(length) { 6 | var result = ''; 7 | var characters = 8 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; 9 | var charactersLength = characters.length; 10 | for (var i = 0; i < length; i++) { 11 | result += characters.charAt(Math.floor(Math.random() * charactersLength)); 12 | } 13 | return result; 14 | } 15 | 16 | class StreamerTransaction { 17 | constructor(transaction_map, resolve, reject, timeoutval = 3000) { 18 | // total transaction id length is 8 19 | this._transactionId = makeid(12); 20 | transaction_map.set(this._transactionId, this); 21 | 22 | this._resolve = resolve; 23 | this._reject = reject; 24 | this._timer = setTimeout( 25 | function () { 26 | this.timeout(); 27 | }.bind(this), 28 | timeoutval 29 | ); 30 | } 31 | 32 | get id() { 33 | return this._transactionId; 34 | } 35 | 36 | _destroyTimer() { 37 | clearTimeout(this._timer); 38 | this._timer = null; 39 | } 40 | 41 | success(result) { 42 | this._destroyTimer(); 43 | return this._resolve(result); 44 | } 45 | 46 | fail(error) { 47 | console.error('Transanction %s failed', this._transactionId); 48 | this._destroyTimer(); 49 | return this._reject(error); 50 | } 51 | 52 | timeout() { 53 | console.error('Transanction %s timeout', this._transactionId); 54 | this._destroyTimer(); 55 | return this._reject(new Error('Timeout')); 56 | } 57 | } 58 | 59 | export default StreamerTransaction; 60 | --------------------------------------------------------------------------------