Compare commits

..

186 Commits
v3.13 ... v5.4

Author SHA1 Message Date
Maxim Devaev
3d4e9fbb1a Bump version: 5.3 → 5.4 2022-04-29 16:45:30 +03:00
Maxim Devaev
4a59b038ec refactoring 2022-04-29 16:44:13 +03:00
Maxim Devaev
6795744aea Merge pull request #153 from FallingSnow/cors
Better CORS support
2022-04-29 13:59:25 +03:00
Maxim Devaev
798fe04905 Merge pull request #152 from FallingSnow/patch-1
Add alpine linux instructions to readme
2022-04-29 13:56:27 +03:00
Ayrton Sparling
1460de95c1 Add "better cors" to /stream http endpoint
Signed-off-by: Ayrton Sparling <ayrton@sparling.us>
2022-04-28 08:40:15 -07:00
Ayrton Sparling
358950d0c2 Better CORS support
Current CORS support only adds an Access-Control-Allow-Origin header to some requests. It also does not support the OPTIONS preflight sent by modern browsers. This commit adds support for OPTIONS preflight as well as more CORS headers.

The OPTIONS preflight is sent without any credentials attached to it so it mist take place before Authorization header processesing. Firefox 99 requires other access control headers like Access-Control-Allow-Headers be returned for a successful CORS interaction.

