331 Commits

Author SHA1 Message Date
open-trade
e86d0a0fc1 too many issues 2022-01-06 18:48:10 +08:00
csf
cf13957b45 need fix header / remote 2022-01-06 16:37:23 +08:00
csf
2a18d7f77d first step to js 2022-01-06 16:36:52 +08:00
csf
7dadf3da7a filename file_trans,grid,header,install,port,remote tis->js 2022-01-06 16:36:52 +08:00
csf
de67e7967a update cm.js 2022-01-06 16:36:52 +08:00
csf
face49de00 filename cm.tis -> cm.js 2022-01-06 16:36:52 +08:00
csf
365781a0c0 filename msgbox.tis -> msgbox.js 2022-01-06 16:36:52 +08:00
csf
ae9c4e5995 update index.js 2022-01-06 16:36:50 +08:00
csf
7bc7ef383a change index.js,need fix TODO 2022-01-06 16:36:21 +08:00
csf
54b37862f1 change ab.js 2022-01-06 16:34:00 +08:00
csf
0409d8f761 just change filename index.tis to index.js 2022-01-06 16:30:54 +08:00
csf
b669bdd8d5 just change filename ab.tis to ab.js & change index.html 2022-01-06 16:30:54 +08:00
csf
b41658138a without test! pre-change to js 2022-01-06 16:30:50 +08:00
csf
d68edb9e1a just change file name common.tis to common.js 2022-01-06 16:29:37 +08:00
rustdesk
1931cb8c7c https://github.com/rustdesk/rustdesk/issues/356 2022-01-05 23:50:13 +08:00
rustdesk
32c5437c5d more equal check in config 2022-01-05 21:12:07 +08:00
open-trade
1b61b77fbe more trans 2022-01-05 18:38:40 +08:00
open-trade
c0b6367137 sock5 gui part 2022-01-05 18:34:30 +08:00
open-trade
12ab22e048 bug fix 2022-01-05 17:10:12 +08:00
open-trade
7bde8a3713 remove some unnessary handler.msgbox 2022-01-05 16:53:37 +08:00
open-trade
9c55e1efc8 fix on msgbox 2022-01-05 16:48:09 +08:00
open-trade
b24e16d6c1 bug fix for msgbox, todo: test more for msgbox in file_transfer.tis 2022-01-05 16:32:45 +08:00
open-trade
6767dda246 refactor 2022-01-05 15:59:01 +08:00
open-trade
5f61c2442a bug fix 2022-01-05 15:47:04 +08:00
open-trade
5631ffac4c fix 2022-01-05 15:09:36 +08:00
open-trade
78097f4006 refactort 2022-01-05 14:38:38 +08:00
rustdesk
1d8cdb5e93 refactor target address 2022-01-05 13:21:14 +08:00
open-trade
3e590b8212 refactor to_socket_addr and dns_check 2022-01-04 19:49:44 +08:00
open-trade
533efd04d7 rename 2022-01-04 17:45:52 +08:00
open-trade
fb392b81cb rendezvous_mediator: ensure once one exits, the others also exit. 2022-01-04 17:44:06 +08:00
rustdesk
cbcad03bc6 fix style 2022-01-04 11:22:09 +08:00
RustDesk
2ec5f8fe7e Merge pull request #353 from fufesou/socks5
Socks5
2022-01-04 01:11:04 +08:00
fufesou
875570e040 refactor udp framed
Signed-off-by: fufesou <shuanglongchen@yeah.net>
2022-01-04 00:44:50 +08:00
fufesou
6d506cbb64 socks5 support
Signed-off-by: fufesou <shuanglongchen@yeah.net>
2022-01-03 22:50:43 +08:00
open-trade
b17bda9a55 resize tab 2022-01-03 16:31:13 +08:00
rustdesk
d6b56a2f35 refactor 2022-01-03 11:16:07 +08:00
rustdesk
64f181e4a1 fav 2022-01-03 00:24:36 +08:00
rustdesk
1552402907 working on fav 2022-01-02 21:56:04 +08:00
rustdesk
f0a6c706fa https://github.com/rustdesk/rustdesk/issues/275 2022-01-02 15:09:44 +08:00
rustdesk
042114ae37 refactor 2022-01-02 14:23:32 +08:00
rustdesk
241623c406 reload session list if alias change 2022-01-02 13:56:47 +08:00
rustdesk
40730cbbae ID search 2022-01-02 11:40:30 +08:00
rustdesk
cedc384ba1 working on search bar 2022-01-01 19:44:02 +08:00
rustdesk
15f3c36c5f header button hover bg 2022-01-01 17:18:10 +08:00
rustdesk
ee088a8ddf workaround for stupid sciter 2021-12-31 18:38:46 +08:00
open-trade
cb1818ab37 same width of session card 2021-12-30 16:31:33 +08:00
rustdesk
66af938858 https://sciter.com/forums/topic/menu-not-be-hidden-when-open-dialog-on-linux/ 2021-12-29 23:40:24 +08:00
open-trade
e26a838882 fix on log after upgrade 2021-12-29 19:01:36 +08:00
open-trade
e0bb25cbe5 upgrade vcpkg 2021-12-29 19:00:29 +08:00
open-trade
3491c79cbc get_local_option for ui style, todo: set_local_option 2021-12-29 17:53:36 +08:00
rustdesk
365fc90d8b refactor msgbox 2021-12-29 11:42:43 +08:00
rustdesk
8be7331cb6 add it 2021-12-29 00:48:58 +08:00
RustDesk
ea46d2493e Merge pull request #347 from ale-rinaldi/feature/italian-translation
Italian translation
2021-12-29 00:46:57 +08:00
Alessandro Rinaldi
1141be01f5 Italian translation 2021-12-28 17:42:50 +01:00
rustdesk
6c713f3135 reset AUDIO_ZERO_COUNT 2021-12-29 00:20:51 +08:00
RustDesk
3059ca061e Merge pull request #346 from Heap-Hop/master
optimize audio
2021-12-29 00:11:41 +08:00
rustdesk
2631c68b88 fix cm minimized not working sometimes 2021-12-29 00:05:52 +08:00
csf
f69f6bc8d4 optimize audio 2021-12-29 00:00:23 +08:00
open-trade
66e39b62a2 https://github.com/rustdesk/rustdesk/issues/223 2021-12-28 18:33:36 +08:00
RustDesk
993a419793 Merge pull request #344 from liyue201/dev
fix dependence
2021-12-28 14:27:22 +08:00
liyue
f1444049bf fix dependence 2021-12-28 14:18:37 +08:00
rustdesk
da629ec42c remove unused 2021-12-27 02:38:22 +08:00
rustdesk
7225c1fcf0 session list style and refactor 2021-12-27 02:28:25 +08:00
rustdesk
dbdff120bc move get_version_number to hbb_common 2021-12-27 00:24:57 +08:00
rustdesk
51f4f736bc update package 2021-12-26 15:34:10 +08:00
rustdesk
d4d90da196 https://github.com/rustdesk/rustdesk/issues/301 2021-12-25 22:31:42 +08:00
RustDesk
9903e9df9e Update README.md 2021-12-25 16:55:01 +08:00
rustdesk
af218dbc83 internationalization 2021-12-25 16:45:22 +08:00
rustdesk
b3e3f6151d get last env instead of the first one avoid problem when just switch from wayland to xorg 2021-12-25 01:07:41 +08:00
rustdesk
3d39d9c27c https://github.com/rustdesk/rustdesk/issues/328 2021-12-25 00:18:54 +08:00
rustdesk
589177fc94 Merge branch 'master' of github.com-rustdesk:rustdesk/rustdesk 2021-12-24 19:13:38 +08:00
rustdesk
4703a7d332 https://github.com/rustdesk/rustdesk/issues/327 2021-12-24 19:13:11 +08:00
rustdesk
8d90c5a93b change codec cpu usage to 0 2021-12-24 12:40:47 +08:00
rustdesk
885d8a4586 https://github.com/rustdesk/rustdesk/issues/332 2021-12-24 00:27:27 +08:00
rustdesk
0e8fc4a815 65515 -> Meta(win) on Linux 2021-12-23 23:03:43 +08:00
rustdesk
96afb88518 change line-through style from grey to red 2021-12-23 21:41:53 +08:00
open-trade
a30aaebc72 fix clipboard crash and https://github.com/rustdesk/rustdesk/issues/302 2021-12-23 17:44:44 +08:00
rustdesk
252d3cb797 refactor 2021-12-23 11:11:48 +08:00
open-trade
26a4b1f3eb comment on bias 2021-12-22 16:51:33 +08:00
open-trade
dc724a30e7 https://github.com/rustdesk/rustdesk/issues/298 2021-12-22 14:56:10 +08:00
open-trade
334c94ceb3 https://github.com/rustdesk/rustdesk/issues/210 2021-12-22 14:28:08 +08:00
RustDesk
b6feaa695f Merge pull request #338 from Heap-Hop/master
adjust #[warn(unreachable_code)] position
2021-12-21 17:45:54 +08:00
csf
5f190297a9 adjust #[warn(unreachable_code)] position 2021-12-21 16:35:18 +08:00
rustdesk
362b5594a2 nothing big 2021-12-21 00:11:12 +08:00
RustDesk
b9d8de1ec1 Merge pull request #335 from fufesou/fix_video_image_tearing
Fix video image tearing
2021-12-20 23:15:07 +08:00
fufesou
8a6b33b841 image tearing fixed
Signed-off-by: fufesou <shuanglongchen@yeah.net>
2021-12-20 22:21:15 +08:00
fufesou
3ffd8ac146 add video channel
Signed-off-by: fufesou <shuanglongchen@yeah.net>
2021-12-20 17:19:56 +08:00
RustDesk
07ea52d620 Merge pull request #331 from fufesou/master
add error log for graphics failure
2021-12-20 13:26:56 +08:00
fufesou
4cb967251b add error log for graphics failure
Signed-off-by: fufesou <shuanglongchen@yeah.net>
2021-12-10 22:36:34 +08:00
rustdesk
29905608b5 fix on NL 2021-12-10 00:46:23 +08:00
RustDesk
36db9f65cd Merge pull request #326 from jeroenhd/master
Add Dutch translation for README
2021-12-10 00:12:16 +08:00
jeroenhd
91445da094 Add hyperlinks to Dutch translation
Signed-off-by: jeroenhd <git@jeroenhd.nl>
2021-12-08 02:34:13 +01:00
jeroenhd
083d6c591a Add Dutch translation of the README
Signed-off-by: jeroenhd <git@jeroenhd.nl>
2021-12-08 02:29:55 +01:00
RustDesk
e352ea67f4 Merge pull request #320 from ioridev/master
README translated to Japanese (README-JP.md)
2021-12-01 18:16:56 +08:00
iori
4103ab70a7 Update README-JP 2021-12-01 17:11:06 +09:00
iori
fd9d6db2ed Create README-JP.md 2021-12-01 17:08:10 +09:00
RustDesk
d0b15fbd2a Merge pull request #316 from josephjosedev/master
Update README-ML.md
2021-11-27 13:19:48 +08:00
Joseph Jose
7c42c04b23 Update README-ML.md
updated
2021-11-27 10:42:38 +05:30
Joseph Jose
81e4998a37 Update README-ML.md 2021-11-26 22:50:40 +05:30
RustDesk
1ab5bb0a2e Update README.md 2021-11-27 01:05:29 +08:00
RustDesk
0f39626782 Merge pull request #315 from varghesejose2020/master
README translated to MALAYALAM (README-ML.md)
2021-11-27 01:00:58 +08:00
Varghese Jose
dc2edcec5d Update README-ML.md 2021-11-26 13:55:56 +05:30
Varghese Jose
3198236a8c Update README-ML.md
updated
2021-11-26 13:54:53 +05:30
Varghese Jose
e044212eb6 Update README-ML.md
updated
2021-11-26 13:50:20 +05:30
Varghese Jose
33e8f2aa85 Update README-ML.md
upd
2021-11-26 13:45:44 +05:30
Varghese Jose
031ca4e50c Update README-ML.md 2021-11-26 13:40:30 +05:30
Varghese Jose
73d0da726d Update README-ML.md 2021-11-26 13:38:28 +05:30
Varghese Jose
5c97f5dce5 Create README-ML.md
MALAYALAM added to README
2021-11-26 13:22:44 +05:30
RustDesk
8d5aa731a1 Merge pull request #306 from mingxingren/master
Delete a line of typos
2021-11-23 20:28:49 +08:00
mamingkun
e8c5a63986 1. Delete a line of duplicate code 2021-11-23 20:07:25 +08:00
mingxingren
46fe37015f Merge pull request #1 from rustdesk/master
Update from master
2021-11-23 20:06:07 +08:00
rustdesk
b79f086df5 suomi -> Suomi 2021-11-22 01:42:53 +08:00
rustdesk
6afb6aaff2 Fix on FI 2021-11-22 01:40:45 +08:00
rustdesk
5a1ab37171 FI 2021-11-22 01:38:58 +08:00
RustDesk
5e0bf8f5a9 Merge pull request #304 from fufesou/master
resolution changed, no need to reconnect
2021-11-21 23:10:00 +08:00
cxl
7964afeb84 resolution changed, no need to reconnect
Signed-off-by: cxl <xiaolong.chen@nazhiai.com>
2021-11-21 22:45:12 +08:00
RustDesk
3759347d47 Merge pull request #294 from hatamiarash7/master
Spell & Format
2021-11-15 00:12:59 +08:00
Arash Hatami
2758f6b7d5 Fix misspelled words 2021-11-14 19:01:34 +03:30
Arash Hatami
70a4ee4318 Merge branch 'rustdesk:master' into master 2021-11-14 18:52:51 +03:30
Arash Hatami
7f13edd14a Fix misspelled words 2021-11-14 18:52:05 +03:30
Arash Hatami
96208e9fef git ignore .vscode 2021-11-14 18:36:03 +03:30
rustdesk
e6bd5b0698 pb in version 2021-11-07 10:18:10 +08:00
rustdesk
231231e51f refactor 2021-10-30 14:03:33 +08:00
RustDesk
247ea5fed3 Merge pull request #279 from cc-morning/master
Clipboard service optimization and bug fixes
2021-10-30 12:50:39 +08:00
cc-morning
0cf2db9239 Clipboard listener lifecycle follows service 2021-10-27 20:02:17 +08:00
cc-morning
318e3cbd7d Code Format 2021-10-26 16:59:31 +08:00
cc-morning
5164f76919 Fix lost clipboard content again 2021-10-25 16:25:23 +08:00
cc-morning
972ec8d79d Fix missing clipboard content 2021-10-24 23:47:02 +08:00
RustDesk
516904551c Merge pull request #268 from cc-morning/master
Optimize clipboard change listener
2021-10-24 00:45:52 +08:00
cc-morning
1bf80e3dd6 Optimize clipboard change listener 2021-10-22 16:02:01 +08:00
RustDesk
8f22273759 Update ci.yml 2021-10-21 10:00:53 +08:00
rustdesk
1ddd5203e5 fix overflow 2021-10-20 17:03:48 +08:00
RustDesk
62d2c0fb6d Merge pull request #265 from dannkunt/master
Fix buiding trough docker
2021-10-20 14:24:44 +08:00
dannkunt
0db250f02a Delete this code
This code is unnessesary and bug casing with previous fix
2021-10-20 08:38:36 +03:00
dannkunt
8be912a8cf Add user privelege
To fix this
2021-10-20 08:35:52 +03:00
RustDesk
03f913e49d Merge pull request #256 from starccy/multiple-selection
Transfer multiple files
2021-10-19 23:36:15 +08:00
Starccy
fb126164ef use multiple jobs to delete 2021-10-19 21:52:59 +08:00
Starccy
eea85b9b5a send & receive multiple files 2021-10-17 21:27:10 +08:00
RustDesk
b16b2bc1b4 Merge pull request #253 from palfrey/ci
CI setup
2021-10-12 23:47:09 +08:00
Tom Parker-Shemilt
55d21ab151 Just build the tests 2021-10-11 22:35:31 +01:00
Tom Parker-Shemilt
d25e17317d Skip tests for the moment 2021-10-11 22:09:13 +01:00
Tom Parker-Shemilt
7a7cca7e45 Add rust cache 2021-10-11 21:48:56 +01:00
Tom Parker-Shemilt
0ef4246360 Set vcpkg commit id 2021-10-11 21:40:06 +01:00
Tom Parker-Shemilt
686e495171 Initial CI setup 2021-10-11 21:36:45 +01:00
rustdesk
c0db2e6da4 refactor and fix 2021-10-08 00:16:10 +08:00
rustdesk
c0459b8f94 move change wayland to linux section 2021-10-02 08:51:56 +08:00
rustdesk
678a3d2d28 README format bug 2021-10-02 08:48:41 +08:00
Arash Hatami
2894a5ab7b Format rust files 2021-10-01 22:48:04 +03:30
RustDesk
2efd0e61b4 Merge pull request #243 from hatamiarash7/master
Update Readme & Other Markdown files
2021-10-01 17:05:17 +08:00
Arash Hatami
18b1646cd4 Fix Markdown syntax in all MD files 2021-10-01 12:28:08 +03:30
Arash Hatami
66cdbbacd0 Update README.md
- Remove extra space after `git clone` command
- Add `VCPKG_ROOT` env before `cargo run` command
2021-10-01 12:10:53 +03:30
rustdesk
aaba4c144c fix README 2021-09-30 12:07:18 +08:00
RustDesk
2d5758e880 Update README.md 2021-09-30 12:01:45 +08:00
RustDesk
b20ec86fac Merge pull request #237 from kerlw/master
Add some optimization options for Chinese developer in README-ZH.md.
2021-09-26 10:10:57 +08:00
kerl.d.w
1df5234eea Add some optimization options for Chinese developer in README-ZH.md. 2021-09-26 09:51:40 +08:00
RustDesk
1b8dbbeac9 https://github.com/rustdesk/rustdesk/issues/226 2021-09-12 17:53:45 +08:00
RustDesk
c5f1222476 Merge pull request #224 from desertstsung/addfun/relogin_xorg
add function
2021-09-09 18:24:58 +08:00
desertstsung
1009eabdfe add function
relogin required if current is wayland
2021-09-09 15:07:09 +08:00
open-trade
8138a661a6 new fall back to gdi 2021-09-07 19:03:59 +08:00
RustDesk
d369955790 Merge pull request #221 from desertstsung/ui/labelchange
ui label change
2021-09-06 20:59:12 +08:00
desertstsung
0afca9d1ea ui label change:
src/ui/index.tis#L547:Fix it -> Disable it
2021-09-06 20:41:37 +08:00
rustdesk
0325500ebf refactor 2021-08-29 19:26:33 +08:00
RustDesk
b0dfd777fb Update Cargo.toml 2021-08-24 22:18:39 +08:00
rustdesk
1a54c50c6f fix cpal crash on alsa linu 2021-08-23 13:04:21 +08:00
RustDesk
5d26dbaa90 Merge pull request #202 from open-trade/patch-1
My stupidness
2021-08-20 13:59:21 +08:00
open-trade
c52f4af17d My stupidness 2021-08-20 13:57:53 +08:00
rustdesk
b2a6c592ba linux clipboard sync issue https://github.com/rustdesk/rustdesk/issues/118 2021-08-20 12:39:10 +08:00
rustdesk
2df4da89dc somebody not tidy, but like tidy code, :), https://github.com/rustdesk/rustdesk/issues/198 2021-08-16 21:28:59 +08:00
rustdesk
aaffbe476e fix 32 2021-08-14 01:13:40 +08:00
rustdesk
dae3a2b43b compile error 2021-08-14 01:06:06 +08:00
rustdesk
64b4d14629 fix on 32 2021-08-14 01:02:39 +08:00
rustdesk
d03172e2f3 prepare 32 2021-08-14 00:45:12 +08:00
rustdesk
44f6233df0 tokio 1.10 2021-08-13 13:02:03 +08:00
RustDesk
88a3266a73 Update CONTRIBUTING.md 2021-08-13 01:31:47 +08:00
rustdesk
3cd9ee2aa3 unify menu style 2021-08-12 20:16:57 +08:00
rustdesk
a76916c520 ignore abnormal latency 2021-08-12 10:55:21 +08:00
rustdesk
2102813ed9 refactor 2021-08-12 01:25:32 +08:00
rustdesk
c970e5b22b shared memory for future usage, but it has permission problem on
Windows, not find way to make files writable for all users on Windows
2021-08-11 21:08:05 +08:00
rustdesk
3a7d64bf34 atomic 2021-08-11 18:29:03 +08:00
rustdesk
4e85841398 refactor msgbox retry 2021-08-11 01:28:53 +08:00
rustdesk
6130792734 fix cm style 2021-08-10 23:50:32 +08:00
rustdesk
61caaa3365 refactor, will do with shared memory 2021-08-10 16:01:39 +08:00
rustdesk
c3a3c1a1c7 atexit crash on mac 2021-08-10 12:19:42 +08:00
rustdesk
e510d2744d fix apps key 2021-08-10 12:18:10 +08:00
rustdesk
bb25964307 safe exit 2021-08-09 04:21:42 +08:00
rustdesk
8affa24400 how about fix_modifiers? 2021-08-09 02:07:54 +08:00
rustdesk
ad182a5f3c comment on altgr 2021-08-08 18:23:44 +08:00
rustdesk
6ed9526a65 comment on jp/kr key mapping 2021-08-08 18:06:26 +08:00
rustdesk
ccd1cab6bc down as press only for linux and non-modifier 2021-08-08 17:29:39 +08:00
rustdesk
ab4843b76e fixing win key problem https://github.com/rustdesk/rustdesk/issues/35 2021-08-08 01:44:37 +08:00
rustdesk
3200002e52 fix unexpected repeating key input on remote linux https://github.com/rustdesk/rustdesk/issues/189 2021-08-06 14:23:50 +08:00
rustdesk
9d7dced7e7 .gitattributes 2021-08-05 11:27:56 +08:00
rustdesk
a70e3e93b0 fix remote_cursor https://github.com/rustdesk/rustdesk/issues/82, host
has higher priority to control mouse https://github.com/rustdesk/rustdesk/issues/40
2021-08-04 15:40:34 +08:00
rustdesk
646b11a3ae typo 2021-08-04 15:30:47 +08:00
rustdesk
eb76f7cecc fix mac key mapping, https://github.com/rustdesk/rustdesk/issues/186, https://github.com/rustdesk/rustdesk/issues/86 2021-08-04 03:44:00 +08:00
rustdesk
39f0dd28b4 <video> can not be relative, add another wrapper to make img cursor work 2021-08-04 00:57:48 +08:00
rustdesk
66bd97c0b3 bigger client timeout 2021-08-04 00:57:03 +08:00
rustdesk
a0b2450888 fix on --password 2021-08-03 20:16:38 +08:00
rustdesk
f558c12866 --password https://github.com/rustdesk/rustdesk/issues/187 2021-08-03 14:59:45 +08:00
rustdesk
c385d88708 https://github.com/rustdesk/rustdesk/issues/133 https://github.com/rustdesk/rustdesk/issues/112 https://github.com/rustdesk/rustdesk/issues/43 2021-08-01 14:51:53 +08:00
rustdesk
2e305e8f11 fix on rubato 2021-08-01 11:05:45 +08:00
rustdesk
e949023dda try out the other audio resampler 2021-08-01 11:01:04 +08:00
rustdesk
25c10453e5 password eye padding 2021-07-31 22:25:04 +08:00
rustdesk
935676468b disable systray which has compatibility issue 2021-07-31 03:51:10 +08:00
rustdesk
49dff161dd enable dxgi https://github.com/rustdesk/rustdesk/issues/79, may fix https://github.com/rustdesk/rustdesk/issues/169 2021-07-31 03:00:07 +08:00
rustdesk
7282a462f4 scrap readme 2021-07-29 13:33:26 +08:00
rustdesk
a740870b67 fix on android 2021-07-29 13:30:12 +08:00
rustdesk
cd9c189c64 bigger relay timeout 2021-07-28 19:41:34 +08:00
rustdesk
905a3a2936 fix sciter-rs utf 2021-07-28 00:00:11 +08:00
rustdesk
e6744d031d connection type 2021-07-27 23:53:12 +08:00
rustdesk
a3f5ffc15a fix on linux numpadenter 2021-07-27 20:12:53 +08:00
rustdesk
191fdc6691 fix keyboard abnormal, https://github.com/rustdesk/rustdesk/issues/146 https://github.com/rustdesk/rustdesk/issues/135 https://github.com/rustdesk/rustdesk/issues/127 2021-07-27 20:10:04 +08:00
rustdesk
f07ce11425 https://github.com/rustdesk/rustdesk/issues/130 better toolbar hide/show 2021-07-26 23:40:58 +08:00
rustdesk
7324cb607c wheel issue for new sciter 2021-07-26 21:34:05 +08:00
rustdesk
1ee92c9f68 fix for file transfer: sort row and remove empty dir 2021-07-26 02:50:33 +08:00
rustdesk
9a86a595ff fix compatibility issue for new sciter 2021-07-26 01:50:47 +08:00
rustdesk
879c300563 boundery check, https://github.com/rustdesk/rustdesk/issues/107 2021-07-25 21:04:11 +08:00
rustdesk
bebe136834 less green 2021-07-25 02:09:57 +08:00
rustdesk
d89d5ef825 https://github.com/rustdesk/rustdesk/issues/132#issuecomment-886069737 2021-07-25 02:06:20 +08:00
rustdesk
56dfcffd1e restore Fedora vpx fix 2021-07-24 20:00:56 +08:00
rustdesk
7c5915e3d3 vpxmt -> vpx after vcpkg upgraded 2021-07-24 19:33:11 +08:00
rustdesk
cb2864202f upgrade vcpkg 2021-07-24 19:06:32 +08:00
RustDesk
dae2814951 Update Dockerfile 2021-07-24 18:41:22 +08:00
rustdesk
6922a1de4c refactor and upgrade sciter 2021-07-24 18:25:07 +08:00
RustDesk
7282c3a16d Update README.md 2021-07-23 17:54:16 +08:00
rustdesk
c15c44788c try out wayland 2021-07-23 17:52:38 +08:00
RustDesk
d83163b6a0 Merge pull request #170 from sitiom/nsis-setup
Replace InnoSetup with improved NSIS Setup
2021-07-15 21:48:55 +08:00
Ryan Caezar Itang
5383c09e3d Replace InnoSetup with improved NSIS Setup 2021-07-15 20:51:41 +08:00
RustDesk
6f8483ece6 Add files via upload 2021-07-14 22:23:42 +08:00
RustDesk
e65aa61fb7 Update README-FR.md 2021-07-08 22:57:07 +08:00
rustdesk
2522c99f47 update readme 2021-07-08 22:55:03 +08:00
rustdesk
fcf24e04bd Merge branch 'master' of https://github.com/rustdesk/rustdesk 2021-07-07 10:53:27 +08:00
rustdesk
2ec5fbb333 opacity 2021-07-07 10:53:13 +08:00
RustDesk
c1b241a8d1 Merge pull request #143 from SET19724/patch-2
Better translation pl readme
2021-07-07 00:38:27 +08:00
SET19724
b13aef98c2 Better translation
Not Polskie :)
Polski
2021-07-06 18:33:46 +02:00
RustDesk
b25c2c0551 Update README.md 2021-07-07 00:30:45 +08:00
rustdesk
e303a3b9b8 fix PL 2021-07-07 00:27:26 +08:00
RustDesk
ec8255b20f Merge pull request #142 from SET19724/patch-1
README-PL.md Tłumaczenie na Polski PL Polish
2021-07-07 00:23:57 +08:00
SET19724
529048bb8e Update README.md
City name fix
2021-07-06 18:23:28 +02:00
SET19724
926d3ca546 Tłumaczenie na Polski PL Polish
;)
2021-07-06 18:20:05 +02:00
rustdesk
7d316f9a51 https://github.com/rustdesk/rustdesk/issues/140 2021-07-06 10:47:49 +08:00
rustdesk
c27865d3ed change to dallas 2021-07-03 14:14:16 +08:00
rustdesk
d769b79a6f update servers 2021-07-03 10:27:34 +08:00
RustDesk
3aa4bdd1fa Merge pull request #137 from ToasterUwU/master
German README and correction of links in other MDs ("Deutsche" to "Deutsch")
2021-07-03 07:52:51 +08:00
mis1852
ad8b23d1a7 German README and correction of links in other mds 2021-07-02 19:29:26 +02:00
RustDesk
e8b8a260fd Merge pull request #128 from SantiagoValdez/patch-1
Update README.md - Fix spanish spelling
2021-06-29 08:52:58 +08:00
Santiago Valdez
b4467370a8 Update README.md - Fix spanish spelling
Spanish language is called Español or in some cases Castellano. 
Referring to Spanish language as 'Española' is not grammatically valid.
2021-06-28 17:14:01 -04:00
RustDesk
25ffaa7966 Merge pull request #122 from EmPablo/patch-2
Update : Panic message is not a string literal.
2021-06-26 12:18:07 +08:00
RustDesk
00b2b30778 Merge pull request #121 from EmPablo/patch-1
Update to the current release version number.
2021-06-26 12:17:49 +08:00
EmPablo
78692793a5 Update : Panic message is not a string literal. 2021-06-26 11:46:22 +08:00
EmPablo
5b9c90809c Update to the current release version number. 2021-06-26 11:43:38 +08:00
rustdesk
05c4dacbe9 ipc windows work 2021-06-26 01:14:22 +08:00
rustdesk
6f796db523 new namedpipe 2021-06-26 00:47:45 +08:00
rustdesk
2d515815ed Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-06-25 21:36:09 +08:00
rustdesk
dc3fcda2c9 tokio1, windows not test yet 2021-06-25 19:42:51 +08:00
RustDesk
25a83f6b4a Update README.md 2021-06-23 00:44:10 +08:00
RustDesk
086d1f9124 Add files via upload 2021-06-23 00:40:08 +08:00
rustdesk
5339b40104 ISSUE TEMPLATE 2021-06-22 11:34:07 +08:00
RustDesk
be9f0a22a0 Update README.md 2021-06-21 23:32:52 +08:00
RustDesk
fc3f76973d Update README.md 2021-06-21 23:32:07 +08:00
RustDesk
0d0c75e2a9 Merge pull request #101 from geshii/master
Create README-FR.md, French translation
2021-06-21 23:28:55 +08:00
Geshi
da7e044f16 Create README-FR.md 2021-06-21 16:16:37 +02:00
RustDesk
2ccbda2bb8 Update README-ES.md 2021-06-21 18:29:46 +08:00
RustDesk
87e161eddb Update README-ZH.md 2021-06-21 18:29:18 +08:00
RustDesk
592630fac4 Update README.md 2021-06-21 18:29:01 +08:00
RustDesk
aa67aab1f2 Merge pull request #97 from geshii/patch-1
Creating security guidelines, also known as SECURITY.md
2021-06-21 17:02:39 +08:00
Geshi
7e873f1c8b Create SECURITY.md 2021-06-21 10:56:43 +02:00
RustDesk
ba00e4daf2 Update README.md 2021-06-21 16:31:01 +08:00
RustDesk
8ef831ee5c Add files via upload 2021-06-21 16:27:16 +08:00
RustDesk
7cc5d138a0 Update README.md 2021-06-21 12:55:34 +08:00
RustDesk
7b4d5bc704 Update README.md 2021-06-21 12:49:05 +08:00
RustDesk
a4a09d5bfc Create README-ZH.md 2021-06-21 12:44:34 +08:00
RustDesk
c8465f9a5d Update README.md 2021-06-21 12:19:13 +08:00
RustDesk
2159423431 Update README.md 2021-06-21 12:18:56 +08:00
RustDesk
9d5cfb04ac Update README.md 2021-06-21 12:18:28 +08:00
RustDesk
43200f236a Merge pull request #94 from mtoohey31/docker-build
Support builds via Docker
2021-06-21 09:53:38 +08:00
mtoohey31
9383e4ecbb Support builds via Docker 2021-06-20 15:12:46 -04:00
RustDesk
6862406e68 Update README.md 2021-06-20 16:02:35 +08:00
RustDesk
c3b6dabcc8 Update README.md 2021-06-20 15:46:24 +08:00
RustDesk
a99e6f38e5 Merge pull request #89 from mtoohey31/display-server-fix
Check for Xorg running in tty
2021-06-20 12:02:05 +08:00
mtoohey31
142eebc9e2 https://github.com/rustdesk/rustdesk/issues/87 2021-06-19 14:35:40 -04:00
RustDesk
ec294451e3 Update README.md 2021-06-17 12:55:34 +08:00
RustDesk
7daeddf560 Update README.md 2021-06-17 12:55:11 +08:00
RustDesk
562b0c79dd Update README.md 2021-06-17 11:41:21 +08:00
RustDesk
b0f3ec40ce Update README.md 2021-06-17 11:41:07 +08:00
rustdesk
51903ede3d rs-ny.rustdesk.com 2021-06-15 11:21:10 +08:00
rustdesk
fda1e5e231 https://github.com/rustdesk/rustdesk/issues/58 2021-06-14 18:27:09 +08:00
rustdesk
e06217536b Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-06-14 17:52:33 +08:00
rustdesk
673986d045 https://github.com/rustdesk/rustdesk/issues/69 2021-06-14 17:51:45 +08:00
rustdesk
a2890fa548 https://github.com/rustdesk/rustdesk/issues/35 2021-06-14 15:29:36 +08:00
rustdesk
f3182a63e9 Merge branch 'master' of github.com:/rustdesk/rustdesk 2021-06-14 13:16:35 +08:00
rustdesk
a830922dea https://github.com/rustdesk/rustdesk/issues/73 2021-06-14 13:16:20 +08:00
RustDesk
ff54a98526 Merge pull request #71 from gitatmax/gitatmax-patch-1
Improved readability of OS list
2021-06-10 21:36:42 +08:00
Maxwell White
912053d99d Improved readability of OS list 2021-06-10 08:41:00 -04:00
rustdesk
da4669366b fix some rare case 2021-06-10 12:19:23 +08:00
rustdesk
c844d99ff1 try multiple time to get X11 env 2021-06-08 17:54:25 +08:00
rustdesk
369a9e0805 CONTRIBUTING.md 2021-06-07 13:44:21 +08:00
RustDesk
7daa080637 Update FUNDING.yml 2021-06-07 12:48:43 +08:00
RustDesk
e8606b8d0c Update README.md 2021-06-07 12:44:19 +08:00
rustdesk
ae9b6edf7c comment 2021-06-07 08:57:26 +08:00
rustdesk
34ce402203 https://github.com/rustdesk/rustdesk/issues/61 2021-06-06 16:27:02 +08:00
rustdesk
0ddfc32f0c refactor 2021-06-05 19:53:34 +08:00
RustDesk
c2d97054dd Merge pull request #60 from Candunc/master
Fixed typos, defaulted MacOS update prompt to use https
2021-06-05 08:03:03 +08:00
Duncan Bristow
155357a7e9 Fixed typos, defaulted MacOS update prompt to use https 2021-06-04 16:27:53 -07:00
RustDesk
14d35fc923 Merge pull request #57 from botiapa/master
Add --needed parameter to pacman install command
2021-06-05 00:10:17 +08:00
killswitch
913568a597 Add --needed parameter to pacman install command
This avoids reinstalling already installed packages.
2021-06-04 18:05:35 +02:00
rustdesk
1da5c1bde9 better linux support 2021-06-04 21:04:40 +08:00
rustdesk
31e6108f40 move confy here 2021-06-02 09:55:38 +08:00
rustdesk
ffcbc2abaa more for right key 2021-06-01 13:05:04 +08:00
rustdesk
5c541179dc update_pk if mismatch 2021-05-31 01:08:27 +08:00
RustDesk
ef6103da25 Update README.md 2021-05-28 13:26:48 +08:00
rustdesk
3be1971ca4 moved to rustdesk-server-demo repo 2021-05-27 22:57:52 +08:00
rustdesk
044f4cb12c demo server 2021-05-27 22:57:37 +08:00
RustDesk
cac416bcc0 Update README.md 2021-05-27 18:30:16 +08:00
rustdesk
8708fb366a righ key mapping and fix mac crash 2021-05-26 12:42:21 +08:00
rustdesk
d825d30e53 fix linux restore button and clipboard initial sync issue 2021-05-25 12:01:27 +08:00
rustdesk
002ca33cec Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-05-23 11:01:56 +08:00
rustdesk
7e1c56033b only dynamic 2021-05-23 11:01:27 +08:00
rustdesk
cd21f61d9c Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-05-23 10:57:49 +08:00
rustdesk
237e889604 move rust-sciter in 2021-05-23 10:55:19 +08:00
rustdesk
bdfb59dd1a remove unnessarey dns call 2021-05-23 00:14:00 +08:00
rustdesk
b7ab1405ee fix home path issue on some linux build 2021-05-21 19:11:09 +08:00
rustdesk
9a4786adb2 possible fix of mac crash 2021-05-20 17:19:37 +08:00
rustdesk
3a570de31e Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-05-20 17:16:01 +08:00
rustdesk
c5032f617b enable tray and fix install problems 2021-05-20 17:15:25 +08:00
rustdesk
d7b9c1aa72 enable tray and fix various install problems caused by format and
encoding
2021-05-20 17:06:25 +08:00
rustdesk
c05dd0b1b7 Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-05-17 20:46:31 +08:00
rustdesk
f760e56f79 better support for win7 2021-05-17 20:46:02 +08:00
rustdesk
7630713534 fix no audio issue with sample rate >= 48000 and strange crash issue
(there is some overflow in unsafe code, will test again)
2021-05-13 00:24:38 +08:00
rustdesk
7a8cf58ab1 Merge branch 'master' of https://github.com/rustdesk/rustdesk into master 2021-04-26 11:46:36 +08:00
rustdesk
7b067ed28d recreate udp socket 2021-04-26 11:44:47 +08:00
176 changed files with 11942 additions and 10809 deletions

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto

