<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chris on Medium]]></title>
        <description><![CDATA[Stories by Chris on Medium]]></description>
        <link>https://medium.com/@monoclechris?source=rss-5ae9d0fcb53b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ISwFmqr_PhaaoInI</url>
            <title>Stories by Chris on Medium</title>
            <link>https://medium.com/@monoclechris?source=rss-5ae9d0fcb53b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:25:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@monoclechris/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[OpenGL Pixel Shader Dewarping]]></title>
            <link>https://medium.com/@monoclechris/opengl-pixel-shader-dewarping-3af703bfd8be?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3af703bfd8be</guid>
            <category><![CDATA[cctv-camera]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[opengl]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 18:28:40 GMT</pubDate>
            <atom:updated>2025-10-10T10:29:13.723Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>When a user requested adding dewarping to my camera streaming software <a href="https://monoclesecurity.com/">Monocle</a>, I tried various methods and found they each have significant drawbacks until I came up with a novel solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HFwKey8WoyCkv8_1xNc4Q.png" /><figcaption>Fisheye Dewarping</figcaption></figure><p><strong>CPU</strong></p><p>Having previously done transformations on the CPU, I knew this would be far too slow to be satisfactory, so I didn’t even try implementing this.</p><p><strong>Vertex Shader</strong></p><p>Using the vertex shader was my first attempt because I knew it would be high performance and I felt intuitively it would be able to provide sufficient accuracy to look good enough. Unfortunately the aliasing looked really poor along triangle edges and required a dense mesh of polygons. It was also difficult to create an exact match to the OpenCV dewarping models.</p><p><strong>CUDA</strong></p><p>Using CUDA was the next experiment. It quickly became very cumbersome, having to draw the original image to a frame buffer, then passing the texture to the CUDA interop, doing the calculations, and then going back to OpenGL to draw the result. Even though the data remained in the GPU throughout the pipeline, the performance was only barely acceptable. It was also unsupported on systems without an NVidia GPU.</p><p><strong>Novel Pixel Shader</strong></p><p>At first sight, it might appear that it wouldn’t be possible to dewarp in a pixel shader. However, with a small amount of engineering, it not only becomes possible, but I believe preferable. The first insight was that a Sampler2D in a pixel shader can be hijacked to contain a lookup table instead of a texture. The second is that OpenGL has sub-pixel accuracy when sampling the colour from a texture, so we can get excellent aliasing. This does not come without any challenges because most OpenGL drivers require the texture type to be GL_UNSIGNED_BYTE, which does not provide a wide enough range to identify each pixel, so we use GL_RGBA so the x can be represented by both the red and green values, and the y by the blue and alpha values, giving a range of 0–65535 which is more than sufficient for most use cases. In the shader below, each output pixel samples the LUT to find its corresponding location in the distorted source image.</p><pre>in vec2 tex_coord;<br>out vec4 FragColor;<br>uniform sampler2D tex;<br>uniform sampler2D lut;<br>void main()<br>{<br>  vec4 lut_value = texture(lut, tex_coord);<br>  float x = lut_value.g + (lut_value.r / 255.0);<br>  float y = lut_value.a + (lut_value.b / 255.0);<br>  FragColor = texture(tex, vec2(x, y));<br>}</pre><p>We also get excellent performance because we only need to draw two triangles and the shader remains simple because the majority of the computationally time intensive work is precalculated when creating the lookup-table. Performance could further be improved by doing the YUV conversion within this shader, instead of first drawing to a separate frame buffer.</p><p>I created an example C++ application demonstrating the novel pixel shader dewarping technique. Full code <a href="https://github.com/MonocleSecurity/DewarpingPlayer">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZMJdsWsgiHHpSUVON7iwg.png" /></figure><p><a href="https://discord.gg/QueVnNVwSr">Discord</a> <a href="https://www.monoclesecurity.com/">Monocle</a> <a href="https://twitter.com/Monocle_Sec">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3af703bfd8be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RTSP to RTMP in C++ Using FFMPEG]]></title>
            <link>https://medium.com/@monoclechris/rtsp-to-rtmp-in-c-using-ffmpeg-8231fb4c610b?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8231fb4c610b</guid>
            <category><![CDATA[rtsp]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[rtmp]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 15:01:08 GMT</pubDate>
            <atom:updated>2024-06-30T15:07:55.673Z</atom:updated>
            <content:encoded><![CDATA[<p>Open the RTSP stream.</p><pre>avformat_open_input(&amp;rtspformatcontext, rtspuri.c_str(), nullptr, &amp;opts);</pre><p>Read the RTSP stream information.</p><pre>  avformat_find_stream_info(rtspformatcontext, nullptr);</pre><p>Create the RTMP output stream.</p><pre>avformat_alloc_output_context2(&amp;rtmpcontext, nullptr, &quot;flv&quot;, rtmpurl.c_str());</pre><p>Create the video stream in the RTMP context.</p><pre>const AVCodec* codec = avcodec_find_decoder(rtspformatcontext-&gt;streams[*video_stream]-&gt;codecpar-&gt;codec_id);<br>AVStream* videooutstream = avformat_new_stream(rtmpcontext, codec);<br>avcodec_parameters_copy(videooutstream-&gt;codecpar, rtspformatcontext-&gt;streams[*video_stream]-&gt;codecpar);</pre><p>Create the optional audio stream in the RTMP context.</p><pre>const AVCodec* avcodecaudio = avcodec_find_decoder(rtspformatcontext-&gt;streams[*audio_stream]-&gt;codecpar-&gt;codec_id);<br>audiooutstream = avformat_new_stream(rtmpcontext, avcodecaudio);<br>avcodec_parameters_copy(audiooutstream-&gt;codecpar, rtspformatcontext-&gt;streams[*audio_stream]-&gt;codecpar);</pre><p>Open the RTMP stream.</p><pre>avio_open(&amp;rtmpcontext-&gt;pb, rtmpurl.c_str(), AVIO_FLAG_WRITE);<br>avformat_write_header(rtmpcontext, nullptr);</pre><p>Read RTSP frames.</p><pre>av_read_frame(rtspformatcontext, packet);</pre><p>Write RTMP frames.</p><pre>av_interleaved_write_frame(rtmpcontext, packet);</pre><p>Full code <a href="https://github.com/MonocleSecurity/RTSP2RTMP">here</a>.</p><p><a href="https://discord.gg/QueVnNVwSr">Discord</a> <a href="https://www.monoclesecurity.com/">Monocle</a> <a href="https://twitter.com/Monocle_Sec">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8231fb4c610b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SecureBoot and Encrypted rootfs NVME on Jetson Orin]]></title>
            <link>https://medium.com/@monoclechris/secureboot-and-encrypted-rootfs-nvme-on-jetson-orin-41d3356d7922?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d3356d7922</guid>
            <category><![CDATA[jetson-xavier-nx]]></category>
            <category><![CDATA[secure-boot]]></category>
            <category><![CDATA[jetson-nano]]></category>
            <category><![CDATA[jetson-tx2]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 10:34:32 GMT</pubDate>
            <atom:updated>2023-12-29T09:56:16.155Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a list of things that I would have found helpful to know before trying to get a SecureBoot with an encrypted rootfs onto a Jetson. Most of the information here will apply to variations of my requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWL6Jd-lCs0yyvK9U6vCDQ.png" /></figure><p><strong>Operating System</strong></p><p>You’re going to be doing a lot of creating, unmounting and mounting of partitions, disks and connecting/disconnecting of USB and networks, so stopping services and operating system events from interfering is important to improving the reliability of this process.</p><pre>sudo systemctl stop udisks2<br>sudo -s echo -1 &gt; /sys/module/usbcore/parameters/autosuspend<br>sudo ufw disable</pre><p><strong>Errors</strong></p><p>If you see an error like one below, you have probably run into an issue where the host operating system has got into a state where it can no longer communicate with your Jetson device. The only solution I have had any success with is restarting both machines together. I found the best way to avoid getting into this situation is to unplug and plug the Jetson between steps.</p><pre>[ 0.3270 ] Sending bct_mem<br>[ 0.3544 ] Sending blob<br>[ 0.4533 ] ERROR: might be timeout in USB write.</pre><p><strong>Disks</strong></p><p>Make sure the SDCard is not plugged in, and the NVME is. Find out what size NVME it is before starting, because you will need to know later.</p><p><strong>UART</strong></p><p>You are definitely going to want to hook up the UART to listen to flashing, boot and kernel messages from the Jetson. These are the commands I used to listen to them from the host depending on what state the Jetson is currently in.</p><pre>minicom -D /dev/ttyUSB0 -8 -b 115200 # Flash messages<br>minicom -D /dev/ttyACM0 -8 -b 115200 # Boot messages</pre><p><strong>OP-TEE</strong></p><p>On the Jetson platform, OP-TEE has a partition of its own, which provides an intermediary operating system to get the main operating system. It implements a suite of APIs which allows the system to securely boot to a signed operating system.</p><p><strong>Helpful Documentation</strong></p><p><a href="https://docs.nvidia.com/jetson/archives/r35.4.1/DeveloperGuide/text/SD/Security/SecureBoot.html">Secure Boot</a></p><p><a href="https://docs.nvidia.com/jetson/archives/r35.1/DeveloperGuide/text/SD/Security/OpTee.html">OP-TEE</a></p><p><a href="https://docs.nvidia.com/jetson/archives/r35.1/DeveloperGuide/text/SD/Security/DiskEncryption.html">Disk Encryption</a></p><p><a href="https://developer.download.nvidia.com/assets/embedded/secure/jetson/agx_orin/Jetson_Orin_Series_Fuse_Specification_DA-10877-001_v1.2.pdf?B8I7Hcf6WO_BbZtbd-XJbRekH7g7DvM7y7qTBgJ9W6rcC39VL6iWqIITTQ89ohv4J3J-oGQj9z_H81q2Sru6JLiBZvYeUYHXnkbv-AKLvMiUl-ThGkInSfeZrbQdVqoKPJqCt_XOcYKJpXakixlFv3R5Io4AoaD3nXiwiir3Kng4mOvSSwqcferk0TPknEydIAwg2tITuzOHnP9b4ImXoIg=&amp;t=eyJscyI6ImdzZW8iLCJsc2QiOiJodHRwczovL3d3dy5nb29nbGUuY29tLyJ9">Fuse Specification</a></p><p><strong>Setting up</strong></p><p>The host operating system must be Ubuntu18 or Ubuntu20 and these are the packages you are going to need on top of a default install.</p><pre><br>apt-get install dislocker cryptsetup libcryptsetup-dev libcryptsetup12 cryptmount cryptmount overlayroot qemu-user-static<br>pip install cryptography<br>pip install pycrypto</pre><p>The first thing to do is download and unpack the tarballs for <a href="https://developer.nvidia.com/embedded/jetson-linux-r3541">Jetson Linux 35.4.1</a>. Make sure they are all exactly the same version, otherwise you are very likely to run into issues.</p><pre><br>wget https://developer.nvidia.com/downloads/embedded/l4t/r35_release_v4.1/release/jetson_linux_r35.4.1_aarch64.tbz2<br>wget https://developer.nvidia.com/downloads/embedded/l4t/r35_release_v4.1/release/tegra_linux_sample-root-filesystem_r35.4.1_aarch64.tbz2<br>wget https://developer.nvidia.com/downloads/embedded/l4t/r35_release_v4.1/sources/public_sources.tbz2<br>tar xvf jetson_linux_r35.4.1_aarch64.tbz2<br>sudo tar xvf tegra_linux_sample-root-filesystem_r35.4.1_aarch64.tbz2 -C Linux_for_Tegra/rootfs/<br>tar xvf public_sources.tbz2<br>cd Linux_for_Tegra/source/public/<br>tar xvf nvidia-jetson-optee-source.tbz2<br>cd ../..<br>sudo tools/l4t_flash_prerequisites.sh<br>sudo ./apply_binaries.sh</pre><p><strong>Generating Keys</strong></p><p>You will need a private key and its hash, a SBK(Secure Boot Key) and a KEK(Key Encryption Key) in a variety of formats. You will need to keep these safe and you will need them again if you want to reflash your device. The EKB and SYM keys below are the default, you might need to change these depending on your requirements.</p><pre>openssl genrsa -out rsa.pem 3072<br>PKCS_KEY_XML_HASH=$(./bootloader/tegrasign_v3.py --pubkeyhash rsa.pubkey rsa.hash --key rsa.pem | grep &quot;tegra-fuse format&quot; | awk &#39;{print $NF}&#39;)<br>SBK_0=$(openssl rand -hex 4)<br>SBK_1=$(openssl rand -hex 4)<br>SBK_2=$(openssl rand -hex 4)<br>SBK_3=$(openssl rand -hex 4)<br>SBK_4=$(openssl rand -hex 4)<br>SBK_5=$(openssl rand -hex 4)<br>SBK_6=$(openssl rand -hex 4)<br>SBK_7=$(openssl rand -hex 4)<br>SBK_KEY=$(echo &quot;0x${SBK_0} 0x${SBK_1} 0x${SBK_2} 0x${SBK_3} 0x${SBK_4} 0x${SBK_5} 0x${SBK_6} 0x${SBK_7}&quot;)<br>echo &quot;${SBK_KEY}&quot; &gt; sbk.key<br>SBK_KEY_XML=&quot;0x${SBK_0}${SBK_1}${SBK_2}${SBK_3}${SBK_4}${SBK_5}${SBK_6}${SBK_7}&quot;<br>echo &quot;${SBK_KEY_XML}&quot; &gt; sbk_xml.key<br>KEK_2_0=$(openssl rand -hex 4)<br>KEK_2_1=$(openssl rand -hex 4)<br>KEK_2_2=$(openssl rand -hex 4)<br>KEK_2_3=$(openssl rand -hex 4)<br>KEK_2_4=$(openssl rand -hex 4)<br>KEK_2_5=$(openssl rand -hex 4)<br>KEK_2_6=$(openssl rand -hex 4)<br>KEK_2_7=$(openssl rand -hex 4)<br>KEK_2_KEY=$(echo &quot;0x${KEK_2_0} 0x${KEK_2_1} 0x${KEK_2_2} 0x${KEK_2_3} 0x${KEK_2_4} 0x${KEK_2_5} 0x${KEK_2_6} 0x${KEK_2_7}&quot;)<br>echo &quot;${KEK_2_KEY}&quot; &gt; kek.key<br>KEK_2_KEY_XML=&quot;0x${KEK_2_0}${KEK_2_1}${KEK_2_2}${KEK_2_3}${KEK_2_4}${KEK_2_5}${KEK_2_6}${KEK_2_7}&quot;<br>echo &quot;${KEK_2_KEY_XML}&quot; &gt; kek_xml.key<br>KEK_2_KEY_OPTEE=&quot;${KEK_2_0}${KEK_2_1}${KEK_2_2}${KEK_2_3}${KEK_2_4}${KEK_2_5}${KEK_2_6}${KEK_2_7}&quot;<br>echo &quot;${KEK_2_KEY_OPTEE}&quot; &gt; kek_optee.key<br>echo &quot;bad66eb4484983684b992fe54a648bb8&quot; &gt; fv_ekb_t234<br>echo &quot;010203040506070809a0b0c0d0e0f001&quot; &gt; sym_t234.key<br>echo &quot;f0e0d0c0b0a001020304050607080900&quot; &gt; sym2_t234.key</pre><p><strong>Generating the OP-TEE image</strong></p><p>This will create a .img that will go into one of the partitions when flashing.</p><pre>python3 ./source/public/optee/samples/hwkey-agent/host/tool/gen_ekb/gen_ekb.py -chip t234 -oem_k2_key kek_optee.key -fv fv_ekb_t234 -in_sym_key sym_t234.key -in_sym_key2 sym2_t234.key -out bootloader/eks_t234.img</pre><p><strong>Fusing</strong></p><p>Fuses on the device are secure ROM that can be only written to once in an irreversible process. This is the part where you need to be very careful. The BootSecurityInfo is a bitmap that can be calculated from the Fuse specification linked above.</p><pre>echo &quot;&lt;genericfuse MagicId=\&quot;0x45535546\&quot; version=\&quot;1.0.0\&quot;&gt;&quot; &gt; fuse.xml<br>echo &quot;  &lt;fuse name=\&quot;PublicKeyHash\&quot; size=\&quot;64\&quot; value=\&quot;${PKCS_KEY_XML_HASH}\&quot;/&gt;&quot; &gt;&gt; fuse.xml<br>echo &quot;  &lt;fuse name=\&quot;SecureBootKey\&quot; size=\&quot;32\&quot; value=\&quot;${SBK_KEY_XML}\&quot;/&gt;&quot; &gt;&gt; fuse.xml<br>echo &quot;  &lt;fuse name=\&quot;OemK2\&quot; size=\&quot;32\&quot; value=\&quot;${KEK_2_KEY_XML}\&quot;/&gt;&quot; &gt;&gt; fuse.xml<br>echo &quot;  &lt;fuse name=\&quot;BootSecurityInfo\&quot; size=\&quot;4\&quot; value=\&quot;0x209\&quot;/&gt;&quot; &gt;&gt; fuse.xml<br>echo &quot;  &lt;fuse name=\&quot;SecurityMode\&quot; size=\&quot;4\&quot; value=\&quot;0x1\&quot;/&gt;&quot; &gt;&gt; fuse.xml<br>echo &quot;&lt;/genericfuse&gt;&quot; &gt;&gt; fuse.xml</pre><pre>sudo ./odmfuse.sh -i 0x23 -k rsa.pem -S sbk.key -X fuse.xml jetson-orin-nano-devkit</pre><p><strong>QSPI Setup</strong></p><p>Before continuing, you must replace the “NUM_SECTORS” text inside “tools/kernel_flash/flash_l4t_t234_nvme_rootfs_enc.xml”. This is because the host scripts are not able to determine the size of the disk in the Jetson, so you have to calculate it manually. It’s not clear to me what the exact number should be, but I put it slightly below the maximum total number of bytes on the disk. So for me, a 500GB disk, I calculated the value `500(size in GiB) * 1000 * 1000 * 1000) / 500(sector size)` = 1,000,000,000. Once set, then this script below will create an image for the QSPI, but not flash it, then copy it to a location where it will be flashed later. The device must be plugged in during this phase, because it will be queried by the scripts.</p><pre>sudo ./tools/kernel_flash/l4t_initrd_flash.sh --network usb0 -u ./rsa.pem -v ./sbk.key --no-flash --showlogs -p &quot;-c bootloader/t186ref/cfg/flash_t234_qspi.xml&quot; jetson-orin-nano-devkit internal<br>sudo cp bootloader/eks_t234_sigheader_encrypt.img.signed ./tools/kernel_flash/images/internal/</pre><p><strong>RootFs Setup</strong></p><p>Due to the same issue described above, you need to replace the “-S 400Gib” argument with a size that will fit for your own hardware. This must be below the size set above, but also have enough room for all the other partitions on the disk. The device must be plugged in during this phase, because it will be queried by the scripts.</p><pre>sudo ROOTFS_ENC=1 ./tools/kernel_flash/l4t_initrd_flash.sh --showlogs -u ./rsa.pem -v ./sbk.key --no-flash --external-device nvme0n1p1 -i ./sym2_t234.key -c ./tools/kernel_flash/flash_l4t_t234_nvme_rootfs_enc.xml -S 400GiB --external-only --append --network usb0 jetson-orin-nano-devkit external</pre><p><strong>Flash</strong></p><p>This will flash the device. Although not necessary, you should have the UART plugged in to see progress from the devices perspective. If there are any issues, particularly if you need help with them, this will be very important.</p><pre>sudo ./tools/kernel_flash/l4t_initrd_flash.sh --showlogs -u rsa.pem -v sbk.key --network usb0 --flash-only</pre><p><strong>Conclusion</strong></p><p>A lot of perseverance and persistence may still be required, but hopefully this article has helped. The entire script is available <a href="https://gist.github.com/MonocleSecurity/ecbbd0489a4a72c3b1fadc95e8aa9274">here</a>.</p><p><a href="https://discord.gg/QueVnNVwSr">Discord</a> <a href="https://www.monoclesecurity.com/">Monocle</a> <a href="https://twitter.com/Monocle_Sec">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d3356d7922" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreaded Memset]]></title>
            <link>https://medium.com/@monoclechris/multithreaded-memset-e2f114e74d1c?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f114e74d1c</guid>
            <category><![CDATA[cpplus]]></category>
            <category><![CDATA[c-programmin]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 08:58:55 GMT</pubDate>
            <atom:updated>2023-04-09T09:07:13.549Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>I was writing some code and, as I often do, I needed to use memset and a thought occurred to me that there would likely be some size threshold where a multithreaded memset would be faster. I wasn’t interested in securely setting it to zero, I wanted to leave the optimiser to do the best job it could without discarding the code entirely and see what the results might be. The processor on my machine is a 1950x Threadripper on Windows and it using 32 threads to memset. Your results will almost certainly differ wildly. Code is available <a href="https://github.com/MonocleSecurity/memzerotest">here</a>.</p><p><strong>The Test</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*v0vcK-u5jUuxLSOafnzysA.png" /></figure><p>I was quite sure there would be a crossover threshold where multithreaded memset would be faster, but I wasn’t quite expecting it to look like this. This graph shows that, at least one my machine and for certain sizes of memset, it is sometimes faster to multithreaded memset more memory.</p><p><a href="https://discord.gg/QueVnNVwSr">Discord</a> <a href="https://www.monoclesecurity.com/">Monocle</a> <a href="https://twitter.com/Monocle_Sec">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f114e74d1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inter-thread Communication Latency]]></title>
            <link>https://medium.com/@monoclechris/inter-thread-communication-latency-f2324a5d2ec8?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2324a5d2ec8</guid>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 01:01:40 GMT</pubDate>
            <atom:updated>2023-03-10T01:13:02.824Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>The goal was to compare the latency between threads using a variety of messaging mechanisms. The tests run 50 times to get a good sample size. The tests use std::chrono::high_resolution_clock which isn’t perfect, especially when getting start and end times in different threads, but I believe it is the best available. Each communication mechanism uses a varying amounts of syscalls which may affect your performance. The tests created are for examining latency, not throughput. I have attempted to reduce the amount of overhead or interference from cache sharing between threads to get the most consistent results. I did not adjust any scheduling priorities for threads or processes. Results will very likely vary on your architecture and operating system, but I have ran them on what I had available. Code is available <a href="https://github.com/MonocleSecurity/threadtest">here</a>. Here is a description of each mechanism tested:</p><p><strong>Future</strong></p><p>32 threads all waiting on futures consecutively in a chain to set the value of the following promise.</p><p><strong>Mutex</strong></p><p>32 threads waiting consecutively in a chain for the previous thread to change a value with a mutex all spinning on infinite loops with std::this_thread::yield(). This will consume all of available processing time.</p><p><strong>Atomic</strong></p><p>32 threads waiting consecutively in a chain for the previous thread to change an atomic value all spinning on infinite loops with std::this_thread::yield(). This will consume all of available processing time.</p><p><strong>Condition</strong></p><p>32 threads all waiting on conditions consecutively in a chain notifying each other.</p><p><strong>Pipe</strong></p><p>32 synchronous anonymous pipes each in their own thread waiting to receive a byte and send another byte to the following pipe in a chain.</p><p><strong>Socket</strong></p><p>32 synchronous sockets each in their own thread waiting to receive a byte and send another byte to the following socket in a chain.</p><p><strong>Results</strong></p><p>I have highlighted the mean column because it is probably the most valuable. The most surprising thing to me is how relatively similar they are. I would not have guessed that pipes had similar latency to that of in built C++ threading primitives.</p><pre>Windows 10 x64 1950x Threadripper. All values in microseconds.<br><br>| Name      | Min | Max | <strong>Mean </strong>| StdDev |<br>| --------- | --- | --- | ---- | ------ |<br>| Future    | 4   | 160 | <strong>26</strong>   | 17     |<br>| Mutex     | 0   | 208 | <strong>42</strong>   | 11     |<br>| Atomic    | 0   | 187 | <strong>39</strong>   | 9      |<br>| Condition | 4   | 172 | <strong>27</strong>   | 18     |<br>| Pipe      | 8   | 409 | <strong>32</strong>   | 23     |<br>| Socket    | 23  | 163 | <strong>44</strong>   | 19     |</pre><pre>Raspbian Raspberry Pi 4B. All values in microseconds.<br><br>| Name      | Min | Max  | <strong>Mean </strong>| StdDev |<br>| --------- | --- | ---- | ---- | ------ |<br>| Future    | 19  | 320  | <strong>106</strong>  | 55     |<br>| Mutex     | 0   | 151  | <strong>151</strong>  | 29     |<br>| Atomic    | 0   | 1948 | <strong>40</strong>   | 52     |<br>| Condition | 14  | 138  | <strong>35</strong>   | 20     |<br>| Pipe      | 18  | 158  | <strong>41</strong>   | 22     |<br>| Socket    | 33  | 174  | <strong>62</strong>   | 30     |</pre><pre>Ubuntu 22.04 Intel(R) Core(TM) i5-3570S CPU. All values in microseconds.<br><br>| Name      | Min | Max  | <strong>Mean </strong>| StdDev |<br>| --------- | --- | ---- | ---- | ------ |<br>| Future    | 7   | 109  | <strong>34</strong>   | 17     |<br>| Mutex     | 0   | 77   | <strong>10</strong>   | 9      |<br>| Atomic    | 0   | 246  | <strong>10</strong>   | 11     |<br>| Condition | 5   | 111  | <strong>31</strong>   | 17     |<br>| Pipe      | 6   | 109  | <strong>32</strong>   | 17     |<br>| Socket    | 13  | 119  | <strong>49</strong>   | 20     |</pre><p><a href="https://discord.gg/QueVnNVwSr">Discord</a> <a href="https://www.patreon.com/monoclesecurity">Patreon</a> <a href="https://reddit.com/r/monoclesecurity">Reddit</a> <a href="https://www.monoclesecurity.com/">Monocle</a> <a href="https://github.com/MonocleSecurity/Monocle">Github</a> <a href="https://twitter.com/Monocle_Sec">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2324a5d2ec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I’ve Learned Creating a Large C++ Project]]></title>
            <link>https://medium.com/@monoclechris/what-ive-learned-creating-a-large-c-project-1cc71b1e2998?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cc71b1e2998</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[vms-software]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 18:25:32 GMT</pubDate>
            <atom:updated>2022-10-15T19:26:20.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*3Of4RIzudG7RBL9jpZMLkg.png" /></figure><p>I am the developer of <a href="https://www.monoclesecurity.com/">Monocle</a>: a free, cross platform, high performance video management system with a server, desktop client, phone app and a web interface. This article is about what has helped me build this suite of software and what I might do differently next time. Your own circumstances will differ and I can only speak for myself.</p><p><strong>Aim for Perfection, Suffice with Good</strong></p><p>Perfect code may be unattainable when competing priorities require sacrifices. Often the closer code moves towards perfection, the greater the time cost is to improve it further. The disproportionate cost of achieving perfection is an infinite sinkhole of time so try to avoid it.</p><p><strong>Keep Public Interfaces Stable</strong></p><p>Try to design the outward facing interfaces of networking protocols, libraries interfaces and public classes members and methods to be flexible and consistent. Prepare for potential new features so that if they are required, they do not create a cascading set of code changes.</p><p><strong>Package Manager</strong></p><p>I wasted a lot of time managing dependencies manually, which gradually became unworkable as the number of packages grew. Migrating to vcpkg took a long time to get working well, but it is something I should have done from the beginning. Monocle now has more than 300 dependencies.</p><p><strong>Cross Platform</strong></p><p>Maintaining cross platform compatibility has helped prevent potential bugs because each architecture and compiler set expose different sets of issues. The tools available for each platform differ enough that it is worthwhile to try and maintain cross compatibility.</p><p><strong>Debuggability</strong></p><p>Make it easy to kick off a debugging session. The Monocle project in Visual Studio is a good example where it is possible to simultaneously debug multiple processes with a single click making it easy to begin tracking down issues. Stepping through communication between processes is particularly useful in identifying issues where data has been misunderstood by stepping through the sending and receiving pipeline from one process to another.</p><p><strong>Use of Industry Standard Systems</strong></p><p>Often the standard solution will not fulfil all of your requirements, however the cost of creating and maintaining your own is often very high. Monocle makes a lot of use of vcpkg, Boost io_service, CMake, GRPC, GTest and many more but also has a lot of its own custom data and processing libraries. Spend time understanding the limitations of a package or framework and carefully balance the costs before locking in a choice.</p><p><strong>Logging</strong></p><p>Customers running their own servers can download a “debug” file from their servers which contains a json snapshot representation of the server including all logs, which can then be sent to customer support if there are technical issues. This has saved a lot of time dealing with customer issues because support does not require users to interact with their software to diagnose server issues.</p><p><strong>Documentation</strong></p><p>Automating the screenshot capture and generation of the documentation with LaTeX has become a part of the release process and has saved lots of time.</p><p><strong>Templating</strong></p><p>Avoid templating if possible in places which may get #included a lot. The ONVIF communication library in Monocle uses too much templating, mostly unnecessarily, and this has caused the compilation time to dramatically increase.</p><p><strong>Error Handling</strong></p><p>Whether you choose exceptions, return values or something else entirely, just make it consistent.</p><p><strong>Persistence and Determination</strong></p><p>Without it you may end up with loose threads or a dead project, powering through and finishing components helps maintain motivation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cc71b1e2998" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NVidia Jetson ONVIF RTSP CCTV Camera and NVR with Monocle]]></title>
            <link>https://medium.com/@monoclechris/nvidia-jetson-cameras-and-nvr-ce974f423d7b?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce974f423d7b</guid>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[jetson-nano]]></category>
            <category><![CDATA[jetson-xavier-nx]]></category>
            <category><![CDATA[jetson-tx2]]></category>
            <category><![CDATA[nvr]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Thu, 08 Sep 2022 17:13:11 GMT</pubDate>
            <atom:updated>2026-11-30T21:48:01.432Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating your own smart security system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJJERjDq8j6NQbB-SiHAaQ.jpeg" /><figcaption>A205 Carrier board with TX2 NX Running Monocle</figcaption></figure><p>From a JetPack 4.6.6 or 5.1.2 install, this tutorial will help you create an ONVIF Profile S+G RTSP compatible NVR and cameras with lots of <a href="https://www.monoclesecurity.com/features">features</a>. The setup is simple and the only required steps are to download and install the deb package which automatically starts the Monocle server as a systemd service. If you want your MIPI CSI-2 Argus cameras to be automatically setup, make sure you they are available via Argus before installation. I am using an A205 carrier board with a TX2 NX show above, but it should work on any Jetson compatible hardware including the TX2 development board.</p><pre># For JetPack 4.6.6<br>sudo apt-get update<br>sudo apt-get upgrade<br>wget https://downloads.monoclesecurity.com/monocle/monocleserver-jetson4.6.6-1-45-0.deb<br>sudo apt install ./monocleserver-jetson4.6.6-1–46–0.deb</pre><pre># For JetPack 5.1.2<br>sudo apt-get update<br>sudo apt-get upgrade<br>wget https://downloads.monoclesecurity.com/monocle/monocleserver-jetson5.1.2-1-45-0.deb<br>sudo apt install ./monocleserver-jetson5.1.2-1–46–0.deb</pre><p>These commands will install <a href="https://www.monoclesecurity.com/">monocle</a> server and start the service. Afterwards, you should be able to find your device via ONVIF discovery with a program like <a href="https://sourceforge.net/projects/onvifdm/">ONVIF Device Manager</a>. To login, the default credentials are “admin” and “password”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*udNKdBC6cwwA70NjgEkZ6Q.png" /><figcaption>ONVIF Device Manager</figcaption></figure><p>Local Argus cameras will have been added automatically if available and you can also add and configure other types of cameras from within the <a href="https://www.monoclesecurity.com/download">Monocle Client</a>. You will be able to stream over RTSP with a tool like <a href="https://www.videolan.org/">VLC</a>. Make sure you replace the username, password and hostname with the relevant data. If you have multiple recordings and tracks, you may need to find the exact RTSP uri from within the Monocle Client, however the generic RTSP ip will pick one for you.</p><pre>rtsp://admin:password@192.168.0.10</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*V4FZCn6_5s181sSMfmZG0A.png" /></figure><p>At the moment your Jetson is only streaming live, if you want to enable recording, the server will need a file to begin recording data to. The package installed earlier contains a command line interface for interacting with Monocle servers called <em>monoclecli</em>. Use the command below to add a file, changing the path and parameters to suit your requirements. The “numchunks” argument is effectively the total number of megabytes used to store data, thus 2048 represents 2GB.</p><pre>monoclecli --username admin --password password --addfile               --mountpoint / --path=/var/lib/MonocleServer/file.dat                   --numchunks=2048</pre><p>Your device will now automatically begin recording on all available recordings and will automatically delete the oldest data when full to maintain continuous recording. The recorded video can be played back over the ONVIF replay service, RTSP with timestamps or over the proprietary protocol in the <a href="https://www.monoclesecurity.com/download">Monocle Client</a> as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*RVKvH8p2EALbuVED4jet6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fbEDRjZ7zqdOXGIPRxdxA.jpeg" /></figure><p>The Monocle server is capable of utilising the CUDA cores on the NVidia Jetson platform with an object detector. To enable this feature on a recording, edit the track from within the Monocle Client and enable “Object Detection” and adjust any settings appropriately. This will work for both Argus and any other cameras. You may need to lower the accuracy depending on how much memory your device has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*j44Dzt8O_EIhmXs_1CJwPw.png" /><figcaption>Object Detection</figcaption></figure><p>The Monocle server also contains a web server which you can access with a browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*56ylBbYi3qOwo-8IV_vcqQ.png" /><figcaption>Monocle Web Interface</figcaption></figure><p>The Monocle server supports many other protocols including GPS, OpenAPI, MQTT, GRPC and JSON-RPC. Get in touch via the links below if you have any questions, issues or suggestions.</p><p><a href="https://discord.gg/QueVnNVwSr">Discord</a> <a href="https://www.patreon.com/monoclesecurity">Patreon</a> <a href="https://reddit.com/r/monoclesecurity">Reddit</a> <a href="https://www.monoclesecurity.com/">Monocle</a> <a href="https://github.com/MonocleSecurity/Monocle">Github</a> <a href="https://twitter.com/Monocle_Sec">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce974f423d7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ONVIF Authentication and Streaming]]></title>
            <link>https://medium.com/@monoclechris/onvif-authentication-and-streaming-688691be581c?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/688691be581c</guid>
            <category><![CDATA[rtsp]]></category>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[onvif]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Sun, 14 Aug 2022 19:11:10 GMT</pubDate>
            <atom:updated>2022-08-15T08:09:06.468Z</atom:updated>
            <content:encoded><![CDATA[<p>How to retrieve an RTSP URI with ONVIF.</p><p><strong>ONVIF Concepts</strong></p><p>ONVIF is a SOAP XML standard and this post assumes you are at least modestly familiar with this technology.</p><p>ONVIF Profiles are a set of specifications that a device must support in order to call themselves compatible. For instance, Profile S must support H264 and MJPEG encoding, whereas Profile T must support at least one of H264/H265. Most IP cameras at the moment support Profile S.</p><p>ONVIF Media Profiles represent streaming targets which can include video, audio and a variety of metadata.</p><p><strong>Notes</strong></p><p>Many IP cameras calling themselves ONVIF compliant often contain incompatibilities which are extremely frustrating and need to be navigated carefully in production software, so for the sake of brevity I am writing the fundamental way it <em>should </em>work which I hope will succeed the overwhelming majority of the time.</p><p><strong>Device Service GetSystemDateAndTime</strong></p><p>The first operation to call is GetSystemDateAndTime because authentication will require knowing the devices time. Perhaps not the most secure method to authenticate users, it is the main method for doing so with ONVIF and the only one that is required to work by all ONVIF compatible devices. The response will contain something similar to the XML shown below.</p><pre>&lt;tds:GetSystemDateAndTimeResponse&gt;<br>  &lt;tds:SystemDateAndTime&gt;<br>    &lt;tt:DateTimeType&gt;Manual&lt;/tt:DateTimeType&gt;<br>    &lt;tt:DaylightSavings&gt;true&lt;/tt:DaylightSavings&gt;<br>    &lt;tt:TimeZone&gt;&lt;tt:TZ&gt;CST+8:00:00DST01:00:00,M3.2.0/02:00:00,M11.1.0/02:00:00&lt;/tt:TZ&gt;<br>    &lt;/tt:TimeZone&gt;<br>    &lt;tt:UTCDateTime&gt;<br>      &lt;tt:Time&gt;<br>        &lt;tt:Hour&gt;9&lt;/tt:Hour&gt;<br>        &lt;tt:Minute&gt;3&lt;/tt:Minute&gt;<br>        &lt;tt:Second&gt;32&lt;/tt:Second&gt;<br>      &lt;/tt:Time&gt;<br>      &lt;tt:Date&gt;<br>        &lt;tt:Year&gt;2022&lt;/tt:Year&gt;<br>        &lt;tt:Month&gt;8&lt;/tt:Month&gt;<br>        &lt;tt:Day&gt;15&lt;/tt:Day&gt;<br>      &lt;/tt:Date&gt;<br>    &lt;/tt:UTCDateTime&gt;<br>    &lt;tt:LocalDateTime&gt;<br>      &lt;tt:Time&gt;<br>        &lt;tt:Hour&gt;1&lt;/tt:Hour&gt;<br>        &lt;tt:Minute&gt;3&lt;/tt:Minute&gt;<br>        &lt;tt:Second&gt;32&lt;/tt:Second&gt;<br>      &lt;/tt:Time&gt;<br>      &lt;tt:Date&gt;<br>        &lt;tt:Year&gt;2022&lt;/tt:Year&gt;<br>        &lt;tt:Month&gt;8&lt;/tt:Month&gt;<br>        &lt;tt:Day&gt;15&lt;/tt:Day&gt;<br>      &lt;/tt:Date&gt;<br>    &lt;/tt:LocalDateTime&gt;<br>  &lt;/tds:SystemDateAndTime&gt;<br>&lt;/tds:GetSystemDateAndTimeResponse&gt;</pre><p><strong>Authentication</strong></p><p>Operations which require authentication will need a header similar to the one shown below as a child of the <em>Envelope</em> element. The creation of the XML below is described in the <a href="https://www.onvif.org/wp-content/uploads/2016/12/ONVIF_WG-APG-Application_Programmers_Guide-1.pdf">ONVIF Application Programmers Guide</a> under 6.1.1.3 ONVIF::AuthenticatingByWS-UsernameToken. It is a mixture of formatting and digests and best explained by the original documentation. Some issues to be careful with are that some devices are very strict with the timing requirements and being out by a second might cause a rejection. This means it may be important to disable Nagle’s algorithm on your socket to achieve consistent results, and even compensate for any latency that may occur.</p><pre>&lt;s:Header&gt;<br>  &lt;Security xmlns=&quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd&quot; s:mustUnderstand=&quot;1&quot;&gt;<br>    &lt;UsernameToken&gt;<br>      &lt;Username&gt;admin&lt;/Username&gt;<br>      &lt;Password Type=&quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest&quot;&gt;Dob3XyD3ZVXzBmFM+AmBbkex02U=&lt;/Password&gt;<br>      &lt;Nonce EncodingType=&quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary&quot;&gt;jEkNGosDwy3fteLN56GqoZP0P9M=&lt;/Nonce&gt;<br>      &lt;Created xmlns=&quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd&quot;&gt;2022-08-14T14:36:12.14Z&lt;/Created&gt;<br>    &lt;/UsernameToken&gt;<br>  &lt;/Security&gt;<br>&lt;/s:Header&gt;</pre><p><strong>Retrieving Device Capabilities</strong></p><p>The set of operations which help determine what the device is capable of has not remained consistent over ONVIF’s lifetime. The more modern way is to call GetServices or GetServiceCapabilities, however on older devices you may find that doesn’t exist and you could revert to GetCapabilities if your original requests failed. Despite these issues, you goal is the same, to retrieve the <a href="http://www.onvif.org/ver10/media/wsdl/media.wsdl">Media Service</a> URI.</p><p><strong>Media Service GetProfiles</strong></p><p>This will give a list of ONVIF media profiles, which, for our use here, represent video and/or audio sources, encoders and their respective configurations. Often there are many of these for different resolutions and formats, and it will be up to your application on how to choose which one suits your requirements best.</p><p><strong>Media Service GetStreamUri</strong></p><p>Once you have chosen your profile, pass the uniquely identifying “token” to GetStreamUri along with a transport protocol. The required valid values for “Transport” are identified in the <a href="https://www.onvif.org/specs/srv/media/ONVIF-Media-Service-Spec-v210.pdf">ONVIF Media Service Specification</a> under 5.15.1 Request stream URI. Typically you would request RTP Unicast over UDP, however you may want to use a different transport. Often the URI returned will be the same for all transports because the final choice on which transport to use will come from the decisions made at the RTSP Describe and Setup phase.</p><p><a href="https://discord.gg/QueVnNVwSr">Discord</a> <a href="https://www.patreon.com/monoclesecurity">Patreon</a> <a href="https://reddit.com/r/monoclesecurity">Reddit</a> <a href="https://www.monoclesecurity.com/">Monocle</a> <a href="https://github.com/MonocleSecurity/Monocle">Github</a> <a href="https://twitter.com/Monocle_Sec">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=688691be581c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ and WebRTC: Video and Audio to the Browser]]></title>
            <link>https://medium.com/@monoclechris/c-and-webrtc-video-and-audio-to-the-browser-f9d901c9a340?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d901c9a340</guid>
            <category><![CDATA[monocle]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[rtsp]]></category>
            <category><![CDATA[h264]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Thu, 10 Mar 2022 21:09:10 GMT</pubDate>
            <atom:updated>2025-10-20T10:55:56.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHMLwMn8ndTe4VmzDKN8Aw.png" /></figure><p>The goal of this post is to describe some of the issues I encountered implementing WebRTC video and audio streaming to browsers in Monocle Security’s CCTV software.</p><h3><strong>Receiving the video and audio data</strong></h3><p>The simplest source of video and audio data for this example is RTSP because it will give us the SDP which we can directly compare later with the browsers SDP, however the same ideas can be used when streaming from any source whether it is a file, another WebRTC server, a USB camera or anything else. I’ll be focusing on H264 because it will allow the possibility to avoid transcoding, and the WebRTC standard guarantees support for it. The SDP you receive from the DESCRIBE request from the source will contain something that looks similar to this:</p><pre>a=rtpmap:96 H264/90000<br>a=fmtp:96 profile-level-id=420029;packetization-mode=1; sprop-parameter-sets= Z01AM42NQB4AIf/gLcBAQFAAAD6AAAnEDoYAD0/rvLjQwAHp/XeXCg==,aO44gA==</pre><p>The values that are relevant for our purposes here are:</p><p><em>profile-level-id:</em> A base16 value split into 3 equal parts for the profile(Baseline, Main or High), constraint flags and level.</p><p><em>packetization-mode:</em> Tells us what type of NAL units we can expect to receive from the encoder.</p><p><em>sprop-parameter-sets:</em> A comma separated base64 binary blob that tells us detailed information about the encoder commonly known as the SPS and PPS fragments.</p><p>Once the RTSP/RTP stream is setup, the data will flow as RTP packets in H264 NAL format which need to be depacketized into discrete frames.</p><h3><strong>The Peer connection</strong></h3><p>Currently the creation of WebRTC peer connections is not defined by any standard, but this may change in the future as more standards are introduced. There are many C++ libraries which include WebRTC functionality but the only one I found which gave enough control for Monocle’s purposes was <a href="https://github.com/paullouisageneau/libdatachannel"><em>libdatachannel</em></a>. The main alternative is Google’s WebRTC framework which negotiates the SDP itself and forces the user to transcode the data which increases latency and CPU load. There has been efforts to change this, but none have made it into the main branch as far as I am aware.</p><p>One of the requirements for initialising WebRTC connections are STUN and optionally TURN servers which help determine what the best route for traffic to the browser might be. There are publicly available servers that you can use, but you can also run your own.</p><h3><strong>Browser SDP negotiation</strong></h3><p>The browser or the server can initiate the SDP negotiation, Monocle chose the browser to be the “sender” because it allows the server, the “receiver”, to make the final choice on which format to use for video and audio. The browser will send a set of media descriptions each representing a format which should contain a variety of H264 and VP9 video formats at a minimum, as well as a suite of audio formats. The response should then contain corresponding media descriptions for each entry enabling and disabling them as desired.</p><p>Most browsers will offer multiple H264 media descriptions so we need to choose one. The simplest way to choose is to find entries where the packetization mode matches and then choose the one with the highest profile and level. A more accurate choice can be made by matching the profile and level we received from the SDP in the RTSP stream. For audio, we should try to match the original source format and the SDP as well, but if we can’t, we can either disable the audio, or choose one which we will transcode to.</p><p>Included in the SDP we need to provide ICE candidiates which include the location(s) of the STUN server(s), and a DTLS fingerprint which will be used later by the browser to create the DTLS connection which will provide a mechanism to exchange keys so the browser can decode our encrypted video and audio data via SRTP.</p><h3><strong>Sending the data</strong></h3><p>If the server was unable to negotiate a directly comparable format for video or audio, it will be necessary to decode the original stream and encode it into a suitable format, I found this is more likely to occur with audio, but your browser may differ. Now you can repacketize the H264 data in RTP NAL format, and then encrypt it with AES, convert it to SRTP and send it to the browser. <em>libdatachannel</em> will do a lot of this for you, but you will need to fully depacketize the into the correct format that it expects. Another reason for depacketizing and parsing the H264 data is that it might be necessary to prefix key frames with the SPS and PPS data collected from the original <em>sprop-parameter-sets</em>, there is very little harm in doing this as they are small and it should make the stream more reliably decode.</p><p>One of the issues with debugging WebRTC is that if something was setup incorrectly, you are likely to get no output whatsoever and no reasonable feedback as to what the problem might be. One of the tools to help overcome this that I found useful was Chrome’s webrtc-internals page which gives you lots of information and may help you decipher what is causing your issue.</p><h3>Example application</h3><p>This application I made takes a video file and plays it in a browser over WebRTC using FFmpeg and libdatachannel: <a href="https://github.com/MonocleSecurity/WebRTCPlayer">WebRTCPlayer</a>.</p><h3><strong>Conclusion</strong></h3><p>WebRTC is an excellent method for sending video and audio data because it is the only way to provide low latency media to the browser. It provides a method, albeit very complicated, for sending data to the browser which has been received over RTSP and other formats without requiring any major repackaging into files, processor intensive transcoding or loss of quality.</p><p>If you have any additional questions, please don’t hesitate to contact me on any of the platforms or places below.</p><p><a href="https://discord.gg/QueVnNVwSr">Discord</a> <a href="https://www.patreon.com/monoclesecurity">Patreon</a> <a href="https://reddit.com/r/monoclesecurity">Reddit</a> <a href="https://www.monoclesecurity.com/">Monocle</a> <a href="https://github.com/MonocleSecurity/Monocle">Github</a> <a href="https://twitter.com/Monocle_Sec">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d901c9a340" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ODROID-HC4 64 Camera NVR]]></title>
            <link>https://medium.com/@monoclechris/odroid-hc4-64-camera-nvr-f83b1ec0644b?source=rss-5ae9d0fcb53b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f83b1ec0644b</guid>
            <category><![CDATA[odroid]]></category>
            <category><![CDATA[arm]]></category>
            <category><![CDATA[nvr]]></category>
            <category><![CDATA[ip-camera]]></category>
            <dc:creator><![CDATA[Chris]]></dc:creator>
            <pubDate>Sat, 19 Feb 2022 10:13:21 GMT</pubDate>
            <atom:updated>2023-02-20T09:48:04.838Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating your own security system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D35ehhtqWp52Bw15U3_PgQ.png" /></figure><p>From a fresh <a href="https://wiki.odroid.com/odroid-hc4/os_images/ubuntu/minimal/20201212">ODROID-HC4 Ubuntu20 install</a>, this tutorial will help you setup a 64 camera network video recorder. The installation of the server is simple and the setup is straightforward with the Monocle client.</p><pre>sudo apt-get update<br>sudo apt-get upgrade<br>wget <a href="https://f002.backblazeb2.com/file/Monocle/monocleserver-arm-1-27-0.deb">https://f002.backblazeb2.com/file/Monocle/monocleserver-odroid-1-31-0.deb</a><br>sudo apt install ./monocleserver-aarch64-1-31-0.deb</pre><p>These commands will install and begin the Monocle service which represents the NVR. Initially, the server will not have any locations to record data to, so the next step is to add those. The package installed earlier also contains a command line interface for interacting with Monocle servers. Using the commands below to add the files, changing the “numchunks” argument which is effectively the total number of megabytes used to store data, thus 2048 represents 2GB, the mount point and path where your storage drives are mounted. Doing this will allow the server to continuously record, deleting old data when necessary. The more disks available will improve the performance. This can also be done in the Monocle client interface in the “Manage Files” window.</p><pre>monoclecli --username admin --password password --addfile           --mountpoint /mnt/sda --path=/mnt/sda/file.dat --numchunks=2048<br>monoclecli --username admin --password password --addfile           --mountpoint /mnt/sdb --path=/mnt/sdb/file.dat --numchunks=2048</pre><p>Download and run the appropriate Monocle client for your operating system from <a href="https://www.monoclesecurity.com/download">here</a> and add the device, which should be discovered automatically, but if not, the hostname can be manually added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*RVKvH8p2EALbuVED4jet6A.png" /></figure><p>With the device added, we now need to add the cameras. Use the “Add Camera Wizard” by right clicking on your server and inputting the appropriate username and password for your cameras and click ok.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VGl2WmMDj-K5oDM13ySp4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCNJo3qccdnwrZO-9Q9hWA.png" /></figure><p>There is also a web interface accessible by any modern browser and an example of it is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqKOHd5iLQJjHjmKRyxEYw.jpeg" /></figure><p>Here are screenshots of the “htop” and “iostat” tools while recording 64 cameras on the ODROID HC4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MD9k0wdzhfgh23K6FlNv8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnUoO9bR0Sa0sCPyV0Cp9A.png" /></figure><p>The Monocle server supports many other protocols including MQTT, GRPC, OpenAPI and JSON-RPC as well as having a phone app. Get in touch via the links below if you have any questions, issues or suggestions.</p><p><a href="https://discord.gg/QueVnNVwSr">Discord</a> <a href="https://www.patreon.com/monoclesecurity">Patreon</a> <a href="https://reddit.com/r/monoclesecurity">Reddit</a> <a href="https://www.monoclesecurity.com/">Monocle</a> <a href="https://github.com/MonocleSecurity/Monocle">Github</a> <a href="https://twitter.com/Monocle_Sec">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f83b1ec0644b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>