Signed-off-by: Ayrton Sparling <ayrton@sparling.us>
2022-04-26 16:28:57 -07:00
Ayrton Sparling
caef82d96f Change WITH_PTHREAD_NP=false to WITH_PTHREAD_NP=0 2022-04-21 13:34:05 -07:00
Ayrton Sparling
dff7dd7087 Add alpine linux instructions to readme
Alpine's uses musl rather than libc and does not have support for `pthread_getname_np`. Therefore it must be build with `WITH_PTHREAD_NP=false`.
2022-04-21 10:34:25 -07:00
Maxim Devaev
79bb881a34 Merge pull request #150 from tiny-pilot/h264-guide
Add documentation for integrating with Janus to stream H.264 video
2022-04-16 19:34:19 +03:00
Michael Lynch
f0763e3865 Tweak language in H264 guide (#3)
* Adjust wording in uStreamer Janus guide

* Small tweaks

* Small changes

* Updating based on review notes
2022-04-13 09:50:15 -04:00
jotaen4tinypilot
a8dfa96db0 Document guide for H.264 (#2)
* Setup guide for H.264

* Phrasing, structure

* Remove MJPEG primer and rewrite intro

* Link to library files directly

* Adjust page title

* Remove todo

* Resolve todo (Janus setup)

* Comment all JavaScript

* Rephrase to use active voice, clarify details

* Phrasing and clarifications

* Write backend instructions

* Grammar

* Use generic URL with port number

* Use consistent terminology

* Use term “V4L2 device” to refer to the video device

* Link “building” section of uStreamer README

* Use active voice

* Change page title to “demo”

* Add comment about the `janus.js` library file

* Use window location to construct server URL

* Move `videoElement` variable closer to it’s usage

* Elaborate why we clone the media stream

* Drop obsolete `WITH_OMX` option

* Correct path of shared object file

* Fix shadowing variable of same name

* Send `start` request to avoid (harmless) `400` response

* Add `refcount.h` fix

Co-authored-by: Jan Heuermann <jan@jotaen.net>
2022-04-13 06:31:15 -04:00
Maxim Devaev
7ceb8a3da5 Bump version: 5.2 → 5.3 2022-04-01 18:35:34 +03:00
Maxim Devaev
9344059e0e systemd is required for arch now 2022-04-01 18:33:05 +03:00
Maxim Devaev
ee2b1afe5b note about kernel support 2022-04-01 18:30:21 +03:00
Maxim Devaev
31f47f2eac Bump version: 5.1 → 5.2 2022-03-21 15:01:23 +03:00
Maxim Devaev
69a9bafcd5 moved platform checks to tools.h 2022-03-21 15:00:06 +03:00
Maxim Devaev
dbecdf5d9b disabled paypal 2022-03-20 03:05:23 +03:00
Maxim Devaev
967574a78a Bump version: 5.0 → 5.1 2022-03-15 16:23:24 +03:00
Maxim Devaev
bb4f6f3993 h264 max kbps is 20000 2022-03-15 16:22:07 +03:00
Maxim Devaev
fdc955a713 Bump version: 4.13 → 5.0 2022-03-02 14:42:31 +03:00
Maxim Devaev
322c67f7a5 fix 2022-02-21 05:11:25 +03:00
Maxim Devaev
7aa7f43c7e fix 2022-02-21 05:11:25 +03:00
Maxim Devaev
8ef5505a48 only required m2m options 2022-02-21 05:11:25 +03:00
Maxim Devaev
481f2c9479 readme fix 2022-02-21 05:11:25 +03:00
Maxim Devaev
924ebf7c77 disabled dma for m2m jpeg, fixed device path 2022-02-21 05:11:25 +03:00
Maxim Devaev
d67af7a9dc copyright bump 2022-02-21 05:11:25 +03:00
Maxim Devaev
e6be119ab5 changed some log messages 2022-02-21 05:11:25 +03:00
Maxim Devaev
ead06e741a removed grabbed_mutex 2022-02-21 05:11:25 +03:00
Maxim Devaev
fbabba29ed refactoring 2022-02-21 05:11:25 +03:00
Maxim Devaev
ff9b0f5396 fixed readme 2022-02-21 05:11:25 +03:00
Maxim Devaev
52a31f619b refactoring 2022-02-21 05:11:25 +03:00
Maxim Devaev
743e8ac828 using setuptools 2022-02-21 05:11:25 +03:00
Maxim Devaev
cecec39281 refactoring 2022-02-21 05:11:25 +03:00
Maxim Devaev
280254e231 fixed m2m buffers messing 2022-02-21 05:11:25 +03:00
Maxim Devaev
97a1aa04cb allow_dma flag 2022-02-21 05:11:25 +03:00
Maxim Devaev
e14644572b refactoring 2022-02-21 05:11:25 +03:00
Maxim Devaev
55e0a096e7 renamed m2m encoders 2022-02-21 05:11:25 +03:00
Maxim Devaev
e68e6b6fae renamed MJPG to MJPEG 2022-02-21 05:11:25 +03:00
Maxim Devaev
aa03e1610f supported /dev/video21 2022-02-21 05:11:25 +03:00
Maxim Devaev
2b969dd20d encode_end_ts on noop 2022-02-21 05:11:25 +03:00
Maxim Devaev
c51984c9d9 common --m2m-device option 2022-02-21 05:11:25 +03:00
Maxim Devaev
459060532a m2m jpeg quality 2022-02-21 05:11:25 +03:00
Maxim Devaev
016ee1c554 using actual bitrate range 2022-02-21 05:11:25 +03:00
Maxim Devaev
26e0c9d54c refactoring 2022-02-21 05:11:25 +03:00
Maxim Devaev
e6584da7c8 renamed v4l2 encoder to m2m 2022-02-21 05:11:25 +03:00
Maxim Devaev
630ad66cc8 bunch of fixes for m2m 2022-02-21 05:11:23 +03:00
Maxim Devaev
222b9a0309 mjpeg v4l2 encoding 2022-02-21 05:08:48 +03:00
Maxim Devaev
235a1765d2 fixed m2m encoder fd 2022-02-21 05:08:48 +03:00
Maxim Devaev
bff8a5d854 unused dest_role 2022-02-21 05:08:48 +03:00
Maxim Devaev
fd65ed006a simplified m2m usage 2022-02-21 05:08:48 +03:00
Maxim Devaev
52478df3cf dma_fd in frame 2022-02-21 05:08:48 +03:00
Maxim Devaev
7732841cdf refactoring 2022-02-21 05:08:48 +03:00
Maxim Devaev
10aa33d899 common m2m code, fixed non-dma dq 2022-02-21 05:08:48 +03:00
Maxim Devaev
bd6fa7b0dc renamed zero_copy to dma 2022-02-21 05:08:48 +03:00
Maxim Devaev
536f45eff5 fixed man 2022-02-21 05:08:48 +03:00
Maxim Devaev
bb1dcc005c configure quant_min and quant_max 2022-02-21 05:08:48 +03:00
Maxim Devaev
ea313d3517 changed some log messages 2022-02-21 05:08:48 +03:00
Maxim Devaev
78a12f7ed2 Issue #83: Moved H.264 to h264_v4l2m2m 2022-02-21 05:08:48 +03:00
Maxim Devaev
281f4eb3a0 replaced MEMSET_ZERO to initializers 2022-02-21 05:08:48 +03:00
Maxim Devaev
dabaab4987 renamed buf_info to buf 2022-02-21 05:08:48 +03:00
Maxim Devaev
61ab2a81a5 Bump version: 4.12 → 4.13 2022-02-21 05:06:06 +03:00
Maxim Devaev
d9b511c69f doc update 2022-02-21 05:04:42 +03:00
Maxim Devaev
4d9e72e313 man fix 2022-02-15 01:33:04 +03:00
Maxim Devaev
616a3eb6a6 new option --exit-on-no-clients 2022-02-14 02:44:58 +03:00
Maxim Devaev
3a8f035014 refactoring 2022-02-14 01:47:13 +03:00
Maxim Devaev
be2e0f11da systemd socket activation 2022-02-13 18:59:33 +03:00
Maxim Devaev
fec76dc9eb Bump version: 4.11 → 4.12 2022-02-11 20:53:52 +03:00
Maxim Devaev
48826208fd Fixed #143: Show HDMI info 2022-02-11 20:00:47 +03:00
Maxim Devaev
dd4fda6f5d fixed indent 2022-02-11 19:57:15 +03:00
Maxim Devaev
1dafb54621 Merge pull request #140 from fphammerle/readme-libopenmaxil-on-bullseye
readme: suggest adding `/opt/vc/lib/` to library search path on bullseye
2022-02-05 14:44:26 +03:00
Maxim Devaev
19f9567098 added comment about evbuffer_add_file() 2022-02-05 14:35:07 +03:00
Maxim Devaev
b3d1f06e5d Merge pull request #141 from russdill/evbuffer_add_file_fix
Don't close evbuffer_add_file's file descriptor
2022-02-05 14:30:24 +03:00
Maxim Devaev
f17069153d fixed quotes 2022-02-05 14:12:54 +03:00
Maxim Devaev
8a7d7b9c54 Merge pull request #142 from russdill/client-key-in-state
Expose supplied client key in state
2022-02-05 14:09:34 +03:00
Russ Dill
df7649d56f Expose supplied client key in state
The client key and id is currently supplied in a cookie. This
provides a way for a client to determine it's id in order to match
it within the state response. However if cookies are disabled or
the source domain differs from the ustreamer domain the cookie will
not be set.

This provides an alternate way for a client to find the state
response associated with it's connection by including the client
provided key in the state response. If the client does not supply
a key, the value 0 is supplied.

Signed-off-by: Russ Dill <russ.dill@gmail.com>
2022-02-04 23:07:41 -08:00
Russ Dill
58cc227cba Don't close evbuffer_add_file's file descriptor
evbuffer_add_file takes ownership for the file descriptor we pass
and manages closing it. Closing it ourselves will lead to the function
only being able to make very small transfers.

Signed-off-by: Russ Dill <russ.dill@gmail.com>
2022-02-04 23:06:22 -08:00
Fabian Peter Hammerle
76be4a1d10 readme: suggest adding /opt/vc/lib/ to library search path on bullseye
On Raspberry Pi OS Bullseye:
```sh
$ make WITH_OMX=1
[...]
== LD ustreamer.bin
/usr/bin/ld: warning: libbrcmGLESv2.so, needed by /opt/vc/lib/libopenmaxil.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: warning: libbrcmEGL.so, needed by /opt/vc/lib/libopenmaxil.so, not found (try using -rpath or -rpath-link)
[...]
$ ./ustreamer --features
./ustreamer: error while loading shared libraries: libopenmaxil.so: cannot open shared object file: No such file or directory
$ LD_LIBRARY_PATH=/opt/vc/lib/ ./ustreamer --features
+ WITH_OMX
- WITH_GPIO
+ WITH_PTHREAD_NP
+ WITH_SETPROCTITLE
+ HAS_PDEATHSIG
```
2022-01-30 19:57:43 +01:00
Maxim Devaev
496c9300fc Bump version: 4.10 → 4.11 2021-12-31 01:28:51 +03:00
Maxim Devaev
5b7780cf7c using python-3.10 2021-12-31 01:26:47 +03:00
Maxim Devaev
421f4a1f2e Bump version: 4.9 → 4.10 2021-11-28 08:43:41 +03:00
Maxim Devaev
55a5d4bbdd real bitrate range 2021-11-28 08:40:56 +03:00
Maxim Devaev
666ae0c4f1 Merge pull request #133 from jtrmal/patch-1
correct/updated package name is libgpiod-dev
2021-11-26 03:33:04 +03:00
Jan "yenda" Trmal
ca3afc074c correct/updated package name is libgpiod-dev 2021-11-21 12:19:03 -05:00
Maxim Devaev
030077fb47 Bump version: 4.8 → 4.9 2021-10-30 11:40:31 +03:00
Maxim Devaev
61ddff8b6e Merge pull request #129 from b-rad15/master
Change html links to relative not absolute
2021-10-30 11:27:20 +03:00
Bradley O'Connell
27fbfe149e changed html links to relative not absolute 2021-10-30 03:20:57 -04:00
Maxim Devaev
349f655cd9 Bump version: 4.7 → 4.8 2021-10-19 15:56:19 +03:00
Maxim Devaev
f5c0a15967 removed ansible link 2021-10-19 15:55:34 +03:00
Maxim Devaev
d822ae0890 Fixed #121: static inline 2021-10-19 15:47:42 +03:00
Maxim Devaev
2d82adb2ba Bump version: 4.6 → 4.7 2021-10-17 00:14:25 +03:00
Maxim Devaev
56b21274d1 ru doc, etc 2021-10-17 00:13:01 +03:00
Maxim Devaev
76329ba5a6 Fixed #128: added mjpg_streamer compatibility for --static 2021-10-17 00:08:13 +03:00
Maxim Devaev
4d5c5fffb4 Merge pull request #127 from tiny-pilot/nginx-doc
Document how to integrate uStreamer with nginx
2021-10-17 00:07:55 +03:00
Michael Lynch
29234c330b Document how to integrate uStreamer with nginx
This change documents a gotcha that can occur when clients deploy uStreamer behind an nginx proxy. By default, nginx buffers responses, which introduces latency into the video stream. Disabling the buffer eliminates this latency.
2021-10-14 10:02:42 -04:00
Maxim Devaev
690d291818 Bump version: 4.5 → 4.6 2021-09-27 23:14:24 +03:00
Maxim Devaev
8cfb3fc301 lint fix 2021-09-27 22:55:01 +03:00
Maxim Devaev
69ab3fa831 ustreamer-dump: count and interval 2021-09-27 22:54:08 +03:00
Maxim Devaev
79d6c76084 Bump version: 4.4 → 4.5 2021-08-13 11:02:34 +03:00
Maxim Devaev
f15d2fc194 fixed .dockerignore 2021-08-13 10:49:23 +03:00
Maxim Devaev
99aa4828c5 fixed .gitignore 2021-08-13 10:48:41 +03:00
Maxim Devaev
93969f487c Issue #115: Comment about rtp_wrap_h264() 2021-08-13 10:39:24 +03:00
Maxim Devaev
61407c6596 Issue #115: Avoid usage of uninitialized last_client_ts 2021-08-13 10:36:53 +03:00
Maxim Devaev
6c95a56f3a Merge pull request #119 from PCPartPicker/vcpr_h264_rtp_mark_fix
Fix h264 rtp packetization - the marked bit should only be set for th…
2021-08-05 01:46:22 +03:00
aggieNick02
283f53a961 Fix h264 rtp packetization - the marked bit should only be set for the very last packet of each access unit (frame) - previously it was being set for the last packet of each type 1-5 NALU, which is equivalent and correct if the frame contains only one type 1-5 NALU, but not if it contains more 2021-08-03 23:10:21 -05:00
Maxim Devaev
ef8fb8216e .editorconfig 2021-07-25 04:23:24 +03:00
Devaev Maxim
6293d54296 Bump version: 4.3 → 4.4 2021-06-10 19:32:24 +03:00
Devaev Maxim
c20754e62c Bump version: 4.2 → 4.3 2021-06-10 19:10:51 +03:00
Devaev Maxim
c621e36929 fixed deps 2021-06-10 19:10:13 +03:00
Devaev Maxim
484ff0f32b Bump version: 4.1 → 4.2 2021-06-10 19:06:50 +03:00
Devaev Maxim
adb60124fb compile janus if provided 2021-06-10 19:06:12 +03:00
Devaev Maxim
767d8ac240 Bump version: 4.0 → 4.1 2021-06-10 18:56:00 +03:00
Devaev Maxim
4648ecba17 fixed install 2021-06-10 18:55:19 +03:00
Devaev Maxim
0a08ca657d Bump version: 3.27 → 4.0 2021-06-10 18:48:00 +03:00
Devaev Maxim
48f35ccd32 janus plugin 2021-06-10 18:42:16 +03:00
Devaev Maxim
3558089a22 get_now_monotonic_u64() 2021-06-08 18:55:52 +03:00
Devaev Maxim
47b735c51f Bump version: 3.26 → 3.27 2021-04-26 20:37:27 +03:00
Maxim Devaev
e60991974e Merge pull request #109 from netbr/master
Option to rotate image for Raspberry Pi Camera Module
2021-04-24 01:31:47 +03:00
netbr
3a16d17f8f Update options.c 2021-04-21 07:57:16 +02:00
netbr
08ddb351c7 Update device.h 2021-04-21 07:53:14 +02:00
netbr
3f251a2459 Update device.c 2021-04-21 07:52:06 +02:00
Devaev Maxim
a97f08eac8 Bump version: 3.25 → 3.26 2021-04-20 19:35:49 +03:00
Devaev Maxim
92ff097d7e show memsink has_client in the /state 2021-04-08 08:42:53 +03:00
Devaev Maxim
0eb0370bd3 moved python sources 2021-04-08 05:19:19 +03:00
Devaev Maxim
b329dfed1f Bump version: 3.24 → 3.25 2021-04-07 00:46:39 +03:00
Devaev Maxim
62dc2e5ad5 Fixed #105: using $(MAKE) 2021-04-06 23:43:32 +03:00
Devaev Maxim
7ea81fa627 fix 2021-04-03 06:42:33 +03:00
Devaev Maxim
8ddf77a3d3 Bump version: 3.23 → 3.24 2021-04-03 02:12:22 +03:00
Devaev Maxim
fde89465ac global variables prefix 2021-04-02 13:31:34 +03:00
Devaev Maxim
aa1d78a3cd fix 2021-04-02 12:39:09 +03:00
Devaev Maxim
6dfe077775 refactoring 2021-04-02 12:38:38 +03:00
Devaev Maxim
dd6dc866a6 Fixed #103: symlinks without .bin suffix 2021-04-02 09:01:29 +03:00
Devaev Maxim
3bf68884f5 improved linting 2021-04-02 02:18:27 +03:00
Devaev Maxim
e1b2eceea5 split makefiles 2021-04-02 01:00:22 +03:00
Devaev Maxim
7ce11fecb6 RN 2021-04-01 13:14:58 +03:00
Devaev Maxim
cbc6145977 using strerror_l() 2021-04-01 10:21:12 +03:00
Devaev Maxim
24f7fb797b refactoring 2021-04-01 09:32:29 +03:00
Devaev Maxim
71f1d397bf moved errno_to_string() to the tools 2021-04-01 08:49:18 +03:00
Devaev Maxim
00e83c155e removed managed flag 2021-03-30 10:16:55 +03:00
Devaev Maxim
1f186a0afe refactoring 2021-03-30 10:11:14 +03:00
Devaev Maxim
3c7075d0d2 removed frame name 2021-03-30 10:02:03 +03:00
Devaev Maxim
c1d7bd1595 link fix 2021-03-30 03:21:04 +03:00
Devaev Maxim
04d1d3d5a6 some common macroses 2021-03-30 02:18:40 +03:00
Devaev Maxim
01bc0529e7 refactoring 2021-03-28 22:48:17 +03:00
Devaev Maxim
181231f3ff common list operations 2021-03-28 21:51:34 +03:00
Devaev Maxim
58569f0315 separate major and minor numbers 2021-03-28 08:04:12 +03:00
Maxim Devaev
5903fcf718 Update README.ru.md 2021-03-27 22:45:24 +03:00
Maxim Devaev
1a820b23a5 Merge pull request #101 from Lennie/patch-1
Update README.md
2021-03-27 22:44:51 +03:00
Lennie
67b767b152 Update README.md
On my system I needed to use -d my guess is it was just a typo from you ?
2021-03-27 20:34:33 +01:00
Devaev Maxim
74bf710bb6 Bump version: 3.22 → 3.23 2021-03-26 22:03:40 +03:00
Devaev Maxim
1d3b428a75 using asprintf 2021-03-25 14:23:43 +03:00
Devaev Maxim
749bc5caf7 const 2021-03-25 13:35:56 +03:00
Devaev Maxim
3b7cbc62c4 Bump version: 3.21 → 3.22 2021-03-22 07:07:56 +03:00
Devaev Maxim
dff49d8e7b h264 mmal brokes on 0 fps and 640x480 2021-03-22 07:07:21 +03:00
Maxim Devaev
b23883e65f Update README.md 2021-03-21 17:57:37 +03:00
Maxim Devaev
c2e30c7fc4 Update README.ru.md 2021-03-21 17:57:01 +03:00
Devaev Maxim
37216250b8 Bump version: 3.20 → 3.21 2021-03-21 03:58:35 +03:00
Devaev Maxim
dc82894038 Issue #100: handle X-Forwarded-For 2021-03-21 03:35:47 +03:00
Devaev Maxim
f3a350148e Bump version: 3.19 → 3.20 2021-03-14 18:43:53 +03:00
Devaev Maxim
5e49f50e22 don't cache dict_frame 2021-03-14 18:16:41 +03:00
Devaev Maxim
91ff97f721 Bump version: 3.18 → 3.19 2021-03-14 03:03:54 +03:00
Devaev Maxim
daaa488dd6 segfault fix 2021-03-14 03:03:18 +03:00
Devaev Maxim
bad05a6827 Bump version: 3.17 → 3.18 2021-03-07 16:35:22 +03:00
Devaev Maxim
89d3ed98c7 readme fix 2021-03-07 16:23:22 +03:00
Devaev Maxim
1187ace2a2 removed libuuid dep and using get_now_id() 2021-03-07 14:54:13 +03:00
Devaev Maxim
9704fb054c fixed pikvm/pikvm#222 2021-03-06 13:49:08 +03:00
Maxim Devaev
b10148a438 Update README.md 2021-03-01 07:32:00 +03:00
Devaev Maxim
1b4bcd09fe Bump version: 3.16 → 3.17 2021-02-18 06:34:26 +03:00
Devaev Maxim
245cd94a4c ru readme fix 2021-02-18 04:07:56 +03:00
Devaev Maxim
8a24a0b129 prevent hanging on vcos semaphore 2021-02-18 03:38:48 +03:00
Devaev Maxim
b362c1fa50 russian readme 2021-02-17 23:25:17 +03:00
Maxim Devaev
0414fa5a51 Merge pull request #94 from Drachenkaetzchen/patch-1
Give V4L2_PIX_FMT_MJPEG an unique name
2021-02-17 23:17:06 +03:00
Maxim Devaev
191dd16d7b Merge pull request #91 from mtlynch/trailing-whitespace
Delete trailing whitespace from README
2021-02-17 23:15:11 +03:00
Maxim Devaev
31a03928c9 Merge pull request #90 from mtlynch/libjpeg-dev-ubuntu
Add libjpeg-dev to Ubuntu 20.04 dependencies
2021-02-17 23:14:50 +03:00
Felicia Hummel
185a8b6773 Update README.md 2021-02-17 11:48:16 +01:00
Felicia Hummel
b7501cfbda Add MJPEG to FORMATS_STR
Add missing MJPEG option to FORMATS_STR
2021-02-12 00:17:06 +01:00
Felicia Hummel
1dc90dad7a Give V4L2_PIX_FMT_MJPEG an unique name
This patch gives `V4L2_PIX_FMT_MJPEG` an unique name. Previously, `V4L2_PIX_FMT_MJPEG` would be chosen instead of `V4L2_PIX_FMT_JPEG` if `JPEG` was specified on the command line.

Relates to issue #40
2021-02-12 00:06:03 +01:00
Michael Lynch
45a4d148f5 Delete trailing whitespace from README 2021-02-05 15:19:10 -05:00
Michael Lynch
93ab12b54b Add libjpeg-dev to Ubuntu 20.04 dependencies
Building on Ubuntu 20.04 fails without libjpeg-dev, so this change adds it to the README.
2021-02-05 15:18:26 -05:00
Devaev Maxim
fb07444b70 Bump version: 3.15 → 3.16 2021-02-04 01:55:16 +03:00
Devaev Maxim
a8ba2f7364 H264: disable MMAL_PARAMETER_VIDEO_ENCODE_FRAME_LIMIT_BITS 2021-02-04 01:54:42 +03:00
Devaev Maxim
171bcb315a Bump version: 3.14 → 3.15 2021-02-03 05:49:40 +03:00
Devaev Maxim
911df1af15 rename 2021-02-03 05:48:15 +03:00
Devaev Maxim
a165ff4523 expose keyframe flag 2021-02-03 05:39:18 +03:00
Devaev Maxim
5cfb3b1e60 Bump version: 3.13 → 3.14 2021-01-28 22:16:44 +03:00
Devaev Maxim
82b3b78238 ignore drop-same-frames for sinks 2021-01-27 11:30:35 +03:00
Devaev Maxim
8a82ff6691 using archlinux/archlinux:base-devel 2021-01-25 11:58:52 +03:00
116 changed files with 3214 additions and 2537 deletions

View File

@@ -1,14 +1,22 @@
[bumpversion]
commit = True
tag = True
current_version = 3.13
parse = (?P<major>\d+)\.(?P<minor>\d+)(\.(?P<patch>\d+)(\-(?P<release>[a-z]+))?)?
current_version = 5.4
parse = (?P<major>\d+)\.(?P<minor>\d+)
serialize =
{major}.{minor}
[bumpversion:file:src/libs/config.h]
search = VERSION "{current_version}"
replace = VERSION "{new_version}"
parse = (?P<major>\d+)
serialize = {major}
search = VERSION_MAJOR {current_version}
replace = VERSION_MAJOR {new_version}
[bumpversion:file:./src/libs/config.h]
parse = <major>\d+\.(?P<minor>\d+)
serialize = {minor}
search = VERSION_MINOR {current_version}
replace = VERSION_MINOR {new_version}
[bumpversion:file:python/setup.py]
search = version="{current_version}"

View File

@@ -4,3 +4,6 @@
# Allow source code
!Makefile
!src/**
!python/**
!janus/**
!man/**

10
.editorconfig Normal file
View File

@@ -0,0 +1,10 @@
root = true
[*]
end_of_file = lf
indent_style = tab
indent_size = 4
[*.{py,yaml}]
indent_style = space
indent_size = 4

2
.github/FUNDING.yml vendored
View File

@@ -1,4 +1,4 @@
# These are supported funding model platforms
patreon: pikvm
custom: https://www.paypal.me/mdevaev
#custom: https://www.paypal.me/mdevaev

18
.gitignore vendored
View File

@@ -2,14 +2,16 @@
/linters/.mypy_cache/
/pkg/arch/pkg/
/pkg/arch/src/
/pkg/arch/v*.tar.gz
/pkg/arch/ustreamer-*.pkg.tar.xz
/pkg/arch/ustreamer-*.pkg.tar.zst
/build/
/src/build/
/python/build/
/config.mk
/vgcore.*
/janus/build/
/ustreamer
/ustreamer-dump
/*.so
/*.sock
/config.mk
vgcore.*
*.sock
*.so
*.bin
*.pkg.tar.xz
*.pkg.tar.zst
*.tar.gz

182
Makefile
View File

@@ -1,7 +1,5 @@
-include config.mk
USTR ?= ustreamer
DUMP ?= ustreamer-dump
DESTDIR ?=
PREFIX ?= /usr/local
MANPREFIX ?= $(PREFIX)/share/man
@@ -14,147 +12,82 @@ LDFLAGS ?=
RPI_VC_HEADERS ?= /opt/vc/include
RPI_VC_LIBS ?= /opt/vc/lib
BUILD ?= build
export
LINTERS_IMAGE ?= $(USTR)-linters
_LINTERS_IMAGE ?= ustreamer-linters
# =====
_CFLAGS = -MD -c -std=c11 -Wall -Wextra -D_GNU_SOURCE $(CFLAGS)
_LDFLAGS = $(LDFLAGS)
_COMMON_LIBS = -lm -ljpeg -pthread -lrt
_USTR_LIBS = $(_COMMON_LIBS) -levent -levent_pthreads -luuid
_USTR_SRCS = $(shell ls \
src/libs/*.c \
src/ustreamer/*.c \
src/ustreamer/http/*.c \
src/ustreamer/data/*.c \
src/ustreamer/encoders/cpu/*.c \
src/ustreamer/encoders/hw/*.c \
)
_DUMP_LIBS = $(_COMMON_LIBS)
_DUMP_SRCS = $(shell ls \
src/libs/*.c \
src/dump/*.c \
)
define optbool
$(filter $(shell echo $(1) | tr A-Z a-z), yes on 1)
endef
ifneq ($(call optbool,$(WITH_OMX)),)
_USTR_LIBS += -lbcm_host -lvcos -lvcsm -lopenmaxil -lmmal -lmmal_core -lmmal_util -lmmal_vc_client -lmmal_components -L$(RPI_VC_LIBS)
override _CFLAGS += -DWITH_OMX -DOMX_SKIP64BIT -I$(RPI_VC_HEADERS)
_USTR_SRCS += $(shell ls \
src/ustreamer/encoders/omx/*.c \
src/ustreamer/h264/*.c \
)
endif
ifneq ($(call optbool,$(WITH_GPIO)),)
_USTR_LIBS += -lgpiod
override _CFLAGS += -DWITH_GPIO
_USTR_SRCS += $(shell ls src/ustreamer/gpio/*.c)
endif
WITH_PTHREAD_NP ?= 1
ifneq ($(call optbool,$(WITH_PTHREAD_NP)),)
override _CFLAGS += -DWITH_PTHREAD_NP
endif
WITH_SETPROCTITLE ?= 1
ifneq ($(call optbool,$(WITH_SETPROCTITLE)),)
ifeq ($(shell uname -s | tr A-Z a-z),linux)
_USTR_LIBS += -lbsd
endif
override _CFLAGS += -DWITH_SETPROCTITLE
endif
# =====
all: $(USTR) $(DUMP) python
install: all
mkdir -p $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(MANPREFIX)/man1
install -m755 $(USTR) $(DESTDIR)$(PREFIX)/bin/$(USTR)
install -m755 $(DUMP) $(DESTDIR)$(PREFIX)/bin/$(DUMP)
install -m644 man/$(USTR).1 $(DESTDIR)$(MANPREFIX)/man1/$(USTR).1
install -m644 man/$(DUMP).1 $(DESTDIR)$(MANPREFIX)/man1/$(DUMP).1
gzip -f $(DESTDIR)$(MANPREFIX)/man1/$(USTR).1
gzip -f $(DESTDIR)$(MANPREFIX)/man1/$(DUMP).1
all:
+ $(MAKE) apps
ifneq ($(call optbool,$(WITH_PYTHON)),)
cd python && $(PY) setup.py install --prefix=$(PREFIX) --root=$(if $(DESTDIR),$(DESTDIR),/)
+ $(MAKE) python
endif
ifneq ($(call optbool,$(WITH_JANUS)),)
+ $(MAKE) janus
endif
install-strip: install
strip $(DESTDIR)$(PREFIX)/bin/$(USTR)
strip $(DESTDIR)$(PREFIX)/bin/$(DUMP)
regen:
tools/make-jpeg-h.py src/ustreamer/data/blank.jpeg src/ustreamer/data/blank_jpeg.c BLANK
tools/make-html-h.py src/ustreamer/data/index.html src/ustreamer/data/index_html.c INDEX
$(USTR): $(_USTR_SRCS:%.c=$(BUILD)/%.o)
# $(info ========================================)
$(info == LD $@)
@ $(CC) $^ -o $@ $(_LDFLAGS) $(_USTR_LIBS)
# $(info :: CC = $(CC))
# $(info :: LIBS = $(_USTR_LIBS))
# $(info :: CFLAGS = $(_CFLAGS))
# $(info :: LDFLAGS = $(_LDFLAGS))
$(DUMP): $(_DUMP_SRCS:%.c=$(BUILD)/%.o)
# $(info ========================================)
$(info == LD $@)
@ $(CC) $^ -o $@ $(_LDFLAGS) $(_DUMP_LIBS)
# $(info :: CC = $(CC))
# $(info :: LIBS = $(_DUMP_LIBS))
# $(info :: CFLAGS = $(_CFLAGS))
# $(info :: LDFLAGS = $(_LDFLAGS))
$(BUILD)/%.o: %.c
$(info -- CC $<)
@ mkdir -p $(dir $@) || true
@ $(CC) $< -o $@ $(_CFLAGS)
apps:
$(MAKE) -C src
@ ln -sf src/ustreamer.bin ustreamer
@ ln -sf src/ustreamer-dump.bin ustreamer-dump
python:
ifneq ($(call optbool,$(WITH_PYTHON)),)
$(info == PY_BUILD ustreamer-*.so)
@ cd python && $(PY) setup.py build
$(MAKE) -C python
@ ln -sf python/build/lib.*/*.so .
else
@ true
janus:
$(MAKE) -C janus
@ ln -sf janus/*.so .
install: all
$(MAKE) -C src install
ifneq ($(call optbool,$(WITH_PYTHON)),)
$(MAKE) -C python install
endif
ifneq ($(call optbool,$(WITH_JANUS)),)
$(MAKE) -C janus install
endif
mkdir -p $(DESTDIR)$(MANPREFIX)/man1
for man in $(shell ls man); do \
install -m644 man/$$man $(DESTDIR)$(MANPREFIX)/man1/$$man; \
gzip -f $(DESTDIR)$(MANPREFIX)/man1/$$man; \
done
install-strip: install
$(MAKE) -C src install-strip
regen:
tools/$(MAKE)-jpeg-h.py src/ustreamer/data/blank.jpeg src/ustreamer/data/blank_jpeg.c BLANK
tools/$(MAKE)-html-h.py src/ustreamer/data/index.html src/ustreamer/data/index_html.c INDEX
release:
make clean
make tox
make push
make bump V=$(V)
make push
make clean
$(MAKE) clean
$(MAKE) tox
$(MAKE) push
$(MAKE) bump V=$(V)
$(MAKE) push
$(MAKE) clean
tox: linters
time docker run --rm \
--volume `pwd`:/src:ro \
--volume `pwd`/linters:/src/linters:rw \
-t $(LINTERS_IMAGE) bash -c " \
-t $(_LINTERS_IMAGE) bash -c " \
cd /src \
&& tox -q -c linters/tox.ini $(if $(E),-e $(E),-p auto) \
"
@@ -164,7 +97,7 @@ linters:
docker build \
$(if $(call optbool,$(NC)),--no-cache,) \
--rm \
--tag $(LINTERS_IMAGE) \
--tag $(_LINTERS_IMAGE) \
-f linters/Dockerfile linters
@@ -180,14 +113,15 @@ push:
clean-all: linters clean
- docker run --rm \
--volume `pwd`:/src \
-it $(LINTERS_IMAGE) bash -c "cd src && rm -rf linters/{.tox,.mypy_cache}"
-it $(_LINTERS_IMAGE) bash -c "cd src && rm -rf linters/{.tox,.mypy_cache}"
clean:
rm -rf pkg/arch/pkg pkg/arch/src pkg/arch/v*.tar.gz pkg/arch/ustreamer-*.pkg.tar.{xz,zst}
rm -rf $(USTR) $(DUMP) $(BUILD) python/build vgcore.* *.sock *.so
rm -f ustreamer ustreamer-dump *.so
$(MAKE) -C src clean
$(MAKE) -C python clean
$(MAKE) -C janus clean
.PHONY: python linters
_OBJS = $(_USTR_SRCS:%.c=$(BUILD)/%.o) $(_DUMP_SRCS:%.c=$(BUILD)/%.o)
-include $(_OBJS:%.o=%.d)
.PHONY: python janus linters

View File

@@ -4,28 +4,29 @@
[[Русская версия]](README.ru.md)
µStreamer is a lightweight and very quick server to stream [MJPG](https://en.wikipedia.org/wiki/Motion_JPEG) video from any V4L2 device to the net. All new browsers have native support of this video format, as well as most video players such as mplayer, VLC etc.
µStreamer is a lightweight and very quick server to stream [MJPEG](https://en.wikipedia.org/wiki/Motion_JPEG) video from any V4L2 device to the net. All new browsers have native support of this video format, as well as most video players such as mplayer, VLC etc.
µStreamer is a part of the [Pi-KVM](https://github.com/pikvm/pikvm) project designed to stream [VGA](https://www.amazon.com/dp/B0126O0RDC) and [HDMI](https://auvidea.com/b101-hdmi-to-csi-2-bridge-15-pin-fpc/) screencast hardware data with the highest resolution and FPS possible.
µStreamer is very similar to [mjpg-streamer](https://github.com/jacksonliam/mjpg-streamer) with ```input_uvc.so``` and ```output_http.so``` plugins, however, there are some major differences. The key ones are:
| **Feature** | **µStreamer** | **mjpg-streamer** |
|----------|---------------|-------------------|
| Multithreaded JPEG encoding | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) No |
| [OpenMAX IL](https://www.khronos.org/openmaxil) hardware acceleration<br>on Raspberry Pi | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) No |
| Behavior when the device<br>is disconnected while streaming | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Shows a black screen<br>with ```NO SIGNAL``` on it<br>until reconnected | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) Stops the streaming <sup>1</sup> |
| [DV-timings](https://linuxtv.org/downloads/v4l-dvb-apis-new/userspace-api/v4l/dv-timings.html) support -<br>the ability to change resolution<br>on the fly by source signal | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes | ![#ffaa00](https://placehold.it/15/ffaa00/000000?text=+) Partially yes <sup>1</sup> |
| Option to skip frames when streaming<br>static images by HTTP to save the traffic | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes <sup>2</sup> | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) No |
| Streaming via UNIX domain socket | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) No |
| Debug logs without recompiling,<br>performance statistics log,<br>access to HTTP streaming parameters | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) No |
| Option to serve files<br>with a built-in HTTP server | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes | ![#ffaa00](https://placehold.it/15/ffaa00/000000?text=+) Regular files only |
| Signaling about the stream state<br>on GPIO using [libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/about) | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) No |
| Access to webcam controls (focus, servos)<br>and settings such as brightness via HTTP | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) No | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes |
| Compatibility with mjpg-streamer's API | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Yes | :) |
| Multithreaded JPEG encoding | ✔ | ✘ |
| Hardware image encoding<br>on Raspberry Pi | ✔ | ✘ |
| Behavior when the device<br>is disconnected while streaming | Shows a black screen<br>with ```NO SIGNAL``` on it<br>until reconnected | Stops the streaming <sup>1</sup> |
| [DV-timings](https://linuxtv.org/downloads/v4l-dvb-apis-new/userspace-api/v4l/dv-timings.html) support -<br>the ability to change resolution<br>on the fly by source signal | ✔ | ☹ Partially yes <sup>1</sup> |
| Option to skip frames when streaming<br>static images by HTTP to save the traffic | ✔ <sup>2</sup> | ✘ |
| Streaming via UNIX domain socket | ✔ | ✘ |
| Systemd socket activation | ✔ | ✘ |
| Debug logs without recompiling,<br>performance statistics log,<br>access to HTTP streaming parameters | ✔ | ✘ |
| Option to serve files<br>with a built-in HTTP server | ✔ | ☹ Regular files only |
| Signaling about the stream state<br>on GPIO using [libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/about) | ✔ | ✘ |
| Access to webcam controls (focus, servos)<br>and settings such as brightness via HTTP | ✘ | |
| Compatibility with mjpg-streamer's API | ✔ | :) |
Footnotes:
* ```1``` Long before µStreamer, I made a [patch](https://github.com/jacksonliam/mjpg-streamer/pull/164) to add DV-timings support to mjpg-streamer and to keep it from hanging up no device disconnection. Alas, the patch is far from perfect and I can't guarantee it will work every time - mjpg-streamer's source code is very complicated and its structure is hard to understand. With this in mind, along with needing multithreading and JPEG hardware acceleration in the future, I decided to make my own stream server from scratch instead of supporting legacy code.
* ```2``` This feature allows to cut down outgoing traffic several-fold when streaming HDMI, but it increases CPU usage a little bit. The idea is that HDMI is a fully digital interface and each captured frame can be identical to the previous one byte-wise. There's no need to stream the same image over the net several times a second. With the `--drop-same-frames=20` option enabled, µStreamer will drop all the matching frames (with a limit of 20 in a row). Each new frame is matched with the previous one first by length, then using ```memcmp()```.
-----
@@ -34,14 +35,14 @@ If you're going to live-stream from your backyard webcam and need to control it,
-----
# Building
You'll need ```make```, ```gcc```, ```libevent``` with ```pthreads``` support, ```libjpeg8```/```libjpeg-turbo```, ```libuuid``` and ```libbsd``` (only for Linux).
You'll need ```make```, ```gcc```, ```libevent``` with ```pthreads``` support, ```libjpeg9```/```libjpeg-turbo``` and ```libbsd``` (only for Linux).
* Arch: `sudo pacman -S libevent libjpeg-turbo libutil-linux libbsd`.
* Raspbian: `sudo apt install libevent-dev libjpeg8-dev uuid-dev libbsd-dev`. Add `libraspberrypi-dev` for `WITH_OMX=1` and `libgpiod` for `WITH_GPIO=1`.
* Debian: `sudo apt install build-essential libevent-dev libjpeg62-turbo-dev uuid-dev libbsd-dev`.
* Ubuntu 20.04 x86_64: `sudo apt install build-essential libevent-dev libjpeg62-dev uuid-dev libbsd-dev make gcc libjpeg8 libjpeg-turbo8 libuuid1 libbsd0`.
* Raspbian: `sudo apt install libevent-dev libjpeg8-dev libbsd-dev`. Add `libgpiod-dev` for `WITH_GPIO=1` and `libsystemd-dev` for `WITH_SYSTEMD=1`.
* Debian/Ubuntu: `sudo apt install build-essential libevent-dev libjpeg-dev libbsd-dev`.
* Alpine: `sudo apk add libevent-dev libbsd-dev libjpeg-turbo-dev musl-dev`. Build with `WITH_PTHREAD_NP=0`.
On Raspberry Pi you can build the program with OpenMAX IL. To do this pass option ```WITH_OMX=1``` to ```make```. To enable GPIO support install [libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/about) and pass option ```WITH_GPIO=1```. If the compiler reports about a missing function ```pthread_get_name_np()``` (or similar), add option ```WITH_PTHREAD_NP=0``` (it's enabled by default). For the similar error with ```setproctitle()``` add option ```WITH_SETPROCTITLE=0```.
To enable GPIO support install [libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/about) and pass option ```WITH_GPIO=1```. If the compiler reports about a missing function ```pthread_get_name_np()``` (or similar), add option ```WITH_PTHREAD_NP=0``` (it's enabled by default). For the similar error with ```setproctitle()``` add option ```WITH_SETPROCTITLE=0```.
```
$ git clone --depth=1 https://github.com/pikvm/ustreamer
@@ -50,11 +51,14 @@ $ make
$ ./ustreamer --help
```
AUR has a package for Arch Linux: https://aur.archlinux.org/packages/ustreamer. It should compile automatically with OpenMAX IL on Raspberry Pi, if the corresponding headers are present in ```/opt/vc/include```.
AUR has a package for Arch Linux: https://aur.archlinux.org/packages/ustreamer.
FreeBSD port: https://www.freshports.org/multimedia/ustreamer.
-----
# Usage
**For M2M hardware encoding on Raspberry Pi, you need at least 5.15.32 kernel. OpenMAX and MMAL support on older kernels is deprecated and removed.**
Without arguments, ```ustreamer``` will try to open ```/dev/video0``` with 640x480 resolution and start streaming on ```http://127.0.0.1:8080```. You can override this behavior using parameters ```--device```, ```--host``` and ```--port```. For example, to stream to the world, run:
```
# ./ustreamer --device=/dev/video1 --host=0.0.0.0 --port=80
@@ -66,8 +70,8 @@ The recommended way of running µStreamer with [Auvidea B101](https://www.raspbe
```bash
$ ./ustreamer \
--format=uyvy \ # Device input format
--encoder=omx \ # Hardware encoding with OpenMAX
--workers=3 \ # Maximum workers for OpenMAX
--encoder=m2m-image \ # Hardware encoding on V4L2 M2M driver
--workers=3 \ # Workers number
--persistent \ # Don't re-initialize device on timeout (for example when HDMI cable was disconnected)
--dv-timings \ # Use DV-timings
--drop-same-frames=30 # Save the traffic
@@ -77,14 +81,59 @@ $ ./ustreamer \
You can always view the full list of options with ```ustreamer --help```.
-----
# Raspberry Pi Camera Example
Example usage for the Raspberry Pi v1 camera:
```bash
$ sudo modprobe bcm2835-v4l2
$ ./ustreamer --host :: -m jpeg --device-timeout=5 --buffers=3 -r 2592x1944
```
:exclamation: Please note that newer camera models have a different maximum resolution. You can see the supported resolutions at the [PiCamera documentation](https://picamera.readthedocs.io/en/release-1.13/fov.html#sensor-modes).
:exclamation: If you get a poor framerate, it could be that the camera is switched to photo mode, which produces a low framerate (but a higher quality picture). This is because `bcm2835-v4l2` switches to photo mode at resolutions higher than `1280x720`. To work around this, pass the `max_video_width` and `max_video_height` module parameters like so:
```bash
$ modprobe bcm2835-v4l2 max_video_width=2592 max_video_height=1944
```
-----
# Integrations
## Janus
µStreamer supports bandwidth-efficient streaming using [H.264 compression](https://en.wikipedia.org/wiki/Advanced_Video_Coding) and the Janus WebRTC server. See the [Janus integration guide](docs/h264.md) for full details.
## Nginx
When uStreamer is behind an Nginx proxy, it's buffering behavior introduces latency into the video stream. It's possible to disable Nginx's buffering to eliminate the additional latency:
```nginx
location /stream {
postpone_output 0;
proxy_buffering off;
proxy_ignore_headers X-Accel-Buffering;
proxy_pass http://ustreamer;
}
```
-----
# Tips & tricks for v4l2
v4l2 utilities provide the tools to manage USB webcam setting and information. Scripts can be use to make adjustments and run manually or with cron. Running in cron for example to change the exposure settings at certain times of day. The package is available in all Linux distributions and is usually called `v4l-utils`.
* List of available video devices: `v4l2-ctl --list-devices`.
* List available control settings: `v4l2-ctl -d /dev/video0 --list-ctrls`.
* List available video formats: `v4l2-ctl -d /dev/video0 --list-formats-ext`.
* Read the current setting: `v4l2-ctl -d /dev/video0 --get-ctrl=exposure_auto`.
* Change the setting value: `v4l2-ctl -d /dev/video0 --set-ctrl=exposure_auto=1`.
[Here](https://www.kurokesu.com/main/2016/01/16/manual-usb-camera-settings-in-linux/) you can find more examples. Documentation is available in [`man v4l2-ctl`](https://www.mankier.com/1/v4l2-ctl).
-----
# See also
* [Running uStreamer via systemd service](https://github.com/pikvm/ustreamer/issues/16).
* [uStreamer Ansible Role](https://github.com/mtlynch/ansible-role-ustreamer): Use [Ansible](https://docs.ansible.com/ansible/latest/index.html) to compile uStreamer and install it as a systemd service automatically.
-----
# License
Copyright (C) 2018-2021 by Maxim Devaev mdevaev@gmail.com
Copyright (C) 2018-2022 by Maxim Devaev mdevaev@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@@ -5,27 +5,28 @@
[[English version]](README.md)
µStreamer - это маленький и очень быстрый сервер, который позволяет организовать трансляцию видео в формате [MJPG](https://en.wikipedia.org/wiki/Motion_JPEG) с любого устройства V4L2 в сеть. Этот формат нативно поддерживается всеми современными браузерами и большинством приложений для просмотра видео (mplayer, VLC и так далее). µStreamer был разработан в рамках проекта [Pi-KVM](https://github.com/pikvm/pikvm) специально для стриминга с устройств видеозахвата [VGA](https://www.amazon.com/dp/B0126O0RDC) и [HDMI](https://auvidea.com/b101-hdmi-to-csi-2-bridge-15-pin-fpc/) с максимально возможным разрешением и FPS, которые только позволяет железо.
µStreamer - это маленький и очень быстрый сервер, который позволяет организовать трансляцию видео в формате [MJPEG](https://en.wikipedia.org/wiki/Motion_JPEG) с любого устройства V4L2 в сеть. Этот формат нативно поддерживается всеми современными браузерами и большинством приложений для просмотра видео (mplayer, VLC и так далее). µStreamer был разработан в рамках проекта [Pi-KVM](https://github.com/pikvm/pikvm) специально для стриминга с устройств видеозахвата [VGA](https://www.amazon.com/dp/B0126O0RDC) и [HDMI](https://auvidea.com/b101-hdmi-to-csi-2-bridge-15-pin-fpc/) с максимально возможным разрешением и FPS, которые только позволяет железо.
Функционально µStreamer очень похож на [mjpg-streamer](https://github.com/jacksonliam/mjpg-streamer) при использовании им плагинов ```input_uvc.so``` и ```output_http.so```, однако имеет ряд серьезных отличий. Основные приведены в этой таблице:
| **Фича** | **µStreamer** | **mjpg-streamer** |
|----------|---------------|-------------------|
| Многопоточное кодирование JPEG | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) Нет |
| Аппаратное кодирование с помощью [OpenMAX IL](https://www.khronos.org/openmaxil) на Raspberry Pi | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) Нет |
| Поведение при физическом отключении<br>устройства от сервера во время работы | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Транслирует черный экран<br>с надписью ```NO SIGNAL```,<br>пока устройство не будет подключено снова | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) Прерывает трансляцию <sup>1</sup> |
| Поддержка [DV-таймингов](https://linuxtv.org/downloads/v4l-dvb-apis-new/userspace-api/v4l/dv-timings.html) - возможности<br>изменения параметров разрешения<br>трансляции на лету по сигналу<br>источника (устройства видеозахвата) | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть | ![#ffaa00](https://placehold.it/15/ffaa00/000000?text=+) Условно есть <sup>1</sup> |
| Возможность пропуска фреймов при передаче<br>статического изображения по HTTP<br>для экономии трафика | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть <sup>2</sup> | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) Нет |
| Стрим через UNIX domain socket | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) Нет |
| Дебаг-логи без перекомпиляции,<br>логгирование статистики производительности,<br>возможность получения параметров<br>трансляции по HTTP | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) Нет |
| Возможность сервить файлы встроенным<br>HTTP-сервером | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть | ![#ffaa00](https://placehold.it/15/ffaa00/000000?text=+) Нет каталогов |
| Вывод сигналов о состоянии стрима на GPIO<br>с помощью [libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/about) | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) Нет |
| Поддержка контролов веб-камер (фокус,<br> движение сервами) и всяких настроек,<br> типа яркости, через HTTP | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) Нет | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть |
| Совместимость с API mjpg-streamer'а | ![#00aa00](https://placehold.it/15/00aa00/000000?text=+) Есть | :) |
| Многопоточное кодирование JPEG | ✔ | ✘ |
| Аппаратное кодирование на Raspberry Pi | ✔ | ✘ |
| Поведение при физическом отключении<br>устройства от сервера во время работы | Транслирует черный экран<br>с надписью ```NO SIGNAL```,<br>пока устройство не будет подключено снова | Прерывает трансляцию <sup>1</sup> |
| Поддержка [DV-таймингов](https://linuxtv.org/downloads/v4l-dvb-apis-new/userspace-api/v4l/dv-timings.html) - возможности<br>изменения параметров разрешения<br>трансляции на лету по сигналу<br>источника (устройства видеозахвата) | ✔ | ☹ Условно есть <sup>1</sup> |
| Возможность пропуска фреймов при передаче<br>статического изображения по HTTP<br>для экономии трафика | ✔ <sup>2</sup> | ✘ |
| Стрим через UNIX domain socket | ✔ | ✘ |
| Systemd socket activation | ✔ | ✘ |
| Дебаг-логи без перекомпиляции,<br>логгирование статистики производительности,<br>возможность получения параметров<br>трансляции по HTTP | ✔ | ✘ |
| Возможность сервить файлы встроенным<br>HTTP-сервером | ✔ | ☹ Нет каталогов |
| Вывод сигналов о состоянии стрима на GPIO<br>с помощью [libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/about) | ✔ | ✘ |
| Поддержка контролов веб-камер (фокус,<br> движение сервами) и всяких настроек,<br> типа яркости, через HTTP | ✘ | |
| Совместимость с API mjpg-streamer'а | ✔ | :) |
Сносочки:
* ```1``` Еще до написания µStreamer, я запилил [патч](https://github.com/jacksonliam/mjpg-streamer/pull/164), добавляющий в mjpg-streamer поддержку DV-таймингов и предотвращающий его зависание при отключении устройства. Однако патч, увы, далек от совершенства и я не гарантирую его стопроцентную работоспособность, поскольку код mjpg-streamer чрезвычайно запутан и очень плохо структурирован. Учитывая это, а также то, что в дальнейшем мне потребовались многопоточность и аппаратное кодирование JPEG, было принято решение написать свой стрим-сервер с нуля, чтобы не тратить силы на поддержку лишнего легаси.
* ```2``` Это фича позволяет в несколько раз снизить объем исходящего трафика при трансляции HDMI, однако немного увеличивает загрузку процессора. Суть в том, что HDMI - полностью цифровой интерфейс, и новый захваченный фрейм может быть идентичен предыдущему в точности до байта. В этом случае нет нужды передавать одну и ту же картинку по сети несколько раз в секунду. При использовании опции `--drop-same-frames=20`, µStreamer будет дропать все одинаковые фреймы, но не более 20 подряд. Новый фрейм сравнивается с предыдущим сначала по длине, а затем помощью ```memcmp()```.
-----
@@ -34,14 +35,13 @@
-----
# Сборка
Для сборки вам понадобятся ```make```, ```gcc```, ```libevent``` с поддержкой ```pthreads```, ```libjpeg8```/```libjpeg-turbo```, ```libuuid``` и ```libbsd``` (только для Linux).
Для сборки вам понадобятся ```make```, ```gcc```, ```libevent``` с поддержкой ```pthreads```, ```libjpeg8```/```libjpeg-turbo``` и ```libbsd``` (только для Linux).
* Arch: `sudo pacman -S libevent libjpeg-turbo libutil-linux libbsd`.
* Raspbian: `sudo apt install libevent-dev libjpeg8-dev uuid-dev libbsd-dev`. Добавьте `libraspberrypi-dev` для сборки с `WITH_OMX=1` и `libgpiod` для `WITH_GPIO=1`.
* Debian: `sudo apt install build-essential libevent-dev libjpeg62-turbo-dev uuid-dev libbsd-dev`.
* Ubuntu 20.04 x86_64: `sudo apt install build-essential libevent-dev libjpeg62-dev uuid-dev libbsd-dev make gcc libjpeg8 libjpeg-turbo8 libuuid1 libbsd0`.
* Raspbian: `sudo apt install libevent-dev libjpeg8-dev libbsd-dev`. Добавьте `libgpiod` для `WITH_GPIO=1` и `libsystemd-dev` для `WITH_SYSTEMD=1`.
* Debian/Ubuntu: `sudo apt install build-essential libevent-dev libjpeg-dev libbsd-dev`.
На Raspberry Pi программу можно собрать с поддержкой OpenMAX IL. Для этого передайте ```make``` параметр ```WITH_OMX=1```. Для включения сборки с поддержкой GPIO установите [libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/about) и добавьте параметр ```WITH_GPIO=1```. Если при сборке компилятор ругается на отсутствие функции ```pthread_get_name_np()``` или другой подобной, добавьте параметр ```WITH_PTHREAD_NP=0``` (по умолчанию он включен). При аналогичной ошибке с функцией ```setproctitle()``` добавьте параметр ```WITH_SETPROCTITLE=0```.
Для включения сборки с поддержкой GPIO установите [libgpiod](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/about) и добавьте параметр ```WITH_GPIO=1```. Если при сборке компилятор ругается на отсутствие функции ```pthread_get_name_np()``` или другой подобной, добавьте параметр ```WITH_PTHREAD_NP=0``` (по умолчанию он включен). При аналогичной ошибке с функцией ```setproctitle()``` добавьте параметр ```WITH_SETPROCTITLE=0```.
```
$ git clone --depth=1 https://github.com/pikvm/ustreamer
@@ -50,11 +50,14 @@ $ make
$ ./ustreamer --help
```
Для Arch Linux в AUR есть готовый пакет: https://aur.archlinux.org/packages/ustreamer. На Raspberry Pi програма автоматически собирается с поддержкой OpenMAX IL, если обнаружит нужные хедеры в ```/opt/vc/include```.
Для Arch Linux в AUR есть готовый пакет: https://aur.archlinux.org/packages/ustreamer.
Порт для FreeBSD: https://www.freshports.org/multimedia/ustreamer.
-----
# Использование
**Для аппаратного кодирования M2M на Raspberry Pi, вам нужно ядро минимальной версии 5.15.32. Поддержка OpenMAX и MMAL для более старых ядер объявлена устаревшей и была удалена.**
Будучи запущенным без аргументов, ```ustreamer``` попробует открыть устройство ```/dev/video0``` с разрешением 640x480 и начать трансляцию на ```http://127.0.0.1:8080```. Это поведение может быть изменено с помощью опций ```--device```, ```--host``` и ```--port```. Пример вещания на всю сеть по 80-м порту:
```
# ./ustreamer --device=/dev/video1 --host=0.0.0.0 --port=80
@@ -66,8 +69,8 @@ $ ./ustreamer --help
```bash
$ ./ustreamer \
--format=uyvy \ # Настройка входного формата устройства
--encoder=omx \ # Использование аппаратного кодирования с помощью OpenMAX
--workers=3 \ # Максимум воркеров для OpenMAX
--encoder=m2m-image \ # Аппаратное кодирование с помощью драйвера V4L2 M2M
--workers=3 \ # Максимум воркеров
--persistent \ # Не переинициализировать устройство при таймауте (например, когда был отключен HDMI-кабель)
--dv-timings \ # Включение DV-таймингов
--drop-same-frames=30 # Экономим трафик
@@ -77,14 +80,56 @@ $ ./ustreamer \
За полным списком опций обращайтесь ко встроенной справке: ```ustreamer --help```.
-----
# Камера Raspberry Pi
Пример использования камеры Raspberry Pi v1:
```bash
$ sudo modprobe bcm2835-v4l2
$ ./ustreamer --host :: -m jpeg --device-timeout=5 --buffers=3 -r 2592x1944
```
:exclamation: Обратите внимание что боле новые модели камеры имеют другое максимальное разрешение. Список поддерживаемых разрешений можно найти в [документации PiCamera](https://picamera.readthedocs.io/en/release-1.13/fov.html#sensor-modes).
:exclamation: Если камера выдает низкий фреймрейт, возможно что она работает в фото-режиме, где производит более низкий фпс, но более качественную кратинку. Это происходит потому что `bcm2835-v4l2` переключает камеру в фото-режим на разрешениях выше `1280x720`. Чтобы обойти это, передайте параметры `max_video_width` и `max_video_height` при загрузке модуля, например:
```bash
$ modprobe bcm2835-v4l2 max_video_width=2592 max_video_height=1944
```
-----
# Интеграция
## Nginx
Если uStreamer находится на Nginx, то последний будет буферизировать поток и создавать дополнительную задержку в стриме. Чтобы задержки не было, буферизацию можно отключить:
```nginx
location /stream {
postpone_output 0;
proxy_buffering off;
proxy_ignore_headers X-Accel-Buffering;
proxy_pass http://ustreamer;
}
```
-----
# Утилиты V4L2
V4L2 предоставляет ряд официальных утилит для управления USB-вебкамерами и получения информации об устройствах. С их помощью можно писать всякие настроечные скрипты и запускать их по крону, если, например, вам требуется изменять настройки экспозиции в зависимости от времени суток. Пакет с этими утилитами доступен на всех дистрибутивах Linux и обычно называется `v4l-utils`.
* Вывести список видеоустройств: `v4l2-ctl --list-devices`.
* Вывести список доступных контролов устройства: `v4l2-ctl -d /dev/video0 --list-ctrls`.
* Вывести список доступных форматов видео: `v4l2-ctl -d /dev/video0 --list-formats-ext`.
* Показать текущее значение контрола: `v4l2-ctl -d /dev/video0 --get-ctrl=exposure_auto`.
* Изменить значение контрола: `v4l2-ctl -d /dev/video0 --set-ctrl=exposure_auto=1`.
Больше примеров вы можете найти [здесь](https://www.kurokesu.com/main/2016/01/16/manual-usb-camera-settings-in-linux/), а документацию в [`man v4l2-ctl`](https://www.mankier.com/1/v4l2-ctl).
-----
# Смотрите также
* [Запуск с помощью systemd-сервиса](https://github.com/pikvm/ustreamer/issues/16).
* [uStreamer Ansible Role](https://github.com/mtlynch/ansible-role-ustreamer): Использование [Ansible](https://docs.ansible.com/ansible/latest/index.html) для сборки и установки стримера как systemd-сервиса.
-----
# Лицензия
Copyright (C) 2018-2021 by Maxim Devaev mdevaev@gmail.com
Copyright (C) 2018-2022 by Maxim Devaev mdevaev@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

231
docs/h264.md Normal file
View File

@@ -0,0 +1,231 @@
# Streaming H.264 Video over WebRTC with Janus
µStreamer supports bandwidth-efficient streaming using [H.264 compression](https://en.wikipedia.org/wiki/Advanced_Video_Coding) and the Janus WebRTC server.
This guide explains how to configure µStreamer to provide an H.264 video stream and consume it within a web application using WebRTC.
## Components
In addition to µStreamer, H.264 streaming involves the following components:
- [**Janus**](https://janus.conf.meetecho.com/): A general-purpose WebRTC server.
- [**µStreamer Janus Plugin**](https://github.com/pikvm/ustreamer/tree/master/janus): A Janus plugin that allows Janus to consume a video stream from µStreamer via shared memory.
- [**Janus JavaScript Client**](https://janus.conf.meetecho.com/docs/JS.html): A frontend library that communicates with the Janus server and the µStreamer Janus plugin.
## Control Flow
To connect to a µStreamer video stream over WebRTC, an application must establish the following control flow:
1. The backend server starts the µStreamer service.
1. The backend server starts the Janus WebRTC server with the µStreamer Janus plugin.
1. The client-side JavaScript application establishes a connection to the Janus server.
1. The client-side JavaScript application instructs the Janus server to attach the µStreamer Janus plugin and start the video stream.
1. The client-side JavaScript application renders the video stream in the web browser.
## Server Setup
### Prerequisites
To integrate with Janus, µStreamer has the following prerequisites:
- The system packages that µStreamer depends on (see the [main build instructions](../README.md#building)).
- The Janus WebRTC server with WebSockets transport enabled (see the [Janus documentation](https://github.com/meetecho/janus-gateway)).
### Fixing Janus C Headers
To compile µStreamer with the Janus option, (see [“Installation”](#installation)), you need to make the Janus header files available within µStreamer's build context.
First, create a symbolic link from `/usr/include` to the Janus install directory. By default, Janus installs to `/opt/janus`.
```sh
ln -s /opt/janus/include/janus /usr/include/janus
```
Janus uses `#include` paths that make it difficult for third-party libraries to build against its headers. To fix this, modify the `#include` directive in `janus/plugins/plugin.h` to prepend a `../` to the included file name (`#include "refcount.h"``#include "../refcount.h"`).
```sh
sed \
--in-place \
--expression 's|^#include "refcount.h"$|#include "../refcount.h"|g' \
/usr/include/janus/plugins/plugin.h
```
### Installation
First, compile µStreamer with the Janus plugin option (`WITH_JANUS`).
```sh
git clone --depth=1 https://github.com/pikvm/ustreamer
cd ustreamer
make WITH_JANUS=1
```
The `WITH_JANUS` option compiles the µStreamer Janus plugin and outputs it to `janus/libjanus_ustreamer.so`. Move this file to the plugin directory of your Janus installation.
```sh
mv \
janus/libjanus_ustreamer.so \
/opt/janus/lib/janus/plugins/libjanus_ustreamer.so
```
Finally, specify a qualifier for the shared memory object so that the µStreamer Janus plugin can read µStreamer's video data.
```sh
cat > /opt/janus/lib/janus/configs/janus.plugin.ustreamer.jcfg <<EOF
memsink: {
object = "demo::ustreamer::h264"
}
EOF
```
### Start µStreamer and the Janus WebRTC Server
For µStreamer to share the video stream with the µStreamer Janus plugin, µStreamer must run with the following command-line flags:
- `--h264-sink` with the qualifier of the shared memory object you specified above (`demo::ustreamer::h264`)
- `--h264-sink-mode` with the permissions bitmask for the shared memory object (e.g., `660`)
- `--h264-sink-rm` to clean up the shared memory object when the µStreamer process exits
To load the µStreamer Janus plugin and configuration, the Janus WebRTC server must run with the following command-line flags:
- `--configs-folder` with the path to the Janus configuration directory (e.g., `/opt/janus/lib/janus/configs/`)
- `--plugins-folder` with the path to the Janus plugin directory (e.g., `/opt/janus/lib/janus/plugins/`)
## Client Setup
Once an application's backend server is running µStreamer and Janus, a browser-based JavaScript application can consume the server's video stream.
### Prerequisites
The client needs to load the following JavaScript libraries:
- [WebRTC Adapter library](https://webrtc.github.io/adapter/adapter-8.1.0.js) (`webrtc-adapter.js`, version `8.1.0`)
- [Janus Gateway JavaScript library](https://raw.githubusercontent.com/meetecho/janus-gateway/v1.0.0/html/janus.js) (`janus.js`, version `1.0.0`)
### Control Flow
The client-side JavaScript application uses the following control flow:
1. The client loads and initializes the Janus client library.
1. The client establishes a WebSockets connection to the Janus server.
1. The client instructs the Janus server to attach the µStreamer Janus plugin.
1. On success, the client obtains a plugin handle through which it can send requests directly to the µStreamer Janus plugin. The client processes responses via the `attach` callbacks:
- `onmessage` for general messages
- `onremotetrack` for the H.264 video stream
1. The client issues a `watch` request to the µStreamer Janus plugin, which initiates the H.264 stream in the plugin itself.
- It takes a few seconds for uStreamer's video stream to become available to Janus. The first `watch` request may fail, so the client must retry the `watch` request.
1. The client and server negotiate the underlying parameters of the WebRTC session. This procedure is called JavaScript Session Establishment Protocol (JSEP). The server makes a `jsepOffer` to the client, and the client responds with a `jsepAnswer`.
1. The client issues a `start` request to the µStreamer Janus plugin to indicate that the client wants to begin consuming the video stream.
1. The µStreamer Janus plugin delivers the H.264 video stream to the client via WebRTC.
1. The Janus client library invokes the `onremotetrack` callback. The client attaches the video stream to the `<video>` element, rendering the video stream in the browser window.
### Sample Code
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>µStreamer H.264 demo</title>
<script src="https://webrtc.github.io/adapter/adapter-8.1.0.js"></script>
<!-- janus.js is the JavaScript client library of Janus, as specified above in
the prerequisites section of the client setup. You might need to change
the `src` path, depending on where you serve this file from. -->
<script src="janus.js"></script>
<style>
video {
height: 100%;
width: 100%;
object-fit: contain;
}
</style>
</head>
<body>
<video id="webrtc-output" autoplay playsinline muted></video>
<script type="text/javascript">
// Initialize Janus library.
Janus.init({
// Turn on debug logs in the browser console.
debug: true,
// Configure Janus to use standard browser APIs internally.
dependencies: Janus.useDefaultDependencies(),
});
// Establish a WebSockets connection to the server.
const janus = new Janus({
// Specify the URL of the Janus servers WebSockets endpoint.
server: `ws://${window.location.hostname}:8188/`,
// Callback function if the client connects successfully.
success: attachUStreamerPlugin,
// Callback function if the client fails to connect.
error: console.error,
});
let uStreamerPluginHandle = null;
function attachUStreamerPlugin() {
// Instruct the server to attach the µStreamer Janus plugin.
janus.attach({
// Qualifier of the plugin.
plugin: "janus.plugin.ustreamer",
// Callback function, for when the server attached the plugin
// successfully.
success: function (pluginHandle) {
uStreamerPluginHandle = pluginHandle;
// Instruct the µStreamer Janus plugin to initiate the video stream.
uStreamerPluginHandle.send({ message: { request: "watch" } });
},
// Callback function if the server fails to attach the plugin.
error: console.error,
// Callback function for processing messages from the Janus server.
onmessage: function (msg, jsepOffer) {
// 503 indicates that the plugin is not ready to stream yet. Retry the
// watch request until the video stream is available.
if (msg.error_code === 503) {
uStreamerPluginHandle.send({ message: { request: "watch" } });
return;
}
// If there is a JSEP offer, respond to it. This starts the WebRTC
// connection.
if (jsepOffer) {
uStreamerPluginHandle.createAnswer({
jsep: jsepOffer,
// Prevent the client from sending audio and video, as this would
// trigger a permission dialog in the browser.
media: { audioSend: false, videoSend: false },
success: function (jsepAnswer) {
uStreamerPluginHandle.send({
message: { request: "start" },
jsep: jsepAnswer,
});
},
error: console.error,
});
}
},
// Callback function, for when the video stream arrives.
onremotetrack: function (mediaStreamTrack, mediaId, isAdded) {
if (isAdded) {
// Attach the received media track to the video element. Cloning the
// mediaStreamTrack creates a new object with a distinct, globally
// unique stream identifier.
const videoElement = document.getElementById("webrtc-output");
const stream = new MediaStream();
stream.addTrack(mediaStreamTrack.clone());
videoElement.srcObject = stream;
}
},
});
}
</script>
</body>
</html>
```

54
janus/Makefile Normal file
View File

@@ -0,0 +1,54 @@
DESTDIR ?=
PREFIX ?= /usr/local
CC ?= gcc
CFLAGS ?= -O3
LDFLAGS ?=
# =====
_PLUGIN = libjanus_ustreamer.so
_CFLAGS = -fPIC -MD -c -std=c11 -Wall -Wextra -D_GNU_SOURCE $(shell pkg-config --cflags glib-2.0) $(CFLAGS)
_LDFLAGS = -shared -lm -pthread -lrt -ljansson $(shell pkg-config --libs glib-2.0) $(LDFLAGS)
_SRCS = $(shell ls src/*.c)
_BUILD = build
define optbool
$(filter $(shell echo $(1) | tr A-Z a-z), yes on 1)
endef
WITH_PTHREAD_NP ?= 1
ifneq ($(call optbool,$(WITH_PTHREAD_NP)),)
override _CFLAGS += -DWITH_PTHREAD_NP
endif
# =====
$(_PLUGIN): $(_SRCS:%.c=$(_BUILD)/%.o)
$(info == SO $@)
@ $(CC) $^ -o $@ $(_LDFLAGS)
$(_BUILD)/%.o: %.c
$(info -- CC $<)
@ mkdir -p $(dir $@) || true
@ $(CC) $< -o $@ $(_CFLAGS)
install: $(_PLUGIN)
mkdir -p $(DESTDIR)$(PREFIX)/lib/ustreamer/janus
install -m755 $(_PLUGIN) $(DESTDIR)$(PREFIX)/lib/ustreamer/janus/$(PLUGIN)
clean:
rm -rf $(_PLUGIN) $(_BUILD)
_OBJS = $(_SRCS:%.c=$(_BUILD)/%.o)
-include $(_OBJS:%.o=%.d)

1
janus/src/base64.c Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/base64.c

1
janus/src/base64.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/base64.h

1
janus/src/config.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/config.h

1
janus/src/frame.c Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/frame.c

1
janus/src/frame.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/frame.h

1
janus/src/list.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/list.h

1
janus/src/memsinksh.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/memsinksh.h

522
janus/src/plugin.c Normal file
View File

@@ -0,0 +1,522 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
# #
*****************************************************************************/
#include <stdint.h>
#include <stdbool.h>
#include <stdatomic.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <linux/videodev2.h>
#include <pthread.h>
#include <jansson.h>
#include <janus/config.h>
#include <janus/plugins/plugin.h>
#include "config.h"
#include "tools.h"
#include "threading.h"
#include "list.h"
#include "memsinksh.h"
#include "rtp.h"
static int _plugin_init(janus_callbacks *gw, const char *config_file_path);
static void _plugin_destroy(void);
static void _plugin_create_session(janus_plugin_session *session, int *error);
static void _plugin_destroy_session(janus_plugin_session *session, int *error);
static json_t *_plugin_query_session(janus_plugin_session *session);
static void _plugin_setup_media(janus_plugin_session *session);
static void _plugin_hangup_media(janus_plugin_session *session);
static struct janus_plugin_result *_plugin_handle_message(
janus_plugin_session *session, char *transaction, json_t *msg, json_t *jsep);
static int _plugin_get_api_compatibility(void);
static int _plugin_get_version(void);
static const char *_plugin_get_version_string(void);
static const char *_plugin_get_description(void);
static const char *_plugin_get_name(void);
static const char *_plugin_get_author(void);
static const char *_plugin_get_package(void);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Woverride-init"
static janus_plugin _plugin = JANUS_PLUGIN_INIT(
.init = _plugin_init,
.destroy = _plugin_destroy,
.create_session = _plugin_create_session,
.destroy_session = _plugin_destroy_session,
.query_session = _plugin_query_session,
.setup_media = _plugin_setup_media,
.hangup_media = _plugin_hangup_media,
.handle_message = _plugin_handle_message,
.get_api_compatibility = _plugin_get_api_compatibility,
.get_version = _plugin_get_version,
.get_version_string = _plugin_get_version_string,
.get_description = _plugin_get_description,
.get_name = _plugin_get_name,
.get_author = _plugin_get_author,
.get_package = _plugin_get_package,
);
#pragma GCC diagnostic pop
janus_plugin *create(void) { // cppcheck-suppress unusedFunction
return &_plugin;
}
typedef struct _client_sx {
janus_plugin_session *session;
bool transmit;
LIST_STRUCT(struct _client_sx);
} _client_s;
static char *_g_memsink_obj = NULL;
const long double _g_wait_timeout = 1;
const long double _g_lock_timeout = 1;
const useconds_t _g_lock_polling = 1000;
const useconds_t _g_watchers_polling = 100000;
static _client_s *_g_clients = NULL;
static janus_callbacks *_g_gw = NULL;
static rtp_s *_g_rtp = NULL;
static pthread_t _g_tid;
static pthread_mutex_t _g_lock = PTHREAD_MUTEX_INITIALIZER;
static atomic_bool _g_ready = ATOMIC_VAR_INIT(false);
static atomic_bool _g_stop = ATOMIC_VAR_INIT(false);
static atomic_bool _g_has_watchers = ATOMIC_VAR_INIT(false);
#define JLOG_INFO(_msg, ...) JANUS_LOG(LOG_INFO, "== %s -- " _msg "\n", _plugin_get_name(), ##__VA_ARGS__)
#define JLOG_WARN(_msg, ...) JANUS_LOG(LOG_WARN, "== %s -- " _msg "\n", _plugin_get_name(), ##__VA_ARGS__)
#define JLOG_ERROR(_msg, ...) JANUS_LOG(LOG_ERR, "== %s -- " _msg "\n", _plugin_get_name(), ##__VA_ARGS__)
#define JLOG_PERROR(_msg, ...) { \
char _perror_buf[1024] = {0}; \
char *_perror_ptr = errno_to_string(errno, _perror_buf, 1023); \
JANUS_LOG(LOG_ERR, "[%s] " _msg ": %s\n", _plugin_get_name(), ##__VA_ARGS__, _perror_ptr); \
}
#define LOCK A_MUTEX_LOCK(&_g_lock)
#define UNLOCK A_MUTEX_UNLOCK(&_g_lock)
#define READY atomic_load(&_g_ready)
#define STOP atomic_load(&_g_stop)
#define HAS_WATCHERS atomic_load(&_g_has_watchers)
static void _relay_rtp_clients(const uint8_t *datagram, size_t size) {
janus_plugin_rtp packet = {
.video = true,
.buffer = (char *)datagram,
.length = size,
};
janus_plugin_rtp_extensions_reset(&packet.extensions);
LIST_ITERATE(_g_clients, client, {
if (client->transmit) {
_g_gw->relay_rtp(client->session, &packet);
}
});
}
static int _wait_frame(int fd, memsink_shared_s* mem, uint64_t last_id) {
long double deadline_ts = get_now_monotonic() + _g_wait_timeout;
long double now;
do {
int retval = flock_timedwait_monotonic(fd, _g_lock_timeout);
now = get_now_monotonic();
if (retval < 0 && errno != EWOULDBLOCK) {
JLOG_PERROR("Can't lock memsink");
return -1;
} else if (retval == 0) {
if (mem->magic == MEMSINK_MAGIC && mem->version == MEMSINK_VERSION && mem->id != last_id) {
return 0;
}
if (flock(fd, LOCK_UN) < 0) {
JLOG_PERROR("Can't unlock memsink");
return -1;
}
}
usleep(_g_lock_polling);
} while (now < deadline_ts);
return -2;
}
static int _get_frame(int fd, memsink_shared_s *mem, frame_s *frame, uint64_t *frame_id) {
frame_set_data(frame, mem->data, mem->used);
FRAME_COPY_META(mem, frame);
*frame_id = mem->id;
mem->last_client_ts = get_now_monotonic();
int retval = 0;
if (frame->format != V4L2_PIX_FMT_H264) {
JLOG_ERROR("Got non-H264 frame from memsink");
retval = -1;
}
if (flock(fd, LOCK_UN) < 0) {
JLOG_PERROR("Can't unlock memsink");
retval = -1;
}
return retval;
}
static void *_clients_thread(UNUSED void *arg) {
A_THREAD_RENAME("us_clients");
atomic_store(&_g_ready, true);
frame_s *frame = frame_init();
uint64_t frame_id = 0;
unsigned error_reported = 0;
# define IF_NOT_REPORTED(_error, ...) { \
if (error_reported != _error) { __VA_ARGS__; error_reported = _error; } \
}
while (!STOP) {
if (!HAS_WATCHERS) {
IF_NOT_REPORTED(1, {
JLOG_INFO("No active watchers, memsink disconnected");
});
usleep(_g_watchers_polling);
continue;
}
int fd = -1;
memsink_shared_s *mem = NULL;
if ((fd = shm_open(_g_memsink_obj, O_RDWR, 0)) <= 0) {
IF_NOT_REPORTED(2, {
JLOG_PERROR("Can't open memsink");
});
goto close_memsink;
}
if ((mem = memsink_shared_map(fd)) == NULL) {
IF_NOT_REPORTED(3, {
JLOG_PERROR("Can't map memsink");
});
goto close_memsink;
}
error_reported = 0;
JLOG_INFO("Memsink opened; reading frames ...");
while (!STOP && HAS_WATCHERS) {
int result = _wait_frame(fd, mem, frame_id);
if (result == 0) {
if (_get_frame(fd, mem, frame, &frame_id) != 0) {
goto close_memsink;
}
LOCK;
rtp_wrap_h264(_g_rtp, frame, _relay_rtp_clients);
UNLOCK;
} else if (result == -1) {
goto close_memsink;
}
}
close_memsink:
if (mem != NULL) {
JLOG_INFO("Memsink closed");
memsink_shared_unmap(mem);
mem = NULL;
}
if (fd > 0) {
close(fd);
fd = -1;
}
sleep(1); // error_delay
}
# undef IF_NOT_REPORTED
frame_destroy(frame);
return NULL;
}
static int _read_config(const char *config_dir_path) {
char *config_file_path;
janus_config *config = NULL;
A_ASPRINTF(config_file_path, "%s/%s.jcfg", config_dir_path, _plugin_get_package());
JLOG_INFO("Reading config file '%s' ...", config_file_path);
config = janus_config_parse(config_file_path);
if (config == NULL) {
JLOG_ERROR("Can't read config");
goto error;
}
janus_config_print(config);
janus_config_category *config_memsink = janus_config_get_create(config, NULL, janus_config_type_category, "memsink");
janus_config_item *config_memsink_obj = janus_config_get(config, config_memsink, janus_config_type_item, "object");
if (config_memsink_obj == NULL || config_memsink_obj->value == NULL || config_memsink_obj->value[0] == '\0') {
JLOG_ERROR("Missing config value: memsink.object");
goto error;
}
_g_memsink_obj = strdup(config_memsink_obj->value);
int retval = 0;
goto ok;
error:
retval = -1;
ok:
if (config) {
janus_config_destroy(config);
}
free(config_file_path);
return retval;
}
static int _plugin_init(janus_callbacks *gw, const char *config_dir_path) {
// https://groups.google.com/g/meetecho-janus/c/xoWIQfaoJm8
// sysctl -w net.core.rmem_default=500000
// sysctl -w net.core.wmem_default=500000
// sysctl -w net.core.rmem_max=1000000
// sysctl -w net.core.wmem_max=1000000
JLOG_INFO("Initializing plugin ...");
assert(!READY);
assert(!STOP);
if (gw == NULL || config_dir_path == NULL || _read_config(config_dir_path) < 0) {
return -1;
}
_g_gw = gw;
_g_rtp = rtp_init();
A_THREAD_CREATE(&_g_tid, _clients_thread, NULL);
return 0;
}
static void _plugin_destroy(void) {
JLOG_INFO("Destroying plugin ...");
atomic_store(&_g_stop, true);
if (READY) {
A_THREAD_JOIN(_g_tid);
}
LIST_ITERATE(_g_clients, client, {
LIST_REMOVE(_g_clients, client);
free(client);
});
_g_clients = NULL;
rtp_destroy(_g_rtp);
_g_rtp = NULL;
_g_gw = NULL;
if (_g_memsink_obj) {
free(_g_memsink_obj);
_g_memsink_obj = NULL;
}
}
#define IF_DISABLED(...) { if (!READY || STOP) { __VA_ARGS__ } }
static void _plugin_create_session(janus_plugin_session *session, int *error) {
IF_DISABLED({ *error = -1; return; });
LOCK;
JLOG_INFO("Creating session %p ...", session);
_client_s *client;
A_CALLOC(client, 1);
client->session = session;
client->transmit = true;
LIST_APPEND(_g_clients, client);
atomic_store(&_g_has_watchers, true);
UNLOCK;
}
static void _plugin_destroy_session(janus_plugin_session* session, int *error) {
IF_DISABLED({ *error = -1; return; });
LOCK;
bool found = false;
bool has_watchers = false;
LIST_ITERATE(_g_clients, client, {
if (client->session == session) {
JLOG_INFO("Removing session %p ...", session);
LIST_REMOVE(_g_clients, client);
free(client);
found = true;
} else {
has_watchers = (has_watchers || client->transmit);
}
});
if (!found) {
JLOG_WARN("No session %p", session);
*error = -2;
}
atomic_store(&_g_has_watchers, has_watchers);
UNLOCK;
}
static json_t *_plugin_query_session(janus_plugin_session *session) {
IF_DISABLED({ return NULL; });
json_t *info = NULL;
LOCK;
LIST_ITERATE(_g_clients, client, {
if (client->session == session) {
info = json_string("session_found");
break;
}
});
UNLOCK;
return info;
}
static void _set_transmit(janus_plugin_session *session, UNUSED const char *msg, bool transmit) {
IF_DISABLED({ return; });
LOCK;
bool found = false;
bool has_watchers = false;
LIST_ITERATE(_g_clients, client, {
if (client->session == session) {
client->transmit = transmit;
//JLOG_INFO("%s session %p", msg, session);
found = true;
}
has_watchers = (has_watchers || client->transmit);
});
if (!found) {
JLOG_WARN("No session %p", session);
}
atomic_store(&_g_has_watchers, has_watchers);
UNLOCK;
}
#undef IF_DISABLED
static void _plugin_setup_media(janus_plugin_session *session) { _set_transmit(session, "Unmuted", true); }
static void _plugin_hangup_media(janus_plugin_session *session) { _set_transmit(session, "Muted", false); }
static struct janus_plugin_result *_plugin_handle_message(
janus_plugin_session *session, char *transaction, json_t *msg, json_t *jsep) {
assert(transaction != NULL);
# define FREE_MSG_JSEP { \
if (msg) json_decref(msg); \
if (jsep) json_decref(jsep); \
}
if (session == NULL || msg == NULL) {
free(transaction);
FREE_MSG_JSEP;
return janus_plugin_result_new(JANUS_PLUGIN_ERROR, (msg ? "No session" : "No message"), NULL);
}
# define PUSH_ERROR(_error, _reason) { \
/*JLOG_ERROR("Message error in session %p: %s", session, _reason);*/ \
json_t *_event = json_object(); \
json_object_set_new(_event, "ustreamer", json_string("event")); \
json_object_set_new(_event, "error_code", json_integer(_error)); \
json_object_set_new(_event, "error", json_string(_reason)); \
_g_gw->push_event(session, &_plugin, transaction, _event, NULL); \
json_decref(_event); \
}
json_t *request_obj = json_object_get(msg, "request");
if (request_obj == NULL) {
PUSH_ERROR(400, "Request missing");
goto ok_wait;
}
const char *request_str = json_string_value(request_obj);
if (!request_str) {
PUSH_ERROR(400, "Request not a string");
goto ok_wait;
}
//JLOG_INFO("Message: %s", request_str);
# define PUSH_STATUS(_status, _jsep) { \
json_t *_event = json_object(); \
json_object_set_new(_event, "ustreamer", json_string("event")); \
json_t *_result = json_object(); \
json_object_set_new(_result, "status", json_string(_status)); \
json_object_set_new(_event, "result", _result); \
_g_gw->push_event(session, &_plugin, transaction, _event, _jsep); \
json_decref(_event); \
}
if (!strcmp(request_str, "start")) {
PUSH_STATUS("started", NULL);
} else if (!strcmp(request_str, "stop")) {
PUSH_STATUS("stopped", NULL);
} else if (!strcmp(request_str, "watch")) {
char *sdp = rtp_make_sdp(_g_rtp);
if (sdp == NULL) {
PUSH_ERROR(503, "Haven't received SPS/PPS from memsink yet");
goto ok_wait;
}
//JLOG_INFO("SDP generated:\n%s", sdp);
json_t *offer_jsep = json_pack("{ssss}", "type", "offer", "sdp", sdp);
free(sdp);
PUSH_STATUS("started", offer_jsep);
json_decref(offer_jsep);
} else {
PUSH_ERROR(405, "Not implemented");
}
ok_wait:
FREE_MSG_JSEP;
return janus_plugin_result_new(JANUS_PLUGIN_OK_WAIT, NULL, NULL);
# undef PUSH_ERROR
# undef FREE_MSG_JSEP
}
static int _plugin_get_api_compatibility(void) { return JANUS_PLUGIN_API_VERSION; }
static int _plugin_get_version(void) { return VERSION_U; }
static const char *_plugin_get_version_string(void) { return VERSION; }
static const char *_plugin_get_description(void) { return "Pi-KVM uStreamer Janus plugin for H.264 video"; }
static const char *_plugin_get_name(void) { return "ustreamer"; }
static const char *_plugin_get_author(void) { return "Maxim Devaev <mdevaev@gmail.com>"; }
static const char *_plugin_get_package(void) { return "janus.plugin.ustreamer"; }
#undef STOP
#undef READY
#undef UNLOCK
#undef LOCK
#undef JLOG_PERROR
#undef JLOG_ERROR
#undef JLOG_WARN
#undef JLOG_INFO