1
.github/FUNDING.yml vendored
View File

@@ -1 +1,2 @@
github: [rustdesk]
ko_fi: rustdesk

32
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,32 @@
---
name: Bug Report
about: Report a bug (English only, Please).
title: ""
labels: bug
assignees: ''
---
<!-- Hey there, thank you for creating an issue! -->
**Describe the bug you encountered:**
...
**What did you expect to happen instead?**
...
**How did you install `RustDesk`?**
<!-- GitHub release, build from source, Windows portable version, etc. -->
---
**RustDesk version and environment**
<!--
In order to reproduce your issue, please add some information about the environment
in which you're running RustDesk.
-->

2
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,2 @@
blank_issues_enabled: true

View File

@@ -0,0 +1,10 @@
---
name: Feature Request
about: Suggest an idea for this project ((English only, Please).
title: ''
labels: feature-request
assignees: ''
---

10
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View File

@@ -0,0 +1,10 @@
---
name: Question
about: Ask a question about 'RustDesk' (English only, Please).
title: ''
labels: question
assignees: ''
---

181
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,181 @@
name: CI
# env:
# MIN_SUPPORTED_RUST_VERSION: "1.46.0"
# CICD_INTERMEDIATES_DIR: "_cicd-intermediates"
on:
workflow_dispatch:
pull_request:
push:
branches:
- master
tags:
- '*'
jobs:
# ensure_cargo_fmt:
# name: Ensure 'cargo fmt' has been run
# runs-on: ubuntu-20.04
# steps:
# - uses: actions-rs/toolchain@v1
# with:
# toolchain: stable
# default: true
# profile: minimal
# components: rustfmt
# - uses: actions/checkout@v2
# - run: cargo fmt -- --check
# min_version:
# name: Minimum supported rust version
# runs-on: ubuntu-20.04
# steps:
# - name: Checkout source code
# uses: actions/checkout@v2
# - name: Install rust toolchain (v${{ env.MIN_SUPPORTED_RUST_VERSION }})
# uses: actions-rs/toolchain@v1
# with:
# toolchain: ${{ env.MIN_SUPPORTED_RUST_VERSION }}
# default: true
# profile: minimal # minimal component installation (ie, no documentation)
# components: clippy
# - name: Run clippy (on minimum supported rust version to prevent warnings we can't fix)
# uses: actions-rs/cargo@v1
# with:
# command: clippy
# args: --locked --all-targets --all-features -- --allow clippy::unknown_clippy_lints
# - name: Run tests
# uses: actions-rs/cargo@v1
# with:
# command: test
# args: --locked
build:
name: ${{ matrix.job.target }} (${{ matrix.job.os }})
runs-on: ${{ matrix.job.os }}
strategy:
fail-fast: false
matrix:
job:
# - { target: aarch64-unknown-linux-gnu , os: ubuntu-20.04, use-cross: true }
# - { target: arm-unknown-linux-gnueabihf , os: ubuntu-20.04, use-cross: true }
# - { target: arm-unknown-linux-musleabihf, os: ubuntu-20.04, use-cross: true }
# - { target: i686-pc-windows-msvc , os: windows-2019 }
# - { target: i686-unknown-linux-gnu , os: ubuntu-20.04, use-cross: true }
# - { target: i686-unknown-linux-musl , os: ubuntu-20.04, use-cross: true }
# - { target: x86_64-apple-darwin , os: macos-10.15 }
# - { target: x86_64-pc-windows-gnu , os: windows-2019 }
# - { target: x86_64-pc-windows-msvc , os: windows-2019 }
- { target: x86_64-unknown-linux-gnu , os: ubuntu-20.04 }
# - { target: x86_64-unknown-linux-musl , os: ubuntu-20.04, use-cross: true }
steps:
- name: Checkout source code
uses: actions/checkout@v2
- name: Install prerequisites
shell: bash
run: |
case ${{ matrix.job.target }} in
x86_64-unknown-linux-gnu) sudo apt-get -y update ; sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake ;;
# arm-unknown-linux-*) sudo apt-get -y update ; sudo apt-get -y install gcc-arm-linux-gnueabihf ;;
# aarch64-unknown-linux-gnu) sudo apt-get -y update ; sudo apt-get -y install gcc-aarch64-linux-gnu ;;
esac
- name: Restore from cache and install vcpkg
uses: lukka/run-vcpkg@v7
with:
setupOnly: true
vcpkgGitCommitId: '1d4128f08e30cec31b94500840c7eca8ebc579cb'
- name: Install vcpkg dependencies
run: |
$VCPKG_ROOT/vcpkg install libvpx libyuv opus
shell: bash
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: ${{ matrix.job.target }}
override: true
profile: minimal # minimal component installation (ie, no documentation)
- name: Show version information (Rust, cargo, GCC)
shell: bash
run: |
gcc --version || true
rustup -V
rustup toolchain list
rustup default
cargo -V
rustc -V
- uses: Swatinem/rust-cache@v1
- name: Build
uses: actions-rs/cargo@v1
with:
use-cross: ${{ matrix.job.use-cross }}
command: build
args: --locked --release --target=${{ matrix.job.target }}
# - name: Strip debug information from executable
# id: strip
# shell: bash
# run: |
# # Figure out suffix of binary
# EXE_suffix=""
# case ${{ matrix.job.target }} in
# *-pc-windows-*) EXE_suffix=".exe" ;;
# esac;
# # Figure out what strip tool to use if any
# STRIP="strip"
# case ${{ matrix.job.target }} in
# arm-unknown-linux-*) STRIP="arm-linux-gnueabihf-strip" ;;
# aarch64-unknown-linux-gnu) STRIP="aarch64-linux-gnu-strip" ;;
# *-pc-windows-msvc) STRIP="" ;;
# esac;
# # Setup paths
# BIN_DIR="${{ env.CICD_INTERMEDIATES_DIR }}/stripped-release-bin/"
# mkdir -p "${BIN_DIR}"
# BIN_NAME="${{ env.PROJECT_NAME }}${EXE_suffix}"
# BIN_PATH="${BIN_DIR}/${BIN_NAME}"
# # Copy the release build binary to the result location
# cp "target/${{ matrix.job.target }}/release/${BIN_NAME}" "${BIN_DIR}"
# # Also strip if possible
# if [ -n "${STRIP}" ]; then
# "${STRIP}" "${BIN_PATH}"
# fi
# # Let subsequent steps know where to find the (stripped) bin
# echo ::set-output name=BIN_PATH::${BIN_PATH}
# echo ::set-output name=BIN_NAME::${BIN_NAME}
- name: Set testing options
id: test-options
shell: bash
run: |
# test only library unit tests and binary for arm-type targets
unset CARGO_TEST_OPTIONS
unset CARGO_TEST_OPTIONS ; case ${{ matrix.job.target }} in arm-* | aarch64-*) CARGO_TEST_OPTIONS="--lib --bin ${PROJECT_NAME}" ;; esac;
echo ::set-output name=CARGO_TEST_OPTIONS::${CARGO_TEST_OPTIONS}
- name: Build tests
uses: actions-rs/cargo@v1
with:
use-cross: ${{ matrix.job.use-cross }}
command: build
args: --locked --tests --target=${{ matrix.job.target }}
# - name: Run tests
# uses: actions-rs/cargo@v1
# with:
# use-cross: ${{ matrix.job.use-cross }}
# command: test
# args: --locked --target=${{ matrix.job.target }} ${{ steps.test-options.outputs.CARGO_TEST_OPTIONS}}

2
.gitignore vendored
View File

@@ -1,4 +1,5 @@
/target
.vscode
.idea
.DS_Store
src/ui/inline.rs
@@ -6,3 +7,4 @@ extractor
__pycache__
src/version.rs
*dmg
sciter.dll

BIN
128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

BIN
128x128@2x.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