228
janus/src/rtp.c Normal file
View File

@@ -0,0 +1,228 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# This source file is partially based on this code: #
# - https://github.com/catid/kvm/blob/master/kvm_pipeline/src #
# #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
# #
*****************************************************************************/
#include "rtp.h"
#define PAYLOAD 96 // Payload type
#define PRE 3 // Annex B prefix length
void _rtp_process_nalu(rtp_s *rtp, const uint8_t *data, size_t size, uint32_t pts, bool marked, rtp_callback_f callback);
static void _rtp_write_header(rtp_s *rtp, uint32_t pts, bool marked);
static ssize_t _find_annexb(const uint8_t *data, size_t size);
rtp_s *rtp_init(void) {
rtp_s *rtp;
A_CALLOC(rtp, 1);
rtp->ssrc = triple_u32(get_now_monotonic_u64());
rtp->sps = frame_init();
rtp->pps = frame_init();
A_MUTEX_INIT(&rtp->mutex);
return rtp;
}
void rtp_destroy(rtp_s *rtp) {
A_MUTEX_DESTROY(&rtp->mutex);
frame_destroy(rtp->pps);
frame_destroy(rtp->sps);
free(rtp);
}
char *rtp_make_sdp(rtp_s *rtp) {
A_MUTEX_LOCK(&rtp->mutex);
if (rtp->sps->used == 0 || rtp->pps->used == 0) {
A_MUTEX_UNLOCK(&rtp->mutex);
return NULL;
}
char *sps = NULL;
char *pps = NULL;
base64_encode(rtp->sps->data, rtp->sps->used, &sps, NULL);
base64_encode(rtp->pps->data, rtp->pps->used, &pps, NULL);
A_MUTEX_UNLOCK(&rtp->mutex);
// https://tools.ietf.org/html/rfc6184
// https://github.com/meetecho/janus-gateway/issues/2443
char *sdp;
A_ASPRINTF(sdp,
"v=0" RN
"o=- %" PRIu64 " 1 IN IP4 127.0.0.1" RN
"s=Pi-KVM uStreamer" RN
"t=0 0" RN
"m=video 1 RTP/SAVPF %d" RN
"c=IN IP4 0.0.0.0" RN
"a=rtpmap:%d H264/90000" RN
"a=fmtp:%d profile-level-id=42E01F" RN
"a=fmtp:%d packetization-mode=1" RN
"a=fmtp:%d sprop-sps=%s" RN
"a=fmtp:%d sprop-pps=%s" RN
"a=rtcp-fb:%d nack" RN
"a=rtcp-fb:%d nack pli" RN
"a=rtcp-fb:%d goog-remb" RN
"a=sendonly" RN,
get_now_id() >> 1, PAYLOAD, PAYLOAD, PAYLOAD, PAYLOAD,
PAYLOAD, sps,
PAYLOAD, pps,
PAYLOAD, PAYLOAD, PAYLOAD
);
free(sps);
free(pps);
return sdp;
}
void rtp_wrap_h264(rtp_s *rtp, const frame_s *frame, rtp_callback_f callback) {
// There is a complicated logic here but everything works as it should:
// - https://github.com/pikvm/ustreamer/issues/115#issuecomment-893071775
assert(frame->format == V4L2_PIX_FMT_H264);
const uint32_t pts = get_now_monotonic_u64() * 9 / 100; // PTS units are in 90 kHz
ssize_t last_offset = -PRE;
while (true) { // Find and iterate by nalus
const size_t next_start = last_offset + PRE;
ssize_t offset = _find_annexb(frame->data + next_start, frame->used - next_start);
if (offset < 0) {
break;
}
offset += next_start;
if (last_offset >= 0) {
const uint8_t *data = frame->data + last_offset + PRE;
size_t size = offset - last_offset - PRE;
if (data[size - 1] == 0) { // Check for extra 00
--size;
}
_rtp_process_nalu(rtp, data, size, pts, false, callback);
}
last_offset = offset;
}
if (last_offset >= 0) {
const uint8_t *data = frame->data + last_offset + PRE;
size_t size = frame->used - last_offset - PRE;
_rtp_process_nalu(rtp, data, size, pts, true, callback);
}
}
void _rtp_process_nalu(rtp_s *rtp, const uint8_t *data, size_t size, uint32_t pts, bool marked, rtp_callback_f callback) {
const unsigned ref_idc = (data[0] >> 5) & 3;
const unsigned type = data[0] & 0x1F;
frame_s *ps = NULL;
switch (type) {
case 7: ps = rtp->sps; break;
case 8: ps = rtp->pps; break;
}
if (ps) {
A_MUTEX_LOCK(&rtp->mutex);
frame_set_data(ps, data, size);
A_MUTEX_UNLOCK(&rtp->mutex);
}
# define HEADER_SIZE 12
if (size + HEADER_SIZE <= RTP_DATAGRAM_SIZE) {
_rtp_write_header(rtp, pts, marked);
memcpy(rtp->datagram + HEADER_SIZE, data, size);
callback(rtp->datagram, size + HEADER_SIZE);
return;
}
const size_t fu_overhead = HEADER_SIZE + 2; // FU-A overhead
const uint8_t *src = data + 1;
ssize_t remaining = size - 1;
bool first = true;
while (remaining > 0) {
ssize_t frag_size = RTP_DATAGRAM_SIZE - fu_overhead;
const bool last = (remaining <= frag_size);
if (last) {
frag_size = remaining;
}
_rtp_write_header(rtp, pts, (marked && last));
rtp->datagram[HEADER_SIZE] = 28 | (ref_idc << 5);
uint8_t fu = type;
if (first) {
fu |= 0x80;
}
if (last) {
fu |= 0x40;
}
rtp->datagram[HEADER_SIZE + 1] = fu;
memcpy(rtp->datagram + fu_overhead, src, frag_size);
callback(rtp->datagram, fu_overhead + frag_size);
src += frag_size;
remaining -= frag_size;
first = false;
}
# undef HEADER_SIZE
}
static void _rtp_write_header(rtp_s *rtp, uint32_t pts, bool marked) {
uint32_t word0 = 0x80000000;
if (marked) {
word0 |= 1 << 23;
}
word0 |= (PAYLOAD & 0x7F) << 16;
word0 |= rtp->seq;
++rtp->seq;
# define WRITE_BE_U32(_offset, _value) *((uint32_t *)(rtp->datagram + _offset)) = __builtin_bswap32(_value)
WRITE_BE_U32(0, word0);
WRITE_BE_U32(4, pts);
WRITE_BE_U32(8, rtp->ssrc);
# undef WRITE_BE_U32
}
static ssize_t _find_annexb(const uint8_t *data, size_t size) {
// Parses buffer for 00 00 01 start codes
if (size >= PRE) {
for (size_t index = 0; index <= size - PRE; ++index) {
if (data[index] == 0 && data[index + 1] == 0 && data[index + 2] == 1) {
return index;
}
}
}
return -1;
}
#undef PRE
#undef PAYLOAD

View File

@@ -1,8 +1,11 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# This source file is partially based on this code: #
# - https://github.com/catid/kvm/blob/master/kvm_pipeline/src #
# #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -24,49 +27,43 @@
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/types.h>
#include <linux/videodev2.h>
#include <IL/OMX_Core.h>
#include <IL/OMX_Component.h>
#include <IL/OMX_Broadcom.h>
#include <interface/vcos/vcos_semaphore.h>
#include <pthread.h>
#include "../../../libs/tools.h"
#include "../../../libs/logging.h"
#include "../../../libs/frame.h"
#include "formatters.h"
#include "component.h"
#include "tools.h"
#include "threading.h"
#include "frame.h"
#include "base64.h"
#ifndef CFG_OMX_MAX_ENCODERS
# define CFG_OMX_MAX_ENCODERS 3 // Raspberry Pi limitation
#endif
#define OMX_MAX_ENCODERS ((unsigned)(CFG_OMX_MAX_ENCODERS))
// https://stackoverflow.com/questions/47635545/why-webrtc-chose-rtp-max-packet-size-to-1200-bytes
#define RTP_DATAGRAM_SIZE 1200
typedef struct {
OMX_HANDLETYPE comp;
OMX_BUFFERHEADERTYPE *input_buf;
OMX_BUFFERHEADERTYPE *output_buf;
bool input_required;
bool output_available;
bool failed;
VCOS_SEMAPHORE_T handler_sem;
uint32_t ssrc;
uint16_t seq;
bool i_handler_sem;
bool i_encoder;
bool i_input_port_enabled;
bool i_output_port_enabled;
} omx_encoder_s;
uint8_t datagram[RTP_DATAGRAM_SIZE];
frame_s *sps; // Actually not a frame, just a bytes storage
frame_s *pps;
pthread_mutex_t mutex;
} rtp_s;
typedef void (*rtp_callback_f)(const uint8_t *datagram, size_t size);
omx_encoder_s *omx_encoder_init(void);
void omx_encoder_destroy(omx_encoder_s *omx);
rtp_s *rtp_init(void);
void rtp_destroy(rtp_s *rtp);
int omx_encoder_prepare(omx_encoder_s *omx, const frame_s *frame, unsigned quality);
int omx_encoder_compress(omx_encoder_s *omx, const frame_s *src, frame_s *dest);
char *rtp_make_sdp(rtp_s *rtp);
void rtp_wrap_h264(rtp_s *rtp, const frame_s *frame, rtp_callback_f callback);

1
janus/src/threading.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/threading.h

1
janus/src/tools.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/tools.h

View File