46
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,46 @@
# Contributing to RustDesk
RustDesk welcomes contribution from everyone. Here are the guidelines if you are
thinking of helping us:
## Contributions
Contributions to RustDesk or its dependencies should be made in the form of GitHub
pull requests. Each pull request will be reviewed by a core contributor
(someone with permission to land patches) and either landed in the main tree or
given feedback for changes that would be required. All contributions should
follow this format, even those from core contributors.
Should you wish to work on an issue, please claim it first by commenting on
the GitHub issue that you want to work on it. This is to prevent duplicated
efforts from contributors on the same issue.
## Pull Request Checklist
- Branch from the master branch and, if needed, rebase to the current master
branch before submitting your pull request. If it doesn't merge cleanly with
master you may be asked to rebase your changes.
- Commits should be as small as possible, while ensuring that each commit is
correct independently (i.e., each commit should compile and pass tests).
- Commits should be accompanied by a Developer Certificate of Origin
(http://developercertificate.org) sign-off, which indicates that you (and
your employer if applicable) agree to be bound by the terms of the
[project license](LICENSE). In git, this is the `-s` option to `git commit`
- If your patch is not getting reviewed or you need a specific person to review
it, you can @-reply a reviewer asking for a review in the pull request or a
comment, or you can ask for a review via [email](mailto:info@rustdesk.com).
- Add tests relevant to the fixed bug or new feature.
For specific git instructions, see [GitHub workflow 101](https://github.com/servo/servo/wiki/Github-workflow).
## Conduct
We follow the [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct).
## Communication
RustDesk contributors frequent the [Discord](https://discord.gg/nDceKgxnkV).

2131
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,58 +1,65 @@
[package]
name = "rustdesk"
version = "1.1.2"
version = "1.1.8"
authors = ["rustdesk <info@rustdesk.com>"]
edition = "2018"
build= "build.rs"
description = "A remote control software."
[lib]
crate-type = ["cdylib", "staticlib", "rlib"]
[features]
inline = []
cli = []
use_samplerate = ["samplerate"]
use_rubato = ["rubato"]
use_dasp = ["dasp"]
default = ["use_dasp"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
whoami = "0.9"
whoami = "1.2"
scrap = { path = "libs/scrap" }
hbb_common = { path = "libs/hbb_common" }
enigo = { path = "libs/enigo" }
sys-locale = "0.1"
serde_derive = "1.0"
serde = "1.0"
serde_json = "1.0"
cfg-if = "1.0"
lazy_static = "1.4"
sha2 = "0.9"
sha2 = "0.10"
repng = "0.2"
libc = "0.2"
parity-tokio-ipc = { path = "libs/parity-tokio-ipc" }
flexi_logger = "0.16"
parity-tokio-ipc = { git = "https://github.com/open-trade/parity-tokio-ipc" }
flexi_logger = "0.22"
runas = "0.2"
magnum-opus = { path = "libs/magnum-opus" }
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"] }
magnum-opus = { git = "https://github.com/open-trade/magnum-opus" }
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"], optional = true }
rubato = { version = "0.10", optional = true }
samplerate = { version = "0.2", optional = true }
async-trait = "0.1"
crc32fast = "1.2"
crc32fast = "1.3"
uuid = { version = "0.8", features = ["v4"] }
copypasta = "0.7"
clap = "2.33"
clap = "2.34"
rpassword = "5.0"
base64 = "0.13"
[target.'cfg(not(any(target_os = "android")))'.dependencies]
cpal = { git = "https://github.com/rustaudio/cpal" }
cpal = { git = "https://github.com/open-trade/cpal" }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
machine-uid = "0.2"
mac_address = "1.1"
sciter-rs = { git = "https://github.com/sciter-sdk/rust-sciter", rev = "7702fb17290e76606bdd7010a0c3cbb32e85db76" }
sciter-rs = { git = "https://github.com/open-trade/rust-sciter", branch = "dyn" }
ctrlc = "3.2"
arboard = "2.0"
clipboard-master = "3.1"
[target.'cfg(target_os = "windows")'.dependencies]
systray = { path = "libs/systray-rs" }
systray = { git = "https://github.com/liyue201/systray-rs" }
winapi = { version = "0.3", features = ["winuser"] }
winreg = "0.7"
windows-service = { git = 'https://github.com/mullvad/windows-service-rs.git' }
winreg = "0.10"
windows-service = "0.4"
[target.'cfg(target_os = "macos")'.dependencies]
objc = "0.2"
@@ -62,16 +69,15 @@ core-foundation = "0.9"
core-graphics = "0.22"
[target.'cfg(target_os = "linux")'.dependencies]
libpulse-simple-binding = "2.16"
libpulse-binding = "2.16"
rust-pulsectl = { path = "libs/pulsectl" }
ctrlc = "3.1"
libpulse-simple-binding = "2.24"
libpulse-binding = "2.25"
rust-pulsectl = { git = "https://github.com/open-trade/pulsectl" }
[target.'cfg(not(any(target_os = "windows", target_os = "android", target_os = "ios")))'.dependencies]
psutil = "3.2"
psutil = { version = "3.2", features = [ "process" ], git = "https://github.com/open-trade/rust-psutil" }
[target.'cfg(target_os = "android")'.dependencies]
android_logger = "0.9"
android_logger = "0.10"
[workspace]
members = ["libs/scrap", "libs/hbb_common", "libs/enigo"]

20
Dockerfile Normal file
View File

@@ -0,0 +1,20 @@
FROM debian
WORKDIR /
RUN apt update -y && apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake unzip zip sudo
RUN git clone https://github.com/microsoft/vcpkg && cd vcpkg && git checkout 134505003bb46e20fbace51ccfb69243fbbc5f82
RUN /vcpkg/bootstrap-vcpkg.sh -disableMetrics
RUN /vcpkg/vcpkg --disable-metrics install libvpx libyuv opus
RUN groupadd -r user && useradd -r -g user user --home /home/user && mkdir -p /home/user && chown user /home/user && echo "user ALL=(ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/user
WORKDIR /home/user
RUN wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
USER user
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup.sh
RUN chmod +x rustup.sh
RUN ./rustup.sh -y
USER root
COPY ./entrypoint /
ENTRYPOINT ["/entrypoint"]

162
README-DE.md Normal file
View File

@@ -0,0 +1,162 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#kostenlose-öffentliche-server">Server</a>
<a href="#die-groben-schritte-zum-kompilieren">Kompilieren</a>
<a href="#auf-docker-kompilieren">Docker</a>
<a href="#dateistruktur">Dateistruktur</a>
<a href="#screenshots">Screenshots</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Wir brauchen deine Hilfe um diese README Datei zu verbessern und aktualisieren</b>
</p>
Rede mit uns: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Das hier ist ein Programm was man nutzen kann, um einen Computer fernzusteuern, es wurde in Rust geschrieben. Es funktioniert ohne Konfiguration oder ähnliches, man kann es einfach direkt nutzen. Du hast volle Kontrolle über deine Daten und brauchst dir daher auch keine Sorgen um die Sicherheit dieser Daten zu machen. Du kannst unseren rendezvous/relay Server nutzen, [einen eigenen Server eröffnen](https://rustdesk.com/blog/id-relay-set/) oder [einen neuen eigenen Server programmieren](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk heißt jegliche Mitarbeit willkommen. Schau dir [`CONTRIBUTING.md`](CONTRIBUTING.md) an, wenn du Hilfe brauchst für den Start.
[**PROGRAMM DOWNLOAD**](https://github.com/rustdesk/rustdesk/releases)
## Kostenlose öffentliche Server
Hier sind die Server die du kostenlos nutzen kannst, es kann sein das sich diese Liste immer mal wieder ändert. Falls du nicht in der Nähe einer dieser Server bist, kann es sein, dass deine Verbindung langsam sein wird.
| Standort | Serverart | Spezifikationen | Kommentare |
| --------- | ------------- | ------------------ | ---------- |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM | |
| Singapore | Vultr | 1 VCPU / 1GB RAM | |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Abhängigkeiten
Die Desktop Versionen nutzen [Sciter](https://sciter.com/) für die Oberfläche, bitte lade die dynamische Sciter Bibliothek selbst herunter.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Die groben Schritte zum Kompilieren
- Bereite deine Rust Entwicklungsumgebung und C++ Entwicklungsumgebung vor
- Installiere [vcpkg](https://github.com/microsoft/vcpkg) und füge die `VCPKG_ROOT` Systemumgebungsvariable hinzu
- Windows: `vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static`
- Linux/MacOS: `vcpkg install libvpx libyuv opus`
- Nutze `cargo run`
## Kompilieren auf Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### vcpkg installieren
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### libvpx reparieren (Für Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Kompilieren
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
### Ändere Wayland zu X11 (Xorg)
RustDesk unterstützt "Wayland" nicht. Siehe [hier](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) um Xorg als Standard GNOME Session zu nutzen.
## Auf Docker Kompilieren
Beginne damit das Repository zu klonen und den Docker Container zu bauen:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Jedes Mal, wenn du das Programm Kompilieren musst, nutze diesen Befehl:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Bedenke, dass das erste Mal Kompilieren länger dauern kann, da die Abhängigkeiten erst kompiliert werden müssen bevor sie zwischengespeichert werden können. Darauf folgende Kompiliervorgänge werden schneller sein. Falls du zusätzliche oder andere Argumente für den Kompilierbefehl angeben musst, kannst du diese am Ende des Befehls an der `<OPTIONAL-ARGS>` Position machen. Wenn du zum Beispiel eine optimierte Releaseversion kompilieren willst, kannst du das tun indem du `--release` am Ende des Befehls anhängst. Das daraus entstehende Programm kannst du im “target” Ordner auf deinem System finden. Du kannst es mit folgenden Befehlen ausführen:
```sh
target/debug/rustdesk
```
Oder, wenn du eine Releaseversion benutzt:
```sh
target/release/rustdesk
```
Bitte gehe sicher, dass du diese Befehle vom Stammverzeichnis vom RustDesk Repository nutzt, sonst kann es passieren, dass das Programm die Ressourcen nicht finden kann. Bitte bedenke auch, dass Unterbefehle von Cargo, wie z.B. `install` oder `run` aktuell noch nicht unterstützt werden, da sie das Programm innerhalb des Containers starten oder installieren würden, anstatt auf deinem eigentlichen System.
## Dateistruktur
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: Video Codec, Konfiguration, TCP/UDP Wrapper, Protokoll Puffer, fs Funktionen für Dateitransfer, und ein paar andere nützliche Funktionen
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: Bildschirmaufnahme
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: Plattformspezifische Maus und Tastatur Steuerung
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: Audio/Zwischenablage/Eingabe/Videodienste und Netzwerk Verbindungen
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: Starten einer Peer-Verbindung
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Mit [rustdesk-server](https://github.com/rustdesk/rustdesk-server) kommunizieren, für Verbindung von außen warten, direkt (TCP hole punching) oder weitergeleitet
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: Plattformspezifischer Code
## Screenshots
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

160
README-ES.md Normal file
View File

@@ -0,0 +1,160 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#servidores-gratis-de-uso-público">Servidores</a>
<a href="#pasos-para-compilar-desde-el-inicio">Compilar</a>
<a href="#como-compilar-con-docker">Docker</a>
<a href="#estructura-de-archivos">Estructura</a>
<a href="#captura-de-pantalla">Captura de pantalla</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Necesitamos tu ayuda para traducir este README a tu idioma</b>
</p>
Chat with us: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Otro software de escritorio remoto, escrito en Rust. Funciona de forma inmediata, sin necesidad de configuración. Tienes el control total de sus datos, sin preocupaciones sobre la seguridad. Puedes utilizar nuestro servidor de rendezvous/relay, [set up your own](https://rustdesk.com/blog/id-relay-set/), o [escribir tu propio servidor rendezvous/relay](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk agradece la contribución de todo el mundo. Ve [`CONTRIBUTING.md`](CONTRIBUTING.md) para ayuda inicial.
[**DESCARGA DE BINARIOS**](https://github.com/rustdesk/rustdesk/releases)
## Servidores gratis de uso público
A continuación se muestran los servidores que está utilizando de forma gratuita, puede cambiar en algún momento. Si no estás cerca de uno de ellos, tu red puede ser lenta.
- Seoul, AWS lightsail, 1 VCPU/0.5G RAM
- Singapore, Vultr, 1 VCPU/1G RAM
- Dallas, Vultr, 1 VCPU/1G RAM
## Dependencies
La versión Desktop usa [sciter](https://sciter.com/) para GUI, por favor bajate la librería sciter tu mismo..
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Pasos para compilar desde el inicio
- Prepara el entono de desarrollode Rust y el entorno de compilación de C++ y Rust.
- Instala [vcpkg](https://github.com/microsoft/vcpkg), y configura la variable de entono `VCPKG_ROOT` correctamente.
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx: vcpkg install libvpx libyuv opus
- run `cargo run`
## Como compilar en linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Install vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Soluciona libvpx (For Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Compila
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
### Cambia Wayland a X11 (Xorg)
RustDesk no soporta Wayland. Comprueba [aquí](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) para configurar Xorg en la sesión por defecto de GNOME.
## Como compilar con Docker
Empieza clonando el repositorio y compilando el contenedor de docker:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Entonces, cada vez que necesites compilar una modificación, ejecuta el siguiente comando:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Ten en cuenta que la primera compilación puede tardar más tiempo antes de que las dependencias se almacenen en la caché, las siguientes compilaciones serán más rápidas. Además, si necesitas especificar diferentes argumentos a la orden de compilación, puede hacerlo al final de la linea de comandos en el apartado`<OPTIONAL-ARGS>`. Por ejemplo, si desea compilar una versión optimizada para publicación, deberá ejecutar el comando anterior seguido de `---release`. El ejecutable resultante estará disponible en la carpeta de destino en su sistema, y puede ser ejecutado con:
```sh
target/debug/rustdesk
```
O si estas ejecutando una versión para su publicación:
```sh
target/release/rustdesk
```
Por favor, asegurate de que estás ejecutando estos comandos desde la raíz del repositorio de RustDesk, de lo contrario la aplicación puede ser incapaz de encontrar los recursos necesarios. También hay que tener en cuenta que otros subcomandos de carga como `install` o `run` no estan actualmente soportados via este metodo y podrían requerir ser instalados dentro del contenedor y no en el host.
## Estructura de archivos
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: video codec, configuración, tcp/udp wrapper, protobuf, fs funciones para transferencia de ficheros, y alguna función de utilidad.
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: captura de pantalla
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: control específico por cada plataforma para el teclado/ratón
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: sonido/portapapeles/entrada/servicios de video, y conexiones de red
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: iniciar una conexión "peer to peer"
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Comunicación con [rustdesk-server](https://github.com/rustdesk/rustdesk-server), esperar la conexión remota directa ("TCP hole punching") o conexión indirecta ("relayed")
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: código específico de cada plataforma
## Captura de pantalla
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

161
README-FI.md Normal file
View File

@@ -0,0 +1,161 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Etätyöpöytäsi"><br>
<a href="#free-public-servers">Palvelimet</a>
<a href="#raw-steps-to-build">Rakenna</a>
<a href="#how-to-build-with-docker">Docker</a>
<a href="#file-structure">Rakenne</a>
<a href="#snapshot">Tilannevedos</a><br>
[<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>] | [<a href="README-FI.md">Suomi</a>]<br>
<b>Tarvitsemme apua tämän README-tiedoston kääntämiseksi äidinkielellesi</b>
</p>
Juttele meidän kanssa: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Vielä yksi etätyöpöytäohjelmisto, ohjelmoitu Rust-kielellä. Toimii suoraan pakkauksesta, ei tarvitse asetuksia. Hallitset täysin tietojasi, ei tarvitse murehtia turvallisuutta. Voit käyttää meidän rendezvous/relay-palvelinta, [aseta omasi](https://rustdesk.com/blog/id-relay-set/), tai [kirjoita oma rendezvous/relay-palvelin](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk toivottaa avustukset tervetulleiksi kaikilta. Katso lisätietoja [`CONTRIBUTING.md`](CONTRIBUTING.md) avun saamiseksi.
[**BINAARILATAUS**](https://github.com/rustdesk/rustdesk/releases)
## Vapaita julkisia palvelimia
Alla on palvelimia, joita voit käyttää ilmaiseksi, ne saattavat muuttua ajan mittaan. Jos et ole lähellä yhtä näistä, verkkosi voi olla hidas.
| Sijainti | Myyjä | Määrittely |
| --------- | ------------- | ------------------ |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapore | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Riippuvuudet
Desktop-versiot käyttävät [sciter](https://sciter.com/) graafisena käyttöliittymänä, lataa sciter-dynaaminen kirjasto itsellesi.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Rakentamisaskeleet harppoen
- Valmistele Rust-kehitysympäristö ja C++-rakentamisympäristö
- Asenna [vcpkg](https://github.com/microsoft/vcpkg), ja aseta `VCPKG_ROOT`-ympäristömuuttuja oikein
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/MacOS: vcpkg install libvpx libyuv opus
- aja `cargo run`
## Kuinka rakentaa Linuxissa
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Asenna vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Korjaa libvpx (Fedora-linux-versiota varten)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Rakenna
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
VCPKG_ROOT=$HOME/vcpkg cargo run
```
### Vaihda Wayland-ympäristö X11 (Xorg)-ympäristöön
RustDesk ei tue Waylandia. Tarkista [tämä](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) asettamaan Xorg oletus GNOME-istuntona.
## Kuinka rakennetaan Dockerin kanssa
Aloita kloonaamalla tietovarasto ja rakentamalla docker-säiliö:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Sitten, joka kerta kun sinun on rakennettava sovellus, aja seuraava komento:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Huomaa, että ensimmäinen rakentaminen saattaa kestää pitempään ennen kuin riippuvuudet on siirretty välimuistiin, seuraavat rakentamiset ovat nopeampia. Lisäksi, jos sinun on määritettävä eri argumentteja rakentamiskomennolle, saatat tehdä sen niin, että komennon lopussa <OPTIONAL-ARGS>`-kohdassa. Esimerkiksi, jos haluat rakentaa optimoidun julkaisuversion, sinun on ajettava komento yllä siten, että sitä seuraa argumentti `---release`. Suoritettava tiedosto on saatavilla järjestelmäsi kohdehakemistossa, ja se voidaan suorittaa seuraavan kera:
```sh
target/debug/rustdesk
```
Tai, jos olet suorittamassa jakeluversion suoritettavaa tiedostoa:
```sh
target/release/rustdesk
```
Varmista, että suoritat näitä komentoja RustDesktop-tietovaraston juurihakemistossa, muutoin sovellus ei ehkä löydä vaadittuja resursseja. Huomaa myös, että muita cargo-alikomentoja kuten `install` tai `run` ei nykyisin tueta tässä menetelmässä, koska ne asentavat tai suorittavat ohjelman säiliön sisällä eikä isäntäohjelman sisällä.
## Tiedostorakenne
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: video codec, config, tcp/udp wrapper, protobuf, fs-funktiot tiedostosiirtoon, ja jotkut muut apuohjelmafunktiot
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: näyttökaappaukset
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: platform specific keyboard/mouse control
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: Graafinen käyttöliittymä
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: audio/clipboard/input/video services, and network connections
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: start a peer connection
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Communicate with [rustdesk-server](https://github.com/rustdesk/rustdesk-server), wait for remote direct (TCP hole punching) or relayed connection
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: platform specific code
## Tilannekuvat
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

160
README-FR.md Normal file
View File

@@ -0,0 +1,160 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#serveurs-publics-libres">Serveurs</a> -
<a href="#étapes-brutes-de-la-compilationbuild">Build</a> -
<a href="#comment-construire-avec-docker">Docker</a> -
<a href="#structure-du-projet">Structure</a> -
<a href="#images">Images</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-ES.md">Española</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Nous avons besoin de votre aide pour traduire ce README dans votre langue maternelle</b>.
</p>
Chattez avec nous : [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Encore un autre logiciel de bureau à distance, écrit en Rust. Fonctionne directement, aucune configuration n'est nécessaire. Vous avez le contrôle total de vos données, sans aucun souci de sécurité. Vous pouvez utiliser notre serveur de rendez-vous/relais, [configurer le vôtre](https://rustdesk.com/blog/id-relay-set/), ou [écrire votre propre serveur de rendez-vous/relais](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk accueille les contributions de tout le monde. Voir [`CONTRIBUTING.md`](CONTRIBUTING.md) pour plus d'informations.
[**TÉLÉCHARGEMENT BINAIRE**](https://github.com/rustdesk/rustdesk/releases)
## Serveurs publics libres
Ci-dessous se trouvent les serveurs que vous utilisez gratuitement, cela peut changer au fil du temps. Si vous n'êtes pas proche de l'un d'entre eux, votre réseau peut être lent.
- Séoul, AWS lightsail, 1 VCPU/0.5G RAM
- Singapour, Vultr, 1 VCPU/1G RAM
- Dallas, Vultr, 1 VCPU/1G RAM
## Dépendances
Les versions de bureau utilisent [sciter](https://sciter.com/) pour l'interface graphique, veuillez télécharger la bibliothèque dynamique sciter vous-même.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so)
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Étapes brutes de la compilation/build
- Préparez votre environnement de développement Rust et votre environnement de compilation C++.
- Installez [vcpkg](https://github.com/microsoft/vcpkg), et définissez correctement la variable d'environnement `VCPKG_ROOT`.
- Windows : vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx : vcpkg install libvpx libyuv opus
- Exécuter `cargo run`
## Comment compiler/build sous Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Installer vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Corriger libvpx (Pour Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Construire
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p cible/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
Exécution du cargo
```
### Changer Wayland en X11 (Xorg)
RustDesk ne supporte pas Wayland. Lisez [cela](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) pour configurer Xorg comme la session GNOME par défaut.
## Comment construire avec Docker
Commencez par cloner le dépôt et construire le conteneur Docker :
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Ensuite, chaque fois que vous devez build le logiciel, exécutez la commande suivante :
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Notez que le premier build peut prendre plus de temps avant que les dépendances ne soient mises en cache, les constructions suivantes seront plus rapides. De plus, si vous devez spécifier différents arguments à la commande de compilation, vous pouvez le faire à la fin de la commande dans la position `<OPTIONAL-ARGS>`. Par exemple, si vous voulez construire une version optimisée de la version release, vous devez exécuter la commande ci-dessus suivie de `---release`. L'exécutable résultant sera disponible dans le dossier cible sur votre système, et peut être lancé avec :
```sh
target/debug/rustdesk
```
Ou, si vous exécutez un exécutable provenant d'une release :
```sh
target/release/rustdesk
```
Veuillez vous assurer que vous exécutez ces commandes à partir de la racine du référentiel RustDesk, sinon l'application ne pourra pas trouver les ressources requises. Notez également que les autres sous-commandes de cargo telles que `install` ou `run` ne sont pas actuellement supportées par cette méthode car elles installeraient ou exécuteraient le programme à l'intérieur du conteneur au lieu de l'hôte.
## Structure du projet
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)** : codec vidéo, config, wrapper tcp/udp, protobuf, fonctions fs pour le transfert de fichiers, et quelques autres fonctions utilitaires.
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)** : capture d'écran
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)** : contrôle clavier/souris spécifique à la plate-forme
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)** : INTERFACE GRAPHIQUE
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)** : services audio/clipboard/input/vidéo, et connexions réseau
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)** : démarrer une connexion entre pairs
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)** : Communiquer avec [rustdesk-server](https://github.com/rustdesk/rustdesk-server), attendre une connexion distante directe (TCP hole punching) ou relayée.
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)** : code spécifique à la plateforme
## Images
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

164
README-JP.md Normal file
View File

@@ -0,0 +1,164 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#free-public-servers">Servers</a>
<a href="#raw-steps-to-build">Build</a>
<a href="#how-to-build-with-docker">Docker</a>
<a href="#file-structure">Structure</a>
<a href="#snapshot">Snapshot</a><br>
[<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>このREADMEをあなたの母国語に翻訳するために、あなたの助けが必要です。</b>
</p>
Chat with us: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Rustで書かれた、設定不要ですぐに使えるリモートデスクトップソフトウェアです。自分のデータを完全にコントロールでき、セキュリティの心配もありません。私たちのランデブー/リレーサーバを使うことも、[自分で設定する](https://rustdesk.com/blog/id-relay-set/) ことも、 [自分でランデブー/リレーサーバを書くこともできます。](https://github.com/rustdesk/rustdesk-server-demo).
RustDeskは誰からの貢献も歓迎します。 貢献するには [`CONTRIBUTING.md`](CONTRIBUTING.md) を参照してください。
[**BINARY DOWNLOAD**](https://github.com/rustdesk/rustdesk/releases)
## 無料のパブリックサーバー
下記のサーバーは、無料で使用できますが、後々変更されることがあります。これらのサーバーから遠い場合、接続が遅い可能性があります。
| Location | Vendor | Specification |
| --------- | ------------- | ------------------ |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapore | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## 依存関係
デスクトップ版ではGUIに [sciter](https://sciter.com/) が使われています。 sciter dynamic library をダウンロードしてください。
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## ビルド手順
- Rust開発環境とC ++ビルド環境を準備します
- [vcpkg](https://github.com/microsoft/vcpkg), をインストールし、 `VCPKG_ROOT` 環境変数を正しく設定します。
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/MacOS: vcpkg install libvpx libyuv opus
- run `cargo run`
## Linuxでのビルド手順
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Install vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Fix libvpx (For Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Build
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
VCPKG_ROOT=$HOME/vcpkg cargo run
```
### Wayland の場合、X11Xorgに変更します
RustDeskはWaylandをサポートしていません。
[こちら](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) を確認して、XorgをデフォルトのGNOMEセッションとして構成します。
## Dockerでビルドする方法
リポジトリのクローンを作成し、Dockerコンテナを構築することから始めます。
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
その後、アプリケーションをビルドする必要があるたびに、以下のコマンドを実行します。
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
なお、最初のビルドでは、依存関係がキャッシュされるまで時間がかかることがありますが、その後のビルドではより速くなります。さらに、ビルドコマンドに別の引数を指定する必要がある場合は、コマンドの最後にある `<OPTIONAL-ARGS>` の位置で指定することができます。例えば、最適化されたリリースバージョンをビルドしたい場合は、上記のコマンドの後に
`---release` を実行します。できあがった実行ファイルは、システムのターゲット・フォルダに格納され、次のコマンドで実行できます。
```sh
target/debug/rustdesk
```
あるいは、リリース用の実行ファイルを実行している場合:
```sh
target/release/rustdesk
```
これらのコマンドをRustDeskリポジトリのルートから実行していることを確認してください。そうしないと、アプリケーションが必要なリソースを見つけられない可能性があります。また、 `install``run` などの他の cargo サブコマンドは、ホストではなくコンテナ内にプログラムをインストールまたは実行するため、現在この方法ではサポートされていないことに注意してください。
## File Structure
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: ビデオコーデック、コンフィグ、tcp/udpラッパー、protobuf、ファイル転送用のfs関数、その他のユーティリティ関数
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: スクリーンキャプチャ
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: プラットフォーム固有のキーボード/マウスコントロール
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: オーディオ/クリップボード/入力/ビデオサービス、ネットワーク接続
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: ピア接続の開始
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: [rustdesk-server](https://github.com/rustdesk/rustdesk-server), と通信し、リモートダイレクト (TCP hole punching) または中継接続を待つ。
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: プラットフォーム固有のコード
## Snapshot
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

161
README-ML.md Normal file
View File

@@ -0,0 +1,161 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#free-public-servers">Servers</a>
<a href="#raw-steps-to-build">Build</a>
<a href="#how-to-build-with-docker">Docker</a>
<a href="#file-structure">Structure</a>
<a href="#snapshot">Snapshot</a><br>
[<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>ഈ README നിങ്ങളുടെ മാതൃഭാഷയിലേക്ക് വിവർത്തനം ചെയ്യാൻ ഞങ്ങൾക്ക് നിങ്ങളുടെ സഹായം ആവശ്യമാണ്</b>
</p>
ഞങ്ങളുമായി ചാറ്റ് ചെയ്യുക: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
റസ്റ്റിൽ എഴുതിയ മറ്റൊരു റിമോട്ട് ഡെസ്ക്ടോപ്പ് സോഫ്റ്റ്‌വെയർ. ബോക്‌സിന് പുറത്ത് പ്രവർത്തിക്കുന്നു, കോൺഫിഗറേഷൻ ആവശ്യമില്ല. സുരക്ഷയെക്കുറിച്ച് ആശങ്കകളൊന്നുമില്ലാതെ, നിങ്ങളുടെ ഡാറ്റയുടെ പൂർണ്ണ നിയന്ത്രണം നിങ്ങൾക്കുണ്ട്. നിങ്ങൾക്ക് ഞങ്ങളുടെ rendezvous/relay സെർവർ ഉപയോഗിക്കാം, [സ്വന്തമായി സജ്ജീകരിക്കുക](https://rustdesk.com/blog/id-relay-set/), അല്ലെങ്കിൽ [നിങ്ങളുടെ സ്വന്തം rendezvous/relay സെർവർ എഴുതുക](https://github.com/rustdesk/rustdesk-server-demo).
എല്ലാവരുടെയും സംഭാവനയെ RustDesk സ്വാഗതം ചെയ്യുന്നു. ആരംഭിക്കുന്നതിനുള്ള സഹായത്തിന് [`CONTRIBUTING.md`](CONTRIBUTING.md) കാണുക.
[**BINARY DOWNLOAD**](https://github.com/rustdesk/rustdesk/releases)
## സൗജന്യ പൊതു സെർവറുകൾ
നിങ്ങൾ സൗജന്യമായി ഉപയോഗിക്കുന്ന സെർവറുകൾ ചുവടെയുണ്ട്, അത് സമയത്തിനനുസരിച്ച് മാറിയേക്കാം. നിങ്ങൾ ഇവയിലൊന്നിനോട് അടുത്തല്ലെങ്കിൽ, നിങ്ങളുടെ നെറ്റ്‌വർക്ക് സ്ലോ ആയേക്കാം.
| സ്ഥാനം | കച്ചവടക്കാരൻ | വിവരണം |
| --------- | ------------- | ------------------ |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapore | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## ഡിപെൻഡൻസികൾ
ഡെസ്‌ക്‌ടോപ്പ് പതിപ്പുകൾ GUI-യ്‌ക്കായി [sciter](https://sciter.com/) ഉപയോഗിക്കുന്നു, ദയവായി സ്‌സൈറ്റർ ഡൈനാമിക് ലൈബ്രറി സ്വയം ഡൗൺലോഡ് ചെയ്യുക.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## നിർമ്മിക്കാനുള്ള അസംസ്കൃത പടികൾ
- നിങ്ങളുടെ Rust development envയു and C++ build envയു തയ്യാറാക്കുക
- [vcpkg](https://github.com/microsoft/vcpkg) ഇൻസ്റ്റാൾ ചെയ്ത് `VCPKG_ROOT` env വേരിയബിൾ ശരിയായി സജ്ജമാക്കുക
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/MacOS: vcpkg install libvpx libyuv opus
- run `cargo run`
## ലിനക്സിൽ എങ്ങനെ നിർമ്മിക്കാം
### ഉബുണ്ടു 18 (ഡെബിയൻ 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### ഫെഡോറ 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### ആർച് (മഞ്ചാരോ)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### vcpkg ഇൻസ്റ്റാൾ ചെയ്യുക
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### libvpx പരിഹരിക്കുക (ഫെഡോറയ്ക്ക്)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### നിർമാണം
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
VCPKG_ROOT=$HOME/vcpkg cargo run
```
### വേലാൻഡ് X11 (Xorg) ആയി മാറ്റുക
RustDesk Wayland-നെ പിന്തുണയ്ക്കുന്നില്ല. സ്ഥിരസ്ഥിതി ഗ്നോം സെഷനായി Xorg കോൺഫിഗർ ചെയ്യുന്നതിന് [ഇത്](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) പരിശോധിക്കുക.
## ഡോക്കർ ഉപയോഗിച്ച് എങ്ങനെ നിർമ്മിക്കാം
റെപ്പോസിറ്റോറി ക്ലോണുചെയ്‌ത് ഡോക്കർ കണ്ടെയ്‌നർ നിർമ്മിക്കുന്നതിലൂടെ ആരംഭിക്കുക:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
തുടർന്ന്, ഓരോ തവണയും നിങ്ങൾ ആപ്ലിക്കേഷൻ നിർമ്മിക്കേണ്ടതുണ്ട്, ഇനിപ്പറയുന്ന കമാൻഡ് പ്രവർത്തിപ്പിക്കുക:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
ഡിപൻഡൻസികൾ കാഷെ ചെയ്യുന്നതിനുമുമ്പ് ആദ്യ ബിൽഡ് കൂടുതൽ സമയമെടുത്തേക്കാം, തുടർന്നുള്ള ബിൽഡുകൾ വേഗത്തിലാകും. കൂടാതെ, നിങ്ങൾക്ക് ബിൽഡ് കമാൻഡിലേക്ക് വ്യത്യസ്ത ആർഗ്യുമെന്റുകൾ വ്യക്തമാക്കണമെങ്കിൽ, കമാൻഡിന്റെ അവസാനം `<OPTIONAL-ARGS>` സ്ഥാനത്ത് നിങ്ങൾക്ക് അങ്ങനെ ചെയ്യാം. ഉദാഹരണത്തിന്, നിങ്ങൾ ഒരു ഒപ്റ്റിമൈസ് ചെയ്ത റിലീസ് പതിപ്പ് നിർമ്മിക്കാൻ ആഗ്രഹിക്കുന്നുവെങ്കിൽ, മുകളിലുള്ള കമാൻഡ് തുടർന്ന് `---release` നിങ്ങൾ പ്രവർത്തിപ്പിക്കും. തത്ഫലമായുണ്ടാകുന്ന എക്സിക്യൂട്ടബിൾ നിങ്ങളുടെ സിസ്റ്റത്തിലെ ടാർഗെറ്റ് ഫോൾഡറിൽ ലഭ്യമാകും, കൂടാതെ ഇത് ഉപയോഗിച്ച് പ്രവർത്തിപ്പിക്കാം:
```sh
target/debug/rustdesk
```
അല്ലെങ്കിൽ, നിങ്ങൾ ഒരു റിലീസ് എക്സിക്യൂട്ടബിൾ പ്രവർത്തിപ്പിക്കുകയാണെങ്കിൽ:
```sh
target/release/rustdesk
```
RustDesk റിപ്പോസിറ്ററിയുടെ റൂട്ടിൽ നിന്നാണ് നിങ്ങൾ ഈ കമാൻഡുകൾ പ്രവർത്തിപ്പിക്കുന്നതെന്ന് ദയവായി ഉറപ്പാക്കുക, അല്ലാത്തപക്ഷം ആപ്ലിക്കേഷന് ആവശ്യമായ ഉറവിടങ്ങൾ കണ്ടെത്താൻ കഴിഞ്ഞേക്കില്ല. ഹോസ്റ്റിന് പകരം കണ്ടെയ്‌നറിനുള്ളിൽ പ്രോഗ്രാം ഇൻസ്റ്റാൾ ചെയ്യുകയോ പ്രവർത്തിപ്പിക്കുകയോ ചെയ്യുന്നതിനാൽ, `install` അല്ലെങ്കിൽ `run` പോലുള്ള മറ്റ് കാർഗോ സബ്‌കമാൻഡുകൾ നിലവിൽ ഈ രീതിയെ പിന്തുണയ്ക്കുന്നില്ല എന്നതും ശ്രദ്ധിക്കുക.
## ഫയൽ ഘടന
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: video codec, config, tcp/udp wrapper, protobuf, fs functions for file transfer, and some other utility functions
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: screen capture
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: platform specific keyboard/mouse control
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: audio/clipboard/input/video services, and network connections
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: start a peer connection
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Communicate with [rustdesk-server](https://github.com/rustdesk/rustdesk-server), wait for remote direct (TCP hole punching) or relayed connection
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: platform specific code
## സ്നാപ്പ്ഷോട്ടുകൾ
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

163
README-NL.md Normal file
View File

@@ -0,0 +1,163 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Jouw verbinding op afstand"><br>
<a href="#free-public-servers">Servers</a>
<a href="#raw-steps-to-build">Bouwen</a>
<a href="#how-to-build-with-docker">Docker</a>
<a href="#file-structure">Structuur</a>
<a href="#snapshot">Snapshot</a><br>
[<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>We hebben je hulp nodig om deze README te vertalen naar jouw moedertaal</b>
</p>
Praat met ons: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Nog weer een applicatie voor toegang op afstand, geschreven in Rust. Werkt meteen, geen configuratie nodig. Je hebt volledig beheer over je data, zonder na te hoeven denken over veiligheid. Je kunt onze rendez-vous/relay-server gebruiken, [je eigen server opzetten](https://rustdesk.com/blog/id-relay-set), of [je eigen rendez-vous/relay-server schrijven](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk verwelkomt bijdragen van iedereen. Zie [`CONTRIBUTING.md`](CONTRIBUTING.md) om te lezen hoe je van start kunt gaan.
[**BINARY DOWNLOAD**](https://github.com/rustdesk/rustdesk/releases)
## Gratis openbare servers
Onderstaande servers zijn de servers die je gratis kunt gebruiken, ze kunnen op termijn veranderen. Als je niet fysiek dichtbij een van deze servers bent, kan je verbinding traag werken.
| Locatie | Aanbieder | Specificaties |
| --------- | ------------- | ------------------ |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapore | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Afhankelijkheden
Desktopversies gebruiken [sciter](https://sciter.com/) voor de grafische schil. Gelieve zelf de sciter-library te downloaden.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Handmatige bouwinstructies
- Bereid je Rust-ontwikkelomgeving en C++-bouwomgeving voor.
- Installeer [vcpkg](https://github.com/microsoft/vcpkg) en configureer de `VCPKG_ROOT` omgevingsvariabele op de juiste manier:
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/MacOS: vcpkg install libvpx libyuv opus
- Voer uit: `cargo run`
## Bouwen op Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Installatie van vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Fix voor libvpx (voor Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Bouwen
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
VCPKG_ROOT=$HOME/vcpkg cargo run
```
### Wissel van Wayland naar X11 (Xorg)
RustDesk ondersteunt Wayland niet. Lees [hier](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) hoe je Xorg als standaardsessie kunt instellen voor GNOME.
## Bouwen met Docker
Kloon eerst deze repository en bouw de Docker-container:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Voer vervolgens de volgende commando's uit iedere keer dat je de applicatie opnieuw moet bouwen:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Let op dat de eerste build langer kan duren omdat de dependencies nog niet zijn gecached; latere builds zullen sneller zijn. Als je extra command line arguments wilt toevoegen aan het build-commando, dan kun je dat doen aan het einde van de opdrachtregel in plaats van `<OPTIONAL-ARGS>`. Bijvoorbeeld: als je een geoptimaliseerde releaseversie wilt bouwen, draai dan het bovenstaande commando gevolgd door `---release`.
Het uitvoerbare bestand, in debug-modus, zal verschijnen in de target-map, en kan als volgt worden uitgevoerd:
```sh
target/debug/rustdesk
```
Als je een release-versie hebt gebouwd, is het commando als volgt:
```sh
target/release/rustdesk
```
Zorg ervoor dat je deze commando's van de root van de RustDesk-repository uitvoert, anders kan het programma de nodige afhankelijkheden mogelijk niet vinden. Let ook op dat andere cargo-subcommando's zoals `install` en `run` zijn momenteel niet ondersteund, aangezien deze zouden worden uitgevoerd in een container in plaats van op de host.
## Bestandsstructuur
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: videocodec, configuratie, TCP/UDP-wrapper, protobuf, bestandssysteemfuncties voor bestandsoverdracht en nog wat andere nuttige functies
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: schermopname
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: platformspecifieke muis- en toetsenbordbeheer
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: geluids-, klembord-, invoer- en video-services, netwerkverbindingen
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: voor het opzetten van peer-verbindingen
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Communicatie met [rustdesk-server](https://github.com/rustdesk/rustdesk-server), afwachten van redirect op afstand (TCP hole punching) of een relayed verbinding
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: platformspecifieke code
## Snapshot
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

161
README-PL.md Normal file
View File

@@ -0,0 +1,161 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#darmowe-serwery-publiczne">Serwery</a>
<a href="#podstawowe-kroki-do-kompilacji">Kompilacja</a>
<a href="#jak-kompilować-za-pomocą-dockera">Docker</a>
<a href="#struktura-plików">Struktura</a>
<a href="#migawkisnapshoty">Snapshot</a><br>
[<a href="README.md">English</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-ES.md">Española</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>Potrzebujemy twojej pomocy w tłumaczeniu README na twój ojczysty język</b>
</p>
Porozmawiaj z nami na: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Kolejny program do zdalnego pulpitu, napisany w Rust. Działa od samego początku, nie wymaga konfiguracji. Masz pełną kontrolę nad swoimi danymi, bez obaw o bezpieczeństwo. Możesz skorzystać z naszego darmowego serwera publicznego , [skonfigurować własny](https://rustdesk.com/blog/id-relay-set/), lub [napisać własny serwer rendezvous/relay server](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk zaprasza do współpracy każdego. Zobacz [`CONTRIBUTING.md`](CONTRIBUTING.md) pomoc w uruchomieniu programu.
[**POBIERZ KOMPILACJE**](https://github.com/rustdesk/rustdesk/releases)
## Darmowe Serwery Publiczne
Poniżej znajdują się serwery, z których można korzystać za darmo, może się to zmienić z upływem czasu. Jeśli nie znajdujesz się w pobliżu jednego z nich, Twoja prędkość połączenia może być niska.
| Lokalizacja | Dostawca | Specyfikacja |
| --------- | ------------- | ------------------ |
| Seul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapur | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Zależności
Wersje desktopowe używają [sciter](https://sciter.com/) dla GUI, proszę pobrać bibliotekę dynamiczną sciter samodzielnie.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Podstawowe kroki do kompilacji.
- Przygotuj środowisko programistyczne Rust i środowisko programowania C++
- Zainstaluj [vcpkg](https://github.com/microsoft/vcpkg), i ustaw `VCPKG_ROOT` env zmienną prawidłowo
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/MacOS: vcpkg install libvpx libyuv opus
- uruchom `cargo run`
## Jak Kompilować na Linuxie
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Zainstaluj vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Fix libvpx (For Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Kompilacja
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
### Zmień Wayland na X11 (Xorg)
RustDesk nie obsługuje Waylanda. Sprawdź [this](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) by skonfigurować Xorg jako domyślną sesję GNOME.
## Jak kompilować za pomocą Dockera
Rozpocznij od sklonowania repozytorium i stworzenia kontenera docker:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Następnie, za każdym razem, gdy potrzebujesz skompilować aplikację, uruchom następujące polecenie:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Zauważ, że pierwsza kompilacja może potrwać dłużej zanim zależności zostaną zbuforowane, kolejne będą szybsze. Dodatkowo, jeśli potrzebujesz określić inne argumenty dla polecenia budowania, możesz to zrobić na końcu komendy w miejscu `<OPTIONAL-ARGS>`. Na przykład, jeśli chciałbyś zbudować zoptymalizowaną wersję wydania, uruchomiłbyś powyższą komendę a następnie `---release`. Powstały plik wykonywalny będzie dostępny w folderze docelowym w twoim systemie, i może być uruchomiony z:
```sh
target/debug/rustdesk
```
Lub, jeśli uruchamiasz plik wykonywalny wersji:
```sh
target/release/rustdesk
```
Upewnij się, że uruchamiasz te polecenia z katalogu głównego repozytorium RustDesk, w przeciwnym razie aplikacja może nie być w stanie znaleźć wymaganych zasobów. Należy również pamiętać, że inne podpolecenia ładowania, takie jak `install` lub `run` nie są obecnie obsługiwane za pomocą tej metody, ponieważ instalowałyby lub uruchamiały program wewnątrz kontenera zamiast na hoście.
## Struktura plików
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: kodek wideo, config, wrapper tcp/udp, protobuf, funkcje fs do transferu plików i kilka innych funkcji użytkowych
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: przechwytywanie ekranu
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: specyficzne dla danej platformy sterowanie klawiaturą/myszą
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: audio/schowek/wejście(input)/wideo oraz połączenia sieciowe
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: uruchamia połączenie peer
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Komunikacja z [rustdesk-server](https://github.com/rustdesk/rustdesk-server), wait for remote direct (TCP hole punching) or relayed connection
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: specyficzny dla danej platformy kod
## Migawki(Snapshoty)
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

213
README-ZH.md Normal file
View File

@@ -0,0 +1,213 @@
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#免费公共服务器">服务器</a>
<a href="#基本构建步骤">编译</a>
<a href="#使用Docker编译">Docker</a>
<a href="#文件结构">结构</a>
<a href="#截图">截图</a><br>
[<a href="README.md">English</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
</p>
Chat with us: [知乎](https://www.zhihu.com/people/rustdesk) | [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
远程桌面软件,开箱即用,无需任何配置。您完全掌控数据,不用担心安全问题。您可以使用我们的注册/中继服务器,
或者[自己设置](https://rustdesk.com/blog/id-relay-set/)
亦或者[开发您的版本](https://github.com/rustdesk/rustdesk-server-demo)。
欢迎大家贡献代码, 请看 [`CONTRIBUTING.md`](CONTRIBUTING.md).
[**可执行程序下载**](https://github.com/rustdesk/rustdesk/releases)
## 免费公共服务器
以下是您免费使用的服务器,它可能会随着时间的推移而变化。如果您不靠近其中之一,您的网络可能会很慢。
- 首尔, AWS lightsail, 1 VCPU/0.5G RAM
- 新加坡, Vultr, 1 VCPU/1G RAM
- 达拉斯, Vultr, 1 VCPU/1G RAM
## 依赖
桌面版本界面使用[sciter](https://sciter.com/), 请自行下载。
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## 基本构建步骤
- 请准备好 Rust 开发环境和 C++编译环境
- 安装[vcpkg](https://github.com/microsoft/vcpkg), 正确设置`VCPKG_ROOT`环境变量
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx: vcpkg install libvpx libyuv opus
- 运行 `cargo run`
## 在 Linux 上编译
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### 安装 vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### 修复 libvpx (仅仅针对 Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### 构建
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
```
### 把 Wayland 修改成 X11 (Xorg)
RustDesk 暂时不支持 Wayland不过正在积极开发中.
请查看[this](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/)配置 X11.
## 使用 Docker 编译
首先克隆存储库并构建 docker 容器:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
针对国内网络访问问题,可以做以下几点优化:
1. Dockerfile 中修改系统的源到国内镜像
```
在Dockerfile的RUN apt update之前插入两行
RUN sed -i "s/deb.debian.org/mirrors.163.com/g" /etc/apt/sources.list
RUN sed -i "s/security.debian.org/mirrors.163.com/g" /etc/apt/sources.list
```
2. 修改容器系统中的 cargo 源,在`RUN ./rustup.sh -y`后插入下面代码:
```
RUN echo '[source.crates-io]' > ~/.cargo/config \
&& echo 'registry = "https://github.com/rust-lang/crates.io-index"' >> ~/.cargo/config \
&& echo '# 替换成你偏好的镜像源' >> ~/.cargo/config \
&& echo "replace-with = 'sjtu'" >> ~/.cargo/config \
&& echo '# 上海交通大学' >> ~/.cargo/config \
&& echo '[source.sjtu]' >> ~/.cargo/config \
&& echo 'registry = "https://mirrors.sjtug.sjtu.edu.cn/git/crates.io-index"' >> ~/.cargo/config \
&& echo '' >> ~/.cargo/config
```
3. Dockerfile 中加入代理的 env
```
在User root后插入两行
ENV http_proxy=http://host:port
ENV https_proxy=http://host:port
```
4. docker build 命令后面加上 proxy 参数
```
docker build -t "rustdesk-builder" . --build-arg http_proxy=http://host:port --build-arg https_proxy=http://host:port
```
然后,每次需要构建应用程序时,运行以下命令:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
运行若遇到无权限问题,出现以下提示:
```
usermod: user user is currently used by process 1
groupmod: Permission denied.
groupmod: cannot lock /etc/group; try again later.
```
可以尝试把`-e PUID="$(id -u)" -e PGID="$(id -g)"`参数去掉。(出现这一问题的原因是容器中的 entrypoint 脚本中判定 uid 和 gid 与给定的环境变量不一致时会修改 user 的 uid 和 gid 重新运行,但是重新运行时取不到环境变量中的 uid 和 gid 了,会再次进入 uid 与 gid 与给定值不一致的逻辑分支)
请注意,第一次构建可能需要比较长的时间,因为需要缓存依赖项(国内网络经常出现拉取失败,可多尝试几次),后续构建会更快。此外,如果您需要为构建命令指定不同的参数,
您可以在命令末尾的 `<OPTIONAL-ARGS>` 位置执行此操作。例如,如果你想构建一个优化的发布版本,你可以在命令后跟 `---release`。
将在 target 下产生可执行程序,请通过以下方式运行调试版本:
```sh
target/debug/rustdesk
```
或者运行发布版本:
```sh
target/release/rustdesk
```
请确保您从 RustDesk 存储库的根目录运行这些命令,否则应用程序可能无法找到所需的资源。另请注意,此方法当前不支持其他`Cargo`子命令,
例如 `install` 或 `run`,因为运行在容器里,而不是宿主机上。
## 文件结构
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: 视频编解码, 配置, tcp/udp 封装, protobuf, 文件传输相关文件系统操作函数, 以及一些其他实用函数
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: 截屏
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: 平台相关的鼠标键盘输入
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: GUI
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: 被控端服务audio/clipboard/input/video 服务, 已经连接实现
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: 控制端
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: 与[rustdesk-server](https://github.com/rustdesk/rustdesk-server)保持 UDP 通讯, 等待远程连接(通过打洞直连或者中继)
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: 平台服务相关代码
## 截图
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

109
README.md
View File

@@ -1,55 +1,87 @@
# RustDesk | Your Remote Desktop Software
<p align="center">
<img src="logo-header.svg" alt="RustDesk - Your remote desktop"><br>
<a href="#free-public-servers">Servers</a>
<a href="#raw-steps-to-build">Build</a>
<a href="#how-to-build-with-docker">Docker</a>
<a href="#file-structure">Structure</a>
<a href="#snapshot">Snapshot</a><br>
[<a href="README-ZH.md">中文</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PT.md">Português</a>]<br>
<b>We need your help to translate this README and <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> to your native language</b>
</p>
The best open-source remote desktop client software, written in Rust. Works out of the box, no configuration required. Great alternative to TeamViewer and AnyDesk! You have full control of your data, with no concerns about security. You can use our rendezvous/relay server, [set up your own](https://rustdesk.com/blog/id-relay-set/), or write your own rendezvous/relay server.
Chat with us: [Discord](https://discord.gg/nDceKgxnkV) | [Reddit](https://www.reddit.com/r/rustdesk)
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I2I04VU09)
Yet another remote desktop software, written in Rust. Works out of the box, no configuration required. You have full control of your data, with no concerns about security. You can use our rendezvous/relay server, [set up your own](https://rustdesk.com/blog/id-relay-set/), or [write your own rendezvous/relay server](https://github.com/rustdesk/rustdesk-server-demo).
RustDesk welcomes contribution from everyone. See [`CONTRIBUTING.md`](CONTRIBUTING.md) for help getting started.
[**BINARY DOWNLOAD**](https://github.com/rustdesk/rustdesk/releases)
## Free Public Servers
Below are the servers you are using for free, it may change along the time. If you are not close to one of these, your network may be slow.
| Location | Vendor | Specification |
| --------- | ------------- | ------------------ |
| Seoul | AWS lightsail | 1 VCPU / 0.5GB RAM |
| Singapore | Vultr | 1 VCPU / 1GB RAM |
| Dallas | Vultr | 1 VCPU / 1GB RAM | |
## Dependencies
Desktop versions use [sciter](https://sciter.com/) for GUI, please download sciter dynamic library yourself.
[Windows](https://github.com/c-smile/sciter-sdk/blob/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.win/x64/sciter.dll)
[Linux](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so)
[Osx](https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.osx/sciter-osx-64.dylib)
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[MacOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Raw steps to build
* Prepare your Rust development env and C++ build env
* Install [vcpkg](https://github.com/microsoft/vcpkg), and set `VCPKG_ROOT` env variable correctly
- Prepare your Rust development env and C++ build env
- Install [vcpkg](https://github.com/microsoft/vcpkg), and set `VCPKG_ROOT` env variable correctly
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static
- Linux/Osx: vcpkg install libvpx libyuv opus
- Linux/MacOS: vcpkg install libvpx libyuv opus
* run `cargo run`
- run `cargo run`
## How to build on Linux
### Ubuntu 18 (Debian 10)
```
```sh
sudo apt install -y g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake
```
### Fedora 28 (CentOS 8)
```
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel
```
### Arch (Manjaro)
```
sudo pacman -Syu unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pulseaudio
```
### Install vcpkg
```
git clone https://github.com/microsoft/vcpkg --branch 2020.11-1
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2021.12.01
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus
```
### Fix libvpx (For Fedora)
```
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
@@ -61,20 +93,52 @@ cd
```
### Build
```
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://github.com/c-smile/sciter-sdk/raw/dc65744b66389cd5a0ff6bdb7c63a8b7b05a708b/bin.lnx/x64/libsciter-gtk.so
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
cargo run
VCPKG_ROOT=$HOME/vcpkg cargo run
```
### Change Wayland to X11 (Xorg)
RustDesk does not support Wayland. Check [this](https://docs.fedoraproject.org/en-US/quick-docs/configuring-xorg-as-default-gnome-session/) to configuring Xorg as the default GNOME session.
## How to build with Docker
Begin by cloning the repository and building the docker container:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
docker build -t "rustdesk-builder" .
```
Then, each time you need to build the application, run the following command:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Note that the first build may take longer before dependencies are cached, subsequent builds will be faster. Additionally, if you need to specify different arguments to the build command, you may do so at the end of the command in the `<OPTIONAL-ARGS>` position. For instance, if you wanted to build an optimized release version, you would run the command above followed by `---release`. The resulting executable will be available in the target folder on your system, and can be run with:
```sh
target/debug/rustdesk
```
Or, if you're running a release executable:
```sh
target/release/rustdesk
```
Please ensure that you are running these commands from the root of the RustDesk repository, otherwise the application may be unable to find the required resources. Also note that other cargo subcommands such as `install` or `run` are not currently supported via this method as they would install or run the program inside the container instead of the host.
## File Structure
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: video codec, config, tcp/udp wrapper, protobuf, fs functions for file transfer, and some other utility functions
@@ -87,12 +151,11 @@ RustDesk does not support Wayland. Check [this](https://docs.fedoraproject.org/e
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: platform specific code
## Snapshot
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
![image](https://user-images.githubusercontent.com/71636191/113112619-f705a480-923b-11eb-911d-97e984ef52b6.png)
![image](https://user-images.githubusercontent.com/71636191/113112857-3fbd5d80-923c-11eb-9836-768325faf906.png)
![image](https://user-images.githubusercontent.com/71636191/113112990-65e2fd80-923c-11eb-840e-349b4d6e340d.png)
![image](https://user-images.githubusercontent.com/71636191/135385039-38fdbd72-379a-422d-b97f-33df71fb1cec.png)

13
SECURITY.md Normal file
View File

@@ -0,0 +1,13 @@
# Security Policy
## Supported Versions
| Version | Supported |
| --------- | ------------------ |
| 1.1.x | :white_check_mark: |
| 1.x | :white_check_mark: |
| Below 1.0 | :x: |
## Reporting a Vulnerability
Here we should write what to do in case of a security vulnerability

34
entrypoint Executable file
View File

@@ -0,0 +1,34 @@
#!/bin/sh
cd $HOME/rustdesk
. $HOME/.cargo/env
argv=$@
while test $# -gt 0; do
case "$1" in
--release)
mkdir -p target/release
test -f target/release/libsciter-gtk.so || cp $HOME/libsciter-gtk.so target/release/
release=1
shift
;;
--target)
shift
if test $# -gt 0; then
rustup target add $1
shift
fi
;;
*)
shift
;;
esac
done
if [ -z $release ]; then
mkdir -p target/debug
test -f target/debug/libsciter-gtk.so || cp $HOME/libsciter-gtk.so target/debug/
fi
VCPKG_ROOT=/vcpkg cargo build $argv

View File

@@ -6,7 +6,7 @@ fn main() {
thread::sleep(Duration::from_secs(2));
let mut enigo = Enigo::new();
enigo.key_down(Key::Layout('a'));
enigo.key_down(Key::Layout('a')).ok();
thread::sleep(Duration::from_secs(1));
enigo.key_up(Key::Layout('a'));
}

View File

@@ -10,7 +10,7 @@ fn main() {
enigo.key_sequence("Hello World! here is a lot of text ❤️");
// select all
enigo.key_down(Key::Control);
enigo.key_down(Key::Control).ok();
enigo.key_click(Key::Layout('a'));
enigo.key_up(Key::Control);
}

View File

@@ -11,7 +11,7 @@ fn main() {
enigo.mouse_move_to(500, 200);
thread::sleep(wait_time);
enigo.mouse_down(MouseButton::Left);
enigo.mouse_down(MouseButton::Left).ok();
thread::sleep(wait_time);
enigo.mouse_move_relative(100, 100);

View File

@@ -16,7 +16,7 @@ fn main() {
println!("{:?}", time);
// select all
enigo.key_down(Key::Control);
enigo.key_down(Key::Control).ok();
enigo.key_click(Key::Layout('a'));
enigo.key_up(Key::Control);
}

View File

@@ -299,7 +299,7 @@ pub enum Key {
/// meta key (also known as "windows", "super", and "command")
Meta,
/// option key on macOS (alt key on Linux and Windows)
Option,
Option, // deprecated, use Alt instead
/// page down key
PageDown,
/// page up key
@@ -347,8 +347,6 @@ pub enum Key {
///
Clear,
///
Menu,
///
Pause,
///
Kana,
@@ -409,6 +407,12 @@ pub enum Key {
///
NumpadEnter,
///
RightShift,
///
RightControl,
///
RightAlt,
///
/// Function, /// mac
/// keyboard layout dependent key
Layout(char),

View File

@@ -238,7 +238,6 @@ fn keysequence<'a>(key: Key) -> Cow<'a, str> {
Key::Decimal => "U2E", //"KP_Decimal",
Key::Cancel => "Cancel",
Key::Clear => "Clear",
Key::Menu => "Menu",
Key::Pause => "Pause",
Key::Kana => "Kana",
Key::Hangul => "Hangul",
@@ -260,14 +259,17 @@ fn keysequence<'a>(key: Key) -> Cow<'a, str> {
Key::Mute => "",
Key::Scroll => "Scroll_Lock",
Key::NumLock => "Num_Lock",
Key::RWin => "",
Key::Apps => "",
Key::RWin => "Super_R",
Key::Apps => "Menu",
Key::Multiply => "KP_Multiply",
Key::Add => "KP_Add",
Key::Subtract => "KP_Subtract",
Key::Divide => "KP_Divide",
Key::Equals => "KP_Equal",
Key::NumpadEnter => "KP_Enter",
Key::RightShift => "Shift_R",
Key::RightControl => "Control_R",
Key::RightAlt => "Alt_R",
Key::Command | Key::Super | Key::Windows | Key::Meta => "Super",

View File

@@ -70,3 +70,51 @@ pub const kVK_ANSI_KeypadDivide: u16 = 0x4B;
pub const kVK_ANSI_KeypadEnter: u16 = 0x4C;
pub const kVK_ANSI_KeypadMinus: u16 = 0x4E;
pub const kVK_ANSI_KeypadEquals: u16 = 0x51;
pub const kVK_RIGHT_COMMAND: u16 = 0x36;
pub const kVK_ANSI_A : u16 = 0x00;
pub const kVK_ANSI_S : u16 = 0x01;
pub const kVK_ANSI_D : u16 = 0x02;
pub const kVK_ANSI_F : u16 = 0x03;
pub const kVK_ANSI_H : u16 = 0x04;
pub const kVK_ANSI_G : u16 = 0x05;
pub const kVK_ANSI_Z : u16 = 0x06;
pub const kVK_ANSI_X : u16 = 0x07;
pub const kVK_ANSI_C : u16 = 0x08;
pub const kVK_ANSI_V : u16 = 0x09;
pub const kVK_ANSI_B : u16 = 0x0B;
pub const kVK_ANSI_Q : u16 = 0x0C;
pub const kVK_ANSI_W : u16 = 0x0D;
pub const kVK_ANSI_E : u16 = 0x0E;
pub const kVK_ANSI_R : u16 = 0x0F;
pub const kVK_ANSI_Y : u16 = 0x10;
pub const kVK_ANSI_T : u16 = 0x11;
pub const kVK_ANSI_1 : u16 = 0x12;
pub const kVK_ANSI_2 : u16 = 0x13;
pub const kVK_ANSI_3 : u16 = 0x14;
pub const kVK_ANSI_4 : u16 = 0x15;
pub const kVK_ANSI_6 : u16 = 0x16;
pub const kVK_ANSI_5 : u16 = 0x17;
pub const kVK_ANSI_Equal : u16 = 0x18;
pub const kVK_ANSI_9 : u16 = 0x19;
pub const kVK_ANSI_7 : u16 = 0x1A;
pub const kVK_ANSI_Minus : u16 = 0x1B;
pub const kVK_ANSI_8 : u16 = 0x1C;
pub const kVK_ANSI_0 : u16 = 0x1D;
pub const kVK_ANSI_RightBracket : u16 = 0x1E;
pub const kVK_ANSI_O : u16 = 0x1F;
pub const kVK_ANSI_U : u16 = 0x20;
pub const kVK_ANSI_LeftBracket : u16 = 0x21;
pub const kVK_ANSI_I : u16 = 0x22;
pub const kVK_ANSI_P : u16 = 0x23;
pub const kVK_ANSI_L : u16 = 0x25;
pub const kVK_ANSI_J : u16 = 0x26;
pub const kVK_ANSI_Quote : u16 = 0x27;
pub const kVK_ANSI_K : u16 = 0x28;
pub const kVK_ANSI_Semicolon : u16 = 0x29;
pub const kVK_ANSI_Backslash : u16 = 0x2A;
pub const kVK_ANSI_Comma : u16 = 0x2B;
pub const kVK_ANSI_Slash : u16 = 0x2C;
pub const kVK_ANSI_N : u16 = 0x2D;
pub const kVK_ANSI_M : u16 = 0x2E;
pub const kVK_ANSI_Period : u16 = 0x2F;
pub const kVK_ANSI_Grave : u16 = 0x32;

View File

@@ -9,12 +9,6 @@ use self::core_graphics::event_source::*;
use crate::macos::keycodes::*;
use crate::{Key, KeyboardControllable, MouseButton, MouseControllable};
use objc::runtime::Class;
use std::ffi::CStr;
use std::os::raw::*;
// required for pressedMouseButtons on NSEvent
#[link(name = "AppKit", kind = "framework")]
extern "C" {}
struct MyCGEvent;
@@ -34,8 +28,6 @@ extern "C" {
fn CGEventSourceKeyState(stateID: i32, key: u16) -> bool;
}
pub type CFDataRef = *const c_void;
#[repr(C)]
#[derive(Clone, Copy)]
struct NSPoint {
@@ -43,160 +35,6 @@ struct NSPoint {
y: f64,
}
#[repr(C)]
pub struct __TISInputSource;
pub type TISInputSourceRef = *const __TISInputSource;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __CFString([u8; 0]);
pub type CFStringRef = *const __CFString;
pub type Boolean = c_uchar;
pub type UInt8 = c_uchar;
pub type SInt32 = c_int;
pub type UInt16 = c_ushort;
pub type UInt32 = c_uint;
pub type UniChar = UInt16;
pub type UniCharCount = c_ulong;
pub type OptionBits = UInt32;
pub type OSStatus = SInt32;
pub type CFStringEncoding = UInt32;
#[allow(non_upper_case_globals)]
pub const kUCKeyActionDisplay: _bindgen_ty_702 = _bindgen_ty_702::kUCKeyActionDisplay;
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum _bindgen_ty_702 {
// kUCKeyActionDown = 0,
// kUCKeyActionUp = 1,
// kUCKeyActionAutoKey = 2,
kUCKeyActionDisplay = 3,
}
#[allow(non_snake_case)]
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct UCKeyboardTypeHeader {
pub keyboardTypeFirst: UInt32,
pub keyboardTypeLast: UInt32,
pub keyModifiersToTableNumOffset: UInt32,
pub keyToCharTableIndexOffset: UInt32,
pub keyStateRecordsIndexOffset: UInt32,
pub keyStateTerminatorsOffset: UInt32,
pub keySequenceDataIndexOffset: UInt32,
}
#[allow(non_snake_case)]
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct UCKeyboardLayout {
pub keyLayoutHeaderFormat: UInt16,
pub keyLayoutDataVersion: UInt16,
pub keyLayoutFeatureInfoOffset: UInt32,
pub keyboardTypeCount: UInt32,
pub keyboardTypeList: [UCKeyboardTypeHeader; 1usize],
}
#[allow(non_upper_case_globals)]
pub const kUCKeyTranslateNoDeadKeysBit: _bindgen_ty_703 =
_bindgen_ty_703::kUCKeyTranslateNoDeadKeysBit;
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum _bindgen_ty_703 {
kUCKeyTranslateNoDeadKeysBit = 0,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __CFAllocator([u8; 0]);
pub type CFAllocatorRef = *const __CFAllocator;
// #[repr(u32)]
// #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
// pub enum _bindgen_ty_15 {
// kCFStringEncodingMacRoman = 0,
// kCFStringEncodingWindowsLatin1 = 1280,
// kCFStringEncodingISOLatin1 = 513,
// kCFStringEncodingNextStepLatin = 2817,
// kCFStringEncodingASCII = 1536,
// kCFStringEncodingUnicode = 256,
// kCFStringEncodingUTF8 = 134217984,
// kCFStringEncodingNonLossyASCII = 3071,
// kCFStringEncodingUTF16BE = 268435712,
// kCFStringEncodingUTF16LE = 335544576,
// kCFStringEncodingUTF32 = 201326848,
// kCFStringEncodingUTF32BE = 402653440,
// kCFStringEncodingUTF32LE = 469762304,
// }
#[allow(non_upper_case_globals)]
pub const kCFStringEncodingUTF8: u32 = 134_217_984;
#[allow(improper_ctypes)]
#[link(name = "Carbon", kind = "framework")]
extern "C" {
fn TISCopyCurrentKeyboardInputSource() -> TISInputSourceRef;
// extern void *
// TISGetInputSourceProperty(
// TISInputSourceRef inputSource,
// CFStringRef propertyKey)
#[allow(non_upper_case_globals)]
#[link_name = "kTISPropertyUnicodeKeyLayoutData"]
pub static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
#[allow(non_snake_case)]
pub fn TISGetInputSourceProperty(
inputSource: TISInputSourceRef,
propertyKey: CFStringRef,
) -> *mut c_void;
#[allow(non_snake_case)]
pub fn CFDataGetBytePtr(theData: CFDataRef) -> *const UInt8;
#[allow(non_snake_case)]
pub fn UCKeyTranslate(
keyLayoutPtr: *const UInt8, //*const UCKeyboardLayout,
virtualKeyCode: UInt16,
keyAction: UInt16,
modifierKeyState: UInt32,
keyboardType: UInt32,
keyTranslateOptions: OptionBits,
deadKeyState: *mut UInt32,
maxStringLength: UniCharCount,
actualStringLength: *mut UniCharCount,
unicodeString: *mut UniChar,
) -> OSStatus;
pub fn LMGetKbdType() -> UInt8;
#[allow(non_snake_case)]
pub fn CFStringCreateWithCharacters(
alloc: CFAllocatorRef,
chars: *const UniChar,
numChars: CFIndex,
) -> CFStringRef;
#[allow(non_upper_case_globals)]
#[link_name = "kCFAllocatorDefault"]
pub static kCFAllocatorDefault: CFAllocatorRef;
#[allow(non_snake_case)]
pub fn CFStringGetCString(
theString: CFStringRef,
buffer: *mut c_char,
bufferSize: CFIndex,
encoding: CFStringEncoding,
) -> Boolean;
}
// not present in servo/core-graphics
#[allow(dead_code)]
#[derive(Debug)]
@@ -209,7 +47,6 @@ enum ScrollUnit {
/// The main struct for handling the event emitting
pub struct Enigo {
event_source: Option<CGEventSource>,
keycode_to_string_map: std::collections::HashMap<String, CGKeyCode>,
double_click_interval: u32,
last_click_time: Option<std::time::Instant>,
multiple_click: i64,
@@ -261,7 +98,6 @@ impl Default for Enigo {
} else {
None
},
keycode_to_string_map: Default::default(),
double_click_interval,
multiple_click: 1,
last_click_time: None,
@@ -583,97 +419,71 @@ impl Enigo {
Key::Subtract => kVK_ANSI_KeypadMinus,
Key::Equals => kVK_ANSI_KeypadEquals,
Key::NumLock => kVK_ANSI_KeypadClear,
Key::RWin => kVK_RIGHT_COMMAND,
Key::RightShift => kVK_RightShift,
Key::RightControl => kVK_RightControl,
Key::RightAlt => kVK_RightOption,
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
Key::Layout(c) => self.map_key_board(c),
Key::Super | Key::Command | Key::Windows | Key::Meta => kVK_Command,
_ => 0,
}
}
fn get_layoutdependent_keycode(&mut self, string: String) -> CGKeyCode {
if self.keycode_to_string_map.is_empty() {
self.init_map();
#[inline]
fn map_key_board(&self, ch: char) -> CGKeyCode {
match ch {
'a' => kVK_ANSI_A,
'b' => kVK_ANSI_B,
'c' => kVK_ANSI_C,
'd' => kVK_ANSI_D,
'e' => kVK_ANSI_E,
'f' => kVK_ANSI_F,
'g' => kVK_ANSI_G,
'h' => kVK_ANSI_H,
'i' => kVK_ANSI_I,
'j' => kVK_ANSI_J,
'k' => kVK_ANSI_K,
'l' => kVK_ANSI_L,
'm' => kVK_ANSI_M,
'n' => kVK_ANSI_N,
'o' => kVK_ANSI_O,
'p' => kVK_ANSI_P,
'q' => kVK_ANSI_Q,
'r' => kVK_ANSI_R,
's' => kVK_ANSI_S,
't' => kVK_ANSI_T,
'u' => kVK_ANSI_U,
'v' => kVK_ANSI_V,
'w' => kVK_ANSI_W,
'x' => kVK_ANSI_X,
'y' => kVK_ANSI_Y,
'z' => kVK_ANSI_Z,
'0' => kVK_ANSI_0,
'1' => kVK_ANSI_1,
'2' => kVK_ANSI_2,
'3' => kVK_ANSI_3,
'4' => kVK_ANSI_4,
'5' => kVK_ANSI_5,
'6' => kVK_ANSI_6,
'7' => kVK_ANSI_7,
'8' => kVK_ANSI_8,
'9' => kVK_ANSI_9,
'-' => kVK_ANSI_Minus,
'=' => kVK_ANSI_Equal,
'[' => kVK_ANSI_LeftBracket,
']' => kVK_ANSI_RightBracket,
'\\' => kVK_ANSI_Backslash,
';' => kVK_ANSI_Semicolon,
'\'' => kVK_ANSI_Quote,
',' => kVK_ANSI_Comma,
'.' => kVK_ANSI_Period,
'/' => kVK_ANSI_Slash,
'`' => kVK_ANSI_Grave,
_ => 0,
}
*self.keycode_to_string_map.get(&string).unwrap_or(&0)
}
fn init_map(&mut self) {
self.keycode_to_string_map.insert("".to_owned(), 0);
// loop through every keycode (0 - 127)
for keycode in 0..128 {
// no modifier
if let Some(key_string) = self.keycode_to_string(keycode, 0x100) {
self.keycode_to_string_map.insert(key_string, keycode);
}
// shift modifier
if let Some(key_string) = self.keycode_to_string(keycode, 0x20102) {
self.keycode_to_string_map.insert(key_string, keycode);
}
// alt modifier
// if let Some(string) = self.keycode_to_string(keycode, 0x80120) {
// println!("{:?}", string);
// }
// alt + shift modifier
// if let Some(string) = self.keycode_to_string(keycode, 0xa0122) {
// println!("{:?}", string);
// }
}
}
fn keycode_to_string(&self, keycode: u16, modifier: u32) -> Option<String> {
let cf_string = self.create_string_for_key(keycode, modifier);
unsafe {
if !cf_string.is_null() {
let mut buf: [i8; 255] = [0; 255];
let success = CFStringGetCString(
cf_string,
buf.as_mut_ptr(),
buf.len() as _,
kCFStringEncodingUTF8,
);
if success != 0 {
let name: &CStr = CStr::from_ptr(buf.as_ptr());
if let Ok(name) = name.to_str() {
return Some(name.to_owned());
}
}
}
}
None
}
fn create_string_for_key(&self, keycode: u16, modifier: u32) -> CFStringRef {
let current_keyboard = unsafe { TISCopyCurrentKeyboardInputSource() };
let layout_data = unsafe {
TISGetInputSourceProperty(current_keyboard, kTISPropertyUnicodeKeyLayoutData)
};
let keyboard_layout = unsafe { CFDataGetBytePtr(layout_data) };
let mut keys_down: UInt32 = 0;
// let mut chars: *mut c_void;//[UniChar; 4];
let mut chars: u16 = 0;
let mut real_length: UniCharCount = 0;
unsafe {
UCKeyTranslate(
keyboard_layout,
keycode,
kUCKeyActionDisplay as u16,
modifier,
LMGetKbdType() as u32,
kUCKeyTranslateNoDeadKeysBit as u32,
&mut keys_down,
8, // sizeof(chars) / sizeof(chars[0]),
&mut real_length,
&mut chars,
);
}
unsafe { CFStringCreateWithCharacters(kCFAllocatorDefault, &chars, 1) }
}
}

View File

@@ -1,4 +1,7 @@
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731
//
// JP/KR mapping https://github.com/TigerVNC/tigervnc/blob/1a008c1380305648ab50f1d99e73439747e9d61d/vncviewer/win32.c#L267
// altgr handle: https://github.com/TigerVNC/tigervnc/blob/dccb95f345f7a9c5aa785a19d1bfa3fdecd8f8e0/vncviewer/Viewport.cxx#L1066
pub const EVK_RETURN: u16 = 0x0D;
pub const EVK_TAB: u16 = 0x09;
@@ -7,9 +10,14 @@ pub const EVK_BACK: u16 = 0x08;
pub const EVK_ESCAPE: u16 = 0x1b;
pub const EVK_LWIN: u16 = 0x5b;
pub const EVK_SHIFT: u16 = 0x10;
//pub const EVK_LSHIFT: u16 = 0xa0;
pub const EVK_RSHIFT: u16 = 0xa1;
//pub const EVK_LMENU: u16 = 0xa4;
pub const EVK_RMENU: u16 = 0xa5;
pub const EVK_CAPITAL: u16 = 0x14;
pub const EVK_MENU: u16 = 0x12;
pub const EVK_LCONTROL: u16 = 0xa2;
pub const EVK_RCONTROL: u16 = 0xa3;
pub const EVK_HOME: u16 = 0x24;
pub const EVK_PRIOR: u16 = 0x21;
pub const EVK_NEXT: u16 = 0x22;

View File

@@ -176,13 +176,13 @@ impl KeyboardControllable for Enigo {
}
fn key_click(&mut self, key: Key) {
let scancode = self.key_to_scancode(key);
keybd_event(KEYEVENTF_SCANCODE, 0, scancode);
keybd_event(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE, 0, scancode);
let vk = self.key_to_keycode(key);
keybd_event(0, vk, 0);
keybd_event(KEYEVENTF_KEYUP, vk, 0);
}
fn key_down(&mut self, key: Key) -> crate::ResultType {
let res = keybd_event(KEYEVENTF_SCANCODE, 0, self.key_to_scancode(key));
let res = keybd_event(0, self.key_to_keycode(key), 0);
if res == 0 {
let err = get_error();
if !err.is_empty() {
@@ -193,11 +193,7 @@ impl KeyboardControllable for Enigo {
}
fn key_up(&mut self, key: Key) {
keybd_event(
KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE,
0,
self.key_to_scancode(key),
);
keybd_event(KEYEVENTF_KEYUP, self.key_to_keycode(key), 0);
}
fn get_key_state(&mut self, key: Key) -> bool {
@@ -307,7 +303,6 @@ impl Enigo {
Key::Numpad9 => EVK_NUMPAD9,
Key::Cancel => EVK_CANCEL,
Key::Clear => EVK_CLEAR,
Key::Menu => EVK_MENU,
Key::Pause => EVK_PAUSE,
Key::Kana => EVK_KANA,
Key::Hangul => EVK_HANGUL,
@@ -338,6 +333,9 @@ impl Enigo {
Key::Divide => EVK_DIVIDE,
Key::NumpadEnter => EVK_RETURN,
Key::Equals => '=' as _,
Key::RightShift => EVK_RSHIFT,
Key::RightControl => EVK_RCONTROL,
Key::RightAlt => EVK_RMENU,
Key::Raw(raw_keycode) => raw_keycode,
Key::Layout(c) => self.get_layoutdependent_keycode(c.to_string()),
@@ -345,11 +343,6 @@ impl Enigo {
}
}
fn key_to_scancode(&self, key: Key) -> u16 {
let keycode = self.key_to_keycode(key);
unsafe { MapVirtualKeyW(keycode as u32, 0) as u16 }
}
fn get_layoutdependent_keycode(&self, string: String) -> u16 {
// get the first char from the string ignore the rest
// ensure its not a multybyte char

View File

@@ -7,20 +7,20 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
protobuf = { version = "3.0.0-pre", git = "https://github.com/stepancheg/rust-protobuf" }
tokio = { version = "0.2", features = ["full"] }
tokio-util = { version = "0.3", features = ["full"] }
protobuf = "3.0.0-alpha.2"
tokio = { version = "1.15", features = ["full"] }
tokio-util = { version = "0.6", features = ["full"] }
futures = "0.3"
bytes = "0.5"
bytes = "1.1"
log = "0.4"
env_logger = "0.8"
env_logger = "0.9"
socket2 = { version = "0.3", features = ["reuseport"] }
zstd = "0.5"
quinn = {version = "0.6", optional = true }
zstd = "0.9"
quinn = {version = "0.8", optional = true }
anyhow = "1.0"
futures-util = "0.3"
directories-next = "2.0"
rand = "0.7"
rand = "0.8"
serde_derive = "1.0"
serde = "1.0"
lazy_static = "1.4"
@@ -28,6 +28,8 @@ confy = { git = "https://github.com/open-trade/confy" }
dirs-next = "2.0"
filetime = "0.2"
sodiumoxide = "0.2"
regex = "1.4"
tokio-socks = { git = "https://github.com/fufesou/tokio-socks" }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
mac_address = "1.1"
@@ -36,7 +38,7 @@ mac_address = "1.1"
quic = ["quinn"]
[build-dependencies]
protobuf-codegen-pure = { version = "3.0.0-pre", git = "https://github.com/stepancheg/rust-protobuf" }
protobuf-codegen-pure = "3.0.0-alpha.2"
[target.'cfg(target_os = "windows")'.dependencies]
winapi = { version = "0.3", features = ["winuser"] }

View File

@@ -129,7 +129,7 @@ enum ControlKey {
Numpad9 = 42;
Cancel = 43;
Clear = 44;
Menu = 45;
Menu = 45; // deprecated, use Alt instead
Pause = 46;
Kana = 47;
Hangul = 48;
@@ -157,6 +157,9 @@ enum ControlKey {
Divide = 70;
Equals = 71;
NumpadEnter = 72;
RShift= 73;
RControl = 74;
RAlt = 75;
CtrlAltDel = 100;
LockScreen = 101;
}
@@ -356,7 +359,6 @@ message PublicKey {
message SignedId {
bytes id = 1;
bytes pk = 2;
}
message AudioFormat {

View File

@@ -6,11 +6,19 @@ message RegisterPeer {
int32 serial = 2;
}
enum ConnType {
DEFAULT_CONN = 0;
FILE_TRANSFER = 1;
PORT_FORWARD = 2;
RDP = 3;
}
message RegisterPeerResponse { bool request_pk = 2; }
message PunchHoleRequest {
string id = 1;
NatType nat_type = 2;
ConnType conn_type = 4;
}
message PunchHole {
@@ -40,6 +48,7 @@ message PunchHoleSent {
string id = 2;
string relay_server = 3;
NatType nat_type = 4;
string version = 5;
}
message RegisterPk {
@@ -52,6 +61,11 @@ message RegisterPkResponse {
enum Result {
OK = 1;
UUID_MISMATCH = 2;
ID_EXISTS = 3;
TOO_FREQUENT = 4;
INVALID_ID_FORMAT = 5;
NOT_SUPPORT = 6;
SERVER_ERROR = 7;
}
Result result = 1;
}
@@ -62,6 +76,8 @@ message PunchHoleResponse {
enum Failure {
ID_NOT_EXIST = 1;
OFFLINE = 2;
LICENSE_MISMATCH = 3;
LICENSE_OVERUSE = 4;
}
Failure failure = 3;
string relay_server = 4;
@@ -69,6 +85,7 @@ message PunchHoleResponse {
NatType nat_type = 5;
bool is_local = 6;
}
string other_failure = 7;
}
message ConfigUpdate {
@@ -82,6 +99,7 @@ message RequestRelay {
bytes socket_addr = 3;
string relay_server = 4;
bool secure = 5;
ConnType conn_type = 7;
}
message RelayResponse {
@@ -92,6 +110,8 @@ message RelayResponse {
string id = 4;
bytes pk = 5;
}
string refuse_reason = 6;
string version = 7;
}
message SoftwareUpdate { string url = 1; }
@@ -110,6 +130,7 @@ message LocalAddr {
bytes local_addr = 2;
string relay_server = 3;
string id = 4;
string version = 5;
}
message RendezvousMessage {

View File

@@ -6,18 +6,17 @@ use sodiumoxide::crypto::sign;
use std::{
collections::HashMap,
fs,
net::SocketAddr,
net::{IpAddr, Ipv4Addr, SocketAddr},
path::{Path, PathBuf},
sync::{Arc, Mutex, RwLock},
time::SystemTime,
};
pub const APP_NAME: &str = "RustDesk";
pub const BIND_INTERFACE: &str = "0.0.0.0";
pub const RENDEZVOUS_TIMEOUT: u64 = 12_000;
pub const CONNECT_TIMEOUT: u64 = 18_000;
pub const COMPRESS_LEVEL: i32 = 3;
const SERIAL: i32 = 0;
const SERIAL: i32 = 1;
// 128x128
#[cfg(target_os = "macos")] // 128x128 on 160x160 canvas, then shrink to 128, mac looks better with padding
pub const ICON: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAyVBMVEUAAAAAcf8Acf8Acf8Acv8Acf8Acf8Acf8Acf8AcP8Acf8Ab/8AcP8Acf////8AaP/z+f/o8v/k7v/5/v/T5f8AYP/u9v/X6f+hx/+Kuv95pP8Aef/B1/+TwP9xoP8BdP/g6P+Irv9ZmP8Bgf/E3f98q/9sn/+01f+Es/9nm/9Jif8hhv8off/M4P+syP+avP86iP/c7f+xy/9yqf9Om/9hk/9Rjv+60P99tv9fpf88lv8yjf8Tgf8deP+kvP8BiP8NeP8hkP80gP8oj2VLAAAADXRSTlMA7o7qLvnaxZ1FOxYPjH9HWgAABHJJREFUeNrtm+tW4jAQgBfwuu7MtIUWsOUiCCioIIgLiqvr+z/UHq/LJKVkmwTcc/r9E2nzlU4mSTP9lpGRkZGR8VX5cZjfL+yCEXYL+/nDH//U/Pd8DgyTy39Xbv7oIAcWyB0cqbW/sweW2NtRaj8H1sgpGOwUIAH7Bkd7YJW9dXFwAJY5WNP/cmCZQnJvzIN18on5LwfWySXlxEPYAIcad8D6PdiHDbCfIFCADVBIENiFDbCbIACKPPXrZ+cP8E6/0znvP4EymgIEravIRcTxu8HxNSJ60a8W0AYECKrlAN+YwAthCd9wm1Ug6wKzIn5SgRduXfwkqDasCjx0XFzi9PV6zwNcIuhcWBOg+ikySq8C9UD4dEKWBCoOcspvAuLHTo9sCDQiFPHotRM48j8G5gVur1FdAN2uaYEuiz7xFsgEJ2RUoMUakXuBTHHoGxQYOBhHjeUBAefEnMAowFhaLBOKuOemBBbxLRQrH2PBCgMvNCPQGMeevTb9zLrPxz2Mo+QbEaijzPUcOOHMQZkKGRAIPem39+bypREMPTkQW/oCfk866zAkiIFG4yIKRE/aAnfiSd0WrORY6pFdXQEqi9mvAQm0RIOSnoCcZ8vJoz3diCnjRk+g8VP4/fuQDJ2Lxr6WwG0gXs9aTpDzW0vgDBlVUpixR8gYk44AD8FrUKHr8JQJGgIDnoDqoALxmWPQSi9AVVzm8gKUuEPGr/QCvptwJkbSYT/TC4S8C96DGjTj86aHtAI0x2WaBIq0eSYYpRa4EsdWVVwWu9O0Aj6f6dyBMnwEraeOgSYu0wZlauzA47QCbT7DgAQSE+hZWoEBF/BBmWOewNMK3BsSqKUW4MGcWqCSVmDkbvkXGKQOwg6PAUO9oL3xXhA20yaiCjuwYygRVQlUOTWTCf2SuNJTxeFjgaHByGuAIvd8ItdPLTDhS7IuqEE1YSKVOgbayLhSFQhMzYh8hwfBs1r7c505YVIQYEdNoKwxK06MJiyrpUFHiF0NAfCQUVHoiRclIXJIR6C2fqG37pBHvcWpgwzvAtYwkR5UGV2e42UISdBJETl3mg8ouo54Rcnti1/vaT+iuUQBt500Cgo4U10BeHSkk57FB0JjWkKRMWgLUA0lLodtImAQdaMiiri3+gIAPZQoutHNsgKF1aaDMhMyIdBf8Th+Bh8MTjGWCpl5Wv43tDmnF+IUVMrcZgRoiAxhtrloYizNkZaAnF5leglbNhj0wYCAbCDvGb0mP4nib7O7ZlcYQ2m1gPtIZgVgGNNMeaVAaWR+57TrqgtUnm3sHQ+kYeE6fufUubG1ez50FXbPnWgBlgSABmN3TTcsRl2yWkHRrwbiunvk/W2+Mg1hPZplPDeXRbZzStFH15s1QIVd3UImP5z/bHpeeQLvRJ7XLFUffQIlCvqlXETQbgN9/rlYABGosv+Vi9m2Xs639YLGrZd0br+odetlvdsvbN56abfd4vbCzv9Q3v/ygoOV21A4OPpfXvH4Ai+5ZGRkZGRkbJA/t/I0QMzoMiEAAAAASUVORK5CYII=
@@ -48,12 +47,19 @@ const CHARS: &'static [char] = &[
];
pub const RENDEZVOUS_SERVERS: &'static [&'static str] = &[
"rs-ny.rustdesk.com",
"rs-sg.rustdesk.com",
"rs-cn.rustdesk.com",
];
pub const RENDEZVOUS_PORT: i32 = 21116;
pub const RELAY_PORT: i32 = 21117;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum NetworkType {
Direct,
ProxySocks,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct Config {
#[serde(default)]
@@ -70,6 +76,16 @@ pub struct Config {
keys_confirmed: HashMap<String, bool>,
}
#[derive(Debug, Default, PartialEq, Serialize, Deserialize, Clone)]
pub struct Socks5Server {
#[serde(default)]
pub proxy: String,
#[serde(default)]
pub username: String,
#[serde(default)]
pub password: String,
}
// more variable configs
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct Config2 {
@@ -84,6 +100,9 @@ pub struct Config2 {
#[serde(default)]
serial: i32,
#[serde(default)]
socks: Option<Socks5Server>,
// the other scalar value must before this
#[serde(default)]
pub options: HashMap<String, String>,
@@ -148,6 +167,20 @@ fn patch(path: PathBuf) -> PathBuf {
.into();
#[cfg(target_os = "macos")]
return _tmp.replace("Application Support", "Preferences").into();
#[cfg(target_os = "linux")]
{
if _tmp == "/root" {
if let Ok(output) = std::process::Command::new("whoami").output() {
let user = String::from_utf8_lossy(&output.stdout)
.to_string()
.trim()
.to_owned();
if user != "root" {
return format!("/home/{}", user).into();
}
}
}
}
}
path
}
@@ -259,6 +292,7 @@ impl Config {
return "".into();
}
#[allow(unreachable_code)]
pub fn log_path() -> PathBuf {
#[cfg(target_os = "macos")]
{
@@ -269,11 +303,10 @@ impl Config {
}
#[cfg(target_os = "linux")]
{
if let Some(path) = dirs_next::home_dir().as_mut() {
let mut path = Self::get_home();
path.push(format!(".local/share/logs/{}", APP_NAME));
std::fs::create_dir_all(&path).ok();
return path.clone();
}
return path;
}
if let Some(path) = Self::path("").parent() {
let mut path: PathBuf = path.into();
@@ -312,10 +345,10 @@ impl Config {
#[inline]
pub fn get_any_listen_addr() -> SocketAddr {
format!("{}:0", BIND_INTERFACE).parse().unwrap()
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)
}
pub fn get_rendezvous_server() -> SocketAddr {
pub fn get_rendezvous_server() -> String {
let mut rendezvous_server = Self::get_option("custom-rendezvous-server");
if rendezvous_server.is_empty() {
rendezvous_server = CONFIG2.write().unwrap().rendezvous_server.clone();
@@ -329,11 +362,7 @@ impl Config {
if !rendezvous_server.contains(":") {
rendezvous_server = format!("{}:{}", rendezvous_server, RENDEZVOUS_PORT);
}
if let Ok(addr) = crate::to_socket_addr(&rendezvous_server) {
addr
} else {
Self::get_any_listen_addr()
}
rendezvous_server
}
pub fn get_rendezvous_servers() -> Vec<String> {
@@ -473,6 +502,9 @@ impl Config {
pub fn set_key_pair(pair: (Vec<u8>, Vec<u8>)) {
let mut config = CONFIG.write().unwrap();
if config.key_pair == pair {
return;
}
config.key_pair = pair;
config.store();
}
@@ -505,6 +537,9 @@ impl Config {
pub fn set_options(v: HashMap<String, String>) {
let mut config = CONFIG2.write().unwrap();
if config.options == v {
return;
}
config.options = v;
config.store();
}
@@ -537,7 +572,7 @@ impl Config {
// to-do: how about if one ip register a lot of ids?
let id = Self::get_id();
let mut rng = rand::thread_rng();
let new_id = rng.gen_range(1_000_000_000, 2_000_000_000).to_string();
let new_id = rng.gen_range(1_000_000_000..2_000_000_000).to_string();
Config::set_id(&new_id);
log::info!("id updated from {} to {}", id, new_id);
}
@@ -604,6 +639,26 @@ impl Config {
pub fn get_remote_id() -> String {
CONFIG2.read().unwrap().remote_id.clone()
}
pub fn set_socks(socks: Option<Socks5Server>) {
let mut config = CONFIG2.write().unwrap();
if config.socks == socks {
return;
}
config.socks = socks;
config.store();
}
pub fn get_socks() -> Option<Socks5Server> {
CONFIG2.read().unwrap().socks.clone()
}
pub fn get_network_type() -> NetworkType {
match &CONFIG2.read().unwrap().socks {
None => NetworkType::Direct,
Some(_) => NetworkType::ProxySocks,
}
}
}
const PEERS: &str = "peers";
@@ -636,7 +691,7 @@ impl PeerConfig {
Config::path(path).with_extension("toml")
}
pub fn peers() -> Vec<(String, SystemTime, PeerInfoSerde)> {
pub fn peers() -> Vec<(String, SystemTime, PeerConfig)> {
if let Ok(peers) = Config::path(PEERS).read_dir() {
if let Ok(peers) = peers
.map(|res| res.map(|e| e.path()))
@@ -657,13 +712,13 @@ impl PeerConfig {
.map(|p| p.to_str().unwrap_or(""))
.unwrap_or("")
.to_owned();
let info = PeerConfig::load(&id).info;
if info.platform.is_empty() {
let c = PeerConfig::load(&id);
if c.info.platform.is_empty() {
fs::remove_file(&p).ok();
}
(id, t, info)
(id, t, c)
})
.filter(|p| !p.2.platform.is_empty())
.filter(|p| !p.2.info.platform.is_empty())
.collect();
peers.sort_unstable_by(|a, b| b.1.cmp(&a.1));
return peers;
@@ -673,6 +728,32 @@ impl PeerConfig {
}
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct Fav {
#[serde(default)]
pub peers: Vec<String>,
}
impl Fav {
pub fn load() -> Fav {
let _ = CONFIG.read().unwrap(); // for lock
match confy::load_path(&Config::file_("_fav")) {
Ok(fav) => fav,
Err(err) => {
log::error!("Failed to load fav: {}", err);
Default::default()
}
}
}
pub fn store(peers: Vec<String>) {
let f = Fav { peers };
if let Err(err) = confy::store_path(Config::file_("_fav"), f) {
log::error!("Failed to store fav: {}", err);
}
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -7,7 +7,7 @@ use crate::{
};
#[cfg(windows)]
use std::os::windows::prelude::*;
use tokio::{fs::File, prelude::*};
use tokio::{fs::File, io::*};
pub fn read_dir(path: &PathBuf, include_hidden: bool) -> ResultType<FileDirectory> {
let mut dir = FileDirectory {
@@ -193,7 +193,7 @@ pub struct TransferJob {
file: Option<File>,
total_size: u64,
finished_size: u64,
transfered: u64,
transferred: u64,
}
#[inline]
@@ -268,8 +268,8 @@ impl TransferJob {
}
#[inline]
pub fn transfered(&self) -> u64 {
self.transfered
pub fn transferred(&self) -> u64 {
self.transferred
}
#[inline]
@@ -332,7 +332,7 @@ impl TransferJob {
self.file.as_mut().unwrap().write_all(&block.data).await?;
self.finished_size += block.data.len() as u64;
}
self.transfered += block.data.len() as u64;
self.transferred += block.data.len() as u64;
Ok(())
}
@@ -398,7 +398,7 @@ impl TransferJob {
compressed = true;
}
}
self.transfered += buf.len() as u64;
self.transferred += buf.len() as u64;
}
Ok(Some(FileTransferBlock {
id: self.id,

View File

@@ -6,16 +6,16 @@ pub mod rendezvous_proto;
pub use bytes;
pub use futures;
pub use protobuf;
use socket2::{Domain, Socket, Type};
use std::{
fs::File,
io::{self, BufRead},
net::{Ipv4Addr, SocketAddr, SocketAddrV4, ToSocketAddrs},
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
path::Path,
time::{self, SystemTime, UNIX_EPOCH},
};
pub use tokio;
pub use tokio_util;
pub mod socket_client;
pub mod tcp;
pub mod udp;
pub use env_logger;
@@ -27,7 +27,11 @@ pub use anyhow::{self, bail};
pub use futures_util;
pub mod config;
pub mod fs;
pub use regex;
pub use sodiumoxide;
pub use tokio_socks;
pub use tokio_socks::IntoTargetAddr;
pub use tokio_socks::TargetAddr;
#[cfg(feature = "quic")]
pub type Stream = quic::Connection;
@@ -36,7 +40,7 @@ pub type Stream = tcp::FramedStream;
#[inline]
pub async fn sleep(sec: f32) {
tokio::time::delay_for(time::Duration::from_secs_f32(sec)).await;
tokio::time::sleep(time::Duration::from_secs_f32(sec)).await;
}
#[macro_export]
@@ -61,30 +65,6 @@ pub fn timeout<T: std::future::Future>(ms: u64, future: T) -> tokio::time::Timeo
tokio::time::timeout(std::time::Duration::from_millis(ms), future)
}
fn new_socket(addr: SocketAddr, tcp: bool, reuse: bool) -> Result<Socket, std::io::Error> {
let stype = {
if tcp {
Type::stream()
} else {
Type::dgram()
}
};
let socket = match addr {
SocketAddr::V4(..) => Socket::new(Domain::ipv4(), stype, None),
SocketAddr::V6(..) => Socket::new(Domain::ipv6(), stype, None),
}?;
if reuse {
// windows has no reuse_port, but it's reuse_address
// almost equals to unix's reuse_port + reuse_address,
// though may introduce nondeterministic bahavior
#[cfg(unix)]
socket.set_reuse_port(true)?;
socket.set_reuse_address(true)?;
}
socket.bind(&addr.into())?;
Ok(socket)
}
pub type ResultType<F, E = anyhow::Error> = anyhow::Result<F, E>;
/// Certain router and firewalls scan the packet and if they
@@ -100,10 +80,10 @@ impl AddrMangle {
.duration_since(UNIX_EPOCH)
.unwrap()
.as_micros() as u32) as u128;
let ip = u32::from_ne_bytes(addr_v4.ip().octets()) as u128;
let ip = u32::from_le_bytes(addr_v4.ip().octets()) as u128;
let port = addr.port() as u128;
let v = ((ip + tm) << 49) | (tm << 17) | (port + (tm & 0xFFFF));
let bytes = v.to_ne_bytes();
let bytes = v.to_le_bytes();
let mut n_padding = 0;
for i in bytes.iter().rev() {
if i == &0u8 {
@@ -123,9 +103,9 @@ impl AddrMangle {
pub fn decode(bytes: &[u8]) -> SocketAddr {
let mut padded = [0u8; 16];
padded[..bytes.len()].copy_from_slice(&bytes);
let number = u128::from_ne_bytes(padded);
let number = u128::from_le_bytes(padded);
let tm = (number >> 17) & (u32::max_value() as u128);
let ip = (((number >> 49) - tm) as u32).to_ne_bytes();
let ip = (((number >> 49) - tm) as u32).to_le_bytes();
let port = (number & 0xFFFFFF) - (tm & 0xFFFF);
SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]),
@@ -172,14 +152,6 @@ pub fn get_version_from_url(url: &str) -> String {
"".to_owned()
}
pub fn to_socket_addr(host: &str) -> ResultType<SocketAddr> {
let addrs: Vec<SocketAddr> = host.to_socket_addrs()?.collect();
if addrs.is_empty() {
bail!("Failed to solve {}", host);
}
Ok(addrs[0])
}
pub fn gen_version() {
let mut file = File::create("./src/version.rs").unwrap();
for line in read_lines("Cargo.toml").unwrap() {
@@ -204,6 +176,14 @@ where
Ok(io::BufReader::new(file).lines())
}
pub fn get_version_number(v: &str) -> i64 {
let mut n = 0;
for x in v.split(".") {
n = n * 1000 + x.parse::<i64>().unwrap_or(0);
}
n
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -0,0 +1,91 @@
use crate::{
config::{Config, NetworkType},
tcp::FramedStream,
udp::FramedSocket,
ResultType,
};
use anyhow::Context;
use std::net::SocketAddr;
use tokio::net::ToSocketAddrs;
use tokio_socks::{IntoTargetAddr, TargetAddr};
fn to_socket_addr(host: &str) -> ResultType<SocketAddr> {
use std::net::ToSocketAddrs;
host.to_socket_addrs()?.next().context("Failed to solve")
}
pub fn get_target_addr(host: &str) -> ResultType<TargetAddr<'static>> {
let addr = match Config::get_network_type() {
NetworkType::Direct => to_socket_addr(&host)?.into_target_addr()?,
NetworkType::ProxySocks => host.into_target_addr()?,
}
.to_owned();
Ok(addr)
}
pub fn test_if_valid_server(host: &str) -> String {
let mut host = host.to_owned();
if !host.contains(":") {
host = format!("{}:{}", host, 0);
}
match Config::get_network_type() {
NetworkType::Direct => match to_socket_addr(&host) {
Err(err) => err.to_string(),
Ok(_) => "".to_owned(),
},
NetworkType::ProxySocks => match &host.into_target_addr() {
Err(err) => err.to_string(),
Ok(_) => "".to_owned(),
},
}
}
pub async fn connect_tcp<'t, T: IntoTargetAddr<'t>>(
target: T,
local: SocketAddr,
ms_timeout: u64,
) -> ResultType<FramedStream> {
let target_addr = target.into_target_addr()?;
if let Some(conf) = Config::get_socks() {
FramedStream::connect(
conf.proxy.as_str(),
target_addr,
local,
conf.username.as_str(),
conf.password.as_str(),
ms_timeout,
)
.await
} else {
let addr = std::net::ToSocketAddrs::to_socket_addrs(&target_addr)?
.next()
.context("Invalid target addr")?;
Ok(FramedStream::new(addr, local, ms_timeout).await?)
}
}
pub async fn new_udp<T: ToSocketAddrs>(local: T, ms_timeout: u64) -> ResultType<FramedSocket> {
match Config::get_socks() {
None => Ok(FramedSocket::new(local).await?),
Some(conf) => {
let socket = FramedSocket::new_proxy(
conf.proxy.as_str(),
local,
conf.username.as_str(),
conf.password.as_str(),
ms_timeout,
)
.await?;
Ok(socket)
}
}
}
pub async fn rebind_udp<T: ToSocketAddrs>(local: T) -> ResultType<Option<FramedSocket>> {
match Config::get_network_type() {
NetworkType::Direct => Ok(Some(FramedSocket::new(local).await?)),
_ => Ok(None),
}
}

View File

@@ -1,22 +1,34 @@
use crate::{bail, bytes_codec::BytesCodec, ResultType};
use bytes::{BufMut, Bytes, BytesMut};
use futures::SinkExt;
use futures::{SinkExt, StreamExt};
use protobuf::Message;
use sodiumoxide::crypto::secretbox::{self, Key, Nonce};
use std::{
io::{Error, ErrorKind},
io::{self, Error, ErrorKind},
net::SocketAddr,
ops::{Deref, DerefMut},
pin::Pin,
task::{Context, Poll},
};
use tokio::{
net::{TcpListener, TcpStream, ToSocketAddrs},
stream::StreamExt,
io::{AsyncRead, AsyncWrite, ReadBuf},
net::{lookup_host, TcpListener, TcpSocket, ToSocketAddrs},
};
use tokio_socks::{tcp::Socks5Stream, IntoTargetAddr, ToProxyAddrs};
use tokio_util::codec::Framed;
pub struct FramedStream(Framed<TcpStream, BytesCodec>, Option<(Key, u64, u64)>);
pub trait TcpStreamTrait: AsyncRead + AsyncWrite + Unpin {}
pub struct DynTcpStream(Box<dyn TcpStreamTrait + Send>);
pub struct FramedStream(
Framed<DynTcpStream, BytesCodec>,
SocketAddr,
Option<(Key, u64, u64)>,
u64,
);
impl Deref for FramedStream {
type Target = Framed<TcpStream, BytesCodec>;
type Target = Framed<DynTcpStream, BytesCodec>;
fn deref(&self) -> &Self::Target {
&self.0
@@ -29,41 +41,130 @@ impl DerefMut for FramedStream {
}
}
impl Deref for DynTcpStream {
type Target = Box<dyn TcpStreamTrait + Send>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for DynTcpStream {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
fn new_socket(addr: std::net::SocketAddr, reuse: bool) -> Result<TcpSocket, std::io::Error> {
let socket = match addr {
std::net::SocketAddr::V4(..) => TcpSocket::new_v4()?,
std::net::SocketAddr::V6(..) => TcpSocket::new_v6()?,
};
if reuse {
// windows has no reuse_port, but it's reuse_address
// almost equals to unix's reuse_port + reuse_address,
// though may introduce nondeterministic behavior
#[cfg(unix)]
socket.set_reuseport(true)?;
socket.set_reuseaddr(true)?;
}
socket.bind(addr)?;
Ok(socket)
}
impl FramedStream {
pub async fn new<T: ToSocketAddrs, T2: ToSocketAddrs>(
remote_addr: T,
pub async fn new<T1: ToSocketAddrs, T2: ToSocketAddrs>(
remote_addr: T1,
local_addr: T2,
ms_timeout: u64,
) -> ResultType<Self> {
for local_addr in local_addr.to_socket_addrs().await? {
for remote_addr in remote_addr.to_socket_addrs().await? {
if let Ok(stream) = super::timeout(
for local_addr in lookup_host(&local_addr).await? {
for remote_addr in lookup_host(&remote_addr).await? {
let stream = super::timeout(
ms_timeout,
TcpStream::connect_std(
super::new_socket(local_addr, true, true)?.into_tcp_stream(),
&remote_addr,
),
new_socket(local_addr, true)?.connect(remote_addr),
)
.await?
{
return Ok(Self(Framed::new(stream, BytesCodec::new()), None));
}
.await??;
let addr = stream.local_addr()?;
return Ok(Self(
Framed::new(DynTcpStream(Box::new(stream)), BytesCodec::new()),
addr,
None,
0,
));
}
}
bail!("could not resolve to any address");
}
pub fn from(stream: TcpStream) -> Self {
Self(Framed::new(stream, BytesCodec::new()), None)
pub async fn connect<'a, 't, P, T1, T2>(
proxy: P,
target: T1,
local: T2,
username: &'a str,
password: &'a str,
ms_timeout: u64,
) -> ResultType<Self>
where
P: ToProxyAddrs,
T1: IntoTargetAddr<'t>,
T2: ToSocketAddrs,
{
if let Some(local) = lookup_host(&local).await?.next() {
if let Some(proxy) = proxy.to_proxy_addrs().next().await {
let stream =
super::timeout(ms_timeout, new_socket(local, true)?.connect(proxy?)).await??;
let stream = if username.trim().is_empty() {
super::timeout(
ms_timeout,
Socks5Stream::connect_with_socket(stream, target),
)
.await??
} else {
super::timeout(
ms_timeout,
Socks5Stream::connect_with_password_and_socket(
stream, target, username, password,
),
)
.await??
};
let addr = stream.local_addr()?;
return Ok(Self(
Framed::new(DynTcpStream(Box::new(stream)), BytesCodec::new()),
addr,
None,
0,
));
};
};
bail!("could not resolve to any address");
}
pub fn local_addr(&self) -> SocketAddr {
self.1
}
pub fn set_send_timeout(&mut self, ms: u64) {
self.3 = ms;
}
pub fn from(stream: impl TcpStreamTrait + Send + 'static, addr: SocketAddr) -> Self {
Self(
Framed::new(DynTcpStream(Box::new(stream)), BytesCodec::new()),
addr,
None,
0,
)
}
pub fn set_raw(&mut self) {
self.0.codec_mut().set_raw();
self.1 = None;
self.2 = None;
}
pub fn is_secured(&self) -> bool {
self.1.is_some()
self.2.is_some()
}
#[inline]
@@ -74,24 +175,29 @@ impl FramedStream {
#[inline]
pub async fn send_raw(&mut self, msg: Vec<u8>) -> ResultType<()> {
let mut msg = msg;
if let Some(key) = self.1.as_mut() {
if let Some(key) = self.2.as_mut() {
key.1 += 1;
let nonce = Self::get_nonce(key.1);
msg = secretbox::seal(&msg, &nonce, &key.0);
}
self.0.send(bytes::Bytes::from(msg)).await?;
self.send_bytes(bytes::Bytes::from(msg)).await?;
Ok(())
}
#[inline]
pub async fn send_bytes(&mut self, bytes: Bytes) -> ResultType<()> {
if self.3 > 0 {
super::timeout(self.3, self.0.send(bytes)).await??;
} else {
self.0.send(bytes).await?;
}
Ok(())
}
#[inline]
pub async fn next(&mut self) -> Option<Result<BytesMut, Error>> {
let mut res = self.0.next().await;
if let Some(key) = self.1.as_mut() {
if let Some(key) = self.2.as_mut() {
if let Some(Ok(bytes)) = res.as_mut() {
key.2 += 1;
let nonce = Self::get_nonce(key.2);
@@ -119,28 +225,59 @@ impl FramedStream {
}
pub fn set_key(&mut self, key: Key) {
self.1 = Some((key, 0, 0));
self.2 = Some((key, 0, 0));
}
fn get_nonce(seqnum: u64) -> Nonce {
let mut nonce = Nonce([0u8; secretbox::NONCEBYTES]);
nonce.0[..std::mem::size_of_val(&seqnum)].copy_from_slice(&seqnum.to_ne_bytes());
nonce.0[..std::mem::size_of_val(&seqnum)].copy_from_slice(&seqnum.to_le_bytes());
nonce
}
}
const DEFAULT_BACKLOG: i32 = 128;
const DEFAULT_BACKLOG: u32 = 128;
#[allow(clippy::never_loop)]
pub async fn new_listener<T: ToSocketAddrs>(addr: T, reuse: bool) -> ResultType<TcpListener> {
if !reuse {
Ok(TcpListener::bind(addr).await?)
} else {
for addr in addr.to_socket_addrs().await? {
let socket = super::new_socket(addr, true, true)?;
socket.listen(DEFAULT_BACKLOG)?;
return Ok(TcpListener::from_std(socket.into_tcp_listener())?);
for addr in lookup_host(&addr).await? {
let socket = new_socket(addr, true)?;
return Ok(socket.listen(DEFAULT_BACKLOG)?);
}
bail!("could not resolve to any address");
}
}
impl Unpin for DynTcpStream {}
impl AsyncRead for DynTcpStream {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
AsyncRead::poll_read(Pin::new(&mut self.0), cx, buf)
}
}
impl AsyncWrite for DynTcpStream {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
AsyncWrite::poll_write(Pin::new(&mut self.0), cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
AsyncWrite::poll_flush(Pin::new(&mut self.0), cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
AsyncWrite::poll_shutdown(Pin::new(&mut self.0), cx)
}
}
impl<R: AsyncRead + AsyncWrite + Unpin> TcpStreamTrait for R {}

View File

@@ -1,71 +1,140 @@
use crate::{bail, ResultType};
use bytes::BytesMut;
use futures::SinkExt;
use anyhow::anyhow;
use bytes::{Bytes, BytesMut};
use futures::{SinkExt, StreamExt};
use protobuf::Message;
use std::{
io::Error,
net::SocketAddr,
ops::{Deref, DerefMut},
};
use tokio::{net::ToSocketAddrs, net::UdpSocket, stream::StreamExt};
use socket2::{Domain, Socket, Type};
use std::net::SocketAddr;
use tokio::net::{ToSocketAddrs, UdpSocket};
use tokio_socks::{udp::Socks5UdpFramed, IntoTargetAddr, TargetAddr, ToProxyAddrs};
use tokio_util::{codec::BytesCodec, udp::UdpFramed};
pub struct FramedSocket(UdpFramed<BytesCodec>);
impl Deref for FramedSocket {
type Target = UdpFramed<BytesCodec>;
fn deref(&self) -> &Self::Target {
&self.0
}
pub enum FramedSocket {
Direct(UdpFramed<BytesCodec>),
ProxySocks(Socks5UdpFramed),
}
impl DerefMut for FramedSocket {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
fn new_socket(addr: SocketAddr, reuse: bool) -> Result<Socket, std::io::Error> {
let socket = match addr {
SocketAddr::V4(..) => Socket::new(Domain::ipv4(), Type::dgram(), None),
SocketAddr::V6(..) => Socket::new(Domain::ipv6(), Type::dgram(), None),
}?;
if reuse {
// windows has no reuse_port, but it's reuse_address
// almost equals to unix's reuse_port + reuse_address,
// though may introduce nondeterministic behavior
#[cfg(unix)]
socket.set_reuse_port(true)?;
socket.set_reuse_address(true)?;
}
socket.bind(&addr.into())?;
Ok(socket)
}
impl FramedSocket {
pub async fn new<T: ToSocketAddrs>(addr: T) -> ResultType<Self> {
let socket = UdpSocket::bind(addr).await?;
Ok(Self(UdpFramed::new(socket, BytesCodec::new())))
Ok(Self::Direct(UdpFramed::new(socket, BytesCodec::new())))
}
#[allow(clippy::never_loop)]
pub async fn new_reuse<T: ToSocketAddrs>(addr: T) -> ResultType<Self> {
for addr in addr.to_socket_addrs().await? {
return Ok(Self(UdpFramed::new(
UdpSocket::from_std(super::new_socket(addr, false, true)?.into_udp_socket())?,
pub async fn new_reuse<T: std::net::ToSocketAddrs>(addr: T) -> ResultType<Self> {
for addr in addr.to_socket_addrs()? {
let socket = new_socket(addr, true)?.into_udp_socket();
return Ok(Self::Direct(UdpFramed::new(
UdpSocket::from_std(socket)?,
BytesCodec::new(),
)));
}
bail!("could not resolve to any address");
}
pub async fn new_proxy<'a, 't, P: ToProxyAddrs, T: ToSocketAddrs>(
proxy: P,
local: T,
username: &'a str,
password: &'a str,
ms_timeout: u64,
) -> ResultType<Self> {
let framed = if username.trim().is_empty() {
super::timeout(ms_timeout, Socks5UdpFramed::connect(proxy, Some(local))).await??
} else {
super::timeout(
ms_timeout,
Socks5UdpFramed::connect_with_password(proxy, Some(local), username, password),
)
.await??
};
log::trace!(
"Socks5 udp connected, local addr: {:?}, target addr: {}",
framed.local_addr(),
framed.socks_addr()
);
Ok(Self::ProxySocks(framed))
}
#[inline]
pub async fn send(&mut self, msg: &impl Message, addr: SocketAddr) -> ResultType<()> {
self.0
.send((bytes::Bytes::from(msg.write_to_bytes().unwrap()), addr))
.await?;
pub async fn send(
&mut self,
msg: &impl Message,
addr: impl IntoTargetAddr<'_>,
) -> ResultType<()> {
let addr = addr.into_target_addr()?.to_owned();
let send_data = Bytes::from(msg.write_to_bytes()?);
let _ = match self {
Self::Direct(f) => match addr {
TargetAddr::Ip(addr) => f.send((send_data, addr)).await?,
_ => unreachable!(),
},
Self::ProxySocks(f) => f.send((send_data, addr)).await?,
};
Ok(())
}
// https://stackoverflow.com/a/68733302/1926020
#[inline]
pub async fn send_raw(
&mut self,
msg: &'static [u8],
addr: impl IntoTargetAddr<'static>,
) -> ResultType<()> {
let addr = addr.into_target_addr()?.to_owned();
let _ = match self {
Self::Direct(f) => match addr {
TargetAddr::Ip(addr) => f.send((Bytes::from(msg), addr)).await?,
_ => unreachable!(),
},
Self::ProxySocks(f) => f.send((Bytes::from(msg), addr)).await?,
};
Ok(())
}
#[inline]
pub async fn send_raw(&mut self, msg: &'static [u8], addr: SocketAddr) -> ResultType<()> {
self.0.send((bytes::Bytes::from(msg), addr)).await?;
Ok(())
pub async fn next(&mut self) -> Option<ResultType<(BytesMut, TargetAddr<'static>)>> {
match self {
Self::Direct(f) => match f.next().await {
Some(Ok((data, addr))) => {
Some(Ok((data, addr.into_target_addr().ok()?.to_owned())))
}
Some(Err(e)) => Some(Err(anyhow!(e))),
None => None,
},
Self::ProxySocks(f) => match f.next().await {
Some(Ok((data, _))) => Some(Ok((data.data, data.dst_addr))),
Some(Err(e)) => Some(Err(anyhow!(e))),
None => None,
},
}
}
#[inline]
pub async fn next(&mut self) -> Option<Result<(BytesMut, SocketAddr), Error>> {
self.0.next().await
}
#[inline]
pub async fn next_timeout(&mut self, ms: u64) -> Option<Result<(BytesMut, SocketAddr), Error>> {
pub async fn next_timeout(
&mut self,
ms: u64,
) -> Option<ResultType<(BytesMut, TargetAddr<'static>)>> {
if let Ok(res) =
tokio::time::timeout(std::time::Duration::from_millis(ms), self.0.next()).await
tokio::time::timeout(std::time::Duration::from_millis(ms), self.next()).await
{
res
} else {

View File

@@ -1,2 +0,0 @@
target
Cargo.lock

View File

@@ -1,18 +0,0 @@
[package]
name = "magnum-opus"
version = "0.3.4"
authors = ["Tad Hardesty <tad@platymuus.com>", "Sergey Duck <sergeypechnikov326@gmail.com>"]
edition = "2018"
description = "Safe Rust bindings for libopus"
readme = "README.md"
license = "MIT/Apache-2.0"
keywords = ["opus", "codec", "voice", "sound", "audio"]
categories = ["api-bindings", "encoding", "compression",
"multimedia::audio", "multimedia::encoding"]
repository = "https://github.com/DuckerMan/magnum-opus"
documentation = "https://docs.rs/magnum-opus"
[build-dependencies]
target_build_utils = "0.3"
bindgen = "0.53"

View File

@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,19 +0,0 @@
Copyright (c) 2016 Tad Hardesty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -1,22 +0,0 @@
# magnum-opus [![](https://meritbadge.herokuapp.com/magnum-opus)](https://crates.io/crates/magnum-opus) [![](https://img.shields.io/badge/docs-online-2020ff.svg)](https://docs.rs/magnum-opus)
### This is the fork of @SpaceManiac repo, which now is abandoned
Safe Rust bindings for libopus. The rustdoc (available through `cargo doc`)
includes brief descriptions for methods, and detailed API information can be
found at the [libopus documentation](https://opus-codec.org/docs/opus_api-1.1.2/).
## License
Licensed under either of
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

View File

@@ -1,89 +0,0 @@
use std::{
env,
path::{Path, PathBuf},
};
fn find_package(name: &str) -> Vec<PathBuf> {
let vcpkg_root = std::env::var("VCPKG_ROOT").unwrap();
let mut path: PathBuf = vcpkg_root.into();
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let mut target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
if target_arch == "x86_64" {
target_arch = "x64".to_owned();
} else if target_arch == "aarch64" {
target_arch = "arm64".to_owned();
} else {
target_arch = "arm".to_owned();
}
let target = if target_os == "macos" {
"x64-osx".to_owned()
} else if target_os == "windows" {
"x64-windows-static".to_owned()
} else if target_os == "android" {
format!("{}-android-static", target_arch)
} else {
"x64-linux".to_owned()
};
println!("cargo:info={}", target);
path.push("installed");
path.push(target);
println!(
"{}",
format!("cargo:rustc-link-lib={}", name.trim_start_matches("lib"))
);
println!(
"{}",
format!(
"cargo:rustc-link-search={}",
path.join("lib").to_str().unwrap()
)
);
let include = path.join("include");
println!("{}", format!("cargo:include={}", include.to_str().unwrap()));
vec![include]
}
fn generate_bindings(ffi_header: &Path, include_paths: &[PathBuf], ffi_rs: &Path) {
#[derive(Debug)]
struct ParseCallbacks;
impl bindgen::callbacks::ParseCallbacks for ParseCallbacks {
fn int_macro(&self, name: &str, _value: i64) -> Option<bindgen::callbacks::IntKind> {
if name.starts_with("OPUS") {
Some(bindgen::callbacks::IntKind::Int)
} else {
None
}
}
}
let mut b = bindgen::Builder::default()
.header(ffi_header.to_str().unwrap())
.parse_callbacks(Box::new(ParseCallbacks))
.generate_comments(false);
for dir in include_paths {
b = b.clang_arg(format!("-I{}", dir.display()));
}
b.generate().unwrap().write_to_file(ffi_rs).unwrap();
}
fn gen_opus() {
let includes = find_package("opus");
let src_dir = env::var_os("CARGO_MANIFEST_DIR").unwrap();
let src_dir = Path::new(&src_dir);
let out_dir = env::var_os("OUT_DIR").unwrap();
let out_dir = Path::new(&out_dir);
let ffi_header = src_dir.join("opus_ffi.h");
println!("rerun-if-changed={}", ffi_header.display());
for dir in &includes {
println!("rerun-if-changed={}", dir.display());
}
let ffi_rs = out_dir.join("opus_ffi.rs");
generate_bindings(&ffi_header, &includes, &ffi_rs);
}
fn main() {
gen_opus()
}

View File

@@ -1 +0,0 @@
#include <opus/opus_multistream.h>

View File

@@ -1,843 +0,0 @@
// Copyright 2016 Tad Hardesty
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! High-level bindings for libopus.
//!
//! Only brief descriptions are included here. For detailed information, consult
//! the [libopus documentation](https://opus-codec.org/docs/opus_api-1.1.2/).
#![warn(missing_docs)]
mod opus_ffi;
use opus_ffi as ffi;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::os::raw::c_int;
// ============================================================================
// Constants
// Generic CTLs
const OPUS_RESET_STATE: c_int = 4028; // void
const OPUS_GET_FINAL_RANGE: c_int = 4031; // out *u32
const OPUS_GET_BANDWIDTH: c_int = 4009; // out *i32
const OPUS_GET_SAMPLE_RATE: c_int = 4029; // out *i32
// Encoder CTLs
const OPUS_SET_BITRATE: c_int = 4002; // in i32
const OPUS_GET_BITRATE: c_int = 4003; // out *i32
const OPUS_SET_VBR: c_int = 4006; // in i32
const OPUS_GET_VBR: c_int = 4007; // out *i32
const OPUS_SET_VBR_CONSTRAINT: c_int = 4020; // in i32
const OPUS_GET_VBR_CONSTRAINT: c_int = 4021; // out *i32
const OPUS_SET_INBAND_FEC: c_int = 4012; // in i32
const OPUS_GET_INBAND_FEC: c_int = 4013; // out *i32
const OPUS_SET_PACKET_LOSS_PERC: c_int = 4014; // in i32
const OPUS_GET_PACKET_LOSS_PERC: c_int = 4015; // out *i32
const OPUS_GET_LOOKAHEAD: c_int = 4027; // out *i32
// Decoder CTLs
const OPUS_SET_GAIN: c_int = 4034; // in i32
const OPUS_GET_GAIN: c_int = 4045; // out *i32
const OPUS_GET_LAST_PACKET_DURATION: c_int = 4039; // out *i32
const OPUS_GET_PITCH: c_int = 4033; // out *i32
// Bitrate
const OPUS_AUTO: c_int = -1000;
const OPUS_BITRATE_MAX: c_int = -1;
/// The possible applications for the codec.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Application {
/// Best for most VoIP/videoconference applications where listening quality
/// and intelligibility matter most.
Voip = 2048,
/// Best for broadcast/high-fidelity application where the decoded audio
/// should be as close as possible to the input.
Audio = 2049,
/// Only use when lowest-achievable latency is what matters most.
LowDelay = 2051,
}
/// The available channel setings.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Channels {
/// One channel.
Mono = 1,
/// Two channels, left and right.
Stereo = 2,
}
/// The available bandwidth level settings.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum Bandwidth {
/// Auto/default setting.
Auto = -1000,
/// 4kHz bandpass.
Narrowband = 1101,
/// 6kHz bandpass.
Mediumband = 1102,
/// 8kHz bandpass.
Wideband = 1103,
/// 12kHz bandpass.
Superwideband = 1104,
/// 20kHz bandpass.
Fullband = 1105,
}
impl Bandwidth {
fn from_int(value: i32) -> Option<Bandwidth> {
Some(match value {
-1000 => Bandwidth::Auto,
1101 => Bandwidth::Narrowband,
1102 => Bandwidth::Mediumband,
1103 => Bandwidth::Wideband,
1104 => Bandwidth::Superwideband,
1105 => Bandwidth::Fullband,
_ => return None,
})
}
fn decode(value: i32, what: &'static str) -> Result<Bandwidth> {
match Bandwidth::from_int(value) {
Some(bandwidth) => Ok(bandwidth),
None => Err(Error::bad_arg(what)),
}
}
}
/// Possible error codes.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum ErrorCode {
/// One or more invalid/out of range arguments.
BadArg = -1,
/// Not enough bytes allocated in the buffer.
BufferTooSmall = -2,
/// An internal error was detected.
InternalError = -3,
/// The compressed data passed is corrupted.
InvalidPacket = -4,
/// Invalid/unsupported request number.
Unimplemented = -5,
/// An encoder or decoder structure is invalid or already freed.
InvalidState = -6,
/// Memory allocation has failed.
AllocFail = -7,
/// An unknown failure.
Unknown = -8,
}
impl ErrorCode {
fn from_int(value: c_int) -> ErrorCode {
use ErrorCode::*;
match value {
ffi::OPUS_BAD_ARG => BadArg,
ffi::OPUS_BUFFER_TOO_SMALL => BufferTooSmall,
ffi::OPUS_INTERNAL_ERROR => InternalError,
ffi::OPUS_INVALID_PACKET => InvalidPacket,
ffi::OPUS_UNIMPLEMENTED => Unimplemented,
ffi::OPUS_INVALID_STATE => InvalidState,
ffi::OPUS_ALLOC_FAIL => AllocFail,
_ => Unknown,
}
}
/// Get a human-readable error string for this error code.
pub fn description(self) -> &'static str {
// should always be ASCII and non-null for any input
unsafe { CStr::from_ptr(ffi::opus_strerror(self as c_int)) }.to_str().unwrap()
}
}
/// Possible bitrates.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Bitrate {
/// Explicit bitrate choice (in bits/second).
Bits(i32),
/// Maximum bitrate allowed (up to maximum number of bytes for the packet).
Max,
/// Default bitrate decided by the encoder (not recommended).
Auto,
}
/// Get the libopus version string.
///
/// Applications may look for the substring "-fixed" in the version string to
/// determine whether they have a fixed-point or floating-point build at
/// runtime.
pub fn version() -> &'static str {
// verison string should always be ASCII
unsafe { CStr::from_ptr(ffi::opus_get_version_string()) }.to_str().unwrap()
}
macro_rules! ffi {
($f:ident $(, $rest:expr)*) => {
match unsafe { ffi::$f($($rest),*) } {
code if code < 0 => return Err(Error::from_code(stringify!($f), code)),
code => code,
}
}
}
macro_rules! ctl {
($f:ident, $this:ident, $ctl:ident, $($rest:expr),*) => {
match unsafe { ffi::$f($this.ptr, $ctl, $($rest),*) } {
code if code < 0 => return Err(Error::from_code(
concat!(stringify!($f), "(", stringify!($ctl), ")"),
code,
)),
_ => (),
}
}
}
// ============================================================================
// Encoder
macro_rules! enc_ctl {
($this:ident, $ctl:ident $(, $rest:expr)*) => {
ctl!(opus_encoder_ctl, $this, $ctl, $($rest),*)
}
}
/// An Opus encoder with associated state.
#[derive(Debug)]
pub struct Encoder {
ptr: *mut ffi::OpusEncoder,
channels: Channels,
}
impl Encoder {
/// Create and initialize an encoder.
pub fn new(sample_rate: u32, channels: Channels, mode: Application) -> Result<Encoder> {
let mut error = 0;
let ptr = unsafe { ffi::opus_encoder_create(
sample_rate as i32,
channels as c_int,
mode as c_int,
&mut error) };
if error != ffi::OPUS_OK || ptr.is_null() {
Err(Error::from_code("opus_encoder_create", error))
} else {
Ok(Encoder { ptr: ptr, channels: channels })
}
}
/// Encode an Opus frame.
pub fn encode(&mut self, input: &[i16], output: &mut [u8]) -> Result<usize> {
let len = ffi!(opus_encode, self.ptr,
input.as_ptr(), len(input) / self.channels as c_int,
output.as_mut_ptr(), len(output));
Ok(len as usize)
}
/// Encode an Opus frame from floating point input.
pub fn encode_float(&mut self, input: &[f32], output: &mut [u8]) -> Result<usize> {
let len = ffi!(opus_encode_float, self.ptr,
input.as_ptr(), len(input) / self.channels as c_int,
output.as_mut_ptr(), len(output));
Ok(len as usize)
}
/// Encode an Opus frame to a new buffer.
pub fn encode_vec(&mut self, input: &[i16], max_size: usize) -> Result<Vec<u8>> {
let mut output: Vec<u8> = vec![0; max_size];
let result = self.encode(input, output.as_mut_slice())?;
output.truncate(result);
Ok(output)
}
/// Encode an Opus frame from floating point input to a new buffer.
pub fn encode_vec_float(&mut self, input: &[f32], max_size: usize) -> Result<Vec<u8>> {
let mut output: Vec<u8> = vec![0; max_size];
let result = self.encode_float(input, output.as_mut_slice())?;
output.truncate(result);
Ok(output)
}
// ------------
// Generic CTLs
/// Reset the codec state to be equivalent to a freshly initialized state.
pub fn reset_state(&mut self) -> Result<()> {
enc_ctl!(self, OPUS_RESET_STATE);
Ok(())
}
/// Get the final range of the codec's entropy coder.
pub fn get_final_range(&mut self) -> Result<u32> {
let mut value: u32 = 0;
enc_ctl!(self, OPUS_GET_FINAL_RANGE, &mut value);
Ok(value)
}
/// Get the encoder's configured bandpass.
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_BANDWIDTH, &mut value);
Bandwidth::decode(value, "opus_encoder_ctl(OPUS_GET_BANDWIDTH)")
}
/// Get the samping rate the encoder was intialized with.
pub fn get_sample_rate(&mut self) -> Result<u32> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_SAMPLE_RATE, &mut value);
Ok(value as u32)
}
// ------------
// Encoder CTLs
/// Set the encoder's bitrate.
pub fn set_bitrate(&mut self, value: Bitrate) -> Result<()> {
let value: i32 = match value {
Bitrate::Auto => OPUS_AUTO,
Bitrate::Max => OPUS_BITRATE_MAX,
Bitrate::Bits(b) => b,
};
enc_ctl!(self, OPUS_SET_BITRATE, value);
Ok(())
}
/// Get the encoder's bitrate.
pub fn get_bitrate(&mut self) -> Result<Bitrate> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_BITRATE, &mut value);
Ok(match value {
OPUS_AUTO => Bitrate::Auto,
OPUS_BITRATE_MAX => Bitrate::Max,
_ => Bitrate::Bits(value),
})
}
/// Enable or disable variable bitrate.
pub fn set_vbr(&mut self, vbr: bool) -> Result<()> {
let value: i32 = if vbr { 1 } else { 0 };
enc_ctl!(self, OPUS_SET_VBR, value);
Ok(())
}
/// Determine if variable bitrate is enabled.
pub fn get_vbr(&mut self) -> Result<bool> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_VBR, &mut value);
Ok(value != 0)
}
/// Enable or disable constrained VBR.
pub fn set_vbr_constraint(&mut self, vbr: bool) -> Result<()> {
let value: i32 = if vbr { 1 } else { 0 };
enc_ctl!(self, OPUS_SET_VBR_CONSTRAINT, value);
Ok(())
}
/// Determine if constrained VBR is enabled.
pub fn get_vbr_constraint(&mut self) -> Result<bool> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_VBR_CONSTRAINT, &mut value);
Ok(value != 0)
}
/// Configures the encoder's use of inband forward error correction (FEC).
pub fn set_inband_fec(&mut self, value: bool) -> Result<()> {
let value: i32 = if value { 1 } else { 0 };
enc_ctl!(self, OPUS_SET_INBAND_FEC, value);
Ok(())
}
/// Gets encoder's configured use of inband forward error correction.
pub fn get_inband_fec(&mut self) -> Result<bool> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_INBAND_FEC, &mut value);
Ok(value != 0)
}
/// Sets the encoder's expected packet loss percentage.
pub fn set_packet_loss_perc(&mut self, value: i32) -> Result<()> {
enc_ctl!(self, OPUS_SET_PACKET_LOSS_PERC, value);
Ok(())
}
/// Gets the encoder's expected packet loss percentage.
pub fn get_packet_loss_perc(&mut self) -> Result<i32> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_PACKET_LOSS_PERC, &mut value);
Ok(value)
}
/// Gets the total samples of delay added by the entire codec.
pub fn get_lookahead(&mut self) -> Result<i32> {
let mut value: i32 = 0;
enc_ctl!(self, OPUS_GET_LOOKAHEAD, &mut value);
Ok(value)
}
// TODO: Encoder-specific CTLs
}
impl Drop for Encoder {
fn drop(&mut self) {
unsafe { ffi::opus_encoder_destroy(self.ptr) }
}
}
// "A single codec state may only be accessed from a single thread at
// a time and any required locking must be performed by the caller. Separate
// streams must be decoded with separate decoder states and can be decoded
// in parallel unless the library was compiled with NONTHREADSAFE_PSEUDOSTACK
// defined."
//
// In other words, opus states may be moved between threads at will. A special
// compilation mode intended for embedded platforms forbids multithreaded use
// of the library as a whole rather than on a per-state basis, but the opus-sys
// crate does not use this mode.
unsafe impl Send for Encoder {}
// ============================================================================
// Decoder
macro_rules! dec_ctl {
($this:ident, $ctl:ident $(, $rest:expr)*) => {
ctl!(opus_decoder_ctl, $this, $ctl, $($rest),*)
}
}
/// An Opus decoder with associated state.
#[derive(Debug)]
pub struct Decoder {
ptr: *mut ffi::OpusDecoder,
channels: Channels,
}
impl Decoder {
/// Create and initialize a decoder.
pub fn new(sample_rate: u32, channels: Channels) -> Result<Decoder> {
let mut error = 0;
let ptr = unsafe { ffi::opus_decoder_create(
sample_rate as i32,
channels as c_int,
&mut error) };
if error != ffi::OPUS_OK || ptr.is_null() {
Err(Error::from_code("opus_decoder_create", error))
} else {
Ok(Decoder { ptr: ptr, channels: channels })
}
}
/// Decode an Opus packet.
pub fn decode(&mut self, input: &[u8], output: &mut [i16], fec: bool) -> Result<usize> {
let ptr = match input.len() {
0 => std::ptr::null(),
_ => input.as_ptr(),
};
let len = ffi!(opus_decode, self.ptr,
ptr, len(input),
output.as_mut_ptr(), len(output) / self.channels as c_int,
fec as c_int);
Ok(len as usize)
}
/// Decode an Opus packet with floating point output.
pub fn decode_float(&mut self, input: &[u8], output: &mut [f32], fec: bool) -> Result<usize> {
let ptr = match input.len() {
0 => std::ptr::null(),
_ => input.as_ptr(),
};
let len = ffi!(opus_decode_float, self.ptr,
ptr, len(input),
output.as_mut_ptr(), len(output) / self.channels as c_int,
fec as c_int);
Ok(len as usize)
}
/// Get the number of samples of an Opus packet.
pub fn get_nb_samples(&self, packet: &[u8]) -> Result<usize> {
let len = ffi!(opus_decoder_get_nb_samples, self.ptr,
packet.as_ptr(), packet.len() as i32);
Ok(len as usize)
}
// ------------
// Generic CTLs
/// Reset the codec state to be equivalent to a freshly initialized state.
pub fn reset_state(&mut self) -> Result<()> {
dec_ctl!(self, OPUS_RESET_STATE);
Ok(())
}
/// Get the final range of the codec's entropy coder.
pub fn get_final_range(&mut self) -> Result<u32> {
let mut value: u32 = 0;
dec_ctl!(self, OPUS_GET_FINAL_RANGE, &mut value);
Ok(value)
}
/// Get the decoder's last bandpass.
pub fn get_bandwidth(&mut self) -> Result<Bandwidth> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_BANDWIDTH, &mut value);
Bandwidth::decode(value, "opus_decoder_ctl(OPUS_GET_BANDWIDTH)")
}
/// Get the samping rate the decoder was intialized with.
pub fn get_sample_rate(&mut self) -> Result<u32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_SAMPLE_RATE, &mut value);
Ok(value as u32)
}
// ------------
// Decoder CTLs
/// Configures decoder gain adjustment.
///
/// Scales the decoded output by a factor specified in Q8 dB units. This has
/// a maximum range of -32768 to 32768 inclusive, and returns `BadArg`
/// otherwise. The default is zero indicating no adjustment. This setting
/// survives decoder reset.
///
/// `gain = pow(10, x / (20.0 * 256))`
pub fn set_gain(&mut self, gain: i32) -> Result<()> {
dec_ctl!(self, OPUS_SET_GAIN, gain);
Ok(())
}
/// Gets the decoder's configured gain adjustment.
pub fn get_gain(&mut self) -> Result<i32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_GAIN, &mut value);
Ok(value)
}
/// Gets the duration (in samples) of the last packet successfully decoded
/// or concealed.
pub fn get_last_packet_duration(&mut self) -> Result<u32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_LAST_PACKET_DURATION, &mut value);
Ok(value as u32)
}
/// Gets the pitch of the last decoded frame, if available.
///
/// This can be used for any post-processing algorithm requiring the use of
/// pitch, e.g. time stretching/shortening. If the last frame was not
/// voiced, or if the pitch was not coded in the frame, then zero is
/// returned.
pub fn get_pitch(&mut self) -> Result<i32> {
let mut value: i32 = 0;
dec_ctl!(self, OPUS_GET_PITCH, &mut value);
Ok(value)
}
}
impl Drop for Decoder {
fn drop(&mut self) {
unsafe { ffi::opus_decoder_destroy(self.ptr) }
}
}
// See `unsafe impl Send for Encoder`.
unsafe impl Send for Decoder {}
// ============================================================================
// Packet Analysis
/// Analyze raw Opus packets.
pub mod packet {
use super::*;
use super::ffi;
use std::{ptr, slice};
/// Get the bandwidth of an Opus packet.
pub fn get_bandwidth(packet: &[u8]) -> Result<Bandwidth> {
if packet.len() < 1 {
return Err(Error::bad_arg("opus_packet_get_bandwidth"));
}
let bandwidth = ffi!(opus_packet_get_bandwidth, packet.as_ptr());
Bandwidth::decode(bandwidth, "opus_packet_get_bandwidth")
}
/// Get the number of channels from an Opus packet.
pub fn get_nb_channels(packet: &[u8]) -> Result<Channels> {
if packet.len() < 1 {
return Err(Error::bad_arg("opus_packet_get_nb_channels"));
}
let channels = ffi!(opus_packet_get_nb_channels, packet.as_ptr());
match channels {
1 => Ok(Channels::Mono),
2 => Ok(Channels::Stereo),
_ => Err(Error::bad_arg("opus_packet_get_nb_channels")),
}
}
/// Get the number of frames in an Opus packet.
pub fn get_nb_frames(packet: &[u8]) -> Result<usize> {
let frames = ffi!(opus_packet_get_nb_frames, packet.as_ptr(), len(packet));
Ok(frames as usize)
}
/// Get the number of samples of an Opus packet.
pub fn get_nb_samples(packet: &[u8], sample_rate: u32) -> Result<usize> {
let frames = ffi!(opus_packet_get_nb_samples,
packet.as_ptr(), len(packet),
sample_rate as c_int);
Ok(frames as usize)
}
/// Get the number of samples per frame from an Opus packet.
pub fn get_samples_per_frame(packet: &[u8], sample_rate: u32) -> Result<usize> {
if packet.len() < 1 {
return Err(Error::bad_arg("opus_packet_get_samples_per_frame"))
}
let samples = ffi!(opus_packet_get_samples_per_frame,
packet.as_ptr(), sample_rate as c_int);
Ok(samples as usize)
}
/// Parse an Opus packet into one or more frames.
pub fn parse(packet: &[u8]) -> Result<Packet> {
let mut toc: u8 = 0;
let mut frames = [ptr::null(); 48];
let mut sizes = [0i16; 48];
let mut payload_offset: i32 = 0;
let num_frames = ffi!(opus_packet_parse,
packet.as_ptr(), len(packet),
&mut toc, frames.as_mut_ptr(),
sizes.as_mut_ptr(), &mut payload_offset);
let mut frames_vec = Vec::with_capacity(num_frames as usize);
for i in 0..num_frames as usize {
frames_vec.push(unsafe { slice::from_raw_parts(frames[i], sizes[i] as usize) });
}
Ok(Packet {
toc: toc,
frames: frames_vec,
payload_offset: payload_offset as usize,
})
}
/// A parsed Opus packet, retuned from `parse`.
#[derive(Debug)]
pub struct Packet<'a> {
/// The TOC byte of the packet.
pub toc: u8,
/// The frames contained in the packet.
pub frames: Vec<&'a [u8]>,
/// The offset into the packet at which the payload is located.
pub payload_offset: usize,
}
/// Pad a given Opus packet to a larger size.
///
/// The packet will be extended from the first `prev_len` bytes of the
/// buffer into the rest of the available space.
pub fn pad(packet: &mut [u8], prev_len: usize) -> Result<usize> {
let result = ffi!(opus_packet_pad, packet.as_mut_ptr(),
check_len(prev_len), len(packet));
Ok(result as usize)
}
/// Remove all padding from a given Opus packet and rewrite the TOC sequence
/// to minimize space usage.
pub fn unpad(packet: &mut [u8]) -> Result<usize> {
let result = ffi!(opus_packet_unpad, packet.as_mut_ptr(), len(packet));
Ok(result as usize)
}
}
// ============================================================================
// Float Soft Clipping
/// Soft-clipping to bring a float signal within the [-1,1] range.
#[derive(Debug)]
pub struct SoftClip {
channels: Channels,
memory: [f32; 2],
}
impl SoftClip {
/// Initialize a new soft-clipping state.
pub fn new(channels: Channels) -> SoftClip {
SoftClip { channels: channels, memory: [0.0; 2] }
}
/// Apply soft-clipping to a float signal.
pub fn apply(&mut self, signal: &mut [f32]) {
unsafe { ffi::opus_pcm_soft_clip(
signal.as_mut_ptr(),
len(signal) / self.channels as c_int,
self.channels as c_int,
self.memory.as_mut_ptr()) };
}
}
// ============================================================================
// Repacketizer
/// A repacketizer used to merge together or split apart multiple Opus packets.
#[derive(Debug)]
pub struct Repacketizer {
ptr: *mut ffi::OpusRepacketizer,
}
impl Repacketizer {
/// Create and initialize a repacketizer.
pub fn new() -> Result<Repacketizer> {
let ptr = unsafe { ffi::opus_repacketizer_create() };
if ptr.is_null() {
Err(Error::from_code("opus_repacketizer_create", ffi::OPUS_ALLOC_FAIL))
} else {
Ok(Repacketizer { ptr: ptr })
}
}
/// Shortcut to combine several smaller packets into one larger one.
pub fn combine(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<usize> {
let mut state = self.begin();
for &packet in input {
state.cat(packet)?;
}
state.out(output)
}
/// Begin using the repacketizer.
pub fn begin<'rp, 'buf>(&'rp mut self) -> RepacketizerState<'rp, 'buf> {
unsafe { ffi::opus_repacketizer_init(self.ptr); }
RepacketizerState { rp: self, phantom: PhantomData }
}
}
impl Drop for Repacketizer {
fn drop(&mut self) {
unsafe { ffi::opus_repacketizer_destroy(self.ptr) }
}
}
// See `unsafe impl Send for Encoder`.
unsafe impl Send for Repacketizer {}
// To understand why these lifetime bounds are needed, imagine that the
// repacketizer keeps an internal Vec<&'buf [u8]>, which is added to by cat()
// and accessed by get_nb_frames(), out(), and out_range(). To prove that these
// lifetime bounds are correct, a dummy implementation with the same signatures
// but a real Vec<&'buf [u8]> rather than unsafe blocks may be substituted.
/// An in-progress repacketization.
#[derive(Debug)]
pub struct RepacketizerState<'rp, 'buf> {
rp: &'rp mut Repacketizer,
phantom: PhantomData<&'buf [u8]>,
}
impl<'rp, 'buf> RepacketizerState<'rp, 'buf> {
/// Add a packet to the current repacketizer state.
pub fn cat(&mut self, packet: &'buf [u8]) -> Result<()> {
ffi!(opus_repacketizer_cat, self.rp.ptr,
packet.as_ptr(), len(packet));
Ok(())
}
/// Add a packet to the current repacketizer state, moving it.
#[inline]
pub fn cat_move<'b2>(self, packet: &'b2 [u8]) -> Result<RepacketizerState<'rp, 'b2>> where 'buf: 'b2 {
let mut shorter = self;
shorter.cat(packet)?;
Ok(shorter)
}
/// Get the total number of frames contained in packet data submitted so
/// far via `cat`.
pub fn get_nb_frames(&mut self) -> usize {
unsafe { ffi::opus_repacketizer_get_nb_frames(self.rp.ptr) as usize }
}
/// Construct a new packet from data previously submitted via `cat`.
///
/// All previously submitted frames are used.
pub fn out(&mut self, buffer: &mut [u8]) -> Result<usize> {
let result = ffi!(opus_repacketizer_out, self.rp.ptr,
buffer.as_mut_ptr(), len(buffer));
Ok(result as usize)
}
/// Construct a new packet from data previously submitted via `cat`, with
/// a manually specified subrange.
///
/// The `end` index should not exceed the value of `get_nb_frames()`.
pub fn out_range(&mut self, begin: usize, end: usize, buffer: &mut [u8]) -> Result<usize> {
let result = ffi!(opus_repacketizer_out_range, self.rp.ptr,
check_len(begin), check_len(end),
buffer.as_mut_ptr(), len(buffer));
Ok(result as usize)
}
}
// ============================================================================
// TODO: Multistream API
// ============================================================================
// Error Handling
/// Opus error Result alias.
pub type Result<T> = std::result::Result<T, Error>;
/// An error generated by the Opus library.
#[derive(Debug)]
pub struct Error {
function: &'static str,
code: ErrorCode,
}
impl Error {
fn bad_arg(what: &'static str) -> Error {
Error { function: what, code: ErrorCode::BadArg }
}
fn from_code(what: &'static str, code: c_int) -> Error {
Error { function: what, code: ErrorCode::from_int(code) }
}
/// Get the name of the Opus function from which the error originated.
#[inline]
pub fn function(&self) -> &'static str { self.function }
/// Get a textual description of the error provided by Opus.
#[inline]
pub fn description(&self) -> &'static str { self.code.description() }
/// Get the Opus error code of the error.
#[inline]
pub fn code(&self) -> ErrorCode { self.code }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}: {}", self.function, self.description())
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
self.code.description()
}
}
fn check_len(val: usize) -> c_int {
let len = val as c_int;
if len as usize != val {
panic!("length out of range: {}", val);
}
len
}
#[inline]
fn len<T>(slice: &[T]) -> c_int {
check_len(slice.len())
}

View File

@@ -1,6 +0,0 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
include!(concat!(env!("OUT_DIR"), "/opus_ffi.rs"));

View File

@@ -1,10 +0,0 @@
extern crate opus;
fn main() {
let mut rp = opus::Repacketizer::new().unwrap();
let mut wip = rp.begin().cat_move(
&[1, 2, 3]
//~^ ERROR borrowed value does not live long enough
).unwrap();
wip.out(&mut []);
}

View File

@@ -1,13 +0,0 @@
//! Test that supplying empty packets does forward error correction.
extern crate magnum_opus;
use magnum_opus::*;
#[test]
fn blah() {
let mut magnum_opus = Decoder::new(48000, Channels::Mono).unwrap();
let mut output = vec![0i16; 5760];
let size = magnum_opus.decode(&[], &mut output[..], true).unwrap();
assert_eq!(size, 5760);
}

View File

@@ -1,29 +0,0 @@
// Based on libmagnum_opus/tests/test_magnum_opus_padding.c
/* Check for overflow in reading the padding length.
* http://lists.xiph.org/pipermail/magnum_opus/2012-November/001834.html
*/
extern crate magnum_opus;
#[test]
fn test_overflow() {
const PACKETSIZE: usize = 16909318;
const CHANNELS: magnum_opus::Channels = magnum_opus::Channels::Stereo;
const FRAMESIZE: usize = 5760;
let mut input = vec![0xff; PACKETSIZE];
let mut output = vec![0i16; FRAMESIZE * 2];
input[0] = 0xff;
input[1] = 0x41;
*input.last_mut().unwrap() = 0x0b;
let mut decoder = magnum_opus::Decoder::new(48000, CHANNELS).unwrap();
let result = decoder.decode(&input[..], &mut output[..], false);
drop(decoder);
drop(input);
drop(output);
assert_eq!(result.unwrap_err().code(), magnum_opus::ErrorCode::InvalidPacket);
}

View File

@@ -1,127 +0,0 @@
extern crate magnum_opus;
fn check_ascii(s: &str) -> &str {
for &b in s.as_bytes() {
assert!(b < 0x80, "Non-ASCII character in string");
assert!(b > 0x00, "NUL in string")
}
std::str::from_utf8(s.as_bytes()).unwrap()
}
#[test]
fn strings_ascii() {
use magnum_opus::ErrorCode::*;
println!("\nVersion: {}", check_ascii(magnum_opus::version()));
let codes = [BadArg, BufferTooSmall, InternalError, InvalidPacket,
Unimplemented, InvalidState, AllocFail, Unknown];
for &code in codes.iter() {
println!("{:?}: {}", code, check_ascii(code.description()));
}
}
// 48000Hz * 1 channel * 20 ms / 1000
const MONO_20MS: usize = 48000 * 1 * 20 / 1000;
#[test]
fn encode_mono() {
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Mono, magnum_opus::Application::Audio).unwrap();
let mut output = [0; 256];
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[248, 255, 254]);
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[248, 255, 254]);
let len = encoder.encode(&[1_i16; MONO_20MS], &mut output).unwrap();
assert!(len > 190 && len < 220);
let len = encoder.encode(&[0_i16; MONO_20MS], &mut output).unwrap();
assert!(len > 170 && len < 190);
let myvec = encoder.encode_vec(&[1_i16; MONO_20MS], output.len()).unwrap();
assert!(myvec.len() > 120 && myvec.len() < 140);
}
#[test]
fn encode_stereo() {
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Stereo, magnum_opus::Application::Audio).unwrap();
let mut output = [0; 512];
let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[252, 255, 254]);
let len = encoder.encode(&[0_i16; 4 * MONO_20MS], &mut output).unwrap();
assert_eq!(&output[..len], &[253, 255, 254, 255, 254]);
let len = encoder.encode(&[17_i16; 2 * MONO_20MS], &mut output).unwrap();
assert!(len > 240);
let len = encoder.encode(&[0_i16; 2 * MONO_20MS], &mut output).unwrap();
assert!(len > 240);
// Very small buffer should still succeed
let len = encoder.encode(&[95_i16; 2 * MONO_20MS], &mut [0; 20]).unwrap();
assert!(len <= 20);
let myvec = encoder.encode_vec(&[95_i16; 2 * MONO_20MS], 20).unwrap();
assert!(myvec.len() <= 20);
}
#[test]
fn encode_bad_rate() {
match magnum_opus::Encoder::new(48001, magnum_opus::Channels::Mono, magnum_opus::Application::Audio) {
Ok(_) => panic!("Encoder::new did not return BadArg"),
Err(err) => assert_eq!(err.code(), magnum_opus::ErrorCode::BadArg),
}
}
#[test]
fn encode_bad_buffer() {
let mut encoder = magnum_opus::Encoder::new(48000, magnum_opus::Channels::Stereo, magnum_opus::Application::Audio).unwrap();
match encoder.encode(&[1_i16; 2 * MONO_20MS], &mut [0; 0]) {
Ok(_) => panic!("encode with 0-length buffer did not return BadArg"),
Err(err) => assert_eq!(err.code(), magnum_opus::ErrorCode::BadArg),
}
}
#[test]
fn repacketizer() {
let mut rp = magnum_opus::Repacketizer::new().unwrap();
let mut out = [0; 256];
for _ in 0..2 {
let packet1 = [249, 255, 254, 255, 254];
let packet2 = [248, 255, 254];
let mut state = rp.begin();
state.cat(&packet1).unwrap();
state.cat(&packet2).unwrap();
let len = state.out(&mut out).unwrap();
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
}
for _ in 0..2 {
let packet = [248, 255, 254];
let state = rp.begin().cat_move(&packet).unwrap();
let packet = [249, 255, 254, 255, 254];
let state = state.cat_move(&packet).unwrap();
let len = {state}.out(&mut out).unwrap();
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
}
for _ in 0..2 {
let len = rp.combine(&[
&[249, 255, 254, 255, 254],
&[248, 255, 254],
], &mut out).unwrap();
assert_eq!(&out[..len], &[251, 3, 255, 254, 255, 254, 255, 254]);
}
for _ in 0..2 {
let len = rp.begin()
.cat_move(&[248, 255, 254]).unwrap()
.cat_move(&[248, 71, 71]).unwrap()
.out(&mut out).unwrap();
assert_eq!(&out[..len], &[249, 255, 254, 71, 71]);
}
}

View File

@@ -1,3 +0,0 @@
target
Cargo.lock
.idea

View File

@@ -1,20 +0,0 @@
language: rust
rust:
- stable
- beta
- nightly
matrix:
allow_failures:
- rust: nightly
after_success:
- |-
[ $TRAVIS_BRANCH = master ] &&
[ $TRAVIS_PULL_REQUEST = false ] &&
cargo doc --all --no-deps &&
echo '<meta http-equiv=refresh content=0;url=parity_tokio_ipc/index.html>' > target/doc/index.html &&
pip install --user ghp-import &&
/home/travis/.local/bin/ghp-import -n target/doc &&
git push -fq https://${TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
env:
global:
secure: eUHPLjVMSVclRcEgwgybIKZQJTBW8QDjcjgIsEhOHZn7Kpzw0+rwJVoKkvr/uqyJwyY7pHy36mWX31J8YDSbSiM3W8jXeI97sk+FTUkleqUffPzXnbnR1D4kHZlKndFIbcuO5Z+rtVgsAv5E/u1w9XR+mvgK2lfaIEay+26gBl6dl/1TxWvrwDBeMvfq1JGVDQH4Etubncpi3LSWhbRkie1AKnVnsDIY9sUYVKSnIqjxx0qW6Z7EiCdwZ8gf04LNnqyIoKDpyldotL+nJ67ZlVI2O2DrbOOt55nliFHsH4BcWZIZOyIAM4PxIwhDl8g9E55FLkkUX9VUpVtqjTu9RWkVl7rzyrSxLoBUEjguIPrpFWBwLo0FSDvplB2XCXt8x035Io5PEg6m5dVxx5iytTIbI6HQwcA0ESTuDPuAdRJMNvJS/9e2UzPukdYYaaxF6g8wSmiIQjLuZU/nGBdmAl7Uw6cFlQnyLc/GXQg0oZ+B/J8sc4W2C/Z64oB8jK72RLNTKeeWs/XSOt8NxQiNkWeFIhGqiYOPJgjBiTCLSKJPY3CUTiBT8QpAcpj1x1gsWi+5fRoXYxNig/CmeTwZjuxKNxfQIu3J+lJbNdt44x7whnwhZ/AKVuLFPNNiC2OBNpa738UY60VYDoNZyhomWSdBnz3E6i1VtdiSnujFFnc=

View File

@@ -1,24 +0,0 @@
[package]
name = "parity-tokio-ipc"
version = "0.7.2"
edition = "2018"
authors = ["NikVolf <nikvolf@gmail.com>"]
license = "MIT/Apache-2.0"
readme = "README.md"
repository = "https://github.com/nikvolf/parity-tokio-ipc"
homepage = "https://github.com/nikvolf/parity-tokio-ipc"
description = """
Interprocess communication library for tokio.
"""
[dependencies]
futures = "0.3"
log = "0.4"
mio-named-pipes = "0.1"
miow = "0.3"
rand = "0.7"
tokio = { version = "0.2", features = ["io-driver", "io-util", "uds", "stream", "rt-core", "macros", "time"] }
libc = "0.2"
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winbase", "winnt", "accctrl", "aclapi", "securitybaseapi", "minwinbase", "winbase"] }

View File

@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,25 +0,0 @@
Copyright (c) 2017 Nikolay Volf
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@@ -1,28 +0,0 @@
# parity-tokio-ipc
[![Build Status](https://travis-ci.org/NikVolf/parity-tokio-ipc.svg?branch=master)](https://travis-ci.org/NikVolf/parity-tokio-ipc)
[Documentation](https://nikvolf.github.io/parity-tokio-ipc)
This crate abstracts interprocess transport for UNIX/Windows. On UNIX it utilizes unix sockets (`tokio_uds` crate) and named pipe on windows (experimental `tokio-named-pipes` crate).
Endpoint is transport-agnostic interface for incoming connections:
```rust
let endpoint = Endpoint::new(endpoint_addr, handle).unwrap();
endpoint.incoming().for_each(|_| println!("Connection received!"));
```
And IpcStream is transport-agnostic io:
```rust
let endpoint = Endpoint::new(endpoint_addr, handle).unwrap();
endpoint.incoming().for_each(|(ipc_stream: IpcStream, _)| io::write_all(ipc_stream, b"Hello!"));
```
# License
`parity-tokio-ipc` is primarily distributed under the terms of both the MIT
license and the Apache License (Version 2.0), with portions covered by various
BSD-like licenses.
See LICENSE-APACHE, and LICENSE-MIT for details.

View File

@@ -1,16 +0,0 @@
environment:
matrix:
- TARGET: x86_64-pc-windows-msvc
install:
- curl -sSf -o rustup-init.exe https://win.rustup.rs/
- rustup-init.exe -y --default-host %TARGET%
- set PATH=%PATH%;C:\Users\appveyor\.cargo\bin;C:\MinGW\bin
- rustc -vV
- cargo -vV
build: false
test_script:
- cargo test

View File

@@ -1,24 +0,0 @@
use tokio::{self, prelude::*};
use parity_tokio_ipc::Endpoint;
#[tokio::main]
async fn main() {
let path = std::env::args().nth(1).expect("Run it with server path to connect as argument");
let mut client = Endpoint::connect(&path).await
.expect("Failed to connect client.");
loop {
let mut buf = [0u8; 4];
println!("SEND: PING");
client.write_all(b"ping").await.expect("Unable to write message to client");
client.read_exact(&mut buf[..]).await.expect("Unable to read buffer");
if let Ok("pong") = std::str::from_utf8(&buf[..]) {
println!("RECEIVED: PONG");
} else {
break;
}
tokio::time::delay_for(std::time::Duration::from_secs(2)).await;
}
}

View File

@@ -1,47 +0,0 @@
use futures::StreamExt as _;
use tokio::{
prelude::*,
self,
io::split,
};
use parity_tokio_ipc::{Endpoint, SecurityAttributes};
async fn run_server(path: String) {
let mut endpoint = Endpoint::new(path);
endpoint.set_security_attributes(SecurityAttributes::allow_everyone_create().unwrap());
let mut incoming = endpoint.incoming().expect("failed to open new socket");
while let Some(result) = incoming.next().await
{
match result {
Ok(stream) => {
let (mut reader, mut writer) = split(stream);
tokio::spawn(async move {
loop {
let mut buf = [0u8; 4];
let pong_buf = b"pong";
if let Err(_) = reader.read_exact(&mut buf).await {
println!("Closing socket");
break;
}
if let Ok("ping") = std::str::from_utf8(&buf[..]) {
println!("RECIEVED: PING");
writer.write_all(pong_buf).await.expect("unable to write to socket");
println!("SEND: PONG");
}
}
});
}
_ => unreachable!("ideally")
}
};
}
#[tokio::main]
async fn main() {
let path = std::env::args().nth(1).expect("Run it with server path as argument");
run_server(path).await
}

View File

@@ -1,7 +0,0 @@
#!/bin/bash
echo "Spawning 100 processes"
for i in {1..100} ;
do
( cargo run --example client -- /tmp/test.ipc & )
done

View File

@@ -1,154 +0,0 @@
//! Tokio IPC transport. Under the hood uses Unix Domain Sockets for Linux/Mac
//! and Named Pipes for Windows.
//#![warn(missing_docs)]
//#![deny(rust_2018_idioms)]
#[cfg(windows)]
mod win;
#[cfg(not(windows))]
mod unix;
/// Endpoint for IPC transport
///
/// # Examples
///
/// ```ignore
/// use parity_tokio_ipc::{Endpoint, dummy_endpoint};
/// use futures::{future, Future, Stream, StreamExt};
/// use tokio::runtime::Runtime;
///
/// fn main() {
/// let mut runtime = Runtime::new().unwrap();
/// let mut endpoint = Endpoint::new(dummy_endpoint());
/// let server = endpoint.incoming()
/// .expect("failed to open up a new pipe/socket")
/// .for_each(|_stream| {
/// println!("Connection received");
/// futures::future::ready(())
/// });
/// runtime.block_on(server)
/// }
///```
#[cfg(windows)]
pub use win::{SecurityAttributes, Endpoint, Connection, Incoming};
#[cfg(unix)]
pub use unix::{SecurityAttributes, Endpoint, Connection, Incoming};
/// For testing/examples
pub fn dummy_endpoint() -> String {
let num: u64 = rand::Rng::gen(&mut rand::thread_rng());
if cfg!(windows) {
format!(r"\\.\pipe\my-pipe-{}", num)
} else {
format!(r"/tmp/my-uds-{}", num)
}
}
#[cfg(test)]
mod tests {
use tokio::prelude::*;
use futures::{channel::oneshot, StreamExt as _, FutureExt as _};
use std::time::Duration;
use tokio::{
self,
io::split,
};
use super::{dummy_endpoint, Endpoint, SecurityAttributes};
use std::path::Path;
use futures::future::{Either, select, ready};
async fn run_server(path: String) {
let path = path.to_owned();
let mut endpoint = Endpoint::new(path);
endpoint.set_security_attributes(
SecurityAttributes::empty()
.set_mode(0o777)
.unwrap()
);
let mut incoming = endpoint.incoming().expect("failed to open up a new socket");
while let Some(result) = incoming.next().await {
match result {
Ok(stream) => {
let (mut reader, mut writer) = split(stream);
let mut buf = [0u8; 5];
reader.read_exact(&mut buf).await.expect("unable to read from socket");
writer.write_all(&buf[..]).await.expect("unable to write to socket");
}
_ => unreachable!("ideally")
}
};
}
#[tokio::test]
async fn smoke_test() {
let path = dummy_endpoint();
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let server = select(Box::pin(run_server(path.clone())), shutdown_rx)
.then(|either| {
match either {
Either::Right((_, server)) => {
drop(server);
}
_ => unreachable!("also ideally")
};
ready(())
});
tokio::spawn(server);
tokio::time::delay_for(Duration::from_secs(2)).await;
println!("Connecting to client 0...");
let mut client_0 = Endpoint::connect(&path).await
.expect("failed to open client_0");
tokio::time::delay_for(Duration::from_secs(2)).await;
println!("Connecting to client 1...");
let mut client_1 = Endpoint::connect(&path).await
.expect("failed to open client_1");
let msg = b"hello";
let mut rx_buf = vec![0u8; msg.len()];
client_0.write_all(msg).await.expect("Unable to write message to client");
client_0.read_exact(&mut rx_buf).await.expect("Unable to read message from client");
let mut rx_buf2 = vec![0u8; msg.len()];
client_1.write_all(msg).await.expect("Unable to write message to client");
client_1.read_exact(&mut rx_buf2).await.expect("Unable to read message from client");
assert_eq!(rx_buf, msg);
assert_eq!(rx_buf2, msg);
// shutdown server
if let Ok(()) = shutdown_tx.send(()) {
// wait one second for the file to be deleted.
tokio::time::delay_for(Duration::from_secs(1)).await;
let path = Path::new(&path);
// assert that it has
assert!(!path.exists());
}
}
#[cfg(windows)]
fn create_pipe_with_permissions(attr: SecurityAttributes) -> ::std::io::Result<()> {
let path = dummy_endpoint();
let mut endpoint = Endpoint::new(path);
endpoint.set_security_attributes(attr);
endpoint.incoming().map(|_| ())
}
#[cfg(windows)]
#[tokio::test]
async fn test_pipe_permissions() {
create_pipe_with_permissions(SecurityAttributes::empty())
.expect("failed with no attributes");
create_pipe_with_permissions(SecurityAttributes::allow_everyone_create().unwrap())
.expect("failed with attributes for creating");
create_pipe_with_permissions(SecurityAttributes::empty().allow_everyone_connect().unwrap())
.expect("failed with attributes for connecting");
}
}

View File

@@ -1,163 +0,0 @@
use libc::chmod;
use std::ffi::CString;
use std::io::{self, Error};
use tokio::prelude::*;
use tokio::net::{UnixListener, UnixStream};
use std::path::Path;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::mem::MaybeUninit;
/// Socket permissions and ownership on UNIX
pub struct SecurityAttributes {
// read/write permissions for owner, group and others in unix octal.
mode: Option<u16>
}
impl SecurityAttributes {
/// New default security attributes.
pub fn empty() -> Self {
SecurityAttributes {
mode: None
}
}
/// New security attributes that allow everyone to connect.
pub fn allow_everyone_connect(mut self) -> io::Result<Self> {
self.mode = Some(0o777);
Ok(self)
}
/// Set a custom permission on the socket
pub fn set_mode(mut self, mode: u16) -> io::Result<Self> {
self.mode = Some(mode);
Ok(self)
}
/// New security attributes that allow everyone to create.
pub fn allow_everyone_create() -> io::Result<Self> {
Ok(SecurityAttributes {
mode: None
})
}
/// called in unix, after server socket has been created
/// will apply security attributes to the socket.
pub(crate) unsafe fn apply_permissions(&self, path: &str) -> io::Result<()> {
let path = CString::new(path.to_owned())?;
if let Some(mode) = self.mode {
if chmod(path.as_ptr(), mode as _) == -1 {
return Err(Error::last_os_error())
}
}
Ok(())
}
}
/// Endpoint implementation for unix systems
pub struct Endpoint {
path: String,
security_attributes: SecurityAttributes,
}
pub struct Incoming {
socket: UnixListener,
}
impl Incoming {
pub async fn next(&mut self) -> Option<io::Result<Connection>> {
match self.socket.accept().await {
Ok((stream, _)) => Some(Ok(Connection::wrap(stream))),
Err(err) => Some(Err(err))
}
}
}
impl Endpoint {
/// Stream of incoming connections
pub fn incoming(&mut self) -> io::Result<Incoming> {
unsafe {
// the call to bind in `inner()` creates the file
// `apply_permission()` will set the file permissions.
self.security_attributes.apply_permissions(&self.path)?;
};
let socket = self.inner()?;
Ok(Incoming { socket })
}
/// Inner platform-dependant state of the endpoint
fn inner(&self) -> io::Result<UnixListener> {
UnixListener::bind(&self.path)
}
/// Set security attributes for the connection
pub fn set_security_attributes(&mut self, security_attributes: SecurityAttributes) {
self.security_attributes = security_attributes;
}
/// Make new connection using the provided path and running event pool
pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<Connection> {
Ok(Connection::wrap(UnixStream::connect(path.as_ref()).await?))
}
/// Returns the path of the endpoint.
pub fn path(&self) -> &str {
&self.path
}
/// New IPC endpoint at the given path
pub fn new(path: String) -> Self {
Endpoint {
path,
security_attributes: SecurityAttributes::empty(),
}
}
}
/// IPC connection.
pub struct Connection {
inner: UnixStream,
}
impl Connection {
fn wrap(stream: UnixStream) -> Self {
Self { inner: stream }
}
}
impl AsyncRead for Connection {
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [MaybeUninit<u8>]) -> bool {
self.inner.prepare_uninitialized_buffer(buf)
}
fn poll_read(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_read(ctx, buf)
}
}
impl AsyncWrite for Connection {
fn poll_write(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_write(ctx, buf)
}
fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_flush(ctx)
}
fn poll_shutdown(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_shutdown(ctx)
}
}

View File

@@ -1,488 +0,0 @@
use winapi::shared::winerror::ERROR_SUCCESS;
use winapi::um::accctrl::*;
use winapi::um::aclapi::*;
use winapi::um::minwinbase::{LPTR, PSECURITY_ATTRIBUTES, SECURITY_ATTRIBUTES};
use winapi::um::securitybaseapi::*;
use winapi::um::winbase::{LocalAlloc, LocalFree};
use winapi::um::winnt::*;
use std::io;
use std::marker;
use std::mem;
use std::ptr;
use futures::Stream;
use tokio::prelude::*;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::path::Path;
use std::mem::MaybeUninit;
use tokio::io::PollEvented;
type NamedPipe = PollEvented<mio_named_pipes::NamedPipe>;
const PIPE_AVAILABILITY_TIMEOUT: u64 = 5000;
/// Endpoint implementation for windows
pub struct Endpoint {
path: String,
security_attributes: SecurityAttributes,
}
impl Endpoint {
/// Stream of incoming connections
pub fn incoming(mut self) -> io::Result<Incoming> {
let pipe = self.inner()?;
Ok(Incoming {
path: self.path.clone(),
inner: NamedPipeSupport {
path: self.path,
pipe,
security_attributes: self.security_attributes,
},
})
}
/// Inner platform-dependant state of the endpoint
fn inner(&mut self) -> io::Result<NamedPipe> {
use miow::pipe::NamedPipeBuilder;
use std::os::windows::io::*;
let raw_handle = unsafe {
NamedPipeBuilder::new(&self.path)
.first(true)
.inbound(true)
.outbound(true)
.out_buffer_size(65536)
.in_buffer_size(65536)
.with_security_attributes(self.security_attributes.as_ptr())?
.into_raw_handle()
};
let mio_pipe = unsafe { mio_named_pipes::NamedPipe::from_raw_handle(raw_handle) };
NamedPipe::new(mio_pipe)
}
/// Set security attributes for the connection
pub fn set_security_attributes(&mut self, security_attributes: SecurityAttributes) {
self.security_attributes = security_attributes;
}
/// Returns the path of the endpoint.
pub fn path(&self) -> &str {
&self.path
}
/// Make new connection using the provided path and running event pool.
pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<Connection> {
Ok(Connection::wrap(Self::connect_inner(path.as_ref())?))
}
fn connect_inner(path: &Path) -> io::Result<NamedPipe> {
use std::fs::OpenOptions;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::{FromRawHandle, IntoRawHandle};
use winapi::um::winbase::FILE_FLAG_OVERLAPPED;
// Wait for the pipe to become available or fail after 5 seconds.
miow::pipe::NamedPipe::wait(
path,
Some(std::time::Duration::from_millis(PIPE_AVAILABILITY_TIMEOUT)),
)?;
let file = OpenOptions::new()
.read(true)
.write(true)
.custom_flags(FILE_FLAG_OVERLAPPED)
.open(path)?;
let mio_pipe =
unsafe { mio_named_pipes::NamedPipe::from_raw_handle(file.into_raw_handle()) };
let pipe = NamedPipe::new(mio_pipe)?;
Ok(pipe)
}
/// New IPC endpoint at the given path
pub fn new(path: String) -> Self {
Endpoint {
path,
security_attributes: SecurityAttributes::empty(),
}
}
}
struct NamedPipeSupport {
path: String,
pipe: NamedPipe,
security_attributes: SecurityAttributes,
}
impl NamedPipeSupport {
fn replacement_pipe(&mut self) -> io::Result<NamedPipe> {
use miow::pipe::NamedPipeBuilder;
use std::os::windows::io::*;
let raw_handle = unsafe {
NamedPipeBuilder::new(&self.path)
.first(false)
.inbound(true)
.outbound(true)
.out_buffer_size(65536)
.in_buffer_size(65536)
.with_security_attributes(self.security_attributes.as_ptr())?
.into_raw_handle()
};
let mio_pipe = unsafe { mio_named_pipes::NamedPipe::from_raw_handle(raw_handle) };
NamedPipe::new(mio_pipe)
}
}
/// Stream of incoming connections
pub struct Incoming {
#[allow(dead_code)]
path: String,
inner: NamedPipeSupport,
}
impl Stream for Incoming {
type Item = tokio::io::Result<Connection>;
fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.inner.pipe.get_ref().connect() {
Ok(()) => {
log::trace!("Incoming connection polled successfully");
let new_listener = self.inner.replacement_pipe()?;
Poll::Ready(
Some(Ok(Connection::wrap(std::mem::replace(&mut self.inner.pipe, new_listener))))
)
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
self.inner.pipe.clear_write_ready(ctx);
Poll::Pending
} else {
Poll::Ready(Some(Err(e)))
}
}
}
}
}
/// IPC connection.
pub struct Connection {
inner: NamedPipe,
}
impl Connection {
pub fn wrap(pipe: NamedPipe) -> Self {
Self { inner: pipe }
}
}
impl AsyncRead for Connection {
unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [MaybeUninit<u8>]) -> bool {
self.inner.prepare_uninitialized_buffer(buf)
}
fn poll_read(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_read(ctx, buf)
}
}
impl AsyncWrite for Connection {
fn poll_write(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_write(ctx, buf)
}
fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_flush(ctx)
}
fn poll_shutdown(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
let this = Pin::into_inner(self);
Pin::new(&mut this.inner).poll_shutdown(ctx)
}
}
/// Security attributes.
pub struct SecurityAttributes {
attributes: Option<InnerAttributes>,
}
impl SecurityAttributes {
/// New default security attributes.
pub fn empty() -> SecurityAttributes {
SecurityAttributes { attributes: None }
}
/// New default security attributes that allow everyone to connect.
pub fn allow_everyone_connect(&self) -> io::Result<SecurityAttributes> {
let attributes = Some(InnerAttributes::allow_everyone(
GENERIC_READ | FILE_WRITE_DATA,
)?);
Ok(SecurityAttributes { attributes })
}
/// Set a custom permission on the socket
pub fn set_mode(self, _mode: u32) -> io::Result<Self> {
// for now, does nothing.
Ok(self)
}
/// New default security attributes that allow everyone to create.
pub fn allow_everyone_create() -> io::Result<SecurityAttributes> {
let attributes = Some(InnerAttributes::allow_everyone(
GENERIC_READ | GENERIC_WRITE,
)?);
Ok(SecurityAttributes { attributes })
}
/// Return raw handle of security attributes.
pub(crate) unsafe fn as_ptr(&mut self) -> PSECURITY_ATTRIBUTES {
match self.attributes.as_mut() {
Some(attributes) => attributes.as_ptr(),
None => ptr::null_mut(),
}
}
}
unsafe impl Send for SecurityAttributes {}
struct Sid {
sid_ptr: PSID,
}
impl Sid {
fn everyone_sid() -> io::Result<Sid> {
let mut sid_ptr = ptr::null_mut();
let result = unsafe {
AllocateAndInitializeSid(
SECURITY_WORLD_SID_AUTHORITY.as_mut_ptr() as *mut _,
1,
SECURITY_WORLD_RID,
0,
0,
0,
0,
0,
0,
0,
&mut sid_ptr,
)
};
if result == 0 {
Err(io::Error::last_os_error())
} else {
Ok(Sid { sid_ptr })
}
}
// Unsafe - the returned pointer is only valid for the lifetime of self.
unsafe fn as_ptr(&self) -> PSID {
self.sid_ptr
}
}
impl Drop for Sid {
fn drop(&mut self) {
if !self.sid_ptr.is_null() {
unsafe {
FreeSid(self.sid_ptr);
}
}
}
}
struct AceWithSid<'a> {
explicit_access: EXPLICIT_ACCESS_W,
_marker: marker::PhantomData<&'a Sid>,
}
impl<'a> AceWithSid<'a> {
fn new(sid: &'a Sid, trustee_type: u32) -> AceWithSid<'a> {
let mut explicit_access = unsafe { mem::zeroed::<EXPLICIT_ACCESS_W>() };
explicit_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
explicit_access.Trustee.TrusteeType = trustee_type;
explicit_access.Trustee.ptstrName = unsafe { sid.as_ptr() as *mut _ };
AceWithSid {
explicit_access,
_marker: marker::PhantomData,
}
}
fn set_access_mode(&mut self, access_mode: u32) -> &mut Self {
self.explicit_access.grfAccessMode = access_mode;
self
}
fn set_access_permissions(&mut self, access_permissions: u32) -> &mut Self {
self.explicit_access.grfAccessPermissions = access_permissions;
self
}
fn allow_inheritance(&mut self, inheritance_flags: u32) -> &mut Self {
self.explicit_access.grfInheritance = inheritance_flags;
self
}
}
struct Acl {
acl_ptr: PACL,
}
impl Acl {
fn empty() -> io::Result<Acl> {
Self::new(&mut [])
}
fn new(entries: &mut [AceWithSid<'_>]) -> io::Result<Acl> {
let mut acl_ptr = ptr::null_mut();
let result = unsafe {
SetEntriesInAclW(
entries.len() as u32,
entries.as_mut_ptr() as *mut _,
ptr::null_mut(),
&mut acl_ptr,
)
};
if result != ERROR_SUCCESS {
return Err(io::Error::from_raw_os_error(result as i32));
}
Ok(Acl { acl_ptr })
}
unsafe fn as_ptr(&self) -> PACL {
self.acl_ptr
}
}
impl Drop for Acl {
fn drop(&mut self) {
if !self.acl_ptr.is_null() {
unsafe { LocalFree(self.acl_ptr as *mut _) };
}
}
}
struct SecurityDescriptor {
descriptor_ptr: PSECURITY_DESCRIPTOR,
}
impl SecurityDescriptor {
fn new() -> io::Result<Self> {
let descriptor_ptr = unsafe { LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH) };
if descriptor_ptr.is_null() {
return Err(io::Error::new(
io::ErrorKind::Other,
"Failed to allocate security descriptor",
));
}
if unsafe {
InitializeSecurityDescriptor(descriptor_ptr, SECURITY_DESCRIPTOR_REVISION) == 0
} {
return Err(io::Error::last_os_error());
};
Ok(SecurityDescriptor { descriptor_ptr })
}
fn set_dacl(&mut self, acl: &Acl) -> io::Result<()> {
if unsafe {
SetSecurityDescriptorDacl(self.descriptor_ptr, true as i32, acl.as_ptr(), false as i32)
== 0
} {
return Err(io::Error::last_os_error());
}
Ok(())
}
unsafe fn as_ptr(&self) -> PSECURITY_DESCRIPTOR {
self.descriptor_ptr
}
}
impl Drop for SecurityDescriptor {
fn drop(&mut self) {
if !self.descriptor_ptr.is_null() {
unsafe { LocalFree(self.descriptor_ptr) };
self.descriptor_ptr = ptr::null_mut();
}
}
}
struct InnerAttributes {
descriptor: SecurityDescriptor,
acl: Acl,
attrs: SECURITY_ATTRIBUTES,
}
impl InnerAttributes {
fn empty() -> io::Result<InnerAttributes> {
let descriptor = SecurityDescriptor::new()?;
let mut attrs = unsafe { mem::zeroed::<SECURITY_ATTRIBUTES>() };
attrs.nLength = mem::size_of::<SECURITY_ATTRIBUTES>() as u32;
attrs.lpSecurityDescriptor = unsafe { descriptor.as_ptr() };
attrs.bInheritHandle = false as i32;
let acl = Acl::empty().expect("this should never fail");
Ok(InnerAttributes {
acl,
descriptor,
attrs,
})
}
fn allow_everyone(permissions: u32) -> io::Result<InnerAttributes> {
let mut attributes = Self::empty()?;
let sid = Sid::everyone_sid()?;
let mut everyone_ace = AceWithSid::new(&sid, TRUSTEE_IS_WELL_KNOWN_GROUP);
everyone_ace
.set_access_mode(SET_ACCESS)
.set_access_permissions(permissions)
.allow_inheritance(false as u32);
let mut entries = vec![everyone_ace];
attributes.acl = Acl::new(&mut entries)?;
attributes.descriptor.set_dacl(&attributes.acl)?;
Ok(attributes)
}
unsafe fn as_ptr(&mut self) -> PSECURITY_ATTRIBUTES {
&mut self.attrs as *mut _
}
}
#[cfg(test)]
mod test {
use super::SecurityAttributes;
#[test]
fn test_allow_everyone_everything() {
SecurityAttributes::allow_everyone_create()
.expect("failed to create security attributes that allow everyone to create a pipe");
}
#[test]
fn test_allow_eveyone_read_write() {
SecurityAttributes::empty()
.allow_everyone_connect()
.expect("failed to create security attributes that allow everyone to read and write to/from a pipe");
}
}

View File

@@ -1,4 +0,0 @@
**/target
/target
**/*.rs.bk
.idea/

129
libs/pulsectl/Cargo.lock generated
View File

@@ -1,129 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "libc"
version = "0.2.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a31a0627fdf1f6a39ec0dd577e101440b7db22672c0901fe00a9a6fbb5c24e8"
[[package]]
name = "libpulse-binding"
version = "2.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe925a4d3a96961316c9c1488f97a95938a6093f0d4691eec888776057ce965e"
dependencies = [
"libc",
"libpulse-sys",
"num-derive",
"num-traits",
"winapi",
]
[[package]]
name = "libpulse-sys"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d9073c83dda6aff9b611dc368e8db6e0aa29027546d8800a18b4417e182b4d5"
dependencies = [
"libc",
"num-derive",
"num-traits",
"pkg-config",
"winapi",
]
[[package]]
name = "num-derive"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "num-traits"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
dependencies = [
"autocfg",
]
[[package]]
name = "pkg-config"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677"
[[package]]
name = "proc-macro2"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rust-pulsectl"
version = "0.2.9"
dependencies = [
"libpulse-binding",
]
[[package]]
name = "syn"
version = "1.0.51"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b4f34193997d92804d359ed09953e25d5138df6bcc055a71bf68ee89fdf9223"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

View File

@@ -1,19 +0,0 @@
[package]
name = "rust-pulsectl"
version = "0.2.10"
authors = ["Kristopher Ruzic <krruzic@gmail.com>"]
edition = "2018"
license = "GPL-3.0+"
description = "A higher level API for libpulse_binding"
readme = "README.md"
keywords = ["pulse", "pulseaudio", "binding", "audio", "api"]
categories = ["api-bindings", "multimedia::audio"]
homepage = "https://github.com/krruzic/pulsectl"
repository = "https://github.com/krruzic/pulsectl"
[lib]
name = "pulsectl"
path = "src/lib.rs"
[dependencies]
libpulse-binding = "2.21"

View File

@@ -1,13 +0,0 @@
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 <http://www.gnu.org/licenses/>.

View File

@@ -1,43 +0,0 @@
Rust PulsecAudio API
====================
`pulsectl-rust` is a API wrapper for `libpulse_binding` to make pulseaudio application development easier.
This is a wrapper around the introspector, and thus this library is only capable of modifying PulseAudio data (changing volume, routing applications and muting right now).
### Usage
Add this to your `Cargo.toml`:
```toml
[dependencies]
rust-pulsectl = "0.2.6"
```
Then, connect to PulseAudio by creating a `SinkController` for audio playback devices and apps or a `SourceController` for audio recording devices and apps.
```rust
// Simple application that lists all playback devices and their status
// See examples/change_device_vol.rs for a more complete example
extern crate pulsectl;
use std::io;
use pulsectl::controllers::SinkController;
use pulsectl::controllers::DeviceControl;
fn main() {
// create handler that calls functions on playback devices and apps
let mut handler = SinkController::create();
let devices = handler
.list_devices()
.expect("Could not get list of playback devices");
println!("Playback Devices");
for dev in devices.clone() {
println!(
"[{}] {}, [Volume: {}]",
dev.index,
dev.description.as_ref().unwrap(),
dev.volume.print()
);
}
}
```

View File

@@ -1,34 +0,0 @@
extern crate pulsectl;
use std::io;
use pulsectl::controllers::DeviceControl;
use pulsectl::controllers::SinkController;
fn main() {
// create handler that calls functions on playback devices and apps
let mut handler = SinkController::create().unwrap();
let devices = handler
.list_devices()
.expect("Could not get list of playback devices");
println!("Playback Devices");
for dev in devices.clone() {
println!(
"[{}] {}, [Volume: {}]",
dev.index,
dev.description.as_ref().unwrap(),
dev.volume.print()
);
}
let mut selection = String::new();
io::stdin()
.read_line(&mut selection)
.expect("error: unable to read user input");
for dev in devices.clone() {
if let true = selection.trim() == dev.index.to_string() {
handler.increase_device_volume_by_percent(dev.index, 0.05);
}
}
}

View File

@@ -1,51 +0,0 @@
use std::fmt;
use crate::PulseCtlError;
/// if the error occurs within the Mainloop, we bubble up the error with
/// this conversion
impl From<PulseCtlError> for ControllerError {
fn from(error: super::errors::PulseCtlError) -> Self {
ControllerError {
error: ControllerErrorType::PulseCtlError,
message: format!("{:?}", error),
}
}
}
impl fmt::Debug for ControllerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut error_string = String::new();
match self.error {
ControllerErrorType::PulseCtlError => {
error_string.push_str("PulseCtlError");
}
ControllerErrorType::GetInfoError => {
error_string.push_str("GetInfoError");
}
}
write!(f, "[{}]: {}", error_string, self.message)
}
}
pub(crate) enum ControllerErrorType {
PulseCtlError,
GetInfoError,
}
/// Error thrown while fetching data from pulseaudio,
/// has two variants: PulseCtlError for when PulseAudio returns an error code
/// and GetInfoError when a request for data fails for whatever reason
pub struct ControllerError {
error: ControllerErrorType,
message: String,
}
impl ControllerError {
pub(crate) fn new(err: ControllerErrorType, msg: &str) -> Self {
ControllerError {
error: err,
message: msg.to_string(),
}
}
}

View File

@@ -1,595 +0,0 @@
/// Source = microphone etc. something that takes in audio
/// Source Output = application consuming that audio
///
/// Sink = headphones etc. something that plays out audio
/// Sink Input = application producing that audio
/// When you create a `SinkController`, you are working with audio playback devices and applications
/// if you want to manipulate recording devices such as microphone volume,
/// you'll need to use a `SourceController`. Both of these implement the same api, defined by
/// the traits DeviceControl and AppControl
use std::cell::RefCell;
use std::clone::Clone;
use std::rc::Rc;
use pulse::{
callbacks::ListResult,
context::introspect,
volume::{ChannelVolumes, Volume},
};
use errors::{ControllerError, ControllerErrorType::*};
use types::{ApplicationInfo, DeviceInfo, ServerInfo};
use crate::Handler;
pub(crate) mod errors;
pub mod types;
pub trait DeviceControl<T> {
fn get_default_device(&mut self) -> Result<T, ControllerError>;
fn set_default_device(&mut self, name: &str) -> Result<bool, ControllerError>;
fn list_devices(&mut self) -> Result<Vec<T>, ControllerError>;
fn get_device_by_index(&mut self, index: u32) -> Result<T, ControllerError>;
fn get_device_by_name(&mut self, name: &str) -> Result<T, ControllerError>;
fn set_device_volume_by_index(&mut self, index: u32, volume: &ChannelVolumes);
fn set_device_volume_by_name(&mut self, name: &str, volume: &ChannelVolumes);
fn increase_device_volume_by_percent(&mut self, index: u32, delta: f64);
fn decrease_device_volume_by_percent(&mut self, index: u32, delta: f64);
}
pub trait AppControl<T> {
fn list_applications(&mut self) -> Result<Vec<T>, ControllerError>;
fn get_app_by_index(&mut self, index: u32) -> Result<T, ControllerError>;
fn increase_app_volume_by_percent(&mut self, index: u32, delta: f64);
fn decrease_app_volume_by_percent(&mut self, index: u32, delta: f64);
fn move_app_by_index(
&mut self,
stream_index: u32,
device_index: u32,
) -> Result<bool, ControllerError>;
fn move_app_by_name(
&mut self,
stream_index: u32,
device_name: &str,
) -> Result<bool, ControllerError>;
fn set_app_mute(&mut self, index: u32, mute: bool) -> Result<bool, ControllerError>;
}
fn volume_from_percent(volume: f64) -> f64 {
(volume * 100.0) * (f64::from(pulse::volume::VOLUME_NORM.0) / 100.0)
}
pub struct SinkController {
pub handler: Handler,
}
impl SinkController {
pub fn create() -> Result<Self, ControllerError> {
let handler = Handler::connect("SinkController")?;
Ok(SinkController { handler })
}
pub fn get_server_info(&mut self) -> Result<ServerInfo, ControllerError> {
let server = Rc::new(RefCell::new(Some(None)));
let server_ref = server.clone();
let op = self.handler.introspect.get_server_info(move |res| {
server_ref
.borrow_mut()
.as_mut()
.unwrap()
.replace(res.into());
});
self.handler.wait_for_operation(op)?;
let mut result = server.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting information about the server",
))
}
}
impl DeviceControl<DeviceInfo> for SinkController {
fn get_default_device(&mut self) -> Result<DeviceInfo, ControllerError> {
let server_info = self.get_server_info();
match server_info {
Ok(info) => self.get_device_by_name(info.default_sink_name.unwrap().as_ref()),
Err(e) => Err(e),
}
}
fn set_default_device(&mut self, name: &str) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self
.handler
.context
.borrow_mut()
.set_default_sink(name, move |res| success_ref.borrow_mut().clone_from(&res));
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn list_devices(&mut self) -> Result<Vec<DeviceInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_sink_info_list(
move |sink_list: ListResult<&introspect::SinkInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting device list",
))
}
fn get_device_by_index(&mut self, index: u32) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_sink_info_by_index(
index,
move |sink_list: ListResult<&introspect::SinkInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting requested device",
))
}
fn get_device_by_name(&mut self, name: &str) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_sink_info_by_name(
name,
move |sink_list: ListResult<&introspect::SinkInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting requested device",
))
}
fn set_device_volume_by_index(&mut self, index: u32, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_sink_volume_by_index(index, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn set_device_volume_by_name(&mut self, name: &str, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_sink_volume_by_name(name, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn increase_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_sink_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_sink_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
}
impl AppControl<ApplicationInfo> for SinkController {
fn list_applications(&mut self) -> Result<Vec<ApplicationInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_sink_input_info_list(
move |sink_list: ListResult<&introspect::SinkInputInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_app_by_index(&mut self, index: u32) -> Result<ApplicationInfo, ControllerError> {
let app = Rc::new(RefCell::new(Some(None)));
let app_ref = app.clone();
let op = self.handler.introspect.get_sink_input_info(
index,
move |sink_list: ListResult<&introspect::SinkInputInfo>| {
if let ListResult::Item(item) = sink_list {
app_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = app.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting requested app",
))
}
fn increase_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_sink_input_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_sink_input_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn move_app_by_index(
&mut self,
stream_index: u32,
device_index: u32,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_sink_input_by_index(
stream_index,
device_index,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn move_app_by_name(
&mut self,
stream_index: u32,
device_name: &str,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_sink_input_by_name(
stream_index,
device_name,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn set_app_mute(&mut self, index: u32, mute: bool) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.set_sink_input_mute(
index,
mute,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
}
pub struct SourceController {
pub handler: Handler,
}
impl SourceController {
pub fn create() -> Result<Self, ControllerError> {
let handler = Handler::connect("SourceController")?;
Ok(SourceController { handler })
}
pub fn get_server_info(&mut self) -> Result<ServerInfo, ControllerError> {
let server = Rc::new(RefCell::new(Some(None)));
let server_ref = server.clone();
let op = self.handler.introspect.get_server_info(move |res| {
server_ref
.borrow_mut()
.as_mut()
.unwrap()
.replace(res.into());
});
self.handler.wait_for_operation(op)?;
let mut result = server.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
}
impl DeviceControl<DeviceInfo> for SourceController {
fn get_default_device(&mut self) -> Result<DeviceInfo, ControllerError> {
let server_info = self.get_server_info();
match server_info {
Ok(info) => self.get_device_by_name(info.default_sink_name.unwrap().as_ref()),
Err(e) => Err(e),
}
}
fn set_default_device(&mut self, name: &str) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self
.handler
.context
.borrow_mut()
.set_default_source(name, move |res| success_ref.borrow_mut().clone_from(&res));
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn list_devices(&mut self) -> Result<Vec<DeviceInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_source_info_list(
move |sink_list: ListResult<&introspect::SourceInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_device_by_index(&mut self, index: u32) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_source_info_by_index(
index,
move |sink_list: ListResult<&introspect::SourceInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_device_by_name(&mut self, name: &str) -> Result<DeviceInfo, ControllerError> {
let device = Rc::new(RefCell::new(Some(None)));
let dev_ref = device.clone();
let op = self.handler.introspect.get_source_info_by_name(
name,
move |sink_list: ListResult<&introspect::SourceInfo>| {
if let ListResult::Item(item) = sink_list {
dev_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = device.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn set_device_volume_by_index(&mut self, index: u32, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_source_volume_by_index(index, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn set_device_volume_by_name(&mut self, name: &str, volume: &ChannelVolumes) {
let op = self
.handler
.introspect
.set_source_volume_by_name(name, volume, None);
self.handler.wait_for_operation(op).ok();
}
fn increase_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_source_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_device_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut dev_ref) = self.get_device_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = dev_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_source_volume_by_index(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
}
impl AppControl<ApplicationInfo> for SourceController {
fn list_applications(&mut self) -> Result<Vec<ApplicationInfo>, ControllerError> {
let list = Rc::new(RefCell::new(Some(Vec::new())));
let list_ref = list.clone();
let op = self.handler.introspect.get_source_output_info_list(
move |sink_list: ListResult<&introspect::SourceOutputInfo>| {
if let ListResult::Item(item) = sink_list {
list_ref.borrow_mut().as_mut().unwrap().push(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = list.borrow_mut();
result.take().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn get_app_by_index(&mut self, index: u32) -> Result<ApplicationInfo, ControllerError> {
let app = Rc::new(RefCell::new(Some(None)));
let app_ref = app.clone();
let op = self.handler.introspect.get_source_output_info(
index,
move |sink_list: ListResult<&introspect::SourceOutputInfo>| {
if let ListResult::Item(item) = sink_list {
app_ref.borrow_mut().as_mut().unwrap().replace(item.into());
}
},
);
self.handler.wait_for_operation(op)?;
let mut result = app.borrow_mut();
result.take().unwrap().ok_or(ControllerError::new(
GetInfoError,
"Error getting application list",
))
}
fn increase_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.increase(new_vol) {
let op = self
.handler
.introspect
.set_source_output_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn decrease_app_volume_by_percent(&mut self, index: u32, delta: f64) {
if let Ok(mut app_ref) = self.get_app_by_index(index) {
let new_vol = Volume::from(Volume(volume_from_percent(delta) as u32));
if let Some(volumes) = app_ref.volume.decrease(new_vol) {
let op = self
.handler
.introspect
.set_source_output_volume(index, &volumes, None);
self.handler.wait_for_operation(op).ok();
}
}
}
fn move_app_by_index(
&mut self,
stream_index: u32,
device_index: u32,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_source_output_by_index(
stream_index,
device_index,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn move_app_by_name(
&mut self,
stream_index: u32,
device_name: &str,
) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.move_source_output_by_name(
stream_index,
device_name,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
fn set_app_mute(&mut self, index: u32, mute: bool) -> Result<bool, ControllerError> {
let success = Rc::new(RefCell::new(false));
let success_ref = success.clone();
let op = self.handler.introspect.set_source_mute_by_index(
index,
mute,
Some(Box::new(move |res| {
success_ref.borrow_mut().clone_from(&res)
})),
);
self.handler.wait_for_operation(op)?;
let result = success.borrow_mut().clone();
Ok(result)
}
}

View File

@@ -1,354 +0,0 @@
use pulse::{
channelmap,
context::introspect,
def,
def::PortAvailable,
format,
proplist::Proplist,
sample,
time::MicroSeconds,
volume::{ChannelVolumes, Volume},
};
/// These structs are direct representations of what libpulse_binding gives
/// created to be copyable / cloneable for use in and out of callbacks
/// This is a wrapper around SinkPortInfo and SourcePortInfo as they have the same members
#[derive(Clone)]
pub struct DevicePortInfo {
/// Name of the sink.
pub name: Option<String>,
/// Description of this sink.
pub description: Option<String>,
/// The higher this value is, the more useful this port is as a default.
pub priority: u32,
/// A flag indicating availability status of this port.
pub available: PortAvailable,
}
impl<'a> From<&'a Box<introspect::SinkPortInfo<'a>>> for DevicePortInfo {
fn from(item: &'a Box<introspect::SinkPortInfo<'a>>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
impl<'a> From<&'a introspect::SinkPortInfo<'a>> for DevicePortInfo {
fn from(item: &'a introspect::SinkPortInfo<'a>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
impl<'a> From<&'a Box<introspect::SourcePortInfo<'a>>> for DevicePortInfo {
fn from(item: &'a Box<introspect::SourcePortInfo<'a>>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
impl<'a> From<&'a introspect::SourcePortInfo<'a>> for DevicePortInfo {
fn from(item: &'a introspect::SourcePortInfo<'a>) -> Self {
DevicePortInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
description: item.description.as_ref().map(|cow| cow.to_string()),
priority: item.priority,
available: item.available,
}
}
}
/// This is a wrapper around SinkState and SourceState as they have the same values
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum DevState {
/// This state is used when the server does not support sink state introspection.
Invalid = -1,
/// Running, sink is playing and used by at least one non-corked sink-input.
Running = 0,
/// When idle, the sink is playing but there is no non-corked sink-input attached to it.
Idle = 1,
/// When suspended, actual sink access can be closed, for instance.
Suspended = 2,
}
impl<'a> From<def::SourceState> for DevState {
fn from(s: def::SourceState) -> Self {
match s {
def::SourceState::Idle => DevState::Idle,
def::SourceState::Invalid => DevState::Invalid,
def::SourceState::Running => DevState::Running,
def::SourceState::Suspended => DevState::Suspended,
}
}
}
impl<'a> From<def::SinkState> for DevState {
fn from(s: def::SinkState) -> Self {
match s {
def::SinkState::Idle => DevState::Idle,
def::SinkState::Invalid => DevState::Invalid,
def::SinkState::Running => DevState::Running,
def::SinkState::Suspended => DevState::Suspended,
}
}
}
#[derive(Clone)]
pub enum Flags {
SourceFLags(def::SourceFlagSet),
SinkFlags(def::SinkFlagSet),
}
#[derive(Clone)]
pub struct DeviceInfo {
/// Index of the sink.
pub index: u32,
/// Name of the sink.
pub name: Option<String>,
/// Description of this sink.
pub description: Option<String>,
/// Sample spec of this sink.
pub sample_spec: sample::Spec,
/// Channel map.
pub channel_map: channelmap::Map,
/// Index of the owning module of this sink, or `None` if is invalid.
pub owner_module: Option<u32>,
/// Volume of the sink.
pub volume: ChannelVolumes,
/// Mute switch of the sink.
pub mute: bool,
/// Index of the monitor source connected to this sink.
pub monitor: Option<u32>,
/// The name of the monitor source.
pub monitor_name: Option<String>,
/// Length of queued audio in the output buffer.
pub latency: MicroSeconds,
/// Driver name.
pub driver: Option<String>,
/// Flags.
pub flags: Flags,
/// Property list.
pub proplist: Proplist,
/// The latency this device has been configured to.
pub configured_latency: MicroSeconds,
/// Some kind of “base” volume that refers to unamplified/unattenuated volume in the context of
/// the output device.
pub base_volume: Volume,
/// State.
pub state: DevState,
/// Number of volume steps for sinks which do not support arbitrary volumes.
pub n_volume_steps: u32,
/// Card index, or `None` if invalid.
pub card: Option<u32>,
/// Set of available ports.
pub ports: Vec<DevicePortInfo>,
// Pointer to active port in the set, or None.
pub active_port: Option<DevicePortInfo>,
/// Set of formats supported by the sink.
pub formats: Vec<format::Info>,
}
impl<'a> From<&'a introspect::SinkInfo<'a>> for DeviceInfo {
fn from(item: &'a introspect::SinkInfo<'a>) -> Self {
DeviceInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
index: item.index,
description: item.description.as_ref().map(|cow| cow.to_string()),
sample_spec: item.sample_spec,
channel_map: item.channel_map,
owner_module: item.owner_module,
volume: item.volume,
mute: item.mute,
monitor: Some(item.monitor_source),
monitor_name: item.monitor_source_name.as_ref().map(|cow| cow.to_string()),
latency: item.latency,
driver: item.driver.as_ref().map(|cow| cow.to_string()),
flags: Flags::SinkFlags(item.flags),
proplist: item.proplist.clone(),
configured_latency: item.configured_latency,
base_volume: item.base_volume,
state: DevState::from(item.state),
n_volume_steps: item.n_volume_steps,
card: item.card,
ports: item.ports.iter().map(From::from).collect(),
active_port: item.active_port.as_ref().map(From::from),
formats: item.formats.clone(),
}
}
}
impl<'a> From<&'a introspect::SourceInfo<'a>> for DeviceInfo {
fn from(item: &'a introspect::SourceInfo<'a>) -> Self {
DeviceInfo {
name: item.name.as_ref().map(|cow| cow.to_string()),
index: item.index,
description: item.description.as_ref().map(|cow| cow.to_string()),
sample_spec: item.sample_spec,
channel_map: item.channel_map,
owner_module: item.owner_module,
volume: item.volume,
mute: item.mute,
monitor: item.monitor_of_sink,
monitor_name: item
.monitor_of_sink_name
.as_ref()
.map(|cow| cow.to_string()),
latency: item.latency,
driver: item.driver.as_ref().map(|cow| cow.to_string()),
flags: Flags::SourceFLags(item.flags),
proplist: item.proplist.clone(),
configured_latency: item.configured_latency,
base_volume: item.base_volume,
state: DevState::from(item.state),
n_volume_steps: item.n_volume_steps,
card: item.card,
ports: item.ports.iter().map(From::from).collect(),
active_port: item.active_port.as_ref().map(From::from),
formats: item.formats.clone(),
}
}
}
#[derive(Clone)]
pub struct ApplicationInfo {
/// Index of the sink input.
pub index: u32,
/// Name of the sink input.
pub name: Option<String>,
/// Index of the module this sink input belongs to, or `None` when it does not belong to any
/// module.
pub owner_module: Option<u32>,
/// Index of the client this sink input belongs to, or invalid when it does not belong to any
/// client.
pub client: Option<u32>,
/// Index of the connected sink/source.
pub connection_id: u32,
/// The sample specification of the sink input.
pub sample_spec: sample::Spec,
/// Channel map.
pub channel_map: channelmap::Map,
/// The volume of this sink input.
pub volume: ChannelVolumes,
/// Latency due to buffering in sink input, see
/// [`def::TimingInfo`](../../def/struct.TimingInfo.html) for details.
pub buffer_usec: MicroSeconds,
/// Latency of the sink device, see
/// [`def::TimingInfo`](../../def/struct.TimingInfo.html) for details.
pub connection_usec: MicroSeconds,
/// The resampling method used by this sink input.
pub resample_method: Option<String>,
/// Driver name.
pub driver: Option<String>,
/// Stream muted.
pub mute: bool,
/// Property list.
pub proplist: Proplist,
/// Stream corked.
pub corked: bool,
/// Stream has volume. If not set, then the meaning of this structs volume member is unspecified.
pub has_volume: bool,
/// The volume can be set. If not set, the volume can still change even though clients cant
/// control the volume.
pub volume_writable: bool,
/// Stream format information.
pub format: format::Info,
}
impl<'a> From<&'a introspect::SinkInputInfo<'a>> for ApplicationInfo {
fn from(item: &'a introspect::SinkInputInfo<'a>) -> Self {
ApplicationInfo {
index: item.index,
name: item.name.as_ref().map(|cow| cow.to_string()),
owner_module: item.owner_module,
client: item.client,
connection_id: item.sink,
sample_spec: item.sample_spec,
channel_map: item.channel_map,
volume: item.volume,
buffer_usec: item.buffer_usec,
connection_usec: item.sink_usec,
resample_method: item.resample_method.as_ref().map(|cow| cow.to_string()),
driver: item.driver.as_ref().map(|cow| cow.to_string()),
mute: item.mute,
proplist: item.proplist.clone(),
corked: item.corked,
has_volume: item.has_volume,
volume_writable: item.volume_writable,
format: item.format.clone(),
}
}
}
impl<'a> From<&'a introspect::SourceOutputInfo<'a>> for ApplicationInfo {
fn from(item: &'a introspect::SourceOutputInfo<'a>) -> Self {
ApplicationInfo {
index: item.index,
name: item.name.as_ref().map(|cow| cow.to_string()),
owner_module: item.owner_module,
client: item.client,
connection_id: item.source,
sample_spec: item.sample_spec,
channel_map: item.channel_map,
volume: item.volume,
buffer_usec: item.buffer_usec,
connection_usec: item.source_usec,
resample_method: item.resample_method.as_ref().map(|cow| cow.to_string()),
driver: item.driver.as_ref().map(|cow| cow.to_string()),
mute: item.mute,
proplist: item.proplist.clone(),
corked: item.corked,
has_volume: item.has_volume,
volume_writable: item.volume_writable,
format: item.format.clone(),
}
}
}
pub struct ServerInfo {
/// User name of the daemon process.
pub user_name: Option<String>,
/// Host name the daemon is running on.
pub host_name: Option<String>,
/// Version string of the daemon.
pub server_version: Option<String>,
/// Server package name (usually “pulseaudio”).
pub server_name: Option<String>,
/// Default sample specification.
pub sample_spec: sample::Spec,
/// Name of default sink.
pub default_sink_name: Option<String>,
/// Name of default source.
pub default_source_name: Option<String>,
/// A random cookie for identifying this instance of PulseAudio.
pub cookie: u32,
/// Default channel map.
pub channel_map: channelmap::Map,
}
impl<'a> From<&'a introspect::ServerInfo<'a>> for ServerInfo {
fn from(info: &'a introspect::ServerInfo<'a>) -> Self {
ServerInfo {
user_name: info.user_name.as_ref().map(|cow| cow.to_string()),
host_name: info.host_name.as_ref().map(|cow| cow.to_string()),
server_version: info.server_version.as_ref().map(|cow| cow.to_string()),
server_name: info.server_name.as_ref().map(|cow| cow.to_string()),
sample_spec: info.sample_spec,
default_sink_name: info.default_sink_name.as_ref().map(|cow| cow.to_string()),
default_source_name: info.default_source_name.as_ref().map(|cow| cow.to_string()),
cookie: info.cookie,
channel_map: info.channel_map,
}
}
}

View File

@@ -1,54 +0,0 @@
use std::fmt;
use pulse::error::{PAErr};
impl From<PAErr> for PulseCtlError {
fn from(error: PAErr) -> Self {
PulseCtlError {
error: PulseCtlErrorType::PulseAudioError,
message: format!("PulseAudio returned error: {}", error.to_string().unwrap_or("Unknown".to_owned())),
}
}
}
impl fmt::Debug for PulseCtlError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut error_string = String::new();
match self.error {
PulseCtlErrorType::ConnectError => {
error_string.push_str("ConnectError");
}
PulseCtlErrorType::OperationError => {
error_string.push_str("OperationError");
}
PulseCtlErrorType::PulseAudioError => {
error_string.push_str("PulseAudioError");
}
}
write!(f, "[{}]: {}", error_string, self.message)
}
}
pub(crate) enum PulseCtlErrorType {
ConnectError,
OperationError,
PulseAudioError,
}
/// Error thrown when PulseAudio throws an error code, there are 3 variants
/// `PulseCtlErrorType::ConnectError` when there's an error establishing a connection
/// `PulseCtlErrorType::OperationError` when the requested operation quis unexpecdatly or is cancelled
/// `PulseCtlErrorType::PulseAudioError` when PulseAudio returns an error code in any circumstance
pub struct PulseCtlError {
error: PulseCtlErrorType,
message: String,
}
impl PulseCtlError {
pub(crate) fn new(err: PulseCtlErrorType, msg: &str) -> Self {
PulseCtlError {
error: err,
message: msg.to_string(),
}
}
}

View File

@@ -1,166 +0,0 @@
/// `pulsectl` is a high level wrapper around the PulseAudio bindings supplied by
/// `libpulse_binding`. It provides simple access to sinks, inputs, sources and outputs allowing
/// one to write audio control programs with ease.
///
/// ## Quick Example
///
/// The following example demonstrates listing all of the playback devices currently connected
///
/// See examples/change_device_vol.rs for a more complete example
/// ```no_run
/// extern crate pulsectl;
///
/// use std::io;
///
/// use pulsectl::controllers::SinkController;
/// use pulsectl::controllers::DeviceControl;
/// fn main() {
/// // create handler that calls functions on playback devices and apps
/// let mut handler = SinkController::create().unwrap();
/// let devices = handler
/// .list_devices()
/// .expect("Could not get list of playback devices");
///
/// println!("Playback Devices");
/// for dev in devices.clone() {
/// println!(
/// "[{}] {}, Volume: {}",
/// dev.index,
/// dev.description.as_ref().unwrap(),
/// dev.volume.print()
/// );
/// }
/// }
/// ```
extern crate libpulse_binding as pulse;
use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;
use pulse::{
context::{introspect, Context},
mainloop::standard::{IterateResult, Mainloop},
operation::{Operation, State},
proplist::Proplist,
};
use crate::errors::{PulseCtlError, PulseCtlErrorType::*};
pub mod controllers;
mod errors;
pub struct Handler {
pub mainloop: Rc<RefCell<Mainloop>>,
pub context: Rc<RefCell<Context>>,
pub introspect: introspect::Introspector,
}
fn connect_error(err: &str) -> PulseCtlError {
PulseCtlError::new(ConnectError, err)
}
impl Handler {
pub fn connect(name: &str) -> Result<Handler, PulseCtlError> {
let mut proplist = Proplist::new().unwrap();
proplist
.set_str(pulse::proplist::properties::APPLICATION_NAME, name)
.unwrap();
let mainloop;
if let Some(m) = Mainloop::new() {
mainloop = Rc::new(RefCell::new(m));
} else {
return Err(connect_error("Failed to create mainloop"));
}
let context;
if let Some(c) =
Context::new_with_proplist(mainloop.borrow().deref(), "MainConn", &proplist)
{
context = Rc::new(RefCell::new(c));
} else {
return Err(connect_error("Failed to create new context"));
}
context
.borrow_mut()
.connect(None, pulse::context::flags::NOFLAGS, None)
.map_err(|_| connect_error("Failed to connect context"))?;
loop {
match mainloop.borrow_mut().iterate(false) {
IterateResult::Err(e) => {
eprintln!("iterate state was not success, quitting...");
return Err(e.into());
}
IterateResult::Success(_) => {}
IterateResult::Quit(_) => {
eprintln!("iterate state was not success, quitting...");
return Err(PulseCtlError::new(
ConnectError,
"Iterate state quit without an error",
));
}
}
match context.borrow().get_state() {
pulse::context::State::Ready => break,
pulse::context::State::Failed | pulse::context::State::Terminated => {
eprintln!("context state failed/terminated, quitting...");
return Err(PulseCtlError::new(
ConnectError,
"Context state failed/terminated without an error",
));
}
_ => {}
}
}
let introspect = context.borrow_mut().introspect();
Ok(Handler {
mainloop,
context,
introspect,
})
}
// loop until the passed operation is completed
pub fn wait_for_operation<G: ?Sized>(
&mut self,
op: Operation<G>,
) -> Result<(), errors::PulseCtlError> {
loop {
match self.mainloop.borrow_mut().iterate(false) {
IterateResult::Err(e) => return Err(e.into()),
IterateResult::Success(_) => {}
IterateResult::Quit(_) => {
return Err(PulseCtlError::new(
OperationError,
"Iterate state quit without an error",
));
}
}
match op.get_state() {
State::Done => {
break;
}
State::Running => {}
State::Cancelled => {
return Err(PulseCtlError::new(
OperationError,
"Operation cancelled without an error",
));
}
}
}
Ok(())
}
}
impl Drop for Handler {
fn drop(&mut self) {
self.context.borrow_mut().disconnect();
self.mainloop.borrow_mut().quit(pulse::def::Retval(0));
}
}

View File

@@ -9,6 +9,9 @@ license = "MIT"
authors = ["Ram <quadrupleslap@gmail.com>"]
edition = "2018"
[features]
wayland = ["gstreamer", "gstreamer-app", "gstreamer-video", "dbus", "tracing"]
[dependencies]
block = "0.1"
cfg-if = "1.0"
@@ -18,7 +21,7 @@ num_cpus = "1.13"
[dependencies.winapi]
version = "0.3"
default-features = true
features = ["dxgi", "dxgi1_2", "dxgi1_5", "d3d11"]
features = ["dxgi", "dxgi1_2", "dxgi1_5", "d3d11", "winuser"]
[dev-dependencies]
repng = "0.2"
@@ -29,4 +32,11 @@ quest = "0.3"
[build-dependencies]
target_build_utils = "0.3"
bindgen = "0.53"
bindgen = "0.59"
[target.'cfg(target_os = "linux")'.dependencies]
dbus = { version = "0.9", optional = true }
tracing = { version = "0.1", optional = true }
gstreamer = { version = "0.16", optional = true }
gstreamer-app = { version = "0.16", features = ["v1_10"], optional = true }
gstreamer-video = { version = "0.16", optional = true }

View File

@@ -1,3 +1,5 @@
Derived from https://github.com/quadrupleslap/scrap
# scrap
Scrap records your screen! At least it does if you're on Windows, macOS, or Linux.

View File

@@ -12,25 +12,21 @@ fn find_package(name: &str) -> Vec<PathBuf> {
target_arch = "x64".to_owned();
} else if target_arch == "aarch64" {
target_arch = "arm64".to_owned();
} else {
target_arch = "arm".to_owned();
}
let target = if target_os == "macos" {
let mut target = if target_os == "macos" {
"x64-osx".to_owned()
} else if target_os == "windows" {
"x64-windows-static".to_owned()
} else if target_os == "android" {
format!("{}-android-static", target_arch)
} else {
"x64-linux".to_owned()
format!("{}-{}", target_arch, target_os)
};
if target_arch == "x86" {
target = target.replace("x64", "x86");
}
println!("cargo:info={}", target);
path.push("installed");
path.push(target);
let mut lib = name.trim_start_matches("lib").to_string();
if lib == "vpx" && target_os == "windows" {
lib = format!("{}mt", lib);
}
let lib = name.trim_start_matches("lib").to_string();
println!("{}", format!("cargo:rustc-link-lib=static={}", lib));
println!(
"{}",
@@ -52,9 +48,9 @@ fn generate_bindings(
) {
let mut b = bindgen::builder()
.header(ffi_header.to_str().unwrap())
.whitelist_type("^[vV].*")
.whitelist_var("^[vV].*")
.whitelist_function("^[vV].*")
.allowlist_type("^[vV].*")
.allowlist_var("^[vV].*")
.allowlist_function("^[vV].*")
.rustified_enum("^v.*")
.trust_clang_mangling(false)
.layout_tests(false) // breaks 32/64-bit compat
@@ -93,7 +89,7 @@ fn main() {
// then set x64 to default by "rustup default stable-x86_64-pc-windows-msvc"
let target = target_build_utils::TargetInfo::new();
if target.unwrap().target_pointer_width() != "64" {
panic!("Only support 64bit system");
// panic!("Only support 64bit system");
}
env::remove_var("CARGO_CFG_TARGET_FEATURE");
env::set_var("CARGO_CFG_TARGET_FEATURE", "crt-static");

View File

@@ -43,7 +43,6 @@ struct Args {
flag_time: Option<u64>,
flag_fps: u64,
flag_bv: u32,
flag_ba: u32,
}
#[derive(Debug, serde::Deserialize)]

View File

@@ -23,6 +23,10 @@ fn record(i: usize) {
let one_second = Duration::new(1, 0);
let one_frame = one_second / 60;
for d in Display::all().unwrap() {
println!("{:?} {} {}", d.origin(), d.width(), d.height());
}
let display = get_display(i);
let mut capturer = Capturer::new(display, false).expect("Couldn't begin capture.");
let (w, h) = (capturer.width(), capturer.height());

View File

@@ -66,7 +66,7 @@ macro_rules! call_vpx {
macro_rules! call_vpx_ptr {
($x:expr) => {{
let result = unsafe { $x }; // original expression
let result_int = unsafe { std::mem::transmute::<_, i64>(result) };
let result_int = unsafe { std::mem::transmute::<_, isize>(result) };
if result_int == 0 {
return Err(Error::BadPtr(format!(
"errcode={} {}:{}:{}:{}",

View File

@@ -9,8 +9,8 @@ extern "C" {
src_stride_argb: c_int,
dst_argb: *mut u8,
dst_stride_argb: c_int,
width: c_int,
height: c_int,
src_width: c_int,
src_height: c_int,
mode: c_int,
) -> c_int;

View File

@@ -62,13 +62,23 @@ pub struct Display(dxgi::Display);
impl Display {
pub fn primary() -> io::Result<Display> {
match dxgi::Displays::new()?.next() {
Some(inner) => Ok(Display(inner)),
None => Err(NotFound.into()),
}
// not implemented yet
Err(NotFound.into())
}
pub fn all() -> io::Result<Vec<Display>> {
let tmp = Self::all_().unwrap_or(Default::default());
if tmp.is_empty() {
println!("Display got from gdi");
return Ok(dxgi::Displays::get_from_gdi()
.drain(..)
.map(Display)
.collect::<Vec<_>>());
}
Ok(tmp)
}
fn all_() -> io::Result<Vec<Display>> {
Ok(dxgi::Displays::new()?.map(Display).collect::<Vec<_>>())
}
@@ -92,13 +102,12 @@ impl Display {
self.0.is_online()
}
pub fn origin(&self) -> (usize, usize) {
let o = self.0.origin();
(o.0 as usize, o.1 as usize)
pub fn origin(&self) -> (i32, i32) {
self.0.origin()
}
// to-do: not found primary display api for dxgi
pub fn is_primary(&self) -> bool {
self.name() == Self::primary().unwrap().name()
// https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-devmodea
self.origin() == (0, 0)
}
}

View File

@@ -0,0 +1,117 @@
use crate::common::{
wayland,
x11::{self, Frame},
};
use std::io;
pub enum Capturer {
X11(x11::Capturer),
WAYLAND(wayland::Capturer),
}
impl Capturer {
pub fn new(display: Display, yuv: bool) -> io::Result<Capturer> {
Ok(match display {
Display::X11(d) => Capturer::X11(x11::Capturer::new(d, yuv)?),
Display::WAYLAND(d) => Capturer::WAYLAND(wayland::Capturer::new(d, yuv)?),
})
}
pub fn width(&self) -> usize {
match self {
Capturer::X11(d) => d.width(),
Capturer::WAYLAND(d) => d.width(),
}
}
pub fn height(&self) -> usize {
match self {
Capturer::X11(d) => d.height(),
Capturer::WAYLAND(d) => d.height(),
}
}
pub fn frame<'a>(&'a mut self, timeout_ms: u32) -> io::Result<Frame<'a>> {
match self {
Capturer::X11(d) => d.frame(timeout_ms),
Capturer::WAYLAND(d) => d.frame(timeout_ms),
}
}
}
pub enum Display {
X11(x11::Display),
WAYLAND(wayland::Display),
}
#[inline]
fn is_wayland() -> bool {
std::env::var("IS_WAYLAND").is_ok()
|| std::env::var("XDG_SESSION_TYPE") == Ok("wayland".to_owned())
}
impl Display {
pub fn primary() -> io::Result<Display> {
Ok(if is_wayland() {
Display::WAYLAND(wayland::Display::primary()?)
} else {
Display::X11(x11::Display::primary()?)
})
}
pub fn all() -> io::Result<Vec<Display>> {
Ok(if is_wayland() {
wayland::Display::all()?
.drain(..)
.map(|x| Display::WAYLAND(x))
.collect()
} else {
x11::Display::all()?
.drain(..)
.map(|x| Display::X11(x))
.collect()
})
}
pub fn width(&self) -> usize {
match self {
Display::X11(d) => d.width(),
Display::WAYLAND(d) => d.width(),
}
}
pub fn height(&self) -> usize {
match self {
Display::X11(d) => d.height(),
Display::WAYLAND(d) => d.height(),
}
}
pub fn origin(&self) -> (i32, i32) {
match self {
Display::X11(d) => d.origin(),
Display::WAYLAND(d) => d.origin(),
}
}
pub fn is_online(&self) -> bool {
match self {
Display::X11(d) => d.is_online(),
Display::WAYLAND(d) => d.is_online(),
}
}
pub fn is_primary(&self) -> bool {
match self {
Display::X11(d) => d.is_primary(),
Display::WAYLAND(d) => d.is_primary(),
}
}
pub fn name(&self) -> String {
match self {
Display::X11(d) => d.name(),
Display::WAYLAND(d) => d.name(),
}
}
}

View File

@@ -5,8 +5,17 @@ cfg_if! {
mod quartz;
pub use self::quartz::*;
} else if #[cfg(x11)] {
cfg_if! {
if #[cfg(feature="wayland")] {
mod linux;
mod wayland;
mod x11;
pub use self::linux::*;
} else {
mod x11;
pub use self::x11::*;
}
}
} else if #[cfg(dxgi)] {
mod dxgi;
pub use self::dxgi::*;

View File

@@ -114,9 +114,9 @@ impl Display {
self.0.is_online()
}
pub fn origin(&self) -> (usize, usize) {
pub fn origin(&self) -> (i32, i32) {
let o = self.0.bounds().origin;
(o.x as usize, o.y as usize)
(o.x as _, o.y as _)
}
pub fn is_primary(&self) -> bool {

View File

@@ -0,0 +1,81 @@
use crate::common::x11::Frame;
use crate::wayland::{capturable::*, *};
use std::io;
pub struct Capturer(Display, Box<dyn Recorder>, bool, Vec<u8>);
fn map_err<E: ToString>(err: E) -> io::Error {
io::Error::new(io::ErrorKind::Other, err.to_string())
}
impl Capturer {
pub fn new(display: Display, yuv: bool) -> io::Result<Capturer> {
let r = display.0.recorder(false).map_err(map_err)?;
Ok(Capturer(display, r, yuv, Default::default()))
}
pub fn width(&self) -> usize {
self.0.width()
}
pub fn height(&self) -> usize {
self.0.height()
}
pub fn frame<'a>(&'a mut self, timeout_ms: u32) -> io::Result<Frame<'a>> {
match self.1.capture(timeout_ms as _).map_err(map_err)? {
PixelProvider::BGR0(w, h, x) => Ok(Frame(if self.2 {
crate::common::bgra_to_i420(w as _, h as _, &x, &mut self.3);
&self.3[..]
} else {
x
})),
PixelProvider::NONE => Err(std::io::ErrorKind::WouldBlock.into()),
_ => Err(map_err("Invalid data")),
}
}
}
pub struct Display(pipewire::PipeWireCapturable);
impl Display {
pub fn primary() -> io::Result<Display> {
let mut all = Display::all()?;
if all.is_empty() {
return Err(io::ErrorKind::NotFound.into());
}
Ok(all.remove(0))
}
pub fn all() -> io::Result<Vec<Display>> {
Ok(pipewire::get_capturables(false)
.map_err(map_err)?
.drain(..)
.map(|x| Display(x))
.collect())
}
pub fn width(&self) -> usize {
self.0.size.0
}
pub fn height(&self) -> usize {
self.0.size.1
}
pub fn origin(&self) -> (i32, i32) {
self.0.position
}
pub fn is_online(&self) -> bool {
true
}
pub fn is_primary(&self) -> bool {
false
}
pub fn name(&self) -> String {
"".to_owned()
}
}

View File

@@ -21,7 +21,7 @@ impl Capturer {
}
}
pub struct Frame<'a>(&'a [u8]);
pub struct Frame<'a>(pub(crate) &'a [u8]);
impl<'a> ops::Deref for Frame<'a> {
type Target = [u8];
@@ -68,7 +68,7 @@ impl Display {
self.0.rect().h as usize
}
pub fn origin(&self) -> (usize, usize) {
pub fn origin(&self) -> (i32, i32) {
let r = self.0.rect();
(r.x as _, r.y as _)
}

View File

@@ -13,6 +13,7 @@ use winapi::{
BITMAPINFO,
BITMAPINFOHEADER,
BI_RGB,
CAPTUREBLT,
DIB_RGB_COLORS, //CAPTUREBLT,
HGDI_ERROR,
RGBQUAD,
@@ -97,7 +98,7 @@ impl CapturerGDI {
self.screen_dc,
0,
0,
SRCCOPY, // | CAPTUREBLT, // CAPTUREBLT enable layered window but also make cursor blinking
SRCCOPY | CAPTUREBLT, // CAPTUREBLT enable layered window but also make cursor blinking
);
if res == 0 {
return Err("Failed to copy screen to Windows buffer".into());

View File

@@ -3,46 +3,50 @@ pub mod gdi;
pub use gdi::CapturerGDI;
use winapi::{
shared::dxgi::{
CreateDXGIFactory1, IDXGIAdapter1, IDXGIFactory1, IDXGIResource, IDXGISurface,
IID_IDXGIFactory1, IID_IDXGISurface, DXGI_MAP_READ, DXGI_OUTPUT_DESC,
DXGI_RESOURCE_PRIORITY_MAXIMUM,
shared::{
dxgi::*,
dxgi1_2::*,
dxgitype::*,
minwindef::{DWORD, FALSE, TRUE, UINT},
ntdef::LONG,
windef::HMONITOR,
winerror::*,
// dxgiformat::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_420_OPAQUE},
},
shared::dxgi1_2::IDXGIOutputDuplication,
// shared::dxgiformat::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_420_OPAQUE},
shared::dxgi1_2::{IDXGIOutput1, IID_IDXGIOutput1},
shared::dxgitype::DXGI_MODE_ROTATION,
shared::minwindef::{TRUE, UINT},
shared::ntdef::LONG,
shared::windef::HMONITOR,
shared::winerror::{
DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_INVALID_CALL, DXGI_ERROR_NOT_CURRENTLY_AVAILABLE,
DXGI_ERROR_SESSION_DISCONNECTED, DXGI_ERROR_UNSUPPORTED, DXGI_ERROR_WAIT_TIMEOUT,
E_ACCESSDENIED, E_INVALIDARG, S_OK,
um::{
d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown, wingdi::*,
winnt::HRESULT, winuser::*,
},
um::d3d11::{
D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D, IID_ID3D11Texture2D,
D3D11_CPU_ACCESS_READ, D3D11_SDK_VERSION, D3D11_USAGE_STAGING,
},
um::d3dcommon::D3D_DRIVER_TYPE_UNKNOWN,
um::winnt::HRESULT,
};
//TODO: Split up into files.
pub struct ComPtr<T>(*mut T);
impl<T> ComPtr<T> {
fn is_null(&self) -> bool {
self.0.is_null()
}
}
impl<T> Drop for ComPtr<T> {
fn drop(&mut self) {
unsafe {
if !self.is_null() {
(*(self.0 as *mut IUnknown)).Release();
}
}
}
}
pub struct Capturer {
device: *mut ID3D11Device,
device: ComPtr<ID3D11Device>,
display: Display,
context: *mut ID3D11DeviceContext,
duplication: *mut IDXGIOutputDuplication,
context: ComPtr<ID3D11DeviceContext>,
duplication: ComPtr<IDXGIOutputDuplication>,
fastlane: bool,
surface: *mut IDXGISurface,
data: *const u8,
len: usize,
surface: ComPtr<IDXGISurface>,
width: usize,
height: usize,
use_yuv: bool,
yuv: Vec<u8>,
rotated: Vec<u8>,
gdi_capturer: Option<CapturerGDI>,
gdi_buffer: Vec<u8>,
}
@@ -55,9 +59,12 @@ impl Capturer {
let mut desc = unsafe { mem::MaybeUninit::uninit().assume_init() };
let mut gdi_capturer = None;
let mut res = wrap_hresult(unsafe {
let mut res = if display.gdi {
wrap_hresult(1)
} else {
wrap_hresult(unsafe {
D3D11CreateDevice(
display.adapter as *mut _,
display.adapter.0 as *mut _,
D3D_DRIVER_TYPE_UNKNOWN,
ptr::null_mut(), // No software rasterizer.
0, // No device flags.
@@ -68,7 +75,10 @@ impl Capturer {
ptr::null_mut(),
&mut context,
)
});
})
};
let device = ComPtr(device);
let context = ComPtr(context);
if res.is_err() {
gdi_capturer = display.create_gdi();
@@ -78,7 +88,7 @@ impl Capturer {
}
} else {
res = wrap_hresult(unsafe {
let hres = (*display.inner).DuplicateOutput(device as *mut _, &mut duplication);
let hres = (*display.inner.0).DuplicateOutput(device.0 as *mut _, &mut duplication);
if hres != S_OK {
gdi_capturer = display.create_gdi();
println!("Fallback to GDI");
@@ -118,17 +128,7 @@ impl Capturer {
});
}
if let Err(err) = res {
unsafe {
if !device.is_null() {
(*device).Release();
}
if !context.is_null() {
(*context).Release();
}
}
return Err(err);
}
res?;
if !duplication.is_null() {
unsafe {
@@ -139,16 +139,15 @@ impl Capturer {
Ok(Capturer {
device,
context,
duplication,
duplication: ComPtr(duplication),
fastlane: desc.DesktopImageInSystemMemory == TRUE,
surface: ptr::null_mut(),
surface: ComPtr(ptr::null_mut()),
width: display.width() as usize,
height: display.height() as usize,
display,
data: ptr::null(),
len: 0,
use_yuv,
yuv: Vec::new(),
rotated: Vec::new(),
gdi_capturer,
gdi_buffer: Vec::new(),
})
@@ -168,41 +167,25 @@ impl Capturer {
self.gdi_capturer.take();
}
unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<()> {
unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<(*const u8, i32)> {
let mut frame = ptr::null_mut();
let mut info = mem::MaybeUninit::uninit().assume_init();
self.data = ptr::null();
wrap_hresult((*self.duplication).AcquireNextFrame(timeout, &mut info, &mut frame))?;
wrap_hresult((*self.duplication.0).AcquireNextFrame(timeout, &mut info, &mut frame))?;
let frame = ComPtr(frame);
if *info.LastPresentTime.QuadPart() == 0 {
return Err(std::io::ErrorKind::WouldBlock.into());
}
let mut rect = mem::MaybeUninit::uninit().assume_init();
if self.fastlane {
let mut rect = mem::MaybeUninit::uninit().assume_init();
let res = wrap_hresult((*self.duplication).MapDesktopSurface(&mut rect));
(*frame).Release();
if let Err(err) = res {
Err(err)
wrap_hresult((*self.duplication.0).MapDesktopSurface(&mut rect))?;
} else {
self.data = rect.pBits;
self.len = self.height * rect.Pitch as usize;
Ok(())
}
} else {
self.surface = ptr::null_mut();
self.surface = self.ohgodwhat(frame)?;
let mut rect = mem::MaybeUninit::uninit().assume_init();
wrap_hresult((*self.surface).Map(&mut rect, DXGI_MAP_READ))?;
self.data = rect.pBits;
self.len = self.height * rect.Pitch as usize;
Ok(())
self.surface = ComPtr(self.ohgodwhat(frame.0)?);
wrap_hresult((*self.surface.0).Map(&mut rect, DXGI_MAP_READ))?;
}
Ok((rect.pBits, rect.Pitch))
}
// copy from GPU memory to system memory
@@ -212,9 +195,10 @@ impl Capturer {
&IID_ID3D11Texture2D,
&mut texture as *mut *mut _ as *mut *mut _,
);
let texture = ComPtr(texture);
let mut texture_desc = mem::MaybeUninit::uninit().assume_init();
(*texture).GetDesc(&mut texture_desc);
(*texture.0).GetDesc(&mut texture_desc);
texture_desc.Usage = D3D11_USAGE_STAGING;
texture_desc.BindFlags = 0;
@@ -222,34 +206,24 @@ impl Capturer {
texture_desc.MiscFlags = 0;
let mut readable = ptr::null_mut();
let res = wrap_hresult((*self.device).CreateTexture2D(
wrap_hresult((*self.device.0).CreateTexture2D(
&mut texture_desc,
ptr::null(),
&mut readable,
));
if let Err(err) = res {
(*frame).Release();
(*texture).Release();
(*readable).Release();
Err(err)
} else {
))?;
(*readable).SetEvictionPriority(DXGI_RESOURCE_PRIORITY_MAXIMUM);
let readable = ComPtr(readable);
let mut surface = ptr::null_mut();
(*readable).QueryInterface(
(*readable.0).QueryInterface(
&IID_IDXGISurface,
&mut surface as *mut *mut _ as *mut *mut _,
);
(*self.context).CopyResource(readable as *mut _, texture as *mut _);
(*self.context.0).CopyResource(readable.0 as *mut _, texture.0 as *mut _);
(*frame).Release();
(*texture).Release();
(*readable).Release();
Ok(surface)
}
}
pub fn frame<'a>(&'a mut self, timeout: UINT) -> io::Result<&'a [u8]> {
unsafe {
@@ -265,20 +239,44 @@ impl Capturer {
}
}
} else {
if self.fastlane {
(*self.duplication).UnMapDesktopSurface();
self.unmap();
let r = self.load_frame(timeout)?;
let rotate = match self.display.rotation() {
DXGI_MODE_ROTATION_IDENTITY | DXGI_MODE_ROTATION_UNSPECIFIED => 0,
DXGI_MODE_ROTATION_ROTATE90 => 90,
DXGI_MODE_ROTATION_ROTATE180 => 180,
DXGI_MODE_ROTATION_ROTATE270 => 270,
_ => {
return Err(io::Error::new(
io::ErrorKind::Other,
"Unknown roration".to_string(),
));
}
};
if rotate == 0 {
slice::from_raw_parts(r.0, r.1 as usize * self.height)
} else {
if !self.surface.is_null() {
(*self.surface).Unmap();
(*self.surface).Release();
self.surface = ptr::null_mut();
self.rotated.resize(self.width * self.height * 4, 0);
crate::common::ARGBRotate(
r.0,
r.1,
self.rotated.as_mut_ptr(),
4 * self.width as i32,
if rotate == 180 {
self.width
} else {
self.height
} as _,
if rotate != 180 {
self.width
} else {
self.height
} as _,
rotate,
);
&self.rotated[..]
}
}
(*self.duplication).ReleaseFrame();
self.load_frame(timeout)?;
slice::from_raw_parts(self.data, self.len)
}
};
Ok({
if self.use_yuv {
@@ -295,31 +293,32 @@ impl Capturer {
})
}
}
fn unmap(&self) {
unsafe {
(*self.duplication.0).ReleaseFrame();
if self.fastlane {
(*self.duplication.0).UnMapDesktopSurface();
} else {
if !self.surface.is_null() {
(*self.surface.0).Unmap();
}
}
}
}
}
impl Drop for Capturer {
fn drop(&mut self) {
unsafe {
if !self.surface.is_null() {
(*self.surface).Unmap();
(*self.surface).Release();
}
if !self.duplication.is_null() {
(*self.duplication).Release();
}
if !self.device.is_null() {
(*self.device).Release();
}
if !self.context.is_null() {
(*self.context).Release();
}
self.unmap();
}
}
}
pub struct Displays {
factory: *mut IDXGIFactory1,
adapter: *mut IDXGIAdapter1,
factory: ComPtr<IDXGIFactory1>,
adapter: ComPtr<IDXGIAdapter1>,
/// Index of the CURRENT adapter.
nadapter: UINT,
/// Index of the NEXT display to fetch.
@@ -339,13 +338,63 @@ impl Displays {
};
Ok(Displays {
factory,
adapter,
factory: ComPtr(factory),
adapter: ComPtr(adapter),
nadapter: 0,
ndisplay: 0,
})
}
pub fn get_from_gdi() -> Vec<Display> {
let mut all = Vec::new();
let mut i: DWORD = 0;
loop {
let mut d: DISPLAY_DEVICEW = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
d.cb = std::mem::size_of::<DISPLAY_DEVICEW>() as _;
let ok = unsafe { EnumDisplayDevicesW(std::ptr::null(), i, &mut d as _, 0) };
if ok == FALSE {
break;
}
i += 1;
if 0 == (d.StateFlags & DISPLAY_DEVICE_ACTIVE)
|| (d.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) > 0
{
continue;
}
// let is_primary = (d.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) > 0;
let mut disp = Display {
inner: ComPtr(std::ptr::null_mut()),
adapter: ComPtr(std::ptr::null_mut()),
desc: unsafe { std::mem::zeroed() },
gdi: true,
};
disp.desc.DeviceName = d.DeviceName;
let mut m: DEVMODEW = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
m.dmSize = std::mem::size_of::<DEVMODEW>() as _;
m.dmDriverExtra = 0;
let ok = unsafe {
EnumDisplaySettingsExW(
disp.desc.DeviceName.as_ptr(),
ENUM_CURRENT_SETTINGS,
&mut m as _,
0,
)
};
if ok == FALSE {
continue;
}
disp.desc.DesktopCoordinates.left = unsafe { m.u1.s2().dmPosition.x };
disp.desc.DesktopCoordinates.top = unsafe { m.u1.s2().dmPosition.y };
disp.desc.DesktopCoordinates.right =
disp.desc.DesktopCoordinates.left + m.dmPelsWidth as i32;
disp.desc.DesktopCoordinates.bottom =
disp.desc.DesktopCoordinates.top + m.dmPelsHeight as i32;
disp.desc.AttachedToDesktop = 1;
all.push(disp);
}
all
}
// No Adapter => Some(None)
// Non-Empty Adapter => Some(Some(OUTPUT))
// End of Adapter => None
@@ -360,18 +409,15 @@ impl Displays {
let output = unsafe {
let mut output = ptr::null_mut();
(*self.adapter).EnumOutputs(self.ndisplay, &mut output);
output
(*self.adapter.0).EnumOutputs(self.ndisplay, &mut output);
ComPtr(output)
};
// If the current adapter is done, we free it.
// We return None so the caller gets the next adapter and tries again.
if output.is_null() {
unsafe {
(*self.adapter).Release();
self.adapter = ptr::null_mut();
}
self.adapter = ComPtr(ptr::null_mut());
return None;
}
@@ -383,7 +429,7 @@ impl Displays {
let desc = unsafe {
let mut desc = mem::MaybeUninit::uninit().assume_init();
(*output).GetDesc(&mut desc);
(*output.0).GetDesc(&mut desc);
desc
};
@@ -391,29 +437,26 @@ impl Displays {
let mut inner: *mut IDXGIOutput1 = ptr::null_mut();
unsafe {
(*output).QueryInterface(&IID_IDXGIOutput1, &mut inner as *mut *mut _ as *mut *mut _);
(*output).Release();
(*output.0).QueryInterface(&IID_IDXGIOutput1, &mut inner as *mut *mut _ as *mut *mut _);
}
// If it's null, we have an error.
// So we act like the adapter is done.
if inner.is_null() {
unsafe {
(*self.adapter).Release();
self.adapter = ptr::null_mut();
}
self.adapter = ComPtr(ptr::null_mut());
return None;
}
unsafe {
(*self.adapter).AddRef();
(*self.adapter.0).AddRef();
}
Some(Some(Display {
inner,
adapter: self.adapter,
inner: ComPtr(inner),
adapter: ComPtr(self.adapter.0),
desc,
gdi: false,
}))
}
}
@@ -431,8 +474,8 @@ impl Iterator for Displays {
self.adapter = unsafe {
let mut adapter = ptr::null_mut();
(*self.factory).EnumAdapters1(self.nadapter, &mut adapter);
adapter
(*self.factory.0).EnumAdapters1(self.nadapter, &mut adapter);
ComPtr(adapter)
};
if let Some(res) = self.read_and_invalidate() {
@@ -445,22 +488,17 @@ impl Iterator for Displays {
}
}
impl Drop for Displays {
fn drop(&mut self) {
unsafe {
(*self.factory).Release();
if !self.adapter.is_null() {
(*self.adapter).Release();
}
}
}
pub struct Display {
inner: ComPtr<IDXGIOutput1>,
adapter: ComPtr<IDXGIAdapter1>,
desc: DXGI_OUTPUT_DESC,
gdi: bool,
}
pub struct Display {
inner: *mut IDXGIOutput1,
adapter: *mut IDXGIAdapter1,
desc: DXGI_OUTPUT_DESC,
}
// optimized for updated region
// https://github.com/dchapyshev/aspia/blob/master/source/base/desktop/win/dxgi_output_duplicator.cc
// rotation
// https://github.com/bryal/dxgcap-rs/blob/master/src/lib.rs
impl Display {
pub fn width(&self) -> LONG {
@@ -509,15 +547,6 @@ impl Display {
}
}
impl Drop for Display {
fn drop(&mut self) {
unsafe {
(*self.inner).Release();
(*self.adapter).Release();
}
}
}
fn wrap_hresult(x: HRESULT) -> io::Result<()> {
use std::io::ErrorKind::*;
Err((match x {

View File

@@ -14,6 +14,9 @@ pub mod quartz;
#[cfg(x11)]
pub mod x11;
#[cfg(all(x11, feature="wayland"))]
pub mod wayland;
#[cfg(dxgi)]
pub mod dxgi;

View File

@@ -0,0 +1,3 @@
pub mod pipewire;
mod pipewire_dbus;
pub mod capturable;

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