@@ -1,4 +1,4 @@
FROM archlinux/base
FROM archlinux/archlinux:base-devel
RUN mkdir -p /etc/pacman.d/hooks \
&& ln -s /dev/null /etc/pacman.d/hooks/30-systemd-tmpfiles.hook
@@ -7,8 +7,6 @@ RUN echo "Server = http://mirror.yandex.ru/archlinux/\$repo/os/\$arch" > /etc/pa
RUN pacman -Syu --noconfirm \
&& pacman -S --needed --noconfirm \
base \
base-devel \
vim \
git \
libjpeg \
@@ -20,7 +18,8 @@ RUN pacman -Syu --noconfirm \
python-tox \
cppcheck \
npm \
&& (pacman -Sc --noconfirm || true)
&& (pacman -Sc --noconfirm || true) \
&& rm -rf /var/cache/pacman/pkg/*
RUN npm install htmlhint -g

3
linters/cppcheck.h Normal file
View File

@@ -0,0 +1,3 @@
#define CHAR_BIT 8
#define WITH_GPIO
#define JANUS_PLUGIN_INIT(...) { __VA_ARGS__ }

View File

@@ -30,6 +30,7 @@ disable =
too-many-ancestors,
no-else-return,
len-as-condition,
unspecified-encoding,
[REPORTS]
msg-template = {symbol} -- {path}:{line}({obj}): {msg}

View File

@@ -1,12 +1,12 @@
[tox]
envlist = cppcheck-src, cppcheck-python, flake8, pylint, mypy, vulture, htmlhint
envlist = cppcheck, flake8, pylint, mypy, vulture, htmlhint
skipsdist = true
[testenv]
basepython = python3.9
basepython = python3.10
changedir = /src
[testenv:cppcheck-src]
[testenv:cppcheck]
whitelist_externals = cppcheck
commands = cppcheck \
--force \
@@ -18,25 +18,8 @@ commands = cppcheck \
--suppress=variableScope \
--inline-suppr \
--library=python \
-DCHAR_BIT=8 \
-DWITH_OMX \
-DWITH_GPIO \
src python
[testenv:cppcheck-python]
whitelist_externals = cppcheck
commands = cppcheck \
--force \
--std=c11 \
--error-exitcode=1 \
--quiet \
--enable=warning,unusedFunction,portability,performance,style \
--suppress=assignmentInAssert \
--suppress=variableScope \
--inline-suppr \
--library=python \
-DCHAR_BIT=8 \
python
--include=linters/cppcheck.h \
src python/ustreamer.c janus/rtp.h janus/rtp.c janus/plugin.c
[testenv:flake8]
whitelist_externals = bash

View File

@@ -1,6 +1,6 @@
.\" Manpage for ustreamer-dump.
.\" Open an issue or pull request to https://github.com/pikvm/ustreamer to correct errors or typos
.TH USTREAMER-DUMP 1 "version 3.13" "January 2021"
.TH USTREAMER-DUMP 1 "version 5.4" "January 2021"
.SH NAME
ustreamer-dump \- Dump uStreamer's memory sink to file
@@ -38,6 +38,12 @@ Filename to dump output to. Use '-' for stdout. Default: just consume the sink.
.TP
.BR \-j ", " \-\-output-json
Format output as JSON. Required option --output. Default: disabled.
.TP
.BR \-c ", " \-\-count\ \fIN
Limit the number of frames. Default: 0 (infinite).
.TP
.BR \-i ", "\-\-interval\ \fIsec
Delay between reading frames (float). Default: 0.
.SS "Logging options"
.TP

View File

@@ -1,16 +1,16 @@
.\" Manpage for ustreamer.
.\" Open an issue or pull request to https://github.com/pikvm/ustreamer to correct errors or typos
.TH USTREAMER 1 "version 3.13" "November 2020"
.TH USTREAMER 1 "version 5.4" "November 2020"
.SH NAME
ustreamer \- stream MJPG video from any V4L2 device to the network
ustreamer \- stream MJPEG video from any V4L2 device to the network
.SH SYNOPSIS
.B ustreamer
.RI [OPTIONS]
.SH DESCRIPTION
µStreamer (\fBustreamer\fP) is a lightweight and very quick server to stream MJPG video from any V4L2 device to the network. All new browsers have native support of this video format, as well as most video players such as mplayer, VLC etc. µStreamer is a part of the Pi-KVM project designed to stream VGA and HDMI screencast hardware data with the highest resolution and FPS possible.
µStreamer (\fBustreamer\fP) is a lightweight and very quick server to stream MJPEG video from any V4L2 device to the network. All new browsers have native support of this video format, as well as most video players such as mplayer, VLC etc. µStreamer is a part of the Pi-KVM project designed to stream VGA and HDMI screencast hardware data with the highest resolution and FPS possible.
.SH USAGE
Without arguments, \fBustreamer\fR will try to open \fB/dev/video0\fR with 640x480 resolution and start streaming on \fBhttp://127\.0\.0\.1:8080\fR\. You can override this behavior using parameters \fB\-\-device\fR, \fB\-\-host\fR and \fB\-\-port\fR\. For example, to stream to the world, run: \fBustreamer --device=/dev/video1 --host=0.0.0.0 --port=80\fR
@@ -23,9 +23,9 @@ For example, the recommended way of running µStreamer with Auvidea B101 on a Ra
.RS
\fB\-\-format=uyvy \e\fR # Device input format
.nf
\fB\-\-encoder=omx \e\fR # Hardware encoding with OpenMAX
\fB\-\-encoder=m2m-image \e\fR # Hardware encoding with V4L2 M2M intraface
.nf
\fB\-\-workers=3 \e\fR # Maximum workers for OpenMAX
\fB\-\-workers=3 \e\fR # Maximum workers for V4L2 encoder
.nf
\fB\-\-persistent \e\fR # Don\'t re\-initialize device on timeout (for example when HDMI cable was disconnected)
.nf
@@ -72,7 +72,7 @@ Drop frames smaller then this limit. Useful if the device produces small\-sized
Don't re\-initialize device on timeout. Default: disabled.
.TP
.BR \-t ", " \-\-dv\-timings
Enable DV timings querying and events processing to automatic resolution change. Default: disabled.
Enable DV-timings querying and events processing to automatic resolution change. Default: disabled.
.TP
.BR \-b\ \fIN ", " \-\-buffers\ \fIN
The number of buffers to receive data from the device. Each buffer may processed using an independent thread.
@@ -84,27 +84,29 @@ Default: 1 (the number of CPU cores (but not more than 4)).
.TP
.BR \-q\ \fIN ", " \-\-quality\ \fIN
Set quality of JPEG encoding from 1 to 100 (best). Default: 80.
Note: If HW encoding is used (JPEG source format selected), this parameter attempts to configure the camera or capture device hardware's internal encoder. It does not re\-encode MJPG to MJPG to change the quality level for sources that already output MJPG.
Note: If HW encoding is used (JPEG source format selected), this parameter attempts to configure the camera or capture device hardware's internal encoder. It does not re\-encode MJPEG to MJPEG to change the quality level for sources that already output MJPEG.
.TP
.BR \-c\ \fItype ", " \-\-encoder\ \fItype
Use specified encoder. It may affect the number of workers.
CPU ─ Software MJPG encoding (default).
CPU ─ Software MJPEG encoding (default).
OMX ─ GPU hardware accelerated MJPG encoding with OpenMax (required \fBWITH_OMX\fR feature).
HW ─ Use pre-encoded MJPEG frames directly from camera hardware.
HW ─ Use pre-encoded MJPG frames directly from camera hardware.
M2M-VIDEO ─ GPU-accelerated MJPEG encoding.
NOOP ─ Don't compress MJPG stream (do nothing).
M2M-IMAGE ─ GPU-accelerated JPEG encoding.
NOOP ─ Don't compress MJPEG stream (do nothing).
.TP
.BR \-g\ \fIWxH,... ", " \-\-glitched\-resolutions\ \fIWxH,...
It doesn't do anything. Still here for compatibility. Required \fBWITH_OMX\fR feature.
It doesn't do anything. Still here for compatibility.
.TP
.BR \-k\ \fIpath ", " \-\-blank\ \fIpath
Path to JPEG file that will be shown when the device is disconnected during the streaming. Default: black screen 640x480 with 'NO SIGNAL'.
.TP
.BR \-K\ \fIsec ", " \-\-last\-as\-blank\ \fIsec
Show the last frame received from the camera after it was disconnected, but no more than specified time (or endlessly if 0 is specified). If the device has not yet been online, display 'NO SIGNAL' or the image specified by option \-\-blank. Default: disabled.
Show the last frame received from the camera after it was disconnected, but no more than specified time (or endlessly if 0 is specified). If the device has not yet been online, display 'NO SIGNAL' or the image specified by option \-\-blank. Note: currently this option has no effect on memory sinks. Default: disabled.
.TP
.BR \-l ", " \-\-slowdown
Slowdown capturing to 1 FPS or less when no stream or sink clients are connected. Useful to reduce CPU consumption. Default: disabled.
@@ -114,6 +116,9 @@ Timeout for device querying. Default: 1.
.TP
.BR \-\-device\-error\-delay\ \fIsec
Delay before trying to connect to the device again after an error (timeout for example). Default: 1.
.TP
.BR \-\-m2m\-device\ \fI/dev/path
Path to V4L2 mem-to-mem encoder device. Default: auto-select.
.SS "Image control options"
.TP
@@ -167,12 +172,15 @@ Bind to this TCP port. Default: 8080.
.BR \-U\ \fIpath ", " \-\-unix\ \fIpath
Bind to UNIX domain socket. Default: disabled.
.TP
.BR \-d ", " \-\-unix\-rm
.BR \-D ", " \-\-unix\-rm
Try to remove old unix socket file before binding. default: disabled.
.TP
.BR \-M\ \fImode ", " \-\-unix\-mode\ \fImode
Set UNIX socket file permissions (like 777). Default: disabled.
.TP
.BR \-S ", " \-\-systemd
Bind to systemd socket for socket activation. Required \fBWITH_SYSTEMD\fR feature. Default: disabled.
.TP
.BR \-\-user\ \fIname
HTTP basic auth user. Default: disabled.
.TP
@@ -189,7 +197,7 @@ Don't send identical frames to clients, but no more than specified number. It ca
Override image resolution for the /state. Default: disabled.
.TP
.BR \-\-tcp\-nodelay
Set TCP_NODELAY flag to the client /stream socket. Ignored for \-\-unix.
Set TCP_NODELAY flag to the client /stream socket. Only for TCP socket.
Default: disabled.
.TP
.BR \-\-allow\-origin\ \fIstr
@@ -218,10 +226,8 @@ Timeout for lock. Default: 1.
.SS "H264 sink options"
.TP
Available only if \fBWITH_OMX\fR feature enabled.
.TP
.BR \-\-h264\-sink\ \fIname
Use the specified shared memory object to sink H264 frames encoded by MMAL. Default: disabled.
Use the specified shared memory object to sink H264 frames. Default: disabled.
.TP
.BR \-\-h264\-sink\-mode\ \fImode
Set H264 sink permissions (like 777). Default: 660.
@@ -240,12 +246,19 @@ H264 bitrate in Kbps. Default: 5000.
.TP
.BR \-\-h264\-gop\ \fIN
Intarval between keyframes. Default: 30.
.TP
.BR \-\-h264\-m2m\-device\ \fI/dev/path
Path to V4L2 mem-to-mem encoder device. Default: auto-select.
.SS "Process options"
.TP
.BR \-\-exit\-on\-parent\-death
Exit the program if the parent process is dead. Required \fBHAS_PDEATHSIG\fR feature. Default: disabled.
.TP
.BR \-\-exit\-on\-no\-clients \fIsec
Exit the program if there have been no stream or sink clients or any HTTP requests in the last N seconds. Default: 0 (disabled).
.TP
.BR \-\-process\-name\-prefix\ \fIstr
Set process name prefix which will be displayed in the process list like '\fIstr: ustreamer \-\-blah\-blah\-blah'\fR. Required \fBWITH_SETPROCTITLE\fR feature. Default: disabled.
.TP

View File

@@ -3,28 +3,28 @@
pkgname=ustreamer
pkgver=3.13
pkgver=5.4
pkgrel=1
pkgdesc="Lightweight and fast MJPG-HTTP streamer"
pkgdesc="Lightweight and fast MJPEG-HTTP streamer"
url="https://github.com/pikvm/ustreamer"
license=(GPL)
arch=(i686 x86_64 armv6h armv7h aarch64)
depends=(libjpeg libevent libutil-linux libbsd libgpiod)
makedepends=(gcc make)
depends=(libjpeg libevent libbsd libgpiod systemd)
makedepends=(gcc make systemd)
source=(${pkgname}::"git+https://github.com/pikvm/ustreamer#commit=v${pkgver}")
md5sums=(SKIP)
_options="WITH_GPIO=1"
_options="WITH_GPIO=1 WITH_SYSTEMD=1"
if [ -e /usr/bin/python3 ]; then
_options="$_options WITH_PYTHON=1"
depends+=(python)
makedepends+=(python-setuptools)
fi
if [ -e /opt/vc/include/IL/OMX_Core.h ]; then
depends+=(raspberrypi-firmware)
makedepends+=(raspberrypi-firmware)
_options="$_options WITH_OMX=1"
if [ -e /usr/include/janus/plugins/plugin.h ];then
depends+=(janus-gateway-pikvm)
makedepends+=(janus-gateway-pikvm)
_options="$_options WITH_JANUS=1"
fi

View File

@@ -7,13 +7,12 @@ RUN apt-get update \
gcc \
libjpeg8-dev \
libbsd-dev \
libraspberrypi-dev \
libgpiod-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /build/ustreamer/
COPY . .
RUN make -j5 WITH_OMX=1 WITH_GPIO=1
RUN make -j5 WITH_GPIO=1
RUN ["cross-build-end"]
FROM balenalib/raspberrypi3-debian:run as RUN
@@ -25,7 +24,6 @@ RUN apt-get update \
libevent-2.1 \
libevent-pthreads-2.1-6 \
libjpeg8 \
uuid \
libbsd0 \
libgpiod2 \
&& rm -rf /var/lib/apt/lists/*

View File

@@ -5,13 +5,12 @@ RUN apt-get update \
gcc \
libjpeg8-dev \
libbsd-dev \
libraspberrypi-dev \
libgpiod-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /build/ustreamer/
COPY . .
RUN make -j5 WITH_OMX=1 WITH_GPIO=1
RUN make -j5 WITH_GPIO=1
FROM balenalib/raspberrypi3-debian:run as RUN
@@ -20,7 +19,6 @@ RUN apt-get update \
libevent-2.1 \
libevent-pthreads-2.1-6 \
libjpeg8 \
uuid \
libbsd0 \
libgpiod2 \
&& rm -rf /var/lib/apt/lists/*

View File

@@ -8,7 +8,6 @@ RUN apt-get update \
git \
libevent-dev \
libjpeg62-turbo-dev \
uuid-dev \
libbsd-dev \
libgpiod-dev \
&& rm -rf /var/lib/apt/lists/*
@@ -25,7 +24,6 @@ RUN apt-get update \
libevent-2.1 \
libevent-pthreads-2.1-6 \
libjpeg62-turbo \
uuid \
libbsd0 \
libgpiod2 \
&& rm -rf /var/lib/apt/lists/*

View File

@@ -5,7 +5,7 @@ EAPI=7
inherit git-r3
DESCRIPTION="uStreamer - Lightweight and fast MJPG-HTTP streamer"
DESCRIPTION="uStreamer - Lightweight and fast MJPEG-HTTP streamer"
HOMEPAGE="https://github.com/pikvm/ustreamer"
EGIT_REPO_URI="https://github.com/pikvm/ustreamer.git"
@@ -17,7 +17,6 @@ IUSE=""
DEPEND="
>=dev-libs/libevent-2.1.8
>=media-libs/libjpeg-turbo-1.5.3
>=sys-apps/util-linux-2.33
>=dev-libs/libbsd-0.9.1
"
RDEPEND="${DEPEND}"

View File

@@ -6,7 +6,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=ustreamer
PKG_VERSION:=3.13
PKG_VERSION:=5.4
PKG_RELEASE:=1
PKG_MAINTAINER:=Maxim Devaev <mdevaev@gmail.com>
@@ -25,12 +25,12 @@ define Package/ustreamer
SECTION:=multimedia
CATEGORY:=Multimedia
TITLE:=uStreamer
DEPENDS:=+libpthread +libjpeg +libv4l +libuuid +libbsd +libevent2 +libevent2-core +libevent2-extra +libevent2-pthreads
DEPENDS:=+libpthread +libjpeg +libv4l +libbsd +libevent2 +libevent2-core +libevent2-extra +libevent2-pthreads
URL:=https://github.com/pikvm/ustreamer
endef
define Package/ustreamer/description
µStreamer - Lightweight and fast MJPG-HTTP streamer
µStreamer - Lightweight and fast MJPEG-HTTP streamer
endef
define Package/ustreamer/install

20
python/Makefile Normal file
View File

@@ -0,0 +1,20 @@
-include ../config.mk
DESTDIR ?=
PREFIX ?= /usr/local
PY ?= python3
# =====
all:
$(info == PY_BUILD ustreamer-*.so)
@ $(PY) setup.py build
install:
$(PY) setup.py install --prefix=$(PREFIX) --root=$(if $(DESTDIR),$(DESTDIR),/)
clean:
rm -rf build

View File

@@ -1,12 +1,14 @@
from distutils.core import Extension
from distutils.core import setup
import os
from setuptools import Extension
from setuptools import setup
# =====
if __name__ == "__main__":
setup(
name="ustreamer",
version="3.13",
version="5.4",
description="uStreamer tools",
author="Maxim Devaev",
author_email="mdevaev@gmail.com",
@@ -16,11 +18,8 @@ if __name__ == "__main__":
"ustreamer",
libraries=["rt", "m", "pthread"],
undef_macros=["NDEBUG"],
sources=["ustreamer.c"],
depends=[
"../src/libs/tools.h",
"../src/libs/memsinksh.h",
],
sources=["src/" + name for name in os.listdir("src") if name.endswith(".c")],
depends=["src/" + name for name in os.listdir("src") if name.endswith(".h")],
),
],
)

1
python/src/frame.c Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/frame.c

1
python/src/frame.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/frame.h

1
python/src/memsinksh.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/memsinksh.h

1
python/src/tools.h Symbolic link
View File

@@ -0,0 +1 @@
../../src/libs/tools.h

View File

@@ -13,30 +13,11 @@
#include <Python.h>
#include "../src/libs/tools.h" // Just a header without C-sources
#include "../src/libs/memsinksh.h" // No sources again
#include "tools.h"
#include "frame.h"
#include "memsinksh.h"
typedef struct {
uint64_t id;
long double ts;
uint8_t *data;
size_t used;
size_t allocated;
unsigned width;
unsigned height;
unsigned format;
unsigned stride;
bool online;
long double grab_ts;
long double encode_begin_ts;
long double encode_end_ts;
} tmp_frame_s;
typedef struct {
PyObject_HEAD
@@ -48,34 +29,28 @@ typedef struct {
int fd;
memsink_shared_s *mem;
tmp_frame_s *tmp_frame;
PyObject *dict_frame; // PyDict
uint64_t frame_id;
long double frame_ts;
frame_s *frame;
} MemsinkObject;
#define MEM(_next) self->mem->_next
#define TMP(_next) self->tmp_frame->_next
#define MEM(_next) self->mem->_next
#define FRAME(_next) self->frame->_next
static void MemsinkObject_destroy_internals(MemsinkObject *self) {
if (self->dict_frame != NULL) {
Py_DECREF(self->dict_frame);
self->dict_frame = NULL;
}
if (self->mem != NULL) {
munmap(self->mem, sizeof(memsink_shared_s));
memsink_shared_unmap(self->mem);
self->mem = NULL;
}
if (self->fd > 0) {
close(self->fd);
self->fd = -1;
}
if (self->tmp_frame) {
if (TMP(data)) {
free(TMP(data));
}
free(self->tmp_frame);
self->tmp_frame = NULL;
if (self->frame) {
frame_destroy(self->frame);
self->frame = NULL;
}
}
@@ -103,33 +78,15 @@ static int MemsinkObject_init(MemsinkObject *self, PyObject *args, PyObject *kwa
# undef SET_DOUBLE
A_CALLOC(self->tmp_frame, 1);
TMP(allocated) = 512 * 1024;
A_REALLOC(TMP(data), TMP(allocated));
self->frame = frame_init();
if ((self->fd = shm_open(self->obj, O_RDWR, 0)) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
if ((self->mem = mmap(
NULL,
sizeof(memsink_shared_s),
PROT_READ | PROT_WRITE,
MAP_SHARED,
self->fd,
0
)) == MAP_FAILED) {
if ((self->mem = memsink_shared_map(self->fd)) == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
self->mem = NULL;
goto error;
}
if (self->mem == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Memory mapping is NULL"); \
goto error;
}
if ((self->dict_frame = PyDict_New()) == NULL) {
goto error;
}
@@ -185,23 +142,16 @@ static int wait_frame(MemsinkObject *self) {
RETURN_OS_ERROR;
} else if (retval == 0) {
if (MEM(magic) == MEMSINK_MAGIC && MEM(version) == MEMSINK_VERSION && TMP(id) != MEM(id)) {
if (MEM(magic) == MEMSINK_MAGIC && MEM(version) == MEMSINK_VERSION && MEM(id) != self->frame_id) {
if (self->drop_same_frames > 0) {
# define CMP(_field) (TMP(_field) == MEM(_field))
if (
CMP(used)
&& CMP(width)
&& CMP(height)
&& CMP(format)
&& CMP(stride)
&& CMP(online)
&& (TMP(ts) + self->drop_same_frames > now)
&& !memcmp(TMP(data), MEM(data), MEM(used))
FRAME_COMPARE_META_USED_NOTS(self->mem, self->frame)
&& (self->frame_ts + self->drop_same_frames > now)
&& !memcmp(FRAME(data), MEM(data), MEM(used))
) {
TMP(id) = MEM(id);
self->frame_id = MEM(id);
goto drop;
}
# undef CMP
}
Py_BLOCK_THREADS
@@ -243,64 +193,49 @@ static PyObject *MemsinkObject_wait_frame(MemsinkObject *self, PyObject *Py_UNUS
default: return NULL;
}
# define COPY(_field) TMP(_field) = MEM(_field)
COPY(width);
COPY(height);
COPY(format);
COPY(stride);
COPY(online);
COPY(grab_ts);
COPY(encode_begin_ts);
COPY(encode_end_ts);
COPY(used);
# undef COPY
if (TMP(allocated) < MEM(used)) {
size_t size = MEM(used) + (512 * 1024);
A_REALLOC(TMP(data), size);
TMP(allocated) = size;
}
memcpy(TMP(data), MEM(data), MEM(used));
TMP(used) = MEM(used);
TMP(id) = MEM(id);
TMP(ts) = get_now_monotonic();
MEM(last_client_ts) = TMP(ts);
frame_set_data(self->frame, MEM(data), MEM(used));
FRAME_COPY_META(self->mem, self->frame);
self->frame_id = MEM(id);
self->frame_ts = get_now_monotonic();
MEM(last_client_ts) = self->frame_ts;
if (flock(self->fd, LOCK_UN) < 0) {
return PyErr_SetFromErrno(PyExc_OSError);
}
PyDict_Clear(self->dict_frame);
PyObject *dict_frame = PyDict_New();
if (dict_frame == NULL) {
return NULL;
}
# define SET_VALUE(_key, _maker) { \
PyObject *_tmp = _maker; \
if (_tmp == NULL) { \
return NULL; \
} \
if (PyDict_SetItemString(self->dict_frame, _key, _tmp) < 0) { \
if (PyDict_SetItemString(dict_frame, _key, _tmp) < 0) { \
Py_DECREF(_tmp); \
return NULL; \
} \
Py_DECREF(_tmp); \
}
# define SET_NUMBER(_key, _from, _to) SET_VALUE(#_key, Py##_to##_From##_from(TMP(_key)))
# define SET_NUMBER(_key, _from, _to) SET_VALUE(#_key, Py##_to##_From##_from(FRAME(_key)))
SET_NUMBER(width, Long, Long);
SET_NUMBER(height, Long, Long);
SET_NUMBER(format, Long, Long);
SET_NUMBER(stride, Long, Long);
SET_NUMBER(online, Long, Bool);
SET_NUMBER(key, Long, Bool);
SET_NUMBER(grab_ts, Double, Float);
SET_NUMBER(encode_begin_ts, Double, Float);
SET_NUMBER(encode_end_ts, Double, Float);
SET_VALUE("data", PyBytes_FromStringAndSize((const char *)TMP(data), TMP(used)));
SET_VALUE("data", PyBytes_FromStringAndSize((const char *)FRAME(data), FRAME(used)));
# undef SET_NUMBER
# undef SET_VALUE
Py_INCREF(self->dict_frame);
return self->dict_frame;
return dict_frame;
}
static PyObject *MemsinkObject_is_opened(MemsinkObject *self, PyObject *Py_UNUSED(ignored)) {
@@ -379,5 +314,5 @@ PyMODINIT_FUNC PyInit_ustreamer(void) { // cppcheck-suppress unusedFunction
return module;
}
#undef TMP
#undef FRAME
#undef MEM

108
src/Makefile Normal file
View File

@@ -0,0 +1,108 @@
DESTDIR ?=
PREFIX ?= /usr/local
CC ?= gcc
CFLAGS ?= -O3
LDFLAGS ?=
# =====
_USTR = ustreamer.bin
_DUMP = ustreamer-dump.bin
_CFLAGS = -MD -c -std=c11 -Wall -Wextra -D_GNU_SOURCE $(CFLAGS)
_LDFLAGS = $(LDFLAGS)
_COMMON_LIBS = -lm -ljpeg -pthread -lrt
_USTR_LIBS = $(_COMMON_LIBS) -levent -levent_pthreads
_USTR_SRCS = $(shell ls \
libs/*.c \
ustreamer/*.c \
ustreamer/http/*.c \
ustreamer/data/*.c \
ustreamer/encoders/cpu/*.c \
ustreamer/encoders/hw/*.c \
ustreamer/h264/*.c \
)
_DUMP_LIBS = $(_COMMON_LIBS)
_DUMP_SRCS = $(shell ls \
libs/*.c \
dump/*.c \
)
_BUILD = build
define optbool
$(filter $(shell echo $(1) | tr A-Z a-z), yes on 1)
endef
ifneq ($(call optbool,$(WITH_GPIO)),)
_USTR_LIBS += -lgpiod
override _CFLAGS += -DWITH_GPIO
_USTR_SRCS += $(shell ls ustreamer/gpio/*.c)
endif
ifneq ($(call optbool,$(WITH_SYSTEMD)),)
_USTR_LIBS += -lsystemd
override _CFLAGS += -DWITH_SYSTEMD
_USTR_SRCS += $(shell ls ustreamer/http/systemd/*.c)
endif
WITH_PTHREAD_NP ?= 1
ifneq ($(call optbool,$(WITH_PTHREAD_NP)),)
override _CFLAGS += -DWITH_PTHREAD_NP
endif
WITH_SETPROCTITLE ?= 1
ifneq ($(call optbool,$(WITH_SETPROCTITLE)),)
ifeq ($(shell uname -s | tr A-Z a-z),linux)
_USTR_LIBS += -lbsd
endif
override _CFLAGS += -DWITH_SETPROCTITLE
endif
# =====
all: $(_USTR) $(_DUMP)
install: all
mkdir -p $(DESTDIR)$(PREFIX)/bin
install -m755 $(_USTR) $(DESTDIR)$(PREFIX)/bin/$(subst .bin,,$(_USTR))
install -m755 $(_DUMP) $(DESTDIR)$(PREFIX)/bin/$(subst .bin,,$(_DUMP))
install-strip: install
strip $(DESTDIR)$(PREFIX)/bin/$(subst .bin,,$(_USTR))
strip $(DESTDIR)$(PREFIX)/bin/$(subst .bin,,$(_DUMP))
$(_USTR): $(_USTR_SRCS:%.c=$(_BUILD)/%.o)
$(info == LD $@)
@ $(CC) $^ -o $@ $(_LDFLAGS) $(_USTR_LIBS)
$(_DUMP): $(_DUMP_SRCS:%.c=$(_BUILD)/%.o)
$(info == LD $@)
@ $(CC) $^ -o $@ $(_LDFLAGS) $(_DUMP_LIBS)
$(_BUILD)/%.o: %.c
$(info -- CC $<)
@ mkdir -p $(dir $@) || true
@ $(CC) $< -o $@ $(_CFLAGS)
clean:
rm -rf $(_USTR) $(_DUMP) $(_BUILD)
_OBJS = $(_USTR_SRCS:%.c=$(_BUILD)/%.o) $(_DUMP_SRCS:%.c=$(_BUILD)/%.o)
-include $(_OBJS:%.o=%.d)

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -25,6 +25,8 @@
#include <stdbool.h>
#include <unistd.h>
#include <signal.h>
#include <limits.h>
#include <float.h>
#include <getopt.h>
#include <errno.h>
#include <assert.h>
@@ -44,6 +46,8 @@ enum _OPT_VALUES {
_O_SINK_TIMEOUT = 't',
_O_OUTPUT = 'o',
_O_OUTPUT_JSON = 'j',
_O_COUNT = 'c',
_O_INTERVAL = 'i',
_O_HELP = 'h',
_O_VERSION = 'v',
@@ -61,6 +65,8 @@ static const struct option _LONG_OPTS[] = {
{"sink-timeout", required_argument, NULL, _O_SINK_TIMEOUT},
{"output", required_argument, NULL, _O_OUTPUT},
{"output-json", no_argument, NULL, _O_OUTPUT_JSON},
{"count", required_argument, NULL, _O_COUNT},
{"interval", required_argument, NULL, _O_INTERVAL},
{"log-level", required_argument, NULL, _O_LOG_LEVEL},
{"perf", no_argument, NULL, _O_PERF},
@@ -89,7 +95,10 @@ typedef struct {
static void _signal_handler(int signum);
static void _install_signal_handlers(void);
static int _dump_sink(const char *sink_name, unsigned sink_timeout, _output_context_s *ctx);
static int _dump_sink(
const char *sink_name, unsigned sink_timeout,
long long count, long double interval,
_output_context_s *ctx);
static void _help(FILE *fp);
@@ -102,6 +111,8 @@ int main(int argc, char *argv[]) {
unsigned sink_timeout = 1;
char *output_path = NULL;
bool output_json = false;
long long count = 0;
long double interval = 0;
# define OPT_SET(_dest, _value) { \
_dest = _value; \
@@ -118,6 +129,16 @@ int main(int argc, char *argv[]) {
break; \
}
# define OPT_LDOUBLE(_name, _dest, _min, _max) { \
errno = 0; char *_end = NULL; long double _tmp = strtold(optarg, &_end); \
if (errno || *_end || _tmp < _min || _tmp > _max) { \
printf("Invalid value for '%s=%s': min=%Lf, max=%Lf\n", _name, optarg, (long double)_min, (long double)_max); \
return 1; \
} \
_dest = _tmp; \
break; \
}
char short_opts[128];
build_short_options(_LONG_OPTS, short_opts, 128);
@@ -127,13 +148,15 @@ int main(int argc, char *argv[]) {
case _O_SINK_TIMEOUT: OPT_NUMBER("--sink-timeout", sink_timeout, 1, 60, 0);
case _O_OUTPUT: OPT_SET(output_path, optarg);
case _O_OUTPUT_JSON: OPT_SET(output_json, true);
case _O_COUNT: OPT_NUMBER("--count", count, 0, LLONG_MAX, 0);
case _O_INTERVAL: OPT_LDOUBLE("--interval", interval, 0, 60);
case _O_LOG_LEVEL: OPT_NUMBER("--log-level", log_level, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, 0);
case _O_PERF: OPT_SET(log_level, LOG_LEVEL_PERF);
case _O_VERBOSE: OPT_SET(log_level, LOG_LEVEL_VERBOSE);
case _O_DEBUG: OPT_SET(log_level, LOG_LEVEL_DEBUG);
case _O_FORCE_LOG_COLORS: OPT_SET(log_colored, true);
case _O_NO_LOG_COLORS: OPT_SET(log_colored, false);
case _O_LOG_LEVEL: OPT_NUMBER("--log-level", us_log_level, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, 0);
case _O_PERF: OPT_SET(us_log_level, LOG_LEVEL_PERF);
case _O_VERBOSE: OPT_SET(us_log_level, LOG_LEVEL_VERBOSE);
case _O_DEBUG: OPT_SET(us_log_level, LOG_LEVEL_DEBUG);
case _O_FORCE_LOG_COLORS: OPT_SET(us_log_colored, true);
case _O_NO_LOG_COLORS: OPT_SET(us_log_colored, false);
case _O_HELP: _help(stdout); return 0;
case _O_VERSION: puts(VERSION); return 0;
@@ -143,6 +166,7 @@ int main(int argc, char *argv[]) {
}
}
# undef OPT_LDOUBLE
# undef OPT_NUMBER
# undef OPT_SET
@@ -151,8 +175,7 @@ int main(int argc, char *argv[]) {
return 1;
}
_output_context_s ctx;
MEMSET_ZERO(ctx);
_output_context_s ctx = {0};
if (output_path && output_path[0] != '\0') {
if ((ctx.v_output = (void *)output_file_init(output_path, output_json)) == NULL) {
@@ -163,7 +186,7 @@ int main(int argc, char *argv[]) {
}
_install_signal_handlers();
int retval = abs(_dump_sink(sink_name, sink_timeout, &ctx));
int retval = abs(_dump_sink(sink_name, sink_timeout, count, interval, &ctx));
if (ctx.v_output && ctx.destroy) {
ctx.destroy(ctx.v_output);
}
@@ -182,8 +205,7 @@ static void _signal_handler(int signum) {
}
static void _install_signal_handlers(void) {
struct sigaction sig_act;
MEMSET_ZERO(sig_act);
struct sigaction sig_act = {0};
assert(!sigemptyset(&sig_act.sa_mask));
sig_act.sa_handler = _signal_handler;
@@ -201,8 +223,18 @@ static void _install_signal_handlers(void) {
assert(!sigaction(SIGPIPE, &sig_act, NULL));
}
static int _dump_sink(const char *sink_name, unsigned sink_timeout, _output_context_s *ctx) {
frame_s *frame = frame_init("input");
static int _dump_sink(
const char *sink_name, unsigned sink_timeout,
long long count, long double interval,
_output_context_s *ctx) {
if (count == 0) {
count = -1;
}
useconds_t interval_us = interval * 1000000;
frame_s *frame = frame_init();
memsink_s *sink = NULL;
if ((sink = memsink_init("input", sink_name, false, 0, false, 0, sink_timeout)) == NULL) {
@@ -213,6 +245,8 @@ static int _dump_sink(const char *sink_name, unsigned sink_timeout, _output_cont
unsigned fps_accum = 0;
long long fps_second = 0;
long double last_ts = 0;
while (!global_stop) {
int error = memsink_client_get(sink, frame);
if (error == 0) {
@@ -220,11 +254,12 @@ static int _dump_sink(const char *sink_name, unsigned sink_timeout, _output_cont
const long long now_second = floor_ms(now);
char fourcc_str[8];
LOG_VERBOSE("Frame: size=%zu, resolution=%ux%u, fourcc=%s, stride=%u, online=%d, latency=%.3Lf",
LOG_VERBOSE("Frame: size=%zu, res=%ux%u, fourcc=%s, stride=%u, online=%d, key=%d, latency=%.3Lf, diff=%.3Lf",
frame->used, frame->width, frame->height,
fourcc_to_string(frame->format, fourcc_str, 8),
frame->stride, frame->online,
now - frame->grab_ts);
frame->stride, frame->online, frame->key,
now - frame->grab_ts, (last_ts ? now - last_ts : 0));
last_ts = now;
LOG_DEBUG(" grab_ts=%.3Lf, encode_begin_ts=%.3Lf, encode_end_ts=%.3Lf",
frame->grab_ts, frame->encode_begin_ts, frame->encode_end_ts);
@@ -240,6 +275,17 @@ static int _dump_sink(const char *sink_name, unsigned sink_timeout, _output_cont
if (ctx->v_output) {
ctx->write(ctx->v_output, frame);
}
if (count >= 0) {
--count;
if (count <= 0) {
break;
}
}
if (interval_us > 0) {
usleep(interval_us);
}
} else if (error == -2) {
usleep(1000);
} else {
@@ -268,7 +314,7 @@ static void _help(FILE *fp) {
SAY("\nuStreamer-dump - Dump uStreamer's memory sink to file");
SAY("═════════════════════════════════════════════════════");
SAY("Version: %s; license: GPLv3", VERSION);
SAY("Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com>\n");
SAY("Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com>\n");
SAY("Example:");
SAY("════════");
SAY(" ustreamer-dump --sink test --output - \\");
@@ -279,12 +325,14 @@ static void _help(FILE *fp) {
SAY(" -t|--sink-timeout <sec> ─ Timeout for the upcoming frame. Default: 1.\n");
SAY(" -o|--output <filename> ─── Filename to dump output to. Use '-' for stdout. Default: just consume the sink.\n");
SAY(" -j|--output-json ──────── Format output as JSON. Required option --output. Default: disabled.\n");
SAY(" -c|--count <N> ───────── Limit the number of frames. Default: 0 (infinite).\n");
SAY(" -i|--interval <sec> ───── Delay between reading frames (float). Default: 0.\n");
SAY("Logging options:");
SAY("════════════════");
SAY(" --log-level <N> ──── Verbosity level of messages from 0 (info) to 3 (debug).");
SAY(" Enabling debugging messages can slow down the program.");
SAY(" Available levels: 0 (info), 1 (performance), 2 (verbose), 3 (debug).");
SAY(" Default: %d.\n", log_level);
SAY(" Default: %d.\n", us_log_level);
SAY(" --perf ───────────── Enable performance messages (same as --log-level=1). Default: disabled.\n");
SAY(" --verbose ────────── Enable verbose messages and lower (same as --log-level=2). Default: disabled.\n");
SAY(" --debug ──────────── Enable debug messages and lower (same as --log-level=3). Default: disabled.\n");

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -22,6 +22,11 @@
#pragma once
#ifndef VERSION
# define VERSION "3.13"
#endif
#define VERSION_MAJOR 5
#define VERSION_MINOR 4
#define MAKE_VERSION2(_major, _minor) #_major "." #_minor
#define MAKE_VERSION1(_major, _minor) MAKE_VERSION2(_major, _minor)
#define VERSION MAKE_VERSION1(VERSION_MAJOR, VERSION_MINOR)
#define VERSION_U ((unsigned)(VERSION_MAJOR * 1000 + VERSION_MINOR))

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -23,17 +23,15 @@
#include "frame.h"
frame_s *frame_init(const char *name) {
frame_s *frame_init(void) {
frame_s *frame;
A_CALLOC(frame, 1);
frame->name = name;
frame->managed = true;
frame_realloc_data(frame, 512 * 1024);
frame->dma_fd = -1;
return frame;
}
void frame_destroy(frame_s *frame) {
assert(frame->managed);
if (frame->data) {
free(frame->data);
}
@@ -41,66 +39,36 @@ void frame_destroy(frame_s *frame) {
}
void frame_realloc_data(frame_s *frame, size_t size) {
assert(frame->managed);
if (frame->allocated < size) {
LOG_DEBUG("Increasing frame buffer '%s': %zu -> %zu (+%zu)",
frame->name, frame->allocated, size, size - frame->allocated);
A_REALLOC(frame->data, size);
frame->allocated = size;
}
}
void frame_set_data(frame_s *frame, const uint8_t *data, size_t size) {
assert(frame->managed);
frame_realloc_data(frame, size);
memcpy(frame->data, data, size);
frame->used = size;
}
void frame_append_data(frame_s *frame, const uint8_t *data, size_t size) {
assert(frame->managed);
size_t new_used = frame->used + size;
frame_realloc_data(frame, new_used);
memcpy(frame->data + frame->used, data, size);
frame->used = new_used;
}
#define COPY(_field) dest->_field = src->_field
void frame_copy(const frame_s *src, frame_s *dest) {
assert(dest->managed);
frame_set_data(dest, src->data, src->used);
COPY(used);
frame_copy_meta(src, dest);
FRAME_COPY_META(src, dest);
}
void frame_copy_meta(const frame_s *src, frame_s *dest) {
// Don't copy the name
COPY(width);
COPY(height);
COPY(format);
COPY(stride);
COPY(online);
COPY(grab_ts);
COPY(encode_begin_ts);
COPY(encode_end_ts);
}
#undef COPY
bool frame_compare(const frame_s *a, const frame_s *b) {
# define CMP(_field) (a->_field == b->_field)
return (
a->allocated && b->allocated
&& CMP(used)
&& CMP(width)
&& CMP(height)
&& CMP(format)
&& CMP(stride)
&& CMP(online)
&& FRAME_COMPARE_META_USED_NOTS(a, b)
&& !memcmp(a->data, b->data, b->used)
);
# undef CMP
}
unsigned frame_get_padding(const frame_s *frame) {
@@ -113,7 +81,7 @@ unsigned frame_get_padding(const frame_s *frame) {
// case V4L2_PIX_FMT_H264:
case V4L2_PIX_FMT_MJPEG:
case V4L2_PIX_FMT_JPEG: bytes_per_pixel = 0; break;
default: assert(0 && "Unknown pixelformat");
default: assert(0 && "Unknown format");
}
if (bytes_per_pixel > 0 && frame->stride > frame->width) {
return (frame->stride - frame->width * bytes_per_pixel);

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -32,15 +32,13 @@
#include <linux/videodev2.h>
#include "tools.h"
#include "logging.h"
typedef struct {
const char *name;
uint8_t *data;
size_t used;
size_t allocated;
int dma_fd;
unsigned width;
unsigned height;
@@ -51,16 +49,57 @@ typedef struct {
// https://medium.com/@oleg.shipitko/what-does-stride-mean-in-image-processing-bba158a72bcd
bool online;
bool key;
long double grab_ts;
long double encode_begin_ts;
long double encode_end_ts;
bool managed;
} frame_s;
frame_s *frame_init(const char *name);
#define FRAME_COPY_META(_src, _dest) { \
_dest->width = _src->width; \
_dest->height = _src->height; \
_dest->format = _src->format; \
_dest->stride = _src->stride; \
_dest->online = _src->online; \
_dest->key = _src->key; \
_dest->grab_ts = _src->grab_ts; \
_dest->encode_begin_ts = _src->encode_begin_ts; \
_dest->encode_end_ts = _src->encode_end_ts; \
}
static inline void frame_copy_meta(const frame_s *src, frame_s *dest) {
FRAME_COPY_META(src, dest);
}
#define FRAME_COMPARE_META_USED_NOTS(_a, _b) ( \
_a->used == _b->used \
&& _a->width == _b->width \
&& _a->height == _b->height \
&& _a->format == _b->format \
&& _a->stride == _b->stride \
&& _a->online == _b->online \
&& _a->key == _b->key \
)
static inline void frame_encoding_begin(const frame_s *src, frame_s *dest, unsigned format) {
assert(src->used > 0);
frame_copy_meta(src, dest);
dest->encode_begin_ts = get_now_monotonic();
dest->format = format;
dest->stride = 0;
dest->used = 0;
}
static inline void frame_encoding_end(frame_s *dest) {
assert(dest->used > 0);
dest->encode_end_ts = get_now_monotonic();
}
frame_s *frame_init(void);
void frame_destroy(frame_s *frame);
void frame_realloc_data(frame_s *frame, size_t size);
@@ -68,13 +107,12 @@ void frame_set_data(frame_s *frame, const uint8_t *data, size_t size);
void frame_append_data(frame_s *frame, const uint8_t *data, size_t size);
void frame_copy(const frame_s *src, frame_s *dest);
void frame_copy_meta(const frame_s *src, frame_s *dest);
bool frame_compare(const frame_s *a, const frame_s *b);
unsigned frame_get_padding(const frame_s *frame);
const char *fourcc_to_string(unsigned format, char *buf, size_t size);
inline bool is_jpeg(unsigned format) {
static inline bool is_jpeg(unsigned format) {
return (format == V4L2_PIX_FMT_JPEG || format == V4L2_PIX_FMT_MJPEG);
}

71
src/libs/list.h Normal file
View File

@@ -0,0 +1,71 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
# #
*****************************************************************************/
#pragma once
#include <assert.h>
#define LIST_STRUCT(...) \
__VA_ARGS__ *prev; \
__VA_ARGS__ *next;
#define LIST_ITERATE(_first, _item, ...) { \
for (__typeof__(_first) _item = _first; _item;) { \
__typeof__(_first) _next = _item->next; \
__VA_ARGS__ \
_item = _next; \
} \
}
#define LIST_APPEND(_first, _item) { \
if (_first == NULL) { \
_first = _item; \
} else { \
__typeof__(_first) _last = _first; \
for (; _last->next; _last = _last->next); \
_item->prev = _last; \
_last->next = _item; \
} \
}
#define LIST_APPEND_C(_first, _item, _count) { \
LIST_APPEND(_first, _item); \
++(_count); \
}
#define LIST_REMOVE(_first, _item) { \
if (_item->prev == NULL) { \
_first = _item->next; \
} else { \
_item->prev->next = _item->next; \
} \
if (_item->next != NULL) { \
_item->next->prev = _item->prev; \
} \
}
#define LIST_REMOVE_C(_first, _item, _count) { \
LIST_REMOVE(_first, _item); \
assert((_count) >= 1); \
--(_count); \
}

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -23,8 +23,8 @@
#include "logging.h"
enum log_level_t log_level;
enum log_level_t us_log_level;
bool log_colored;
bool us_log_colored;
pthread_mutex_t log_mutex;
pthread_mutex_t us_log_mutex;

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -45,23 +45,23 @@ enum log_level_t {
};
extern enum log_level_t log_level;
extern enum log_level_t us_log_level;
extern bool log_colored;
extern bool us_log_colored;
extern pthread_mutex_t log_mutex;
extern pthread_mutex_t us_log_mutex;
#define LOGGING_INIT { \
log_level = LOG_LEVEL_INFO; \
log_colored = isatty(2); \
A_MUTEX_INIT(&log_mutex); \
us_log_level = LOG_LEVEL_INFO; \
us_log_colored = isatty(2); \
A_MUTEX_INIT(&us_log_mutex); \
}
#define LOGGING_DESTROY A_MUTEX_DESTROY(&log_mutex)
#define LOGGING_DESTROY A_MUTEX_DESTROY(&us_log_mutex)
#define LOGGING_LOCK A_MUTEX_LOCK(&log_mutex)
#define LOGGING_UNLOCK A_MUTEX_UNLOCK(&log_mutex)
#define LOGGING_LOCK A_MUTEX_LOCK(&us_log_mutex)
#define LOGGING_UNLOCK A_MUTEX_UNLOCK(&us_log_mutex)
#define COLOR_GRAY "\x1b[30;1m"
@@ -84,7 +84,7 @@ extern pthread_mutex_t log_mutex;
}
#define SEP_DEBUG(_ch) { \
if (log_level >= LOG_LEVEL_DEBUG) { \
if (us_log_level >= LOG_LEVEL_DEBUG) { \
SEP_INFO(_ch); \
} \
}
@@ -93,7 +93,7 @@ extern pthread_mutex_t log_mutex;
#define LOG_PRINTF_NOLOCK(_label_color, _label, _msg_color, _msg, ...) { \
char _tname_buf[MAX_THREAD_NAME] = {0}; \
thread_get_name(_tname_buf); \
if (log_colored) { \
if (us_log_colored) { \
fprintf(stderr, COLOR_GRAY "-- " _label_color _label COLOR_GRAY \
" [%.03Lf %9s]" " -- " COLOR_RESET _msg_color _msg COLOR_RESET, \
get_now_monotonic(), _tname_buf, ##__VA_ARGS__); \
@@ -130,25 +130,25 @@ extern pthread_mutex_t log_mutex;
}
#define LOG_PERF(_msg, ...) { \
if (log_level >= LOG_LEVEL_PERF) { \
if (us_log_level >= LOG_LEVEL_PERF) { \
LOG_PRINTF(COLOR_CYAN, "PERF ", COLOR_CYAN, _msg, ##__VA_ARGS__); \
} \
}
#define LOG_PERF_FPS(_msg, ...) { \
if (log_level >= LOG_LEVEL_PERF) { \
if (us_log_level >= LOG_LEVEL_PERF) { \
LOG_PRINTF(COLOR_YELLOW, "PERF ", COLOR_YELLOW, _msg, ##__VA_ARGS__); \
} \
}
#define LOG_VERBOSE(_msg, ...) { \
if (log_level >= LOG_LEVEL_VERBOSE) { \
if (us_log_level >= LOG_LEVEL_VERBOSE) { \
LOG_PRINTF(COLOR_BLUE, "VERB ", COLOR_BLUE, _msg, ##__VA_ARGS__); \
} \
}
#define LOG_VERBOSE_PERROR(_msg, ...) { \
if (log_level >= LOG_LEVEL_VERBOSE) { \
if (us_log_level >= LOG_LEVEL_VERBOSE) { \
char _perror_buf[1024] = {0}; \
char *_perror_ptr = errno_to_string(errno, _perror_buf, 1023); \
LOG_PRINTF(COLOR_BLUE, "VERB ", COLOR_BLUE, _msg ": %s", ##__VA_ARGS__, _perror_ptr); \
@@ -156,17 +156,7 @@ extern pthread_mutex_t log_mutex;
}
#define LOG_DEBUG(_msg, ...) { \
if (log_level >= LOG_LEVEL_DEBUG) { \
if (us_log_level >= LOG_LEVEL_DEBUG) { \
LOG_PRINTF(COLOR_GRAY, "DEBUG", COLOR_GRAY, _msg, ##__VA_ARGS__); \
} \
}
INLINE char *errno_to_string(int error, char *buf, size_t size) {
# if defined(__GLIBC__) && defined(_GNU_SOURCE)
return strerror_r(error, buf, size);
# else
strerror_r(error, buf, size);
return buf;
# endif
}

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -37,6 +37,7 @@ memsink_s *memsink_init(
sink->timeout = timeout;
sink->fd = -1;
sink->mem = MAP_FAILED;
atomic_init(&sink->has_clients, false);
LOG_INFO("Using %s-sink: %s", name, obj);
@@ -54,14 +55,7 @@ memsink_s *memsink_init(
goto error;
}
if ((sink->mem = mmap(
NULL,
sizeof(memsink_shared_s),
PROT_READ | PROT_WRITE,
MAP_SHARED,
sink->fd,
0
)) == MAP_FAILED) {
if ((sink->mem = memsink_shared_map(sink->fd)) == NULL) {
LOG_PERROR("%s-sink: Can't mmap shared memory", name);
goto error;
}
@@ -75,7 +69,7 @@ memsink_s *memsink_init(
void memsink_destroy(memsink_s *sink) {
if (sink->mem != MAP_FAILED) {
if (munmap(sink->mem, sizeof(memsink_shared_s)) < 0) {
if (memsink_shared_unmap(sink->mem) < 0) {
LOG_PERROR("%s-sink: Can't unmap shared memory", sink->name);
}
}
@@ -93,30 +87,35 @@ void memsink_destroy(memsink_s *sink) {
}
bool memsink_server_check(memsink_s *sink, const frame_s *frame) {
// Возвращает true, если если клиенты ИЛИ изменились метаданные
// Return true (the need to write to memsink) on any of these conditions:
// - EWOULDBLOCK - we have an active client;
// - Incorrect magic or version - need to first write;
// - We have some active clients by last_client_ts;
// - Frame meta differs (like size, format, but not timestamp).
assert(sink->server);
if (flock(sink->fd, LOCK_EX | LOCK_NB) < 0) {
if (errno == EWOULDBLOCK) {
sink->has_clients = true;
atomic_store(&sink->has_clients, true);
return true;
}
LOG_PERROR("%s-sink: Can't lock memory", sink->name);
return false;
}
sink->has_clients = (sink->mem->last_client_ts + sink->client_ttl > get_now_monotonic());
if (sink->mem->magic != MEMSINK_MAGIC || sink->mem->version != MEMSINK_VERSION) {
return true;
}
# define NEQ(_field) (sink->mem->_field != frame->_field)
bool retval = (sink->has_clients || NEQ(width) || NEQ(height) || NEQ(format) || NEQ(stride) || NEQ(online));
# undef NEQ
bool has_clients = (sink->mem->last_client_ts + sink->client_ttl > get_now_monotonic());
atomic_store(&sink->has_clients, has_clients);
if (flock(sink->fd, LOCK_UN) < 0) {
LOG_PERROR("%s-sink: Can't unlock memory", sink->name);
return false;
}
return retval;
return (has_clients || !FRAME_COMPARE_META_USED_NOTS(sink->mem, frame));;
}
int memsink_server_put(memsink_s *sink, const frame_s *frame) {
@@ -133,23 +132,16 @@ int memsink_server_put(memsink_s *sink, const frame_s *frame) {
if (flock_timedwait_monotonic(sink->fd, 1) == 0) {
LOG_VERBOSE("%s-sink: >>>>> Exposing new frame ...", sink->name);
# define COPY(_field) sink->mem->_field = frame->_field
sink->last_id = get_now_id();
sink->mem->id = sink->last_id;
COPY(used);
COPY(width);
COPY(height);
COPY(format);
COPY(stride);
COPY(online);
COPY(grab_ts);
COPY(encode_begin_ts);
COPY(encode_end_ts);
sink->has_clients = (sink->mem->last_client_ts + sink->client_ttl > get_now_monotonic());
memcpy(sink->mem->data, frame->data, frame->used);
sink->mem->used = frame->used;
FRAME_COPY_META(frame, sink->mem);
sink->mem->magic = MEMSINK_MAGIC;
sink->mem->version = MEMSINK_VERSION;
# undef COPY
atomic_store(&sink->has_clients, (sink->mem->last_client_ts + sink->client_ttl > get_now_monotonic()));
if (flock(sink->fd, LOCK_UN) < 0) {
LOG_PERROR("%s-sink: Can't unlock memory", sink->name);
@@ -188,18 +180,9 @@ int memsink_client_get(memsink_s *sink, frame_s *frame) { // cppcheck-suppress u
goto done;
}
if (sink->mem->id != sink->last_id) { // When updated
# define COPY(_field) frame->_field = sink->mem->_field
sink->last_id = sink->mem->id;
COPY(width);
COPY(height);
COPY(format);
COPY(stride);
COPY(online);
COPY(grab_ts);
COPY(encode_begin_ts);
COPY(encode_end_ts);
frame_set_data(frame, sink->mem->data, sink->mem->used);
# undef COPY
FRAME_COPY_META(sink->mem, frame);
retval = 0;
}
sink->mem->last_client_ts = get_now_monotonic();

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -24,6 +24,7 @@
#include <stdint.h>
#include <stdbool.h>
#include <stdatomic.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
@@ -51,7 +52,7 @@ typedef struct {
int fd;
memsink_shared_s *mem;
uint64_t last_id;
bool has_clients; // Only for server
atomic_bool has_clients; // Only for server
} memsink_s;

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -26,10 +26,11 @@
#include <stdbool.h>
#include <sys/types.h>
#include <sys/mman.h>
#define MEMSINK_MAGIC ((uint64_t)0xCAFEBABECAFEBABE)
#define MEMSINK_VERSION ((uint32_t)1)
#define MEMSINK_VERSION ((uint32_t)2)
#ifndef CFG_MEMSINK_MAX_DATA
# define CFG_MEMSINK_MAX_DATA 33554432
@@ -49,6 +50,7 @@ typedef struct {
unsigned format;
unsigned stride;
bool online;
bool key;
long double grab_ts;
long double encode_begin_ts;
@@ -58,3 +60,25 @@ typedef struct {
uint8_t data[MEMSINK_MAX_DATA];
} memsink_shared_s;
INLINE memsink_shared_s *memsink_shared_map(int fd) {
memsink_shared_s *mem = mmap(
NULL,
sizeof(memsink_shared_s),
PROT_READ | PROT_WRITE,
MAP_SHARED,
fd,
0
);
if (mem == MAP_FAILED) {
return NULL;
}
assert(mem != NULL);
return mem;
}
INLINE int memsink_shared_unmap(memsink_shared_s *mem) {
assert(mem != NULL);
return munmap(mem, sizeof(memsink_shared_s));
}

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -137,3 +137,11 @@ INLINE void process_notify_parent(void) {
LOG_PERROR("Can't send SIGUSR2 to the parent process %d", parent);
}
}
INLINE void process_suicide(void) {
pid_t pid = getpid();
if (kill(pid, SIGTERM) < 0) {
LOG_PERROR("Can't send SIGTERM to own pid %d", pid);
}
}

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -26,7 +26,10 @@
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <locale.h>
#include <errno.h>
#include <math.h>
#include <time.h>
@@ -35,17 +38,30 @@
#include <sys/file.h>
#define A_CALLOC(_dest, _nmemb) assert((_dest = calloc(_nmemb, sizeof(*(_dest)))))
#define A_REALLOC(_dest, _nmemb) assert((_dest = realloc(_dest, _nmemb * sizeof(*(_dest)))))
#define MEMSET_ZERO(_obj) memset(&(_obj), 0, sizeof(_obj))
#ifdef NDEBUG
# error WTF dude? Asserts are good things!
#endif
#define ARRAY_LEN(_array) (sizeof(_array) / sizeof(_array[0]))
#if CHAR_BIT != 8
# error There are not 8 bits in a char!
#endif
#define RN "\r\n"
#define INLINE inline __attribute__((always_inline))
#define UNUSED __attribute__((unused))
#define A_CALLOC(_dest, _nmemb) assert((_dest = calloc(_nmemb, sizeof(*(_dest)))))
#define A_REALLOC(_dest, _nmemb) assert((_dest = realloc(_dest, _nmemb * sizeof(*(_dest)))))
#define MEMSET_ZERO(_obj) memset(&(_obj), 0, sizeof(_obj))
INLINE char *bool_to_string(bool flag) {
#define A_ASPRINTF(_dest, _fmt, ...) assert(asprintf(&(_dest), _fmt, ##__VA_ARGS__) >= 0)
#define ARRAY_LEN(_array) (sizeof(_array) / sizeof(_array[0]))
INLINE const char *bool_to_string(bool flag) {
return (flag ? "true" : "false");
}
@@ -104,10 +120,14 @@ INLINE long double get_now_monotonic(void) {
return (long double)sec + ((long double)msec) / 1000;
}
INLINE uint64_t get_now_id(void) {
INLINE uint64_t get_now_monotonic_u64(void) {
struct timespec ts;
assert(!clock_gettime(X_CLOCK_MONOTONIC, &ts));
uint64_t now = (uint64_t)(ts.tv_nsec / 1000) + (uint64_t)ts.tv_sec * 1000000;
return (uint64_t)(ts.tv_nsec / 1000) + (uint64_t)ts.tv_sec * 1000000;
}
INLINE uint64_t get_now_id(void) {
uint64_t now = get_now_monotonic_u64();
return (uint64_t)triple_u32(now) | ((uint64_t)triple_u32(now + 12345) << 32);
}
@@ -141,3 +161,16 @@ INLINE int flock_timedwait_monotonic(int fd, long double timeout) {
}
return retval;
}
INLINE char *errno_to_string(int error, char *buf, size_t size) {
assert(buf);
assert(size > 0);
locale_t locale = newlocale(LC_MESSAGES_MASK, "C", NULL);
char *str = "!!! newlocale() error !!!";
strncpy(buf, (locale ? strerror_l(error, locale) : str), size - 1);
buf[size - 1] = '\0';
if (locale) {
freelocale(locale);
}
return buf;
}

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -87,6 +87,6 @@ static void _jpeg_error_handler(j_common_ptr jpeg) {
char msg[JMSG_LENGTH_MAX];
(*jpeg_error->mgr.format_message)(jpeg, msg);
LOG_ERROR("Can't decompress %s JPEG: %s", jpeg_error->frame->name, msg);
LOG_ERROR("Can't decompress JPEG: %s", msg);
longjmp(jpeg_error->jmp, -1);
}

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -44,7 +44,7 @@ frame_s *blank_frame_init(const char *path) {
}
static frame_s *_init_internal(void) {
frame_s *blank = frame_init("blank_internal");
frame_s *blank = frame_init();
frame_set_data(blank, BLANK_JPEG_DATA, BLANK_JPEG_DATA_SIZE);
blank->width = BLANK_JPEG_WIDTH;
blank->height = BLANK_JPEG_HEIGHT;
@@ -55,7 +55,7 @@ static frame_s *_init_internal(void) {
static frame_s *_init_external(const char *path) {
FILE *fp = NULL;
frame_s *blank = frame_init("blank_external");
frame_s *blank = frame_init();
blank->format = V4L2_PIX_FMT_JPEG;
if ((fp = fopen(path, "rb")) == NULL) {
@@ -83,7 +83,7 @@ static frame_s *_init_external(const char *path) {
}
# undef CHUNK_SIZE
frame_s *decoded = frame_init("blank_external_decoded");
frame_s *decoded = frame_init();
if (unjpeg(blank, decoded, false) < 0) {
frame_destroy(decoded);
goto error;

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -12,30 +12,30 @@
<hr>
<ul>
<li>
<a href="/state"><b>/state</b></a><br>
<a href="state"><b>/state</b></a><br>
Get JSON structure with the state of the server.
</li>
<br>
<li>
<a href="/snapshot"><b>/snapshot</b></a><br>
<a href="snapshot"><b>/snapshot</b></a><br>
Get a current actual image from the server.
</li>
<br>
<li>
<a href="/stream"><b>/stream</b></a><br>
<a href="stream"><b>/stream</b></a><br>
Get a live stream. Query params:<br>
<br>
<ul>
<li>
<b>key=abc123</b><br>
The user-defined key, which is part of cookie <i>stream_client</i>, which allows<br>
the stream client to determine its identifier and view statistics using <a href="/state">/state</a>.
the stream client to determine its identifier and view statistics using <a href="state">/state</a>.
</li>
<br>
<li>
<b>extra_headers=1</b><br>
Add <i>X-UStreamer-*</i> headers to the <a href="/stream">/stream</a> handle
(like with the <a href="/snapshot">/snapshot</a>).
Add <i>X-UStreamer-*</i> headers to the <a href="stream">/stream</a> handle
(like with the <a href="snapshot">/snapshot</a>).
</li>
<br>
<li>
@@ -62,9 +62,9 @@
The mjpg-streamer compatibility layer:<br>
<br>
<ul>
<li><a href="/?action=snapshot">/?action=snapshot</a> as alias to the <a href="/snapshot">/snapshot</a>.</li>
<li><a href="?action=snapshot">/?action=snapshot</a> as alias to the <a href="snapshot">/snapshot</a>.</li>
<br>
<li><a href="/?action=stream">/?action=stream</a> as alias to the <a href="/stream">/stream</a>.</li>
<li><a href="?action=stream">/?action=stream</a> as alias to the <a href="stream">/stream</a>.</li>
</ul>
</li>
</ul>

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -37,30 +37,30 @@ const char *const HTML_INDEX_PAGE = " \
<hr> \
<ul> \
<li> \
<a href=\"/state\"><b>/state</b></a><br> \
<a href=\"state\"><b>/state</b></a><br> \
Get JSON structure with the state of the server. \
</li> \
<br> \
<li> \
<a href=\"/snapshot\"><b>/snapshot</b></a><br> \
<a href=\"snapshot\"><b>/snapshot</b></a><br> \
Get a current actual image from the server. \
</li> \
<br> \
<li> \
<a href=\"/stream\"><b>/stream</b></a><br> \
<a href=\"stream\"><b>/stream</b></a><br> \
Get a live stream. Query params:<br> \
<br> \
<ul> \
<li> \
<b>key=abc123</b><br> \
The user-defined key, which is part of cookie <i>stream_client</i>, which allows<br> \
the stream client to determine its identifier and view statistics using <a href=\"/state\">/state</a>. \
the stream client to determine its identifier and view statistics using <a href=\"state\">/state</a>. \
</li> \
<br> \
<li> \
<b>extra_headers=1</b><br> \
Add <i>X-UStreamer-*</i> headers to the <a href=\"/stream\">/stream</a> handle \
(like with the <a href=\"/snapshot\">/snapshot</a>). \
Add <i>X-UStreamer-*</i> headers to the <a href=\"stream\">/stream</a> handle \
(like with the <a href=\"snapshot\">/snapshot</a>). \
</li> \
<br> \
<li> \
@@ -87,9 +87,9 @@ const char *const HTML_INDEX_PAGE = " \
The mjpg-streamer compatibility layer:<br> \
<br> \
<ul> \
<li><a href=\"/?action=snapshot\">/?action=snapshot</a> as alias to the <a href=\"/snapshot\">/snapshot</a>.</li> \
<li><a href=\"?action=snapshot\">/?action=snapshot</a> as alias to the <a href=\"snapshot\">/snapshot</a>.</li> \
<br> \
<li><a href=\"/?action=stream\">/?action=stream</a> as alias to the <a href=\"/stream\">/stream</a>.</li> \
<li><a href=\"?action=stream\">/?action=stream</a> as alias to the <a href=\"stream\">/stream</a>.</li> \
</ul> \
</li> \
</ul> \

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -41,7 +41,7 @@ static const struct {
{"UYVY", V4L2_PIX_FMT_UYVY},
{"RGB565", V4L2_PIX_FMT_RGB565},
{"RGB24", V4L2_PIX_FMT_RGB24},
{"JPEG", V4L2_PIX_FMT_MJPEG},
{"MJPEG", V4L2_PIX_FMT_MJPEG},
{"JPEG", V4L2_PIX_FMT_JPEG},
};
@@ -178,21 +178,15 @@ void device_close(device_s *dev) {
for (unsigned index = 0; index < RUN(n_bufs); ++index) {
# define HW(_next) RUN(hw_bufs)[index]._next
# ifdef WITH_OMX
if (HW(vcsm_handle) > 0) {
vcsm_free(HW(vcsm_handle));
HW(vcsm_handle) = -1;
}
if (HW(dma_fd) >= 0) {
close(HW(dma_fd));
HW(dma_fd) = -1;
}
# endif
if (dev->io_method == V4L2_MEMORY_MMAP) {
if (HW(raw.allocated) > 0 && HW(raw.data) != MAP_FAILED) {
if (munmap(HW(raw.data), HW(raw.allocated)) < 0) {
LOG_PERROR("Can't unmap device buffer %u", index);
LOG_PERROR("Can't unmap device buffer=%u", index);
}
}
} else { // V4L2_MEMORY_USERPTR
@@ -200,7 +194,6 @@ void device_close(device_s *dev) {
free(HW(raw.data));
}
}
A_MUTEX_DESTROY(&HW(grabbed_mutex));
# undef HW
}
@@ -220,41 +213,26 @@ void device_close(device_s *dev) {
}
}
#ifdef WITH_OMX
int device_export_to_vcsm(device_s *dev) {
int device_export_to_dma(device_s *dev) {
# define DMA_FD RUN(hw_bufs[index].dma_fd)
# define VCSM_HANDLE RUN(hw_bufs[index].vcsm_handle)
for (unsigned index = 0; index < RUN(n_bufs); ++index) {
struct v4l2_exportbuffer exp;
MEMSET_ZERO(exp);
struct v4l2_exportbuffer exp = {0};
exp.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
exp.index = index;
LOG_DEBUG("Calling ioctl(VIDIOC_EXPBUF) for buffer index=%u ...", index);
LOG_DEBUG("Exporting device buffer=%u to DMA ...", index);
if (xioctl(RUN(fd), VIDIOC_EXPBUF, &exp) < 0) {
LOG_PERROR("Unable to export device buffer index=%u", index);
LOG_PERROR("Can't export device buffer=%u to DMA", index);
goto error;
}
DMA_FD = exp.fd;
LOG_DEBUG("Importing DMA buffer fd=%d into VCSM ...", DMA_FD);
int vcsm_handle = vcsm_import_dmabuf(DMA_FD, "v4l2_buf");
if (vcsm_handle <= 0) {
LOG_PERROR("Unable to import DMA buffer fd=%d into VCSM", DMA_FD);
goto error;
}
VCSM_HANDLE = vcsm_handle;
}
return 0;
error:
for (unsigned index = 0; index < RUN(n_bufs); ++index) {
if (VCSM_HANDLE > 0) {
vcsm_free(VCSM_HANDLE);
VCSM_HANDLE = -1;
}
if (DMA_FD >= 0) {
close(DMA_FD);
DMA_FD = -1;
@@ -262,18 +240,16 @@ int device_export_to_vcsm(device_s *dev) {
}
return -1;
# undef VCSM_HANDLE
# undef DMA_FD
}
#endif
int device_switch_capturing(device_s *dev, bool enable) {
if (enable != RUN(capturing)) {
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
LOG_DEBUG("Calling ioctl(%s) ...", (enable ? "VIDIOC_STREAMON" : "VIDIOC_STREAMOFF"));
LOG_DEBUG("%s device capturing ...", (enable ? "Starting" : "Stopping"));
if (xioctl(RUN(fd), (enable ? VIDIOC_STREAMON : VIDIOC_STREAMOFF), &type) < 0) {
LOG_PERROR("Unable to %s capturing", (enable ? "start" : "stop"));
LOG_PERROR("Can't %s capturing", (enable ? "start" : "stop"));
if (enable) {
return -1;
}
@@ -282,7 +258,7 @@ int device_switch_capturing(device_s *dev, bool enable) {
RUN(capturing) = enable;
LOG_INFO("Capturing %s", (enable ? "started" : "stopped"));
}
return 0;
return 0;
}
int device_select(device_s *dev, bool *has_read, bool *has_write, bool *has_error) {
@@ -334,23 +310,20 @@ int device_select(device_s *dev, bool *has_read, bool *has_write, bool *has_erro
int device_grab_buffer(device_s *dev, hw_buffer_s **hw) {
*hw = NULL;
struct v4l2_buffer buf_info;
MEMSET_ZERO(buf_info);
buf_info.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf_info.memory = dev->io_method;
struct v4l2_buffer buf = {0};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = dev->io_method;
LOG_DEBUG("Grabbing device buffer ...");
if (xioctl(RUN(fd), VIDIOC_DQBUF, &buf_info) < 0) {
LOG_PERROR("Unable to grab device buffer");
if (xioctl(RUN(fd), VIDIOC_DQBUF, &buf) < 0) {
LOG_PERROR("Can't grab device buffer");
return -1;
}
LOG_DEBUG("Grabbed new frame in device buffer: index=%u, bytesused=%u",
buf_info.index, buf_info.bytesused);
LOG_DEBUG("Grabbed new frame: buffer=%u, bytesused=%u", buf.index, buf.bytesused);
if (buf_info.index >= RUN(n_bufs)) {
LOG_ERROR("V4L2 error: grabbed invalid device buffer: index=%u, n_bufs=%u",
buf_info.index, RUN(n_bufs));
if (buf.index >= RUN(n_bufs)) {
LOG_ERROR("V4L2 error: grabbed invalid device buffer=%u, n_bufs=%u", buf.index, RUN(n_bufs));
return -1;
}
@@ -359,61 +332,56 @@ int device_grab_buffer(device_s *dev, hw_buffer_s **hw) {
// The good thing is such frames are quite small compared to the regular frames.
// For example a VGA (640x480) webcam frame is normally >= 8kByte large,
// corrupted frames are smaller.
if (buf_info.bytesused < dev->min_frame_size) {
LOG_DEBUG("Dropped too small frame sized %d bytes, assuming it was broken", buf_info.bytesused);
LOG_DEBUG("Releasing device buffer index=%u (broken frame) ...", buf_info.index);
if (xioctl(RUN(fd), VIDIOC_QBUF, &buf_info) < 0) {
LOG_PERROR("Unable to release device buffer index=%u (broken frame)", buf_info.index);
if (buf.bytesused < dev->min_frame_size) {
LOG_DEBUG("Dropped too small frame, assuming it was broken: buffer=%u, bytesused=%u",
buf.index, buf.bytesused);
LOG_DEBUG("Releasing device buffer=%u (broken frame) ...", buf.index);
if (xioctl(RUN(fd), VIDIOC_QBUF, &buf) < 0) {
LOG_PERROR("Can't release device buffer=%u (broken frame)", buf.index);
return -1;
}
return -2;
}
# define HW(_next) RUN(hw_bufs)[buf_info.index]._next
# define HW(_next) RUN(hw_bufs)[buf.index]._next
A_MUTEX_LOCK(&HW(grabbed_mutex));
if (HW(grabbed)) {
LOG_ERROR("V4L2 error: grabbed device buffer is already used: index=%u, bytesused=%u",
buf_info.index, buf_info.bytesused);
A_MUTEX_UNLOCK(&HW(grabbed_mutex));
LOG_ERROR("V4L2 error: grabbed device buffer=%u is already used", buf.index);
return -1;
}
HW(grabbed) = true;
A_MUTEX_UNLOCK(&HW(grabbed_mutex));
HW(raw.used) = buf_info.bytesused;
HW(raw.dma_fd) = HW(dma_fd);
HW(raw.used) = buf.bytesused;
HW(raw.width) = RUN(width);
HW(raw.height) = RUN(height);
HW(raw.format) = RUN(format);
HW(raw.stride) = RUN(stride);
HW(raw.online) = true;
memcpy(&HW(buf_info), &buf_info, sizeof(struct v4l2_buffer));
memcpy(&HW(buf), &buf, sizeof(struct v4l2_buffer));
HW(raw.grab_ts) = get_now_monotonic();
# undef HW
*hw = &RUN(hw_bufs[buf_info.index]);
return buf_info.index;
*hw = &RUN(hw_bufs[buf.index]);
return buf.index;
}
int device_release_buffer(device_s *dev, hw_buffer_s *hw) {
const unsigned index = hw->buf_info.index;
LOG_DEBUG("Releasing device buffer index=%u ...", index);
const unsigned index = hw->buf.index;
LOG_DEBUG("Releasing device buffer=%u ...", index);
A_MUTEX_LOCK(&hw->grabbed_mutex);
if (xioctl(RUN(fd), VIDIOC_QBUF, &hw->buf_info) < 0) {
LOG_PERROR("Unable to release device buffer index=%u", index);
A_MUTEX_UNLOCK(&hw->grabbed_mutex);
if (xioctl(RUN(fd), VIDIOC_QBUF, &hw->buf) < 0) {
LOG_PERROR("Can't release device buffer=%u", index);
return -1;
}
hw->grabbed = false;
A_MUTEX_UNLOCK(&hw->grabbed_mutex);
return 0;
}
int device_consume_event(device_s *dev) {
struct v4l2_event event;
LOG_DEBUG("Calling ioctl(VIDIOC_DQEVENT) ...");
LOG_DEBUG("Consuming V4L2 event ...");
if (xioctl(RUN(fd), VIDIOC_DQEVENT, &event) == 0) {
switch (event.type) {
case V4L2_EVENT_SOURCE_CHANGE:
@@ -430,22 +398,21 @@ int device_consume_event(device_s *dev) {
}
static int _device_open_check_cap(device_s *dev) {
struct v4l2_capability cap;
MEMSET_ZERO(cap);
struct v4l2_capability cap = {0};
LOG_DEBUG("Calling ioctl(VIDIOC_QUERYCAP) ...");
LOG_DEBUG("Querying device capabilities ...");
if (xioctl(RUN(fd), VIDIOC_QUERYCAP, &cap) < 0) {
LOG_PERROR("Can't query device (VIDIOC_QUERYCAP)");
LOG_PERROR("Can't query device capabilities");
return -1;
}
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
LOG_ERROR("Video capture not supported by the device");
LOG_ERROR("Video capture is not supported by device");
return -1;
}
if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
LOG_ERROR("Device does not support streaming IO");
LOG_ERROR("Device doesn't support streaming IO");
return -1;
}
@@ -471,20 +438,18 @@ static int _device_open_check_cap(device_s *dev) {
static int _device_open_dv_timings(device_s *dev) {
_device_apply_resolution(dev, dev->width, dev->height);
if (dev->dv_timings) {
LOG_DEBUG("Using DV timings");
LOG_DEBUG("Using DV-timings");
if (_device_apply_dv_timings(dev) < 0) {
return -1;
}
struct v4l2_event_subscription sub;
MEMSET_ZERO(sub);
struct v4l2_event_subscription sub = {0};
sub.type = V4L2_EVENT_SOURCE_CHANGE;
LOG_DEBUG("Calling ioctl(VIDIOC_SUBSCRIBE_EVENT) ...");
LOG_DEBUG("Subscribing to DV-timings events ...")
if (xioctl(RUN(fd), VIDIOC_SUBSCRIBE_EVENT, &sub) < 0) {
LOG_PERROR("Can't subscribe to V4L2_EVENT_SOURCE_CHANGE");
LOG_PERROR("Can't subscribe to DV-timings events");
return -1;
}
}
@@ -492,17 +457,30 @@ static int _device_open_dv_timings(device_s *dev) {
}
static int _device_apply_dv_timings(device_s *dev) {
struct v4l2_dv_timings dv;
MEMSET_ZERO(dv);
struct v4l2_dv_timings dv = {0};
LOG_DEBUG("Calling ioctl(VIDIOC_QUERY_DV_TIMINGS) ...");
if (xioctl(RUN(fd), VIDIOC_QUERY_DV_TIMINGS, &dv) == 0) {
LOG_INFO("Got new DV timings: resolution=%ux%u, pixclk=%llu",
dv.bt.width, dv.bt.height, (unsigned long long)dv.bt.pixelclock); // Issue #11
if (dv.type == V4L2_DV_BT_656_1120) {
// See v4l2_print_dv_timings() in the kernel
unsigned htot = V4L2_DV_BT_FRAME_WIDTH(&dv.bt);
unsigned vtot = V4L2_DV_BT_FRAME_HEIGHT(&dv.bt);
if (dv.bt.interlaced) {
vtot /= 2;
}
unsigned fps = ((htot * vtot) > 0 ? ((100 * (uint64_t)dv.bt.pixelclock)) / (htot * vtot) : 0);
LOG_INFO("Got new DV-timings: %ux%u%s%u.%02u, pixclk=%llu, vsync=%u, hsync=%u",
dv.bt.width, dv.bt.height, (dv.bt.interlaced ? "i" : "p"), fps / 100, fps % 100,
(unsigned long long)dv.bt.pixelclock, dv.bt.vsync, dv.bt.hsync); // See #11 about %llu
} else {
LOG_INFO("Got new DV-timings: %ux%u, pixclk=%llu, vsync=%u, hsync=%u",
dv.bt.width, dv.bt.height,
(unsigned long long)dv.bt.pixelclock, dv.bt.vsync, dv.bt.hsync);
}
LOG_DEBUG("Calling ioctl(VIDIOC_S_DV_TIMINGS) ...");
if (xioctl(RUN(fd), VIDIOC_S_DV_TIMINGS, &dv) < 0) {
LOG_PERROR("Failed to set DV timings");
LOG_PERROR("Failed to set DV-timings");
return -1;
}
@@ -526,8 +504,7 @@ static int _device_apply_dv_timings(device_s *dev) {
static int _device_open_format(device_s *dev, bool first) {
const unsigned stride = align_size(RUN(width), 32) << 1;
struct v4l2_format fmt;
MEMSET_ZERO(fmt);
struct v4l2_format fmt = {0};
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = RUN(width);
fmt.fmt.pix.height = RUN(height);
@@ -536,10 +513,10 @@ static int _device_open_format(device_s *dev, bool first) {
fmt.fmt.pix.bytesperline = stride;
// Set format
LOG_DEBUG("Calling ioctl(VIDIOC_S_FMT) ...");
LOG_DEBUG("Probing device format=%s, stride=%u, resolution=%ux%u ...",
_format_to_string_supported(dev->format), stride, RUN(width), RUN(height));
if (xioctl(RUN(fd), VIDIOC_S_FMT, &fmt) < 0) {
LOG_PERROR("Unable to set pixelformat=%s, stride=%u, resolution=%ux%u",
_format_to_string_supported(dev->format), stride, RUN(width), RUN(height));
LOG_PERROR("Can't set device format");
return -1;
}
@@ -559,23 +536,23 @@ static int _device_open_format(device_s *dev, bool first) {
// Check format
if (fmt.fmt.pix.pixelformat != dev->format) {
LOG_ERROR("Could not obtain the requested pixelformat=%s; driver gave us %s",
LOG_ERROR("Could not obtain the requested format=%s; driver gave us %s",
_format_to_string_supported(dev->format),
_format_to_string_supported(fmt.fmt.pix.pixelformat));
char *format_str;
if ((format_str = (char *)_format_to_string_nullable(fmt.fmt.pix.pixelformat)) != NULL) {
LOG_INFO("Falling back to pixelformat=%s", format_str);
LOG_INFO("Falling back to format=%s", format_str);
} else {
char fourcc_str[8];
LOG_ERROR("Unsupported pixelformat=%s (fourcc)",
LOG_ERROR("Unsupported format=%s (fourcc)",
fourcc_to_string(fmt.fmt.pix.pixelformat, fourcc_str, 8));
return -1;
}
}
RUN(format) = fmt.fmt.pix.pixelformat;
LOG_INFO("Using pixelformat: %s", _format_to_string_supported(RUN(format)));
LOG_INFO("Using format: %s", _format_to_string_supported(RUN(format)));
RUN(stride) = fmt.fmt.pix.bytesperline;
RUN(raw_size) = fmt.fmt.pix.sizeimage; // Only for userptr
@@ -585,16 +562,15 @@ static int _device_open_format(device_s *dev, bool first) {
static void _device_open_hw_fps(device_s *dev) {
RUN(hw_fps) = 0;
struct v4l2_streamparm setfps;
MEMSET_ZERO(setfps);
struct v4l2_streamparm setfps = {0};
setfps.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
LOG_DEBUG("Calling ioctl(VIDIOC_G_PARM) ...");
LOG_DEBUG("Querying HW FPS ...");
if (xioctl(RUN(fd), VIDIOC_G_PARM, &setfps) < 0) {
if (errno == ENOTTY) { // Quiet message for Auvidea B101
if (errno == ENOTTY) { // Quiet message for TC358743
LOG_INFO("Querying HW FPS changing is not supported");
} else {
LOG_PERROR("Unable to query HW FPS changing");
LOG_PERROR("Can't query HW FPS changing");
}
return;
}
@@ -612,7 +588,7 @@ static void _device_open_hw_fps(device_s *dev) {
SETFPS_TPF(denominator) = (dev->desired_fps == 0 ? 255 : dev->desired_fps);
if (xioctl(RUN(fd), VIDIOC_S_PARM, &setfps) < 0) {
LOG_PERROR("Unable to set HW FPS");
LOG_PERROR("Can't set HW FPS");
return;
}
@@ -640,15 +616,14 @@ static void _device_open_jpeg_quality(device_s *dev) {
unsigned quality = 0;
if (is_jpeg(RUN(format))) {
struct v4l2_jpegcompression comp;
MEMSET_ZERO(comp);
struct v4l2_jpegcompression comp = {0};
if (xioctl(RUN(fd), VIDIOC_G_JPEGCOMP, &comp) < 0) {
LOG_ERROR("Device does not support setting of HW encoding quality parameters");
LOG_ERROR("Device doesn't support setting of HW encoding quality parameters");
} else {
comp.quality = dev->jpeg_quality;
if (xioctl(RUN(fd), VIDIOC_S_JPEGCOMP, &comp) < 0) {
LOG_ERROR("Unable to change MJPG quality for JPEG source with HW pass-through encoder");
LOG_ERROR("Can't change MJPEG quality for JPEG source with HW pass-through encoder");
} else {
quality = dev->jpeg_quality;
}
@@ -669,15 +644,14 @@ static int _device_open_io_method(device_s *dev) {
}
static int _device_open_io_method_mmap(device_s *dev) {
struct v4l2_requestbuffers req;
MEMSET_ZERO(req);
struct v4l2_requestbuffers req = {0};
req.count = dev->n_bufs;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
LOG_DEBUG("Calling ioctl(VIDIOC_REQBUFS) for V4L2_MEMORY_MMAP ...");
LOG_DEBUG("Requesting %u device buffers for MMAP ...", req.count);
if (xioctl(RUN(fd), VIDIOC_REQBUFS, &req) < 0) {
LOG_PERROR("Device '%s' doesn't support V4L2_MEMORY_MMAP", dev->path);
LOG_PERROR("Device '%s' doesn't support MMAP method", dev->path);
return -1;
}
@@ -692,40 +666,34 @@ static int _device_open_io_method_mmap(device_s *dev) {
A_CALLOC(RUN(hw_bufs), req.count);
for (RUN(n_bufs) = 0; RUN(n_bufs) < req.count; ++RUN(n_bufs)) {
struct v4l2_buffer buf_info;
MEMSET_ZERO(buf_info);
buf_info.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf_info.memory = V4L2_MEMORY_MMAP;
buf_info.index = RUN(n_bufs);
struct v4l2_buffer buf = {0};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = RUN(n_bufs);
LOG_DEBUG("Calling ioctl(VIDIOC_QUERYBUF) for device buffer %u ...", RUN(n_bufs));
if (xioctl(RUN(fd), VIDIOC_QUERYBUF, &buf_info) < 0) {
LOG_DEBUG("Calling ioctl(VIDIOC_QUERYBUF) for device buffer=%u ...", RUN(n_bufs));
if (xioctl(RUN(fd), VIDIOC_QUERYBUF, &buf) < 0) {
LOG_PERROR("Can't VIDIOC_QUERYBUF");
return -1;
}
# define HW(_next) RUN(hw_bufs)[RUN(n_bufs)]._next
# ifdef WITH_OMX
HW(dma_fd) = -1;
HW(vcsm_handle) = -1;
# endif
A_MUTEX_INIT(&HW(grabbed_mutex));
LOG_DEBUG("Mapping device buffer %u ...", RUN(n_bufs));
LOG_DEBUG("Mapping device buffer=%u ...", RUN(n_bufs));
if ((HW(raw.data) = mmap(
NULL,
buf_info.length,
buf.length,
PROT_READ | PROT_WRITE,
MAP_SHARED,
RUN(fd),
buf_info.m.offset
buf.m.offset
)) == MAP_FAILED) {
LOG_PERROR("Can't map device buffer %u", RUN(n_bufs));
LOG_PERROR("Can't map device buffer=%u", RUN(n_bufs));
return -1;
}
HW(raw.allocated) = buf_info.length;
HW(raw.allocated) = buf.length;
# undef HW
}
@@ -733,15 +701,14 @@ static int _device_open_io_method_mmap(device_s *dev) {
}
static int _device_open_io_method_userptr(device_s *dev) {
struct v4l2_requestbuffers req;
MEMSET_ZERO(req);
struct v4l2_requestbuffers req = {0};
req.count = dev->n_bufs;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_USERPTR;
LOG_DEBUG("Calling ioctl(VIDIOC_REQBUFS) for V4L2_MEMORY_USERPTR ...");
LOG_DEBUG("Requesting %u device buffers for USERPTR ...", req.count);
if (xioctl(RUN(fd), VIDIOC_REQBUFS, &req) < 0) {
LOG_PERROR("Device '%s' doesn't support V4L2_MEMORY_USERPTR", dev->path);
LOG_PERROR("Device '%s' doesn't support USERPTR method", dev->path);
return -1;
}
@@ -771,18 +738,17 @@ static int _device_open_io_method_userptr(device_s *dev) {
static int _device_open_queue_buffers(device_s *dev) {
for (unsigned index = 0; index < RUN(n_bufs); ++index) {
struct v4l2_buffer buf_info;
MEMSET_ZERO(buf_info);
buf_info.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf_info.memory = dev->io_method;
buf_info.index = index;
struct v4l2_buffer buf = {0};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = dev->io_method;
buf.index = index;
if (dev->io_method == V4L2_MEMORY_USERPTR) {
buf_info.m.userptr = (unsigned long)RUN(hw_bufs)[index].raw.data;
buf_info.length = RUN(hw_bufs)[index].raw.allocated;
buf.m.userptr = (unsigned long)RUN(hw_bufs)[index].raw.data;
buf.length = RUN(hw_bufs)[index].raw.allocated;
}
LOG_DEBUG("Calling ioctl(VIDIOC_QBUF) for buffer %u ...", index);
if (xioctl(RUN(fd), VIDIOC_QBUF, &buf_info) < 0) {
LOG_DEBUG("Calling ioctl(VIDIOC_QBUF) for buffer=%u ...", index);
if (xioctl(RUN(fd), VIDIOC_QBUF, &buf) < 0) {
LOG_PERROR("Can't VIDIOC_QBUF");
return -1;
}
@@ -792,7 +758,7 @@ static int _device_open_queue_buffers(device_s *dev) {
static int _device_apply_resolution(device_s *dev, unsigned width, unsigned height) {
// Тут VIDEO_MIN_* не используются из-за странностей минимального разрешения при отсутствии сигнала
// у некоторых устройств, например Auvidea B101
// у некоторых устройств, например TC358743
if (
width == 0 || width > VIDEO_MAX_WIDTH
|| height == 0 || height > VIDEO_MAX_HEIGHT
@@ -852,6 +818,7 @@ static void _device_apply_controls(device_s *dev) {
CONTROL_AUTO_CID (V4L2_CID_AUTO_WHITE_BALANCE, V4L2_CID_WHITE_BALANCE_TEMPERATURE, white_balance);
CONTROL_AUTO_CID (V4L2_CID_AUTOGAIN, V4L2_CID_GAIN, gain);
CONTROL_MANUAL_CID ( V4L2_CID_COLORFX, color_effect);
CONTROL_MANUAL_CID ( V4L2_CID_ROTATE, rotate);
CONTROL_MANUAL_CID ( V4L2_CID_VFLIP, flip_vertical);
CONTROL_MANUAL_CID ( V4L2_CID_HFLIP, flip_horizontal);
@@ -890,8 +857,7 @@ static void _device_set_control(
return;
}
struct v4l2_control ctl;
MEMSET_ZERO(ctl);
struct v4l2_control ctl = {0};
ctl.id = cid;
ctl.value = value;
@@ -905,12 +871,12 @@ static void _device_set_control(
}
static const char *_format_to_string_nullable(unsigned format) {
for (unsigned index = 0; index < ARRAY_LEN(_FORMATS); ++index) {
for (unsigned index = 0; index < ARRAY_LEN(_FORMATS); ++index) {
if (format == _FORMATS[index].format) {
return _FORMATS[index].name;
}
}
return NULL;
}
return NULL;
}
static const char *_format_to_string_supported(unsigned format) {

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -40,9 +40,6 @@
#include <pthread.h>
#include <linux/videodev2.h>
#include <linux/v4l2-controls.h>
#ifdef WITH_OMX
# include <interface/vcsm/user-vcsm.h>
#endif
#include "../libs/tools.h"
#include "../libs/logging.h"
@@ -64,24 +61,17 @@
#define STANDARDS_STR "PAL, NTSC, SECAM"
#define FORMAT_UNKNOWN -1
#define FORMATS_STR "YUYV, UYVY, RGB565, RGB24, JPEG"
#define FORMATS_STR "YUYV, UYVY, RGB565, RGB24, MJPEG, JPEG"
#define IO_METHOD_UNKNOWN -1
#define IO_METHODS_STR "MMAP, USERPTR"
typedef struct {
frame_s raw;
struct v4l2_buffer buf_info;
# ifdef WITH_OMX
int dma_fd;
int vcsm_handle;
# endif
pthread_mutex_t grabbed_mutex;
bool grabbed;
frame_s raw;
struct v4l2_buffer buf;
int dma_fd;
bool grabbed;
} hw_buffer_s;
typedef struct {
@@ -122,6 +112,7 @@ typedef struct {
control_s white_balance;
control_s gain;
control_s color_effect;
control_s rotate;
control_s flip_vertical;
control_s flip_horizontal;
} controls_s;
@@ -158,9 +149,7 @@ int device_parse_io_method(const char *str);
int device_open(device_s *dev);
void device_close(device_s *dev);
#ifdef WITH_OMX
int device_export_to_vcsm(device_s *dev);
#endif
int device_export_to_dma(device_s *dev);
int device_switch_capturing(device_s *dev, bool enable);
int device_select(device_s *dev, bool *has_read, bool *has_write, bool *has_error);
int device_grab_buffer(device_s *dev, hw_buffer_s **hw);

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -27,16 +27,18 @@ static const struct {
const char *name;
const encoder_type_e type;
} _ENCODER_TYPES[] = {
{"CPU", ENCODER_TYPE_CPU},
{"HW", ENCODER_TYPE_HW},
# ifdef WITH_OMX
{"OMX", ENCODER_TYPE_OMX},
# endif
{"NOOP", ENCODER_TYPE_NOOP},
{"CPU", ENCODER_TYPE_CPU},
{"HW", ENCODER_TYPE_HW},
{"M2M-VIDEO", ENCODER_TYPE_M2M_VIDEO},
{"M2M-IMAGE", ENCODER_TYPE_M2M_IMAGE},
{"M2M-MJPEG", ENCODER_TYPE_M2M_VIDEO},
{"M2M-JPEG", ENCODER_TYPE_M2M_IMAGE},
{"OMX", ENCODER_TYPE_M2M_IMAGE},
{"NOOP", ENCODER_TYPE_NOOP},
};
static void *_worker_job_init(worker_s *wr, void *v_enc);
static void *_worker_job_init(void *v_enc);
static void _worker_job_destroy(void *v_job);
static bool _worker_run_job(worker_s *wr);
@@ -60,16 +62,14 @@ encoder_s *encoder_init(void) {
}
void encoder_destroy(encoder_s *enc) {
# ifdef WITH_OMX
if (ER(omxs)) {
for (unsigned index = 0; index < ER(n_omxs); ++index) {
if (ER(omxs[index])) {
omx_encoder_destroy(ER(omxs[index]));
if (ER(m2ms)) {
for (unsigned index = 0; index < ER(n_m2ms); ++index) {
if (ER(m2ms[index])) {
m2m_encoder_destroy(ER(m2ms[index]));
}
}
free(ER(omxs));
free(ER(m2ms));
}
# endif
A_MUTEX_DESTROY(&ER(mutex));
free(enc->run);
free(enc);
@@ -113,63 +113,30 @@ workers_pool_s *encoder_workers_pool_init(encoder_s *enc, device_s *dev) {
}
quality = DR(jpeg_quality);
n_workers = 1;
}
# ifdef WITH_OMX
else if (type == ENCODER_TYPE_OMX) {
if (align_size(DR(width), 32) != DR(width)) {
LOG_INFO("Switching to CPU encoder: OMX can't handle width=%u ...", DR(width));
goto use_cpu;
} else if (type == ENCODER_TYPE_M2M_VIDEO || type == ENCODER_TYPE_M2M_IMAGE) {
LOG_DEBUG("Preparing M2M-%s encoder ...", (type == ENCODER_TYPE_M2M_VIDEO ? "VIDEO" : "IMAGE"));
if (ER(m2ms) == NULL) {
A_CALLOC(ER(m2ms), n_workers);
}
LOG_DEBUG("Preparing OMX encoder ...");
if (n_workers > OMX_MAX_ENCODERS) {
LOG_INFO("OMX encoder sets limit for worker threads: %u", OMX_MAX_ENCODERS);
n_workers = OMX_MAX_ENCODERS;
}
if (ER(omxs) == NULL) {
A_CALLOC(ER(omxs), OMX_MAX_ENCODERS);
}
// Начинаем с нуля и доинициализируем на следующих заходах при необходимости
for (; ER(n_omxs) < n_workers; ++ER(n_omxs)) {
if ((ER(omxs[ER(n_omxs)]) = omx_encoder_init()) == NULL) {
LOG_ERROR("Can't initialize OMX encoder, falling back to CPU");
goto force_cpu;
for (; ER(n_m2ms) < n_workers; ++ER(n_m2ms)) {
// Начинаем с нуля и доинициализируем на следующих заходах при необходимости
char name[32];
snprintf(name, 32, "JPEG-%u", ER(n_m2ms));
if (type == ENCODER_TYPE_M2M_VIDEO) {
ER(m2ms[ER(n_m2ms)]) = m2m_mjpeg_encoder_init(name, enc->m2m_path, quality);
} else {
ER(m2ms[ER(n_m2ms)]) = m2m_jpeg_encoder_init(name, enc->m2m_path, quality);
}
}
frame_s frame;
MEMSET_ZERO(frame);
frame.width = DR(width);
frame.height = DR(height);
frame.format = DR(format);
frame.stride = DR(stride);
for (unsigned index = 0; index < ER(n_omxs); ++index) {
int omx_error = omx_encoder_prepare(ER(omxs[index]), &frame, quality);
if (omx_error == -2) {
goto use_cpu;
} else if (omx_error < 0) {
goto force_cpu;
}
}
}
# endif
else if (type == ENCODER_TYPE_NOOP) {
} else if (type == ENCODER_TYPE_NOOP) {
n_workers = 1;
quality = 0;
}
goto ok;
# ifdef WITH_OMX
force_cpu:
LOG_ERROR("Forced CPU encoder permanently");
cpu_forced = true;
# endif
use_cpu:
type = ENCODER_TYPE_CPU;
quality = dev->jpeg_quality;
@@ -212,23 +179,17 @@ void encoder_get_runtime_params(encoder_s *enc, encoder_type_e *type, unsigned *
A_MUTEX_UNLOCK(&ER(mutex));
}
static void *_worker_job_init(worker_s *wr, void *v_enc) {
static void *_worker_job_init(void *v_enc) {
encoder_job_s *job;
A_CALLOC(job, 1);
job->enc = (encoder_s *)v_enc;
const size_t dest_role_len = strlen(wr->name) + 16;
A_CALLOC(job->dest_role, dest_role_len);
snprintf(job->dest_role, dest_role_len, "%s_dest", wr->name);
job->dest = frame_init(job->dest_role);
job->dest = frame_init();
return (void *)job;
}
static void _worker_job_destroy(void *v_job) {
encoder_job_s *job = (encoder_job_s *)v_job;
frame_destroy(job->dest);
free(job->dest_role);
free(job);
}
@@ -241,55 +202,47 @@ static bool _worker_run_job(worker_s *wr) {
# define ER(_next) job->enc->run->_next
LOG_DEBUG("Worker %s compressing JPEG from buffer %u ...", wr->name, job->hw->buf_info.index);
assert(ER(type) != ENCODER_TYPE_UNKNOWN);
assert(src->used > 0);
frame_copy_meta(src, dest);
dest->format = V4L2_PIX_FMT_JPEG;
dest->stride = 0;
dest->encode_begin_ts = get_now_monotonic();
dest->used = 0;
if (ER(type) == ENCODER_TYPE_CPU) {
LOG_VERBOSE("Compressing buffer using CPU");
LOG_VERBOSE("Compressing JPEG using CPU: worker=%s, buffer=%u",
wr->name, job->hw->buf.index);
cpu_encoder_compress(src, dest, ER(quality));
} else if (ER(type) == ENCODER_TYPE_HW) {
LOG_VERBOSE("Compressing buffer using HW (just copying)");
LOG_VERBOSE("Compressing JPEG using HW (just copying): worker=%s, buffer=%u",
wr->name, job->hw->buf.index);
hw_encoder_compress(src, dest);
}
# ifdef WITH_OMX
else if (ER(type) == ENCODER_TYPE_OMX) {
LOG_VERBOSE("Compressing buffer using OMX");
if (omx_encoder_compress(ER(omxs[wr->number]), src, dest) < 0) {
} else if (ER(type) == ENCODER_TYPE_M2M_VIDEO || ER(type) == ENCODER_TYPE_M2M_IMAGE) {
LOG_VERBOSE("Compressing JPEG using M2M-%s: worker=%s, buffer=%u",
(ER(type) == ENCODER_TYPE_M2M_VIDEO ? "VIDEO" : "IMAGE"), wr->name, job->hw->buf.index);
if (m2m_encoder_compress(ER(m2ms[wr->number]), src, dest, false) < 0) {
goto error;
}
}
# endif
else if (ER(type) == ENCODER_TYPE_NOOP) {
LOG_VERBOSE("Compressing buffer using NOOP (do nothing)");
} else if (ER(type) == ENCODER_TYPE_NOOP) {
LOG_VERBOSE("Compressing JPEG using NOOP (do nothing): worker=%s, buffer=%u",
wr->name, job->hw->buf.index);
usleep(5000); // Просто чтобы работала логика desired_fps
dest->encode_end_ts = get_now_monotonic();
}
dest->encode_end_ts = get_now_monotonic();
LOG_VERBOSE("Compressed new JPEG: size=%zu, time=%0.3Lf, worker=%s, buffer=%u",
job->dest->used,
job->dest->encode_end_ts - job->dest->encode_begin_ts,
wr->name,
job->hw->buf_info.index);
job->hw->buf.index);
return true;
# ifdef WITH_OMX
error:
LOG_ERROR("Compression failed: worker=%s, buffer=%u", wr->name, job->hw->buf_info.index);
LOG_ERROR("Compression failed: worker=%s, buffer=%u", wr->name, job->hw->buf.index);
LOG_ERROR("Error while compressing buffer, falling back to CPU");
A_MUTEX_LOCK(&ER(mutex));
ER(cpu_forced) = true;
A_MUTEX_UNLOCK(&ER(mutex));
return false;
# endif
# undef ER
}

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -37,30 +37,20 @@
#include "device.h"
#include "workers.h"
#include "m2m.h"
#include "encoders/cpu/encoder.h"
#include "encoders/hw/encoder.h"
#ifdef WITH_OMX
# include "encoders/omx/encoder.h"
# define ENCODER_TYPES_OMX_HINT ", OMX"
#else
# define ENCODER_TYPES_OMX_HINT ""
#endif
#define ENCODER_TYPES_STR \
"CPU, HW" \
ENCODER_TYPES_OMX_HINT \
", NOOP"
#define ENCODER_TYPES_STR "CPU, HW, M2M-VIDEO, M2M-IMAGE, NOOP"
typedef enum {
ENCODER_TYPE_UNKNOWN, // Only for encoder_parse_type() and main()
ENCODER_TYPE_CPU,
ENCODER_TYPE_HW,
# ifdef WITH_OMX
ENCODER_TYPE_OMX,
# endif
ENCODER_TYPE_M2M_VIDEO,
ENCODER_TYPE_M2M_IMAGE,
ENCODER_TYPE_NOOP,
} encoder_type_e;
@@ -70,15 +60,14 @@ typedef struct {
bool cpu_forced;
pthread_mutex_t mutex;
# ifdef WITH_OMX
unsigned n_omxs;
omx_encoder_s **omxs;
# endif
unsigned n_m2ms;
m2m_encoder_s **m2ms;
} encoder_runtime_s;
typedef struct {
encoder_type_e type;
unsigned n_workers;
char *m2m_path;
encoder_runtime_s *run;
} encoder_s;
@@ -86,7 +75,6 @@ typedef struct {
typedef struct {
encoder_s *enc;
hw_buffer_s *hw;
char *dest_role;
frame_s *dest;
} encoder_job_s;

View File

@@ -1,13 +1,13 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# This source file based on code of MJPG-Streamer. #
# #
# Copyright (C) 2005-2006 Laurent Pinchart & Michel Xhaard #
# Copyright (C) 2006 Gabriel A. Devenyi #
# Copyright (C) 2007 Tom Stöveken #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -50,6 +50,8 @@ static void _jpeg_term_destination(j_compress_ptr jpeg);
void cpu_encoder_compress(const frame_s *src, frame_s *dest, unsigned quality) {
// This function based on compress_image_to_jpeg() from mjpg-streamer
frame_encoding_begin(src, dest, V4L2_PIX_FMT_JPEG);
struct jpeg_compress_struct jpeg;
struct jpeg_error_mgr jpeg_error;
@@ -85,7 +87,7 @@ void cpu_encoder_compress(const frame_s *src, frame_s *dest, unsigned quality) {
jpeg_finish_compress(&jpeg);
jpeg_destroy_compress(&jpeg);
assert(dest->used > 0);
frame_encoding_end(dest);
}
static void _jpeg_set_dest_frame(j_compress_ptr jpeg, frame_s *frame) {

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,13 +1,13 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# This source file based on code of MJPG-Streamer. #
# #
# Copyright (C) 2005-2006 Laurent Pinchart & Michel Xhaard #
# Copyright (C) 2006 Gabriel A. Devenyi #
# Copyright (C) 2007 Tom Stöveken #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -38,6 +38,8 @@ void hw_encoder_compress(const frame_s *src, frame_s *dest) {
}
void _copy_plus_huffman(const frame_s *src, frame_s *dest) {
frame_encoding_begin(src, dest, V4L2_PIX_FMT_JPEG);
if (!_is_huffman(src->data)) {
const uint8_t *src_ptr = src->data;
const uint8_t *src_end = src->data + src->used;
@@ -55,9 +57,12 @@ void _copy_plus_huffman(const frame_s *src, frame_s *dest) {
frame_set_data(dest, src->data, paste);
frame_append_data(dest, HUFFMAN_TABLE, sizeof(HUFFMAN_TABLE));
frame_append_data(dest, src_ptr, src->used - paste);
} else {
frame_set_data(dest, src->data, src->used);
}
frame_encoding_end(dest);
}
static bool _is_huffman(const uint8_t *data) {

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,13 +1,13 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# This source file based on code of MJPG-Streamer. #
# #
# Copyright (C) 2005-2006 Laurent Pinchart & Michel Xhaard #
# Copyright (C) 2006 Gabriel A. Devenyi #
# Copyright (C) 2007 Tom Stöveken #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,154 +0,0 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
# #
*****************************************************************************/
#include "component.h"
static int _omx_component_wait_port_changed(OMX_HANDLETYPE *comp, OMX_U32 port, OMX_BOOL enabled);
static int _omx_component_wait_state_changed(OMX_HANDLETYPE *comp, OMX_STATETYPE wanted);
int omx_component_enable_port(OMX_HANDLETYPE *comp, OMX_U32 port) {
OMX_ERRORTYPE error;
LOG_DEBUG("Enabling OMX port %u ...", port);
if ((error = OMX_SendCommand(*comp, OMX_CommandPortEnable, port, NULL)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't enable OMX port %u", port);
return -1;
}
return _omx_component_wait_port_changed(comp, port, OMX_TRUE);
}
int omx_component_disable_port(OMX_HANDLETYPE *comp, OMX_U32 port) {
OMX_ERRORTYPE error;
LOG_DEBUG("Disabling OMX port %u ...", port);
if ((error = OMX_SendCommand(*comp, OMX_CommandPortDisable, port, NULL)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't disable OMX port %u", port);
return -1;
}
return _omx_component_wait_port_changed(comp, port, OMX_FALSE);
}
int omx_component_get_portdef(OMX_HANDLETYPE *comp, OMX_PARAM_PORTDEFINITIONTYPE *portdef, OMX_U32 port) {
OMX_ERRORTYPE error;
// cppcheck-suppress redundantPointerOp
OMX_INIT_STRUCTURE(*portdef);
portdef->nPortIndex = port;
LOG_DEBUG("Fetching OMX port %u definition ...", port);
if ((error = OMX_GetParameter(*comp, OMX_IndexParamPortDefinition, portdef)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't get OMX port %u definition", port);
return -1;
}
return 0;
}
int omx_component_set_portdef(OMX_HANDLETYPE *comp, OMX_PARAM_PORTDEFINITIONTYPE *portdef) {
OMX_ERRORTYPE error;
LOG_DEBUG("Writing OMX port %u definition ...", portdef->nPortIndex);
if ((error = OMX_SetParameter(*comp, OMX_IndexParamPortDefinition, portdef)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't set OMX port %u definition", portdef->nPortIndex);
return -1;
}
return 0;
}
int omx_component_set_state(OMX_HANDLETYPE *comp, OMX_STATETYPE state) {
const char *state_str = omx_state_to_string(state);
OMX_ERRORTYPE error;
LOG_DEBUG("Switching component state to %s ...", state_str);
int retries = 50;
do {
error = OMX_SendCommand(*comp, OMX_CommandStateSet, state, NULL);
if (error == OMX_ErrorNone) {
return _omx_component_wait_state_changed(comp, state);
} else if (error == OMX_ErrorInsufficientResources && retries) {
// Иногда железо не инициализируется, хз почему, просто ретраим, со второй попытки сработает
if (retries > 45) {
LOG_VERBOSE("Can't switch OMX component state to %s, need to retry: %s",
state_str, omx_error_to_string(error));
} else {
LOG_ERROR_OMX(error, "Can't switch OMX component state to %s, need to retry", state_str);
}
retries -= 1;
usleep(8000);
} else {
break;
}
} while (retries);
LOG_ERROR_OMX(error, "Can't switch OMX component state to %s", state_str);
return -1;
}
static int _omx_component_wait_port_changed(OMX_HANDLETYPE *comp, OMX_U32 port, OMX_BOOL enabled) {
OMX_ERRORTYPE error;
OMX_PARAM_PORTDEFINITIONTYPE portdef;
OMX_INIT_STRUCTURE(portdef);
portdef.nPortIndex = port;
int retries = 50;
do {
if ((error = OMX_GetParameter(*comp, OMX_IndexParamPortDefinition, &portdef)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't get OMX port %u definition for waiting", port);
return -1;
}
if (portdef.bEnabled != enabled) {
LOG_DEBUG("Waiting for OMX %s port %u", (enabled ? "enabling" : "disabling"), port);
retries -= 1;
usleep(8000);
}
} while (portdef.bEnabled != enabled && retries);
LOG_DEBUG("OMX port %u %s", port, (enabled ? "enabled" : "disabled"));
return (portdef.bEnabled == enabled ? 0 : -1);
}
static int _omx_component_wait_state_changed(OMX_HANDLETYPE *comp, OMX_STATETYPE wanted) {
OMX_ERRORTYPE error;
OMX_STATETYPE state;
int retries = 50;
do {
if ((error = OMX_GetState(*comp, &state)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Failed to get OMX component state");
return -1;
}
if (state != wanted) {
LOG_DEBUG("Waiting when OMX component state changes to %s", omx_state_to_string(wanted));
retries -= 1;
usleep(8000);
}
} while (state != wanted && retries);
LOG_DEBUG("Switched OMX component state to %s", omx_state_to_string(wanted))
return (state == wanted ? 0 : -1);
}

View File

@@ -1,481 +0,0 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
# #
*****************************************************************************/
#include "encoder.h"
static const OMX_U32 _INPUT_PORT = 340;
static const OMX_U32 _OUTPUT_PORT = 341;
static int _vcos_semwait(VCOS_SEMAPHORE_T *sem);
static int _omx_init_component(omx_encoder_s *omx);
static int _omx_init_disable_ports(omx_encoder_s *omx);
static int _omx_setup_input(omx_encoder_s *omx, const frame_s *frame);
static int _omx_setup_output(omx_encoder_s *omx, unsigned quality);
static int _omx_encoder_clear_ports(omx_encoder_s *omx);
static OMX_ERRORTYPE _omx_event_handler(
UNUSED OMX_HANDLETYPE comp,
OMX_PTR v_omx, OMX_EVENTTYPE event, OMX_U32 data1,
UNUSED OMX_U32 data2, UNUSED OMX_PTR event_data);
static OMX_ERRORTYPE _omx_input_required_handler(
UNUSED OMX_HANDLETYPE comp,
OMX_PTR v_omx, UNUSED OMX_BUFFERHEADERTYPE *buf);
static OMX_ERRORTYPE _omx_output_available_handler(
UNUSED OMX_HANDLETYPE comp,
OMX_PTR v_omx, UNUSED OMX_BUFFERHEADERTYPE *buf);
omx_encoder_s *omx_encoder_init(void) {
// Some theory:
// - http://www.fourcc.org/yuv.php
// - https://kwasi-ich.de/blog/2017/11/26/omx/
// - https://github.com/hopkinskong/rpi-omx-jpeg-encode/blob/master/jpeg_bench.cpp
// - https://github.com/kwasmich/OMXPlayground/blob/master/omxJPEGEnc.c
// - https://github.com/gagle/raspberrypi-openmax-jpeg/blob/master/jpeg.c
// - https://www.raspberrypi.org/forums/viewtopic.php?t=154790
// - https://bitbucket.org/bensch128/omxjpegencode/src/master/jpeg_encoder.cpp
// - http://home.nouwen.name/RaspberryPi/documentation/ilcomponents/image_encode.html
LOG_INFO("Initializing OMX encoder ...");
omx_encoder_s *omx;
A_CALLOC(omx, 1);
if (vcos_semaphore_create(&omx->handler_sem, "handler_sem", 0) != VCOS_SUCCESS) {
LOG_ERROR("Can't create VCOS semaphore");
goto error;
}
omx->i_handler_sem = true;
if (_omx_init_component(omx) < 0) {
goto error;
}
if (_omx_init_disable_ports(omx) < 0) {
goto error;
}
return omx;
error:
omx_encoder_destroy(omx);
return NULL;
}
void omx_encoder_destroy(omx_encoder_s *omx) {
LOG_INFO("Destroying OMX encoder ...");
omx_component_set_state(&omx->comp, OMX_StateIdle);
_omx_encoder_clear_ports(omx);
omx_component_set_state(&omx->comp, OMX_StateLoaded);
if (omx->i_handler_sem) {
vcos_semaphore_delete(&omx->handler_sem);
}
if (omx->i_encoder) {
OMX_ERRORTYPE error;
if ((error = OMX_FreeHandle(omx->comp)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't free OMX.broadcom.image_encode");
}
}
free(omx);
}
int omx_encoder_prepare(omx_encoder_s *omx, const frame_s *frame, unsigned quality) {
if (align_size(frame->width, 32) != frame->width && frame_get_padding(frame) == 0) {
LOG_ERROR("%u %u", frame->width, frame->stride);
LOG_ERROR("OMX encoder can't handle unaligned width");
return -2;
}
if (omx_component_set_state(&omx->comp, OMX_StateIdle) < 0) {
return -1;
}
if (_omx_encoder_clear_ports(omx) < 0) {
return -1;
}
if (_omx_setup_input(omx, frame) < 0) {
return -1;
}
if (_omx_setup_output(omx, quality) < 0) {
return -1;
}
if (omx_component_set_state(&omx->comp, OMX_StateExecuting) < 0) {
return -1;
}
return 0;
}
int omx_encoder_compress(omx_encoder_s *omx, const frame_s *src, frame_s *dest) {
# define IN(_next) omx->input_buf->_next
# define OUT(_next) omx->output_buf->_next
OMX_ERRORTYPE error;
if ((error = OMX_FillThisBuffer(omx->comp, omx->output_buf)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Failed to request filling of the output buffer on encoder");
return -1;
}
dest->width = align_size(src->width, 32);
dest->used = 0;
omx->output_available = false;
omx->input_required = true;
size_t slice_size = (IN(nAllocLen) < src->used ? IN(nAllocLen) : src->used);
size_t pos = 0;
while (true) {
if (omx->failed) {
return -1;
}
if (omx->output_available) {
omx->output_available = false;
frame_append_data(dest, OUT(pBuffer) + OUT(nOffset), OUT(nFilledLen));
if (OUT(nFlags) & OMX_BUFFERFLAG_ENDOFFRAME) {
OUT(nFlags) = 0;
break;
}
if ((error = OMX_FillThisBuffer(omx->comp, omx->output_buf)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Failed to request filling of the output buffer on encoder");
return -1;
}
}
if (omx->input_required) {
omx->input_required = false;
if (pos == src->used) {
continue;
}
memcpy(IN(pBuffer), src->data + pos, slice_size);
IN(nOffset) = 0;
IN(nFilledLen) = slice_size;
pos += slice_size;
if (pos + slice_size > src->used) {
slice_size = src->used - pos;
}
if ((error = OMX_EmptyThisBuffer(omx->comp, omx->input_buf)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Failed to request emptying of the input buffer on encoder");
return -1;
}
}
if (_vcos_semwait(&omx->handler_sem) != 0) {
return -1;
}
}
# undef OUT
# undef IN
return 0;
}
static int _vcos_semwait(VCOS_SEMAPHORE_T *sem) {
// vcos_semaphore_wait() can wait infinite
// vcos_semaphore_wait_timeout() is broken by design:
// - https://github.com/pikvm/ustreamer/issues/56
// - https://github.com/raspberrypi/userland/issues/658
// CFG_OMX_SEMWAIT_TIMEOUT is ugly busyloop
// Три стула.
# ifdef CFG_OMX_SEMWAIT_TIMEOUT
long double deadline_ts = get_now_monotonic() + (long double)CFG_OMX_SEMWAIT_TIMEOUT; // Seconds
VCOS_STATUS_T sem_status;
while (true) {
sem_status = vcos_semaphore_trywait(sem);
if (sem_status == VCOS_SUCCESS) {
return 0;
} else if (sem_status != VCOS_EAGAIN || get_now_monotonic() > deadline_ts) {
break;
}
if (usleep(1000) < 0) {
break;
}
}
switch (sem_status) {
case VCOS_EAGAIN: LOG_ERROR("Can't wait VCOS semaphore: EAGAIN (timeout)"); break;
case VCOS_EINVAL: LOG_ERROR("Can't wait VCOS semaphore: EINVAL"); break;
default: LOG_ERROR("Can't wait VCOS semaphore: %d", sem_status); break;
}
return -1;
# else
return (vcos_semaphore_wait(sem) == VCOS_SUCCESS ? 0 : -1);
# endif
}
static int _omx_init_component(omx_encoder_s *omx) {
OMX_ERRORTYPE error;
OMX_CALLBACKTYPE callbacks;
MEMSET_ZERO(callbacks);
callbacks.EventHandler = _omx_event_handler;
callbacks.EmptyBufferDone = _omx_input_required_handler;
callbacks.FillBufferDone = _omx_output_available_handler;
LOG_DEBUG("Initializing OMX.broadcom.image_encode ...");
if ((error = OMX_GetHandle(&omx->comp, "OMX.broadcom.image_encode", omx, &callbacks)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't initialize OMX.broadcom.image_encode");
return -1;
}
omx->i_encoder = true;
return 0;
}
static int _omx_init_disable_ports(omx_encoder_s *omx) {
OMX_ERRORTYPE error;
OMX_INDEXTYPE types[] = {
OMX_IndexParamAudioInit, OMX_IndexParamVideoInit,
OMX_IndexParamImageInit, OMX_IndexParamOtherInit,
};
OMX_PORT_PARAM_TYPE ports;
OMX_INIT_STRUCTURE(ports);
if ((error = OMX_GetParameter(omx->comp, OMX_IndexParamImageInit, &ports)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't OMX_GetParameter(OMX_IndexParamImageInit)");
return -1;
}
for (unsigned index = 0; index < 4; ++index) {
if ((error = OMX_GetParameter(omx->comp, types[index], &ports)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't OMX_GetParameter(types[%u])", index);
return -1;
}
for (OMX_U32 port = ports.nStartPortNumber; port < ports.nStartPortNumber + ports.nPorts; ++port) {
if (omx_component_disable_port(&omx->comp, port) < 0) {
return -1;
}
}
}
return 0;
}
static int _omx_setup_input(omx_encoder_s *omx, const frame_s *frame) {
LOG_DEBUG("Setting up OMX JPEG input port ...");
OMX_ERRORTYPE error;
OMX_PARAM_PORTDEFINITIONTYPE portdef;
if (omx_component_get_portdef(&omx->comp, &portdef, _INPUT_PORT) < 0) {
LOG_ERROR("... first");
return -1;
}
# define IFMT(_next) portdef.format.image._next
IFMT(nFrameWidth) = align_size(frame->width, 32);
IFMT(nFrameHeight) = frame->height;
IFMT(nStride) = align_size(frame->width, 32) << 1;
IFMT(nSliceHeight) = align_size(frame->height, 16);
IFMT(bFlagErrorConcealment) = OMX_FALSE;
IFMT(eCompressionFormat) = OMX_IMAGE_CodingUnused;
portdef.nBufferSize = ((frame->width * frame->height) << 1) * 2;
switch (frame->format) {
// https://www.fourcc.org/yuv.php
// Also see comments inside OMX_IVCommon.h
case V4L2_PIX_FMT_YUYV: IFMT(eColorFormat) = OMX_COLOR_FormatYCbYCr; break;
case V4L2_PIX_FMT_UYVY: IFMT(eColorFormat) = OMX_COLOR_FormatCbYCrY; break;
case V4L2_PIX_FMT_RGB565: IFMT(eColorFormat) = OMX_COLOR_Format16bitRGB565; break;
case V4L2_PIX_FMT_RGB24: IFMT(eColorFormat) = OMX_COLOR_Format24bitRGB888; break;
// TODO: найти устройство с RGB565 и протестить его.
// FIXME: RGB24 не работает нормально, нижняя половина экрана зеленая.
// FIXME: Китайский EasyCap тоже не работает, мусор на экране.
// Вероятно обе проблемы вызваны некорректной реализацией OMX на пае.
default: assert(0 && "Unsupported pixelformat");
}
# undef IFMT
if (omx_component_set_portdef(&omx->comp, &portdef) < 0) {
return -1;
}
if (omx_component_get_portdef(&omx->comp, &portdef, _INPUT_PORT) < 0) {
LOG_ERROR("... second");
return -1;
}
if (omx_component_enable_port(&omx->comp, _INPUT_PORT) < 0) {
return -1;
}
omx->i_input_port_enabled = true;
if ((error = OMX_AllocateBuffer(omx->comp, &omx->input_buf, _INPUT_PORT, NULL, portdef.nBufferSize)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't allocate OMX JPEG input buffer");
return -1;
}
return 0;
}
static int _omx_setup_output(omx_encoder_s *omx, unsigned quality) {
LOG_DEBUG("Setting up OMX JPEG output port ...");
OMX_ERRORTYPE error;
OMX_PARAM_PORTDEFINITIONTYPE portdef;
if (omx_component_get_portdef(&omx->comp, &portdef, _OUTPUT_PORT) < 0) {
LOG_ERROR("... first");
return -1;
}
# define OFMT(_next) portdef.format.image._next
OFMT(bFlagErrorConcealment) = OMX_FALSE;
OFMT(eCompressionFormat) = OMX_IMAGE_CodingJPEG;
OFMT(eColorFormat) = OMX_COLOR_FormatYCbYCr;
# undef OFMT
if (omx_component_set_portdef(&omx->comp, &portdef) < 0) {
return -1;
}
if (omx_component_get_portdef(&omx->comp, &portdef, _OUTPUT_PORT) < 0) {
LOG_ERROR("... second");
return -1;
}
# define SET_PARAM(_key, _value) { \
if ((error = OMX_SetParameter(omx->comp, OMX_IndexParam##_key, _value)) != OMX_ErrorNone) { \
LOG_ERROR_OMX(error, "Can't set OMX param %s", #_key); \
return -1; \
} \
}
OMX_CONFIG_BOOLEANTYPE exif;
OMX_INIT_STRUCTURE(exif);
exif.bEnabled = OMX_FALSE;
SET_PARAM(BrcmDisableEXIF, &exif);
OMX_PARAM_IJGSCALINGTYPE ijg;
OMX_INIT_STRUCTURE(ijg);
ijg.nPortIndex = _OUTPUT_PORT;
ijg.bEnabled = OMX_TRUE;
SET_PARAM(BrcmEnableIJGTableScaling, &ijg);
OMX_IMAGE_PARAM_QFACTORTYPE qfactor;
OMX_INIT_STRUCTURE(qfactor);
qfactor.nPortIndex = _OUTPUT_PORT;
qfactor.nQFactor = quality;
SET_PARAM(QFactor, &qfactor);
# undef SET_PARAM
if (omx_component_enable_port(&omx->comp, _OUTPUT_PORT) < 0) {
return -1;
}
omx->i_output_port_enabled = true;
if ((error = OMX_AllocateBuffer(omx->comp, &omx->output_buf, _OUTPUT_PORT, NULL, portdef.nBufferSize)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't allocate OMX JPEG output buffer");
return -1;
}
return 0;
}
static int _omx_encoder_clear_ports(omx_encoder_s *omx) {
OMX_ERRORTYPE error;
int retval = 0;
if (omx->i_output_port_enabled) {
retval -= omx_component_disable_port(&omx->comp, _OUTPUT_PORT);
omx->i_output_port_enabled = false;
}
if (omx->i_input_port_enabled) {
retval -= omx_component_disable_port(&omx->comp, _INPUT_PORT);
omx->i_input_port_enabled = false;
}
if (omx->input_buf) {
if ((error = OMX_FreeBuffer(omx->comp, _INPUT_PORT, omx->input_buf)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't free OMX JPEG input buffer");
// retval -= 1;
}
omx->input_buf = NULL;
}
if (omx->output_buf) {
if ((error = OMX_FreeBuffer(omx->comp, _OUTPUT_PORT, omx->output_buf)) != OMX_ErrorNone) {
LOG_ERROR_OMX(error, "Can't free OMX JPEG output buffer");
// retval -= 1;
}
omx->output_buf = NULL;
}
return retval;
}
static OMX_ERRORTYPE _omx_event_handler(
UNUSED OMX_HANDLETYPE comp,
OMX_PTR v_omx, OMX_EVENTTYPE event, OMX_U32 data1,
UNUSED OMX_U32 data2, UNUSED OMX_PTR event_data) {
// OMX calls this handler for all the events it emits
omx_encoder_s *omx = (omx_encoder_s *)v_omx;
if (event == OMX_EventError) {
LOG_ERROR_OMX((OMX_ERRORTYPE)data1, "OMX error event received");
omx->failed = true;
assert(vcos_semaphore_post(&omx->handler_sem) == VCOS_SUCCESS);
}
return OMX_ErrorNone;
}
static OMX_ERRORTYPE _omx_input_required_handler(
UNUSED OMX_HANDLETYPE comp,
OMX_PTR v_omx, UNUSED OMX_BUFFERHEADERTYPE *buf) {
// Called by OMX when the encoder component requires
// the input buffer to be filled with RAW image data
omx_encoder_s *omx = (omx_encoder_s *)v_omx;
omx->input_required = true;
assert(vcos_semaphore_post(&omx->handler_sem) == VCOS_SUCCESS);
return OMX_ErrorNone;
}
static OMX_ERRORTYPE _omx_output_available_handler(
UNUSED OMX_HANDLETYPE comp,
OMX_PTR v_omx, UNUSED OMX_BUFFERHEADERTYPE *buf) {
// Called by OMX when the encoder component has filled
// the output buffer with JPEG data
omx_encoder_s *omx = (omx_encoder_s *)v_omx;
omx->output_available = true;
assert(vcos_semaphore_post(&omx->handler_sem) == VCOS_SUCCESS);
return OMX_ErrorNone;
}

View File

@@ -1,95 +0,0 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
# #
*****************************************************************************/
#include "formatters.h"
#define CASE_TO_STRING(_value) \
case _value: { return #_value; }
const char *omx_error_to_string(OMX_ERRORTYPE error) {
switch (error) {
CASE_TO_STRING(OMX_ErrorNone);
CASE_TO_STRING(OMX_ErrorInsufficientResources);
CASE_TO_STRING(OMX_ErrorUndefined);
CASE_TO_STRING(OMX_ErrorInvalidComponentName);
CASE_TO_STRING(OMX_ErrorComponentNotFound);
CASE_TO_STRING(OMX_ErrorInvalidComponent);
CASE_TO_STRING(OMX_ErrorBadParameter);
CASE_TO_STRING(OMX_ErrorNotImplemented);
CASE_TO_STRING(OMX_ErrorUnderflow);
CASE_TO_STRING(OMX_ErrorOverflow);
CASE_TO_STRING(OMX_ErrorHardware);
CASE_TO_STRING(OMX_ErrorInvalidState);
CASE_TO_STRING(OMX_ErrorStreamCorrupt);
CASE_TO_STRING(OMX_ErrorPortsNotCompatible);
CASE_TO_STRING(OMX_ErrorResourcesLost);
CASE_TO_STRING(OMX_ErrorNoMore);
CASE_TO_STRING(OMX_ErrorVersionMismatch);
CASE_TO_STRING(OMX_ErrorNotReady);
CASE_TO_STRING(OMX_ErrorTimeout);
CASE_TO_STRING(OMX_ErrorSameState);
CASE_TO_STRING(OMX_ErrorResourcesPreempted);
CASE_TO_STRING(OMX_ErrorPortUnresponsiveDuringAllocation);
CASE_TO_STRING(OMX_ErrorPortUnresponsiveDuringDeallocation);
CASE_TO_STRING(OMX_ErrorPortUnresponsiveDuringStop);
CASE_TO_STRING(OMX_ErrorIncorrectStateTransition);
CASE_TO_STRING(OMX_ErrorIncorrectStateOperation);
CASE_TO_STRING(OMX_ErrorUnsupportedSetting);
CASE_TO_STRING(OMX_ErrorUnsupportedIndex);
CASE_TO_STRING(OMX_ErrorBadPortIndex);
CASE_TO_STRING(OMX_ErrorPortUnpopulated);
CASE_TO_STRING(OMX_ErrorComponentSuspended);
CASE_TO_STRING(OMX_ErrorDynamicResourcesUnavailable);
CASE_TO_STRING(OMX_ErrorMbErrorsInFrame);
CASE_TO_STRING(OMX_ErrorFormatNotDetected);
CASE_TO_STRING(OMX_ErrorContentPipeOpenFailed);
CASE_TO_STRING(OMX_ErrorContentPipeCreationFailed);
CASE_TO_STRING(OMX_ErrorSeperateTablesUsed);
CASE_TO_STRING(OMX_ErrorTunnelingUnsupported);
CASE_TO_STRING(OMX_ErrorKhronosExtensions);
CASE_TO_STRING(OMX_ErrorVendorStartUnused);
CASE_TO_STRING(OMX_ErrorDiskFull);
CASE_TO_STRING(OMX_ErrorMaxFileSize);
CASE_TO_STRING(OMX_ErrorDrmUnauthorised);
CASE_TO_STRING(OMX_ErrorDrmExpired);
CASE_TO_STRING(OMX_ErrorDrmGeneral);
default: return "Unknown OMX error";
}
}
const char *omx_state_to_string(OMX_STATETYPE state) {
switch (state) {
CASE_TO_STRING(OMX_StateInvalid);
CASE_TO_STRING(OMX_StateLoaded);
CASE_TO_STRING(OMX_StateIdle);
CASE_TO_STRING(OMX_StateExecuting);
CASE_TO_STRING(OMX_StatePause);
CASE_TO_STRING(OMX_StateWaitForResources);
// cppcheck-suppress constArgument
// cppcheck-suppress knownArgument
default: break;
}
assert(0 && "Unsupported OMX state");
}
#undef CASE_TO_STRING

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -23,7 +23,7 @@
#include "gpio.h"
gpio_s gpio = {
gpio_s us_gpio = {
.path = "/dev/gpiochip0",
.consumer_prefix = "ustreamer",
@@ -51,42 +51,42 @@ static void _gpio_output_destroy(gpio_output_s *output);
void gpio_init(void) {
assert(gpio.chip == NULL);
assert(us_gpio.chip == NULL);
if (
gpio.prog_running.pin >= 0
|| gpio.stream_online.pin >= 0
|| gpio.has_http_clients.pin >= 0
us_gpio.prog_running.pin >= 0
|| us_gpio.stream_online.pin >= 0
|| us_gpio.has_http_clients.pin >= 0
) {
A_MUTEX_INIT(&gpio.mutex);
LOG_INFO("GPIO: Using chip device: %s", gpio.path);
if ((gpio.chip = gpiod_chip_open(gpio.path)) != NULL) {
_gpio_output_init(&gpio.prog_running);
_gpio_output_init(&gpio.stream_online);
_gpio_output_init(&gpio.has_http_clients);
A_MUTEX_INIT(&us_gpio.mutex);
LOG_INFO("GPIO: Using chip device: %s", us_gpio.path);
if ((us_gpio.chip = gpiod_chip_open(us_gpio.path)) != NULL) {
_gpio_output_init(&us_gpio.prog_running);
_gpio_output_init(&us_gpio.stream_online);
_gpio_output_init(&us_gpio.has_http_clients);
} else {
LOG_PERROR("GPIO: Can't initialize chip device %s", gpio.path);
LOG_PERROR("GPIO: Can't initialize chip device %s", us_gpio.path);
}
}
}
void gpio_destroy(void) {
_gpio_output_destroy(&gpio.prog_running);
_gpio_output_destroy(&gpio.stream_online);
_gpio_output_destroy(&gpio.has_http_clients);
if (gpio.chip) {
gpiod_chip_close(gpio.chip);
gpio.chip = NULL;
A_MUTEX_DESTROY(&gpio.mutex);
_gpio_output_destroy(&us_gpio.prog_running);
_gpio_output_destroy(&us_gpio.stream_online);
_gpio_output_destroy(&us_gpio.has_http_clients);
if (us_gpio.chip) {
gpiod_chip_close(us_gpio.chip);
us_gpio.chip = NULL;
A_MUTEX_DESTROY(&us_gpio.mutex);
}
}
int gpio_inner_set(gpio_output_s *output, bool state) {
int retval = 0;
assert(gpio.chip);
assert(us_gpio.chip);
assert(output->line);
assert(output->state != state); // Must be checked in macro for the performance
A_MUTEX_LOCK(&gpio.mutex);
A_MUTEX_LOCK(&us_gpio.mutex);
if (gpiod_line_set_value(output->line, (int)state) < 0) { \
LOG_PERROR("GPIO: Can't write value %d to line %s (will be disabled)", state, output->consumer); \
@@ -94,19 +94,18 @@ int gpio_inner_set(gpio_output_s *output, bool state) {
retval = -1;
}
A_MUTEX_UNLOCK(&gpio.mutex);
A_MUTEX_UNLOCK(&us_gpio.mutex);
return retval;
}
static void _gpio_output_init(gpio_output_s *output) {
assert(gpio.chip);
assert(us_gpio.chip);
assert(output->line == NULL);
A_CALLOC(output->consumer, strlen(gpio.consumer_prefix) + strlen(output->role) + 16);
sprintf(output->consumer, "%s::%s", gpio.consumer_prefix, output->role);
A_ASPRINTF(output->consumer, "%s::%s", us_gpio.consumer_prefix, output->role);
if (output->pin >= 0) {
if ((output->line = gpiod_chip_get_line(gpio.chip, output->pin)) != NULL) {
if ((output->line = gpiod_chip_get_line(us_gpio.chip, output->pin)) != NULL) {
if (gpiod_line_request_output(output->line, output->consumer, 0) < 0) {
LOG_PERROR("GPIO: Can't request pin=%d as %s", output->pin, output->consumer);
_gpio_output_destroy(output);

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -56,7 +56,7 @@ typedef struct {
} gpio_s;
extern gpio_s gpio;
extern gpio_s us_gpio;
void gpio_init(void);
@@ -73,15 +73,15 @@ int gpio_inner_set(gpio_output_s *output, bool state);
}
INLINE void gpio_set_prog_running(bool state) {
SET_STATE(gpio.prog_running, state);
SET_STATE(us_gpio.prog_running, state);
}
INLINE void gpio_set_stream_online(bool state) {
SET_STATE(gpio.stream_online, state);
SET_STATE(us_gpio.stream_online, state);
}
INLINE void gpio_set_has_http_clients(bool state) {
SET_STATE(gpio.has_http_clients, state);
SET_STATE(us_gpio.has_http_clients, state);
}
#undef SET_STATE

View File

@@ -1,391 +0,0 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
# #
*****************************************************************************/
#include "encoder.h"
static void _h264_encoder_cleanup(h264_encoder_s *enc);
static int _h264_encoder_compress_raw(h264_encoder_s *enc, const frame_s *src, int src_vcsm_handle, frame_s *dest, bool force_key);
static void _mmal_callback(MMAL_WRAPPER_T *wrapper);
static const char *_mmal_error_to_string(MMAL_STATUS_T error);
#define LOG_ERROR_MMAL(_error, _msg, ...) { \
LOG_ERROR(_msg ": %s", ##__VA_ARGS__, _mmal_error_to_string(_error)); \
}
h264_encoder_s *h264_encoder_init(unsigned bitrate, unsigned gop, unsigned fps) {
LOG_INFO("H264: Initializing MMAL encoder ...");
LOG_INFO("H264: Using bitrate: %u Kbps", bitrate);
LOG_INFO("H264: Using GOP: %u", gop);
h264_encoder_s *enc;
A_CALLOC(enc, 1);
enc->bitrate = bitrate; // Kbps
enc->gop = gop; // Interval between keyframes
enc->fps = fps;
enc->last_online = -1;
if (vcos_semaphore_create(&enc->handler_sem, "h264_handler_sem", 0) != VCOS_SUCCESS) {
LOG_PERROR("H264: Can't create VCOS semaphore");
goto error;
}
enc->i_handler_sem = true;
MMAL_STATUS_T error = mmal_wrapper_create(&enc->wrapper, MMAL_COMPONENT_DEFAULT_VIDEO_ENCODER);
if (error != MMAL_SUCCESS) {
LOG_ERROR_MMAL(error, "H264: Can't create MMAL wrapper");
enc->wrapper = NULL;
goto error;
}
enc->wrapper->user_data = (void *)enc;
enc->wrapper->callback = _mmal_callback;
return enc;
error:
h264_encoder_destroy(enc);
return NULL;
}
void h264_encoder_destroy(h264_encoder_s *enc) {
LOG_INFO("H264: Destroying MMAL encoder ...");
_h264_encoder_cleanup(enc);
if (enc->wrapper) {
MMAL_STATUS_T error = mmal_wrapper_destroy(enc->wrapper);
if (error != MMAL_SUCCESS) {
LOG_ERROR_MMAL(error, "H264: Can't destroy MMAL encoder");
}
}
if (enc->i_handler_sem) {
vcos_semaphore_delete(&enc->handler_sem);
}
free(enc);
}
bool h264_encoder_is_prepared_for(h264_encoder_s *enc, const frame_s *frame, bool zero_copy) {
# define EQ(_field) (enc->_field == frame->_field)
return (EQ(width) && EQ(height) && EQ(format) && EQ(stride) && (enc->zero_copy == zero_copy));
# undef EQ
}
int h264_encoder_prepare(h264_encoder_s *enc, const frame_s *frame, bool zero_copy) {
LOG_INFO("H264: Configuring MMAL encoder: zero_copy=%d ...", zero_copy);
_h264_encoder_cleanup(enc);
enc->width = frame->width;
enc->height = frame->height;
enc->format = frame->format;
enc->stride = frame->stride;
enc->zero_copy = zero_copy;
if (align_size(frame->width, 32) != frame->width && frame_get_padding(frame) == 0) {
LOG_ERROR("H264: MMAL encoder can't handle unaligned width");
goto error;
}
MMAL_STATUS_T error;
# define PREPARE_PORT(_id) { \
enc->_id##_port = enc->wrapper->_id[0]; \
if (enc->_id##_port->is_enabled) { \
if ((error = mmal_wrapper_port_disable(enc->_id##_port)) != MMAL_SUCCESS) { \
LOG_ERROR_MMAL(error, "H264: Can't disable MMAL %s port while configuring", #_id); \
goto error; \
} \
} \
}
# define COMMIT_PORT(_id) { \
if ((error = mmal_port_format_commit(enc->_id##_port)) != MMAL_SUCCESS) { \
LOG_ERROR_MMAL(error, "H264: Can't commit MMAL %s port", #_id); \
goto error; \
} \
}
# define SET_PORT_PARAM(_id, _type, _key, _value) { \
if ((error = mmal_port_parameter_set_##_type(enc->_id##_port, MMAL_PARAMETER_##_key, _value)) != MMAL_SUCCESS) { \
LOG_ERROR_MMAL(error, "H264: Can't set %s for the %s port", #_key, #_id); \
goto error; \
} \
}
# define ENABLE_PORT(_id) { \
if ((error = mmal_wrapper_port_enable(enc->_id##_port, MMAL_WRAPPER_FLAG_PAYLOAD_ALLOCATE)) != MMAL_SUCCESS) { \
LOG_ERROR_MMAL(error, "H264: Can't enable MMAL %s port", #_id); \
goto error; \
} \
}
{
PREPARE_PORT(input);
# define IFMT(_next) enc->input_port->format->_next
IFMT(type) = MMAL_ES_TYPE_VIDEO;
switch (frame->format) {
case V4L2_PIX_FMT_YUYV: IFMT(encoding) = MMAL_ENCODING_YUYV; break;
case V4L2_PIX_FMT_UYVY: IFMT(encoding) = MMAL_ENCODING_UYVY; break;
case V4L2_PIX_FMT_RGB565: IFMT(encoding) = MMAL_ENCODING_RGB16; break;
case V4L2_PIX_FMT_RGB24: IFMT(encoding) = MMAL_ENCODING_RGB24; break;
default: assert(0 && "Unsupported pixelformat");
}
IFMT(es->video.width) = align_size(frame->width, 32);
IFMT(es->video.height) = align_size(frame->height, 16);
IFMT(es->video.crop.x) = 0;
IFMT(es->video.crop.y) = 0;
IFMT(es->video.crop.width) = frame->width;
IFMT(es->video.crop.height) = frame->height;
IFMT(flags) = MMAL_ES_FORMAT_FLAG_FRAMED;
enc->input_port->buffer_size = 1000 * 1000;
enc->input_port->buffer_num = enc->input_port->buffer_num_recommended * 4;
# undef IFMT
COMMIT_PORT(input);
SET_PORT_PARAM(input, boolean, ZERO_COPY, zero_copy);
}
{
PREPARE_PORT(output);
# define OFMT(_next) enc->output_port->format->_next
OFMT(type) = MMAL_ES_TYPE_VIDEO;
OFMT(encoding) = MMAL_ENCODING_H264;
OFMT(encoding_variant) = MMAL_ENCODING_VARIANT_H264_DEFAULT;
OFMT(bitrate) = enc->bitrate * 1000;
OFMT(es->video.frame_rate.num) = enc->fps;
OFMT(es->video.frame_rate.den) = 1;
enc->output_port->buffer_size = enc->output_port->buffer_size_recommended * 4;
enc->output_port->buffer_num = enc->output_port->buffer_num_recommended;
# undef OFMT
COMMIT_PORT(output);
{
MMAL_PARAMETER_VIDEO_PROFILE_T profile;
MEMSET_ZERO(profile);
profile.hdr.id = MMAL_PARAMETER_PROFILE;
profile.hdr.size = sizeof(profile);
// http://blog.mediacoderhq.com/h264-profiles-and-levels
profile.profile[0].profile = MMAL_VIDEO_PROFILE_H264_CONSTRAINED_BASELINE;
profile.profile[0].level = MMAL_VIDEO_LEVEL_H264_4; // Supports 1080p
if ((error = mmal_port_parameter_set(enc->output_port, &profile.hdr)) != MMAL_SUCCESS) {
LOG_ERROR_MMAL(error, "H264: Can't set MMAL_PARAMETER_PROFILE for the output port");
goto error;
}
}
SET_PORT_PARAM(output, boolean, ZERO_COPY, MMAL_TRUE);
SET_PORT_PARAM(output, uint32, INTRAPERIOD, enc->gop);
SET_PORT_PARAM(output, uint32, NALUNITFORMAT, MMAL_VIDEO_NALUNITFORMAT_STARTCODES);
SET_PORT_PARAM(output, boolean, MINIMISE_FRAGMENTATION, MMAL_TRUE);
SET_PORT_PARAM(output, uint32, MB_ROWS_PER_SLICE, 0);
SET_PORT_PARAM(output, boolean, VIDEO_IMMUTABLE_INPUT, MMAL_TRUE);
SET_PORT_PARAM(output, boolean, VIDEO_DROPPABLE_PFRAMES, MMAL_FALSE);
SET_PORT_PARAM(output, boolean, VIDEO_ENCODE_INLINE_HEADER, MMAL_TRUE); // SPS/PPS: https://github.com/raspberrypi/userland/issues/443
SET_PORT_PARAM(output, uint32, VIDEO_BIT_RATE, enc->bitrate * 1000);
SET_PORT_PARAM(output, uint32, VIDEO_ENCODE_PEAK_RATE, enc->bitrate * 1000);
SET_PORT_PARAM(output, uint32, VIDEO_ENCODE_MIN_QUANT, 16);
SET_PORT_PARAM(output, uint32, VIDEO_ENCODE_MAX_QUANT, 34);
SET_PORT_PARAM(output, uint32, VIDEO_ENCODE_FRAME_LIMIT_BITS, 1000000);
SET_PORT_PARAM(output, uint32, VIDEO_ENCODE_H264_AU_DELIMITERS, MMAL_FALSE);
}
ENABLE_PORT(input);
ENABLE_PORT(output);
enc->ready = true;
return 0;
error:
_h264_encoder_cleanup(enc);
LOG_ERROR("H264: Encoder disabled due error (prepare)");
return -1;
# undef ENABLE_PORT
# undef SET_PORT_PARAM
# undef COMMIT_PORT
# undef PREPARE_PORT
}
static void _h264_encoder_cleanup(h264_encoder_s *enc) {
MMAL_STATUS_T error;
# define DISABLE_PORT(_id) { \
if (enc->_id##_port) { \
if ((error = mmal_wrapper_port_disable(enc->_id##_port)) != MMAL_SUCCESS) { \
LOG_ERROR_MMAL(error, "H264: Can't disable MMAL %s port", #_id); \
} \
enc->_id##_port = NULL; \
} \
}
DISABLE_PORT(input);
DISABLE_PORT(output);
# undef DISABLE_PORT
if (enc->wrapper) {
enc->wrapper->status = MMAL_SUCCESS; // Это реально надо?
}
enc->last_online = -1;
enc->ready = false;
}
int h264_encoder_compress(h264_encoder_s *enc, const frame_s *src, int src_vcsm_handle, frame_s *dest, bool force_key) {
assert(enc->ready);
assert(src->used > 0);
assert(enc->width == src->width);
assert(enc->height == src->height);
assert(enc->format == src->format);
assert(enc->stride == src->stride);
frame_copy_meta(src, dest);
dest->encode_begin_ts = get_now_monotonic();
dest->format = V4L2_PIX_FMT_H264;
dest->stride = 0;
force_key = (force_key || enc->last_online != src->online);
if (_h264_encoder_compress_raw(enc, src, src_vcsm_handle, dest, force_key) < 0) {
_h264_encoder_cleanup(enc);
LOG_ERROR("H264: Encoder disabled due error (compress)");
return -1;
}
dest->encode_end_ts = get_now_monotonic();
LOG_VERBOSE("H264: Compressed new frame: size=%zu, time=%0.3Lf, force_key=%d",
dest->used, dest->encode_end_ts - dest->encode_begin_ts, force_key);
enc->last_online = src->online;
return 0;
}
static int _h264_encoder_compress_raw(h264_encoder_s *enc, const frame_s *src, int src_vcsm_handle, frame_s *dest, bool force_key) {
LOG_DEBUG("H264: Compressing new frame; force_key=%d ...", force_key);
MMAL_STATUS_T error;
if (force_key) {
if ((error = mmal_port_parameter_set_boolean(
enc->output_port,
MMAL_PARAMETER_VIDEO_REQUEST_I_FRAME,
MMAL_TRUE
)) != MMAL_SUCCESS) {
LOG_ERROR_MMAL(error, "H264: Can't request keyframe");
return -1;
}
}
MMAL_BUFFER_HEADER_T *out = NULL;
MMAL_BUFFER_HEADER_T *in = NULL;
bool eos = false;
bool sent = false;
dest->used = 0;
while (!eos) {
out = NULL;
while (mmal_wrapper_buffer_get_empty(enc->output_port, &out, 0) == MMAL_SUCCESS) {
if ((error = mmal_port_send_buffer(enc->output_port, out)) != MMAL_SUCCESS) {
LOG_ERROR_MMAL(error, "H264: Can't send MMAL output buffer");
return -1;
}
}
in = NULL;
if (!sent && mmal_wrapper_buffer_get_empty(enc->input_port, &in, 0) == MMAL_SUCCESS) {
if (enc->zero_copy && src_vcsm_handle > 0) {
in->data = (uint8_t *)vcsm_vc_hdl_from_hdl(src_vcsm_handle);
} else {
in->data = src->data;
}
in->alloc_size = src->used;
in->length = src->used;
in->offset = 0;
in->flags = MMAL_BUFFER_HEADER_FLAG_EOS;
if ((error = mmal_port_send_buffer(enc->input_port, in)) != MMAL_SUCCESS) {
LOG_ERROR_MMAL(error, "H264: Can't send MMAL input buffer");
return -1;
}
sent = true;
}
error = mmal_wrapper_buffer_get_full(enc->output_port, &out, 0);
if (error == MMAL_EAGAIN) {
vcos_semaphore_wait(&enc->handler_sem);
continue;
} else if (error != MMAL_SUCCESS) {
LOG_ERROR_MMAL(error, "H264: Can't get MMAL output buffer");
return -1;
}
frame_append_data(dest, out->data, out->length);
eos = out->flags & MMAL_BUFFER_HEADER_FLAG_EOS;
mmal_buffer_header_release(out);
}
if ((error = mmal_port_flush(enc->output_port)) != MMAL_SUCCESS) {
LOG_ERROR_MMAL(error, "H264: Can't flush MMAL output buffer; ignored");
}
return 0;
}
static void _mmal_callback(MMAL_WRAPPER_T *wrapper) {
vcos_semaphore_post(&((h264_encoder_s *)(wrapper->user_data))->handler_sem);
}
static const char *_mmal_error_to_string(MMAL_STATUS_T error) {
// http://www.jvcref.com/files/PI/documentation/html/group___mmal_types.html
# define CASE_ERROR(_name, _msg) case MMAL_##_name: return "MMAL_" #_name " [" _msg "]"
switch (error) {
case MMAL_SUCCESS: return "MMAL_SUCCESS";
CASE_ERROR(ENOMEM, "Out of memory");
CASE_ERROR(ENOSPC, "Out of resources");
CASE_ERROR(EINVAL, "Invalid argument");
CASE_ERROR(ENOSYS, "Function not implemented");
CASE_ERROR(ENOENT, "No such file or directory");
CASE_ERROR(ENXIO, "No such device or address");
CASE_ERROR(EIO, "IO error");
CASE_ERROR(ESPIPE, "Illegal seek");
CASE_ERROR(ECORRUPT, "Data is corrupt");
CASE_ERROR(ENOTREADY, "Component is not ready");
CASE_ERROR(ECONFIG, "Component is not configured");
CASE_ERROR(EISCONN, "Port is already connected");
CASE_ERROR(ENOTCONN, "Port is disconnected");
CASE_ERROR(EAGAIN, "Resource temporarily unavailable");
CASE_ERROR(EFAULT, "Bad address");
case MMAL_STATUS_MAX: break; // Makes cpplint happy
}
return "Unknown error";
# undef CASE_ERROR
}
#undef LOG_ERROR_MMAL

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -23,72 +23,42 @@
#include "stream.h"
h264_stream_s *h264_stream_init(memsink_s *sink, unsigned bitrate, unsigned gop) {
h264_stream_s *h264_stream_init(memsink_s *sink, const char *path, unsigned bitrate, unsigned gop) {
h264_stream_s *h264;
A_CALLOC(h264, 1);
h264->sink = sink;
h264->tmp_src = frame_init("h264_tmp_src");
h264->dest = frame_init("h264_dest");
h264->tmp_src = frame_init();
h264->dest = frame_init();
atomic_init(&h264->online, false);
// FIXME: 30 or 0? https://github.com/6by9/yavta/blob/master/yavta.c#L210
if ((h264->enc = h264_encoder_init(bitrate, gop, 0)) == NULL) {
goto error;
}
h264->enc = m2m_h264_encoder_init("H264", path, bitrate, gop);
return h264;
error:
h264_stream_destroy(h264);
return NULL;
}
void h264_stream_destroy(h264_stream_s *h264) {
if (h264->enc) {
h264_encoder_destroy(h264->enc);
}
m2m_encoder_destroy(h264->enc);
frame_destroy(h264->dest);
frame_destroy(h264->tmp_src);
free(h264);
}
void h264_stream_process(h264_stream_s *h264, const frame_s *frame, int vcsm_handle, bool force_key) {
void h264_stream_process(h264_stream_s *h264, const frame_s *frame, bool force_key) {
if (!memsink_server_check(h264->sink, frame)) {
return;
}
long double now = get_now_monotonic();
bool zero_copy = false;
if (is_jpeg(frame->format)) {
assert(vcsm_handle <= 0);
long double now = get_now_monotonic();
LOG_DEBUG("H264: Input frame is JPEG; decoding ...");
if (unjpeg(frame, h264->tmp_src, true) < 0) {
return;
}
frame = h264->tmp_src;
LOG_VERBOSE("H264: JPEG decoded; time=%.3Lf", get_now_monotonic() - now);
} else if (vcsm_handle > 0) {
LOG_DEBUG("H264: Zero-copy available for the input");
zero_copy = true;
} else {
LOG_DEBUG("H264: Copying source to tmp buffer ...");
frame_copy(frame, h264->tmp_src);
frame = h264->tmp_src;
LOG_VERBOSE("H264: Source copied; time=%.3Lf", get_now_monotonic() - now);
}
bool online = false;
if (!h264_encoder_is_prepared_for(h264->enc, frame, zero_copy)) {
h264_encoder_prepare(h264->enc, frame, zero_copy);
if (!m2m_encoder_compress(h264->enc, frame, h264->dest, force_key)) {
online = !memsink_server_put(h264->sink, h264->dest);
}
if (h264->enc->ready) {
if (h264_encoder_compress(h264->enc, frame, vcsm_handle, h264->dest, force_key) == 0) {
online = !memsink_server_put(h264->sink, h264->dest);
}
}
atomic_store(&h264->online, online);
}

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -31,19 +31,18 @@
#include "../../libs/frame.h"
#include "../../libs/memsink.h"
#include "../../libs/unjpeg.h"
#include "encoder.h"
#include "../m2m.h"
typedef struct {
memsink_s *sink;
frame_s *tmp_src;
frame_s *dest;
h264_encoder_s *enc;
m2m_encoder_s *enc;
atomic_bool online;
} h264_stream_s;
h264_stream_s *h264_stream_init(memsink_s *sink, unsigned bitrate, unsigned gop);
h264_stream_s *h264_stream_init(memsink_s *sink, const char *path, unsigned bitrate, unsigned gop);
void h264_stream_destroy(h264_stream_s *h264);
void h264_stream_process(h264_stream_s *h264, const frame_s *frame, int vcsm_handle, bool force_key);
void h264_stream_process(h264_stream_s *h264, const frame_s *frame, bool force_key);

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -25,6 +25,8 @@
static int _http_preprocess_request(struct evhttp_request *request, server_s *server);
static int _http_check_run_compat_action(struct evhttp_request *request, void *v_server);
static void _http_callback_root(struct evhttp_request *request, void *v_server);
static void _http_callback_static(struct evhttp_request *request, void *v_server);
static void _http_callback_state(struct evhttp_request *request, void *v_server);
@@ -34,11 +36,14 @@ static void _http_callback_stream(struct evhttp_request *request, void *v_server
static void _http_callback_stream_write(struct bufferevent *buf_event, void *v_ctx);
static void _http_callback_stream_error(struct bufferevent *buf_event, short what, void *v_ctx);
static void _http_exposed_refresh(int fd, short event, void *v_server);
static void _http_request_watcher(int fd, short event, void *v_server);
static void _http_refresher(int fd, short event, void *v_server);
static void _http_queue_send_stream(server_s *server, bool stream_updated, bool frame_updated);
static bool _expose_new_frame(server_s *server);
static char *_http_get_client_hostport(struct evhttp_request *request);
#define RUN(_next) server->run->_next
#define STREAM(_next) RUN(stream->_next)
@@ -49,7 +54,7 @@ static bool _expose_new_frame(server_s *server);
server_s *server_init(stream_s *stream) {
exposed_s *exposed;
A_CALLOC(exposed, 1);
exposed->frame = frame_init("http_exposed");
exposed->frame = frame_init();
server_runtime_s *run;
A_CALLOC(run, 1);
@@ -71,19 +76,24 @@ server_s *server_init(stream_s *stream) {
assert(!evthread_use_pthreads());
assert((run->base = event_base_new()));
assert((run->http = evhttp_new(run->base)));
evhttp_set_allowed_methods(run->http, EVHTTP_REQ_GET|EVHTTP_REQ_HEAD);
evhttp_set_allowed_methods(run->http, EVHTTP_REQ_GET|EVHTTP_REQ_HEAD|EVHTTP_REQ_OPTIONS);
return server;
}
void server_destroy(server_s *server) {
if (RUN(refresh)) {
event_del(RUN(refresh));
event_free(RUN(refresh));
if (RUN(refresher)) {
event_del(RUN(refresher));
event_free(RUN(refresher));
}
if (RUN(request_watcher)) {
event_del(RUN(request_watcher));
event_free(RUN(request_watcher));
}
evhttp_free(RUN(http));
if (RUN(unix_fd)) {
close(RUN(unix_fd));
if (RUN(ext_fd)) {
close(RUN(ext_fd));
}
event_base_free(RUN(base));
@@ -91,12 +101,11 @@ void server_destroy(server_s *server) {
libevent_global_shutdown();
# endif
for (stream_client_s *client = RUN(stream_clients); client != NULL;) {
stream_client_s *next = client->next;
LIST_ITERATE(RUN(stream_clients), client, {
free(client->key);
free(client->hostport);
free(client);
client = next;
}
});
if (RUN(auth_token)) {
free(RUN(auth_token));
@@ -125,33 +134,36 @@ int server_listen(server_s *server) {
EX(notify_last_width) = EX(frame->width);
EX(notify_last_height) = EX(frame->height);
if (server->exit_on_no_clients > 0) {
RUN(last_request_ts) = get_now_monotonic();
struct timeval interval = {0};
interval.tv_usec = 100000;
assert((RUN(request_watcher) = event_new(RUN(base), -1, EV_PERSIST, _http_request_watcher, server)));
assert(!event_add(RUN(request_watcher), &interval));
}
{
struct timeval refresh_interval;
refresh_interval.tv_sec = 0;
struct timeval interval = {0};
if (STREAM(dev->desired_fps) > 0) {
refresh_interval.tv_usec = 1000000 / (STREAM(dev->desired_fps) * 2);
interval.tv_usec = 1000000 / (STREAM(dev->desired_fps) * 2);
} else {
refresh_interval.tv_usec = 16000; // ~60fps
interval.tv_usec = 16000; // ~60fps
}
assert((RUN(refresh) = event_new(RUN(base), -1, EV_PERSIST, _http_exposed_refresh, server)));
assert(!event_add(RUN(refresh), &refresh_interval));
assert((RUN(refresher) = event_new(RUN(base), -1, EV_PERSIST, _http_refresher, server)));
assert(!event_add(RUN(refresher), &interval));
}
evhttp_set_timeout(RUN(http), server->timeout);
if (server->user[0] != '\0') {
char *raw_token;
char *encoded_token = NULL;
A_CALLOC(raw_token, strlen(server->user) + strlen(server->passwd) + 16);
sprintf(raw_token, "%s:%s", server->user, server->passwd);
char *raw_token;
A_ASPRINTF(raw_token, "%s:%s", server->user, server->passwd);
base64_encode((uint8_t *)raw_token, strlen(raw_token), &encoded_token, NULL);
free(raw_token);
A_CALLOC(RUN(auth_token), strlen(encoded_token) + 16);
sprintf(RUN(auth_token), "Basic %s", encoded_token);
A_ASPRINTF(RUN(auth_token), "Basic %s", encoded_token);
free(encoded_token);
LOG_INFO("Using HTTP basic auth");
@@ -159,7 +171,7 @@ int server_listen(server_s *server) {
if (server->unix_path[0] != '\0') {
LOG_DEBUG("Binding HTTP to UNIX socket '%s' ...", server->unix_path);
if ((RUN(unix_fd) = evhttp_my_bind_unix(
if ((RUN(ext_fd) = evhttp_my_bind_unix(
RUN(http),
server->unix_path,
server->unix_rm,
@@ -168,9 +180,16 @@ int server_listen(server_s *server) {
return -1;
}
LOG_INFO("Listening HTTP on UNIX socket '%s'", server->unix_path);
if (server->tcp_nodelay) {
LOG_ERROR("TCP_NODELAY flag can't be used with UNIX socket and will be ignored");
# ifdef WITH_SYSTEMD
} else if (server->systemd) {
LOG_DEBUG("Binding HTTP to systemd socket ...");
if ((RUN(ext_fd) = evhttp_my_bind_systemd(RUN(http))) < 0) {
return -1;
}
LOG_INFO("Listening systemd socket ...");
# endif
} else {
LOG_DEBUG("Binding HTTP to [%s]:%u ...", server->host, server->port);
if (evhttp_bind_socket(RUN(http), server->host, server->port) < 0) {
@@ -193,12 +212,36 @@ void server_loop_break(server_s *server) {
event_base_loopbreak(RUN(base));
}
#define GET_HEADER(_key) \
evhttp_find_header(evhttp_request_get_input_headers(request), _key)
#define ADD_HEADER(_key, _value) \
assert(!evhttp_add_header(evhttp_request_get_output_headers(request), _key, _value))
static int _http_preprocess_request(struct evhttp_request *request, server_s *server) {
RUN(last_request_ts) = get_now_monotonic();
if (server->allow_origin[0] != '\0') {
const char *cors_headers = GET_HEADER("Access-Control-Request-Headers");
const char *cors_method = GET_HEADER("Access-Control-Request-Method");
ADD_HEADER("Access-Control-Allow-Origin", server->allow_origin);
ADD_HEADER("Access-Control-Allow-Credentials", "true");
if (cors_headers != NULL) {
ADD_HEADER("Access-Control-Allow-Headers", cors_headers);
}
if (cors_method != NULL) {
ADD_HEADER("Access-Control-Allow-Methods", cors_method);
}
}
if (evhttp_request_get_command(request) == EVHTTP_REQ_OPTIONS) {
evhttp_send_reply(request, HTTP_OK, "OK", NULL);
return -1;
}
if (RUN(auth_token)) {
const char *token = evhttp_find_header(evhttp_request_get_input_headers(request), "Authorization");
const char *token = GET_HEADER("Authorization");
if (token == NULL || strcmp(token, RUN(auth_token)) != 0) {
ADD_HEADER("WWW-Authenticate", "Basic realm=\"Restricted area\"");
@@ -207,8 +250,8 @@ static int _http_preprocess_request(struct evhttp_request *request, server_s *se
}
}
if (evhttp_request_get_command(request) == EVHTTP_REQ_HEAD) { \
evhttp_send_reply(request, HTTP_OK, "OK", NULL); \
if (evhttp_request_get_command(request) == EVHTTP_REQ_HEAD) {
evhttp_send_reply(request, HTTP_OK, "OK", NULL);
return -1;
}
@@ -221,41 +264,63 @@ static int _http_preprocess_request(struct evhttp_request *request, server_s *se
} \
}
static void _http_callback_root(struct evhttp_request *request, void *v_server) {
server_s *server = (server_s *)v_server;
static int _http_check_run_compat_action(struct evhttp_request *request, void *v_server) {
// MJPG-Streamer compatibility layer
PREPROCESS_REQUEST;
struct evkeyvalq params;
int error = 0;
struct evkeyvalq params; // For mjpg-streamer compatibility
evhttp_parse_query(evhttp_request_get_uri(request), &params);
const char *action = evhttp_find_header(&params, "action");
if (action && !strcmp(action, "snapshot")) {
_http_callback_snapshot(request, v_server);
goto ok;
} else if (action && !strcmp(action, "stream")) {
_http_callback_stream(request, v_server);
} else {
struct evbuffer *buf;
assert((buf = evbuffer_new()));
assert(evbuffer_add_printf(buf, "%s", HTML_INDEX_PAGE));
ADD_HEADER("Content-Type", "text/html");
evhttp_send_reply(request, HTTP_OK, "OK", buf);
evbuffer_free(buf);
goto ok;
}
evhttp_clear_headers(&params);
error = -1;
ok:
evhttp_clear_headers(&params);
return error;
}
#define COMPAT_REQUEST { \
if (_http_check_run_compat_action(request, v_server) == 0) { \
return; \
} \
}
static void _http_callback_root(struct evhttp_request *request, void *v_server) {
server_s *server = (server_s *)v_server;
PREPROCESS_REQUEST;
COMPAT_REQUEST;
struct evbuffer *buf;
assert((buf = evbuffer_new()));
assert(evbuffer_add_printf(buf, "%s", HTML_INDEX_PAGE));
ADD_HEADER("Content-Type", "text/html");
evhttp_send_reply(request, HTTP_OK, "OK", buf);
evbuffer_free(buf);
}
static void _http_callback_static(struct evhttp_request *request, void *v_server) {
server_s *server = (server_s *)v_server;
PREPROCESS_REQUEST;
COMPAT_REQUEST;
struct evbuffer *buf = NULL;
struct evhttp_uri *uri = NULL;
char *decoded_path = NULL;
char *static_path = NULL;
int fd = -1;
PREPROCESS_REQUEST;
{
char *uri_path;
@@ -294,6 +359,10 @@ static void _http_callback_static(struct evhttp_request *request, void *v_server
goto not_found;
}
// evbuffer_add_file() owns the resulting file descriptor
// and will close it when finished transferring data
fd = -1;
ADD_HEADER("Content-Type", guess_mime_type(static_path));
evhttp_send_reply(request, HTTP_OK, "OK", buf);
goto cleanup;
@@ -325,6 +394,8 @@ static void _http_callback_static(struct evhttp_request *request, void *v_server
}
}
#undef COMPAT_REQUEST
static void _http_callback_state(struct evhttp_request *request, void *v_server) {
server_s *server = (server_s *)v_server;
@@ -343,7 +414,7 @@ static void _http_callback_state(struct evhttp_request *request, void *v_server)
encoder_type_to_string(enc_type),
enc_quality
));
# ifdef WITH_OMX
if (STREAM(run->h264)) {
assert(evbuffer_add_printf(buf,
" \"h264\": {\"bitrate\": %u, \"gop\": %u, \"online\": %s},",
@@ -352,7 +423,25 @@ static void _http_callback_state(struct evhttp_request *request, void *v_server)
bool_to_string(atomic_load(&STREAM(run->h264->online)))
));
}
# endif
if (STREAM(sink) || STREAM(h264_sink)) {
assert(evbuffer_add_printf(buf, " \"sinks\": {"));
if (STREAM(sink)) {
assert(evbuffer_add_printf(buf,
"\"jpeg\": {\"has_clients\": %s}",
bool_to_string(atomic_load(&STREAM(sink->has_clients)))
));
}
if (STREAM(h264_sink)) {
assert(evbuffer_add_printf(buf,
"%s\"h264\": {\"has_clients\": %s}",
(STREAM(sink) ? ", " : ""),
bool_to_string(atomic_load(&STREAM(h264_sink->has_clients)))
));
}
assert(evbuffer_add_printf(buf, "},"));
}
assert(evbuffer_add_printf(buf,
" \"source\": {\"resolution\": {\"width\": %u, \"height\": %u},"
" \"online\": %s, \"desired_fps\": %u, \"captured_fps\": %u},"
@@ -366,19 +455,20 @@ static void _http_callback_state(struct evhttp_request *request, void *v_server)
RUN(stream_clients_count)
));
for (stream_client_s * client = RUN(stream_clients); client != NULL; client = client->next) {
LIST_ITERATE(RUN(stream_clients), client, {
assert(evbuffer_add_printf(buf,
"\"%s\": {\"fps\": %u, \"extra_headers\": %s, \"advance_headers\": %s,"
" \"dual_final_frames\": %s, \"zero_data\": %s}%s",
"\"%" PRIx64 "\": {\"fps\": %u, \"extra_headers\": %s, \"advance_headers\": %s,"
" \"dual_final_frames\": %s, \"zero_data\": %s, \"key\": \"%s\"}%s",
client->id,
client->fps,
bool_to_string(client->extra_headers),
bool_to_string(client->advance_headers),
bool_to_string(client->dual_final_frames),
bool_to_string(client->zero_data),
(client->key != NULL ? client->key : "0"),
(client->next ? ", " : "")
));
}
});
assert(evbuffer_add_printf(buf, "}}}}"));
@@ -396,9 +486,6 @@ static void _http_callback_snapshot(struct evhttp_request *request, void *v_serv
assert((buf = evbuffer_new()));
assert(!evbuffer_add(buf, (const void *)EX(frame->data), EX(frame->used)));
if (server->allow_origin[0] != '\0') {
ADD_HEADER("Access-Control-Allow-Origin", server->allow_origin);
}
ADD_HEADER("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate, pre-check=0, post-check=0, max-age=0");
ADD_HEADER("Pragma", "no-cache");
ADD_HEADER("Expires", "Mon, 3 Jan 2000 12:34:56 GMT");
@@ -473,20 +560,10 @@ static void _http_callback_stream(struct evhttp_request *request, void *v_server
# undef PARSE_PARAM
evhttp_clear_headers(&params);
uuid_t uuid;
uuid_generate(uuid);
uuid_unparse_lower(uuid, client->id);
client->hostport = _http_get_client_hostport(request);
client->id = get_now_id();
if (RUN(stream_clients) == NULL) {
RUN(stream_clients) = client;
} else {
stream_client_s *last = RUN(stream_clients);
for (; last->next != NULL; last = last->next);
client->prev = last;
last->next = client;
}
RUN(stream_clients_count) += 1;
LIST_APPEND_C(RUN(stream_clients), client, RUN(stream_clients_count));
if (RUN(stream_clients_count) == 1) {
atomic_store(&VID(has_clients), true);
@@ -495,23 +572,18 @@ static void _http_callback_stream(struct evhttp_request *request, void *v_server
# endif
}
char *client_addr;
unsigned short client_port;
evhttp_connection_get_peer(conn, &client_addr, &client_port);
LOG_INFO("HTTP: Registered client: [%s]:%u, id=%s; clients now: %u",
client_addr, client_port, client->id, RUN(stream_clients_count));
LOG_INFO("HTTP: Registered client: %s, id=%" PRIx64 "; clients now: %u",
client->hostport, client->id, RUN(stream_clients_count));
struct bufferevent *buf_event = evhttp_connection_get_bufferevent(conn);
if (server->tcp_nodelay && !RUN(unix_fd)) {
if (server->tcp_nodelay && !RUN(ext_fd)) {
evutil_socket_t fd;
int on = 1;
LOG_DEBUG("HTTP: Setting up TCP_NODELAY to the client [%s]:%u ...", client_addr, client_port);
LOG_DEBUG("HTTP: Setting up TCP_NODELAY to the client %s ...", client->hostport);
assert((fd = bufferevent_getfd(buf_event)) >= 0);
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void *)&on, sizeof(on)) != 0) {
LOG_PERROR("HTTP: Can't set TCP_NODELAY to the client [%s]:%u", client_addr, client_port);
LOG_PERROR("HTTP: Can't set TCP_NODELAY to the client %s", client->hostport);
}
}
bufferevent_setcb(buf_event, NULL, NULL, _http_callback_stream_error, (void *)client);
@@ -525,9 +597,9 @@ static void _http_callback_stream(struct evhttp_request *request, void *v_server
static void _http_callback_stream_write(struct bufferevent *buf_event, void *v_client) {
# define BOUNDARY "boundarydonotcross"
# define RN "\r\n"
stream_client_s *client = (stream_client_s *)v_client;
struct evhttp_request *request = client->request; // for GET_HEADER
server_s *server = client->server;
long double now = get_now_monotonic();
@@ -555,7 +627,7 @@ static void _http_callback_stream_write(struct bufferevent *buf_event, void *v_c
// будущего фрейма сразу после данных текущего, чтобы триггернуть отрисовку.
// Естественным следствием этого является невозможность установки заголовка
// Content-Length, так как предсказывать будущее мы еще не научились.
// Его наличие не требуется RFC, однако никаких стандартов на MJPG over HTTP
// Его наличие не требуется RFC, однако никаких стандартов на MJPEG over HTTP
// в природе не существует, и никто не может гарантировать, что отсутствие
// Content-Length не сломает вещание для каких-нибудь маргинальных браузеров.
//
@@ -568,14 +640,29 @@ static void _http_callback_stream_write(struct bufferevent *buf_event, void *v_c
if (client->need_initial) {
assert(evbuffer_add_printf(buf, "HTTP/1.0 200 OK" RN));
if (client->server->allow_origin[0] != '\0') {
assert(evbuffer_add_printf(buf, "Access-Control-Allow-Origin: %s" RN, client->server->allow_origin));
const char *cors_headers = GET_HEADER("Access-Control-Request-Headers");
const char *cors_method = GET_HEADER("Access-Control-Request-Method");
assert(evbuffer_add_printf(buf,
"Access-Control-Allow-Origin: %s" RN
"Access-Control-Allow-Credentials: true" RN,
client->server->allow_origin
));
if (cors_headers != NULL) {
assert(evbuffer_add_printf(buf, "Access-Control-Allow-Headers: %s" RN, cors_headers));
}
if (cors_method != NULL) {
assert(evbuffer_add_printf(buf, "Access-Control-Allow-Methods: %s" RN, cors_method));
}
}
assert(evbuffer_add_printf(buf,
"Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate, pre-check=0, post-check=0, max-age=0" RN
"Pragma: no-cache" RN
"Expires: Mon, 3 Jan 2000 12:34:56 GMT" RN
"Set-Cookie: stream_client=%s/%s; path=/; max-age=30" RN
"Set-Cookie: stream_client=%s/%" PRIx64 "; path=/; max-age=30" RN
"Content-Type: multipart/x-mixed-replace;boundary=" BOUNDARY RN
RN
"--" BOUNDARY RN,
@@ -650,7 +737,6 @@ static void _http_callback_stream_write(struct bufferevent *buf_event, void *v_c
bufferevent_enable(buf_event, EV_READ);
# undef ADD_ADVANCE_HEADERS
# undef RN
# undef BOUNDARY
}
@@ -658,10 +744,7 @@ static void _http_callback_stream_error(UNUSED struct bufferevent *buf_event, UN
stream_client_s *client = (stream_client_s *)v_client;
server_s *server = client->server;
char *reason = bufferevent_my_format_reason(what);
assert(RUN(stream_clients_count) > 0);
RUN(stream_clients_count) -= 1;
LIST_REMOVE_C(RUN(stream_clients), client, RUN(stream_clients_count));
if (RUN(stream_clients_count) == 0) {
atomic_store(&VID(has_clients), false);
@@ -670,40 +753,26 @@ static void _http_callback_stream_error(UNUSED struct bufferevent *buf_event, UN
# endif
}
char *client_addr = "???";
unsigned short client_port = 0;
char *reason = bufferevent_my_format_reason(what);
LOG_INFO("HTTP: Disconnected client: %s, id=%" PRIx64 ", %s; clients now: %u",
client->hostport, client->id, reason, RUN(stream_clients_count));
free(reason);
struct evhttp_connection *conn = evhttp_request_get_connection(client->request);
if (conn) {
evhttp_connection_get_peer(conn, &client_addr, &client_port);
}
LOG_INFO("HTTP: Disconnected client: [%s]:%u, id=%s, %s; clients now: %u",
client_addr, client_port, client->id, reason, RUN(stream_clients_count));
if (conn) {
evhttp_connection_free(conn);
}
if (client->prev == NULL) {
RUN(stream_clients) = client->next;
} else {
client->prev->next = client->next;
}
if (client->next != NULL) {
client->next->prev = client->prev;
}
free(client->key);
free(client->hostport);
free(client);
free(reason);
}
static void _http_queue_send_stream(server_s *server, bool stream_updated, bool frame_updated) {
bool has_clients = false;
bool queued = false;
for (stream_client_s *client = RUN(stream_clients); client != NULL; client = client->next) {
LIST_ITERATE(RUN(stream_clients), client, {
struct evhttp_connection *conn = evhttp_request_get_connection(client->request);
if (conn) {
// Фикс для бага WebKit. При включенной опции дропа одинаковых фреймов,
@@ -734,7 +803,7 @@ static void _http_queue_send_stream(server_s *server, bool stream_updated, bool
has_clients = true;
}
}
});
if (queued) {
static unsigned queued_fps_accum = 0;
@@ -751,7 +820,21 @@ static void _http_queue_send_stream(server_s *server, bool stream_updated, bool
}
}
static void _http_exposed_refresh(UNUSED int fd, UNUSED short what, void *v_server) {
static void _http_request_watcher(UNUSED int fd, UNUSED short what, void *v_server) {
server_s *server = (server_s *)v_server;
const long double now = get_now_monotonic();
if (stream_has_clients(RUN(stream))) {
RUN(last_request_ts) = now;
} else if (RUN(last_request_ts) + server->exit_on_no_clients < now) {
LOG_INFO("HTTP: No requests or HTTP/sink clients found in last %u seconds, exiting ...",
server->exit_on_no_clients);
process_suicide();
RUN(last_request_ts) = now;
}
}
static void _http_refresher(UNUSED int fd, UNUSED short what, void *v_server) {
server_s *server = (server_s *)v_server;
bool stream_updated = false;
bool frame_updated = false;
@@ -836,3 +919,39 @@ static bool _expose_new_frame(server_s *server) {
#undef VID
#undef STREAM
#undef RUN
static char *_http_get_client_hostport(struct evhttp_request *request) {
char *addr = NULL;
unsigned short port = 0;
struct evhttp_connection *conn = evhttp_request_get_connection(request);
if (conn) {
char *peer;
evhttp_connection_get_peer(conn, &peer, &port);
assert(addr = strdup(peer));
}
const char *xff = GET_HEADER("X-Forwarded-For");
if (xff) {
if (addr) {
free(addr);
}
assert(addr = strndup(xff, 1024));
for (unsigned index = 0; addr[index]; ++index) {
if (addr[index] == ',') {
addr[index] = '\0';
break;
}
}
}
if (addr == NULL) {
assert(addr = strdup("???"));
}
char *hostport;
A_ASPRINTF(hostport, "[%s]:%u", addr, port);
free(addr);
return hostport;
}
#undef GET_HEADER

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -28,6 +28,7 @@
#include <stdbool.h>
#include <stdatomic.h>
#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
@@ -47,8 +48,6 @@
#include <event2/bufferevent.h>
#include <event2/keyvalq_struct.h>
#include <uuid/uuid.h>
#ifndef EVTHREAD_USE_PTHREADS_IMPLEMENTED
# error Required libevent-pthreads support
#endif
@@ -59,6 +58,7 @@
#include "../../libs/process.h"
#include "../../libs/frame.h"
#include "../../libs/base64.h"
#include "../../libs/list.h"
#include "../data/index_html.h"
#include "../encoder.h"
#include "../stream.h"
@@ -71,6 +71,9 @@
#include "uri.h"
#include "mime.h"
#include "static.h"
#ifdef WITH_SYSTEMD
# include "systemd/systemd.h"
#endif
typedef struct stream_client_sx {
@@ -83,7 +86,8 @@ typedef struct stream_client_sx {
bool dual_final_frames;
bool zero_data;
char id[37]; // ex. "1b4e28ba-2fa1-11d2-883f-0016d3cca427" + "\0"
char *hostport;
uint64_t id;
bool need_initial;
bool need_first_frame;
bool updated_prev;
@@ -91,8 +95,7 @@ typedef struct stream_client_sx {
unsigned fps_accum;
long long fps_accum_second;
struct stream_client_sx *prev;
struct stream_client_sx *next;
LIST_STRUCT(struct stream_client_sx);
} stream_client_s;
typedef struct {
@@ -112,11 +115,17 @@ typedef struct {
typedef struct {
struct event_base *base;
struct evhttp *http;
evutil_socket_t unix_fd;
evutil_socket_t ext_fd; // Unix or socket activation
char *auth_token;
struct event *refresh;
struct event *request_watcher;
long double last_request_ts;
struct event *refresher;
stream_s *stream;
exposed_s *exposed;
stream_client_s *stream_clients;
unsigned stream_clients_count;
} server_runtime_s;
@@ -124,9 +133,15 @@ typedef struct {
typedef struct server_sx {
char *host;
unsigned port;
char *unix_path;
bool unix_rm;
mode_t unix_mode;
# ifdef WITH_SYSTEMD
bool systemd;
# endif
bool tcp_nodelay;
unsigned timeout;
@@ -140,6 +155,7 @@ typedef struct server_sx {
unsigned fake_height;
bool notify_parent;
unsigned exit_on_no_clients;
server_runtime_s *run;
} server_s;

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -32,7 +32,7 @@ char *find_static_file_path(const char *root_path, const char *request_path) {
goto error;
}
A_CALLOC(path, strlen(root_path) + strlen(simplified_path) + 16);
A_CALLOC(path, strlen(root_path) + strlen(simplified_path) + 16); // + reserved for /index.html
sprintf(path, "%s/%s", root_path, simplified_path);
struct stat st;

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -20,34 +20,27 @@
*****************************************************************************/
#pragma once
#include <string.h>
#include <unistd.h>
#include <IL/OMX_Core.h>
#include <IL/OMX_Component.h>
#include "../../../libs/logging.h"
#include "formatters.h"
#include "systemd.h"
#define OMX_INIT_STRUCTURE(_var) { \
memset(&(_var), 0, sizeof(_var)); \
(_var).nSize = sizeof(_var); \
(_var).nVersion.nVersion = OMX_VERSION; \
(_var).nVersion.s.nVersionMajor = OMX_VERSION_MAJOR; \
(_var).nVersion.s.nVersionMinor = OMX_VERSION_MINOR; \
(_var).nVersion.s.nRevision = OMX_VERSION_REVISION; \
(_var).nVersion.s.nStep = OMX_VERSION_STEP; \
evutil_socket_t evhttp_my_bind_systemd(struct evhttp *http) {
int fds = sd_listen_fds(1);
if (fds < 1) {
LOG_ERROR("No available systemd sockets");
return -1;
}
int fd;
for (fd = 1; fd < fds; ++fd) {
close(SD_LISTEN_FDS_START + fd);
}
fd = SD_LISTEN_FDS_START;
int omx_component_enable_port(OMX_HANDLETYPE *comp, OMX_U32 port);
int omx_component_disable_port(OMX_HANDLETYPE *comp, OMX_U32 port);
assert(!evutil_make_socket_nonblocking(fd));
int omx_component_get_portdef(OMX_HANDLETYPE *comp, OMX_PARAM_PORTDEFINITIONTYPE *portdef, OMX_U32 port);
int omx_component_set_portdef(OMX_HANDLETYPE *comp, OMX_PARAM_PORTDEFINITIONTYPE *portdef);
int omx_component_set_state(OMX_HANDLETYPE *comp, OMX_STATETYPE state);
if (evhttp_accept_socket(http, fd) < 0) {
LOG_PERROR("Can't evhttp_accept_socket() systemd socket");
return -1;
}
return fd;
}

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -22,21 +22,16 @@
#pragma once
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <IL/OMX_IVCommon.h>
#include <IL/OMX_Core.h>
#include <IL/OMX_Image.h>
#include <event2/http.h>
#include <event2/util.h>
#include <systemd/sd-daemon.h>
#include "../../../libs/tools.h"
#include "../../../libs/logging.h"
#define LOG_ERROR_OMX(_error, _msg, ...) { \
LOG_ERROR(_msg ": %s", ##__VA_ARGS__, omx_error_to_string(_error)); \
}
const char *omx_error_to_string(OMX_ERRORTYPE error);
const char *omx_state_to_string(OMX_STATETYPE state);
evutil_socket_t evhttp_my_bind_systemd(struct evhttp *http);

View File

@@ -1,8 +1,8 @@
/*****************************************************************************
# #
# uStreamer - Lightweight and fast MJPG-HTTP streamer. #
# uStreamer - Lightweight and fast MJPEG-HTTP streamer. #
# #
# Copyright (C) 2018-2021 Maxim Devaev <mdevaev@gmail.com> #
# Copyright (C) 2018-2022 Maxim Devaev <mdevaev@gmail.com> #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
@@ -24,7 +24,7 @@
evutil_socket_t evhttp_my_bind_unix(struct evhttp *http, const char *path, bool rm, mode_t mode) {
struct sockaddr_un addr;
struct sockaddr_un addr = {0};
# define MAX_SUN_PATH (sizeof(addr.sun_path) - 1)
@@ -33,7 +33,6 @@ evutil_socket_t evhttp_my_bind_unix(struct evhttp *http, const char *path, bool
return -1;
}
MEMSET_ZERO(addr);
strncpy(addr.sun_path, path, MAX_SUN_PATH);
addr.sun_family = AF_UNIX;

Some files were not shown because too many files have changed in this diff Show More