Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
623f8ccf61 | ||
|
|
cd7b01a736 | ||
|
|
be8a3bf00c | ||
|
|
c7f212df2c | ||
|
|
7f5a401947 | ||
|
|
bbffc1de5a | ||
|
|
4b92080e3e | ||
|
|
0cbeb04730 | ||
|
|
1042a26deb | ||
|
|
53996e3c40 | ||
|
|
e400bb7554 | ||
|
|
392188596c | ||
|
|
c0750fb50c | ||
|
|
f705902ec3 | ||
|
|
0d36ac0cba |
Generated
+2
-2
@@ -3888,8 +3888,8 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
|
||||
|
||||
[[package]]
|
||||
name = "hwcodec"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/rustdesk-org/hwcodec#778df1f99597722473b29443bac22ae6c23946fe"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/rustdesk-org/hwcodec#febec27e1b40bb9fbbae02e9c59b71ac824b9fe1"
|
||||
dependencies = [
|
||||
"bindgen 0.59.2",
|
||||
"cc",
|
||||
|
||||
+8
-1
@@ -9,6 +9,10 @@
|
||||
<b>Kami membutuhkan bantuanmu untuk menterjemahkan file README dan <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> ke Bahasa Indonesia</b>
|
||||
</p>
|
||||
|
||||
> [!Caution]
|
||||
> **Peringatan Penyalahgunaan:** <br>
|
||||
> Pengembang RustDesk tidak membenarkan atau mendukung penggunaan perangkat lunak ini yang tidak etis atau melanggar hukum. Penyalahgunaan, seperti akses tanpa izin, pengambilalihan kendali, atau pelanggaran privasi, sangat dilarang berdasarkan pedoman kami. Para pengembang tidak bertanggung jawab atas penyalahgunaan aplikasi ini.
|
||||
|
||||
Mari mengobrol bersama kami: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
|
||||
|
||||
[](https://rustdesk.com/pricing.html)
|
||||
@@ -30,6 +34,9 @@ RustDesk mengajak semua orang untuk ikut berkontribusi. Lihat [`docs/CONTRIBUTIN
|
||||
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
|
||||
alt="Get it on F-Droid"
|
||||
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
|
||||
[<img src="https://flathub.org/api/badge?svg&locale=en"
|
||||
alt="Get it on Flathub"
|
||||
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
|
||||
|
||||
## Dependensi
|
||||
|
||||
@@ -154,7 +161,7 @@ Harap pastikan bahwa kamu menjalankan perintah ini dari repositori root RustDesk
|
||||
- **[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)**: Komunikasi dengan [rustdesk-server](https://github.com/rustdesk/rustdesk-server), menunggu untuk remote direct (TCP hole punching) atau relayed connection
|
||||
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: kode khusus platform
|
||||
|
||||
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: kode Flutter untuk platform desktop dan perangkat seluler
|
||||
## Snapshots
|
||||
|
||||

|
||||
|
||||
@@ -346,7 +346,7 @@ prebuild)
|
||||
pushd flutter
|
||||
|
||||
flutter clean
|
||||
flutter packages pub get
|
||||
flutter packages pub get --enforce-lockfile
|
||||
|
||||
popd # flutter
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/models/platform_model.dart';
|
||||
|
||||
String _resolveApiServer({required String api, required String custom}) {
|
||||
final key = 'resolve-api-server:${jsonEncode([api, custom])}';
|
||||
final response = jsonDecode(bind.mainGetCommonSync(key: key));
|
||||
if (response['error'] != null) {
|
||||
throw FormatException('Failed to resolve API server: ${response['error']}');
|
||||
}
|
||||
return response['url'] as String;
|
||||
}
|
||||
|
||||
bool shouldWarnApiServer(String? apiServer) {
|
||||
final uri = Uri.tryParse(apiServer?.trim() ?? '');
|
||||
if (uri == null || uri.host.isEmpty || uri.scheme != 'http') {
|
||||
return false;
|
||||
}
|
||||
return !const {'localhost', '127.0.0.1', '::1'}.contains(uri.host);
|
||||
}
|
||||
|
||||
class ApiServerWarning extends StatelessWidget {
|
||||
final TextEditingController controller;
|
||||
final TextEditingController idController;
|
||||
final String message;
|
||||
final String emptyMessage;
|
||||
final String Function({required String api, required String custom})
|
||||
resolveApiServer;
|
||||
|
||||
const ApiServerWarning({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.idController,
|
||||
required this.message,
|
||||
required this.emptyMessage,
|
||||
this.resolveApiServer = _resolveApiServer,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: Listenable.merge([controller, idController]),
|
||||
builder: (context, child) {
|
||||
final apiServer = controller.text;
|
||||
final idServer = idController.text;
|
||||
final String effectiveApiServer;
|
||||
try {
|
||||
effectiveApiServer =
|
||||
resolveApiServer(api: apiServer.trim(), custom: idServer.trim());
|
||||
} catch (error, stack) {
|
||||
FlutterError.reportError(FlutterErrorDetails(
|
||||
exception: error,
|
||||
stack: stack,
|
||||
context: ErrorDescription('while resolving the API server warning'),
|
||||
));
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
if (!shouldWarnApiServer(effectiveApiServer)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: Text(
|
||||
controller.text.trim().isEmpty ? emptyMessage : message,
|
||||
style: TextStyle(color: Colors.orange.shade700),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -497,7 +497,12 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
},
|
||||
onExit: (evt) =>
|
||||
widget._mouseFocusScope.value = MouseFocusScope.none,
|
||||
child: _buildFileList(context, _fileListScrollController),
|
||||
child: Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
onKeyEvent: _onFileListKeyEvent,
|
||||
child: _buildFileList(context, _fileListScrollController),
|
||||
),
|
||||
))
|
||||
],
|
||||
),
|
||||
@@ -1135,6 +1140,7 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
: "${entry.lastModified().toString().replaceAll(".000", "")} ";
|
||||
var secondaryPosition = RelativeRect.fromLTRB(0, 0, 0, 0);
|
||||
onTap() {
|
||||
_keyboardNode.requestFocus();
|
||||
final items = selectedItems;
|
||||
// handle double click
|
||||
if (_checkDoubleClick(entry)) {
|
||||
@@ -1363,6 +1369,102 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
debugPrint("focused on ${searchResult.first.name}");
|
||||
}
|
||||
|
||||
KeyEventResult _onFileListKeyEvent(FocusNode node, KeyEvent event) {
|
||||
// A focused child such as a sort header keeps its default keys, e.g.
|
||||
// Enter to sort.
|
||||
if (!_keyboardNode.hasPrimaryFocus) return KeyEventResult.ignored;
|
||||
for (final binding in _fileListKeyBindings().entries) {
|
||||
if (binding.key.accepts(event, HardwareKeyboard.instance)) {
|
||||
binding.value();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
Map<ShortcutActivator, VoidCallback> _fileListKeyBindings() {
|
||||
int all() => controller.directory.value.entries.length;
|
||||
return {
|
||||
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
|
||||
_moveSelectionByKey(-1, false),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
|
||||
_moveSelectionByKey(1, false),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): () =>
|
||||
_moveSelectionByKey(-1, true),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): () =>
|
||||
_moveSelectionByKey(1, true),
|
||||
// Unhandled, they would move keyboard focus to the other pane.
|
||||
const SingleActivator(LogicalKeyboardKey.arrowLeft): () {},
|
||||
const SingleActivator(LogicalKeyboardKey.arrowRight): () {},
|
||||
const SingleActivator(LogicalKeyboardKey.pageUp): () =>
|
||||
_moveSelectionByKey(_pageDelta(false), false),
|
||||
const SingleActivator(LogicalKeyboardKey.pageDown): () =>
|
||||
_moveSelectionByKey(_pageDelta(true), false),
|
||||
const SingleActivator(LogicalKeyboardKey.home): () =>
|
||||
_moveSelectionByKey(-all(), false),
|
||||
const SingleActivator(LogicalKeyboardKey.end): () =>
|
||||
_moveSelectionByKey(all(), false),
|
||||
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): () =>
|
||||
_moveSelectionByKey(_pageDelta(false), true),
|
||||
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): () =>
|
||||
_moveSelectionByKey(_pageDelta(true), true),
|
||||
const SingleActivator(LogicalKeyboardKey.home, shift: true): () =>
|
||||
_moveSelectionByKey(-all(), true),
|
||||
const SingleActivator(LogicalKeyboardKey.end, shift: true): () =>
|
||||
_moveSelectionByKey(all(), true),
|
||||
const SingleActivator(LogicalKeyboardKey.enter): _openSelectedDirectory,
|
||||
const SingleActivator(LogicalKeyboardKey.numpadEnter):
|
||||
_openSelectedDirectory,
|
||||
};
|
||||
}
|
||||
|
||||
void _openSelectedDirectory() {
|
||||
final items = selectedItems.items;
|
||||
if (items.length != 1 || items.first.isFile) return;
|
||||
controller.openDirectory(items.first.path);
|
||||
selectedItems.clear();
|
||||
}
|
||||
|
||||
List<Entry> _filteredEntries() {
|
||||
final entries = controller.directory.value.entries;
|
||||
return _searchText.isNotEmpty
|
||||
? entries.where((element) {
|
||||
return element.name.contains(_searchText.value);
|
||||
}).toList(growable: false)
|
||||
: entries;
|
||||
}
|
||||
|
||||
int _pageDelta(bool down) {
|
||||
final entries = _filteredEntries();
|
||||
final items = selectedItems.items;
|
||||
final index = items.isEmpty ? -1 : entries.indexOf(items.last);
|
||||
final position = _fileListScrollController.position;
|
||||
final first = (position.pixels / kDesktopFileTransferRowHeight).ceil();
|
||||
final last = ((position.pixels + position.viewportDimension) /
|
||||
kDesktopFileTransferRowHeight)
|
||||
.floor() -
|
||||
1;
|
||||
return pageDelta(
|
||||
index >= 0 ? index : (down ? -1 : entries.length), first, last, down);
|
||||
}
|
||||
|
||||
void _moveSelectionByKey(int delta, bool extend) {
|
||||
final filteredEntries = _filteredEntries();
|
||||
final selection =
|
||||
navigateSelection(filteredEntries, selectedItems.items, delta, extend);
|
||||
if (selection.isEmpty) return;
|
||||
selectedItems.items.assignAll(selection.where((e) => !e.isDrive));
|
||||
final position = _fileListScrollController.position;
|
||||
final top =
|
||||
filteredEntries.indexOf(selection.last) * kDesktopFileTransferRowHeight;
|
||||
final bottom = top + kDesktopFileTransferRowHeight;
|
||||
if (top < position.pixels) {
|
||||
_fileListScrollController.jumpTo(top);
|
||||
} else if (bottom > position.pixels + position.viewportDimension) {
|
||||
_fileListScrollController.jumpTo(bottom - position.viewportDimension);
|
||||
}
|
||||
}
|
||||
|
||||
void _onSelectedChanged(SelectedItems selectedItems, List<Entry> entries,
|
||||
Entry entry, bool isLocal) {
|
||||
final isCtrlDown = RawKeyboard.instance.keysPressed
|
||||
@@ -1717,6 +1819,36 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
// }
|
||||
}
|
||||
|
||||
/// Selection after a navigation key moves it by [delta] rows. A shift range is
|
||||
/// returned ordered from its anchor to the moved end, so the first and last
|
||||
/// items of [selected] stand for those two ends on the next press without
|
||||
/// separate state.
|
||||
@visibleForTesting
|
||||
List<Entry> navigateSelection(
|
||||
List<Entry> entries, List<Entry> selected, int delta, bool extend) {
|
||||
if (entries.isEmpty) return [];
|
||||
final current = selected.isEmpty ? -1 : entries.indexOf(selected.last);
|
||||
// With nothing selected, moving down starts above the first row and moving
|
||||
// up below the last one, as the Sciter grid did.
|
||||
final lead = current >= 0 ? current : (delta > 0 ? -1 : entries.length);
|
||||
final next = (lead + delta).clamp(0, entries.length - 1);
|
||||
if (!extend || current < 0) return [entries[next]];
|
||||
final first = entries.indexOf(selected.first);
|
||||
final anchor = first < 0 ? current : first;
|
||||
final step = next < anchor ? -1 : 1;
|
||||
return [for (var i = anchor; i != next + step; i += step) entries[i]];
|
||||
}
|
||||
|
||||
/// Rows a PageUp/PageDown press moves from [lead] while rows [first]..[last]
|
||||
/// are fully visible: to that edge first, then a page further, as list views
|
||||
/// do.
|
||||
@visibleForTesting
|
||||
int pageDelta(int lead, int first, int last, bool down) {
|
||||
final page = max(1, last - first);
|
||||
if (down) return lead < last ? last - lead : page;
|
||||
return lead > first ? first - lead : -page;
|
||||
}
|
||||
|
||||
Widget buildWindowsThisPC(BuildContext context, [TextStyle? textStyle]) {
|
||||
final color = Theme.of(context).iconTheme.color?.withOpacity(0.7);
|
||||
return Row(children: [
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class ListSearchActionListener extends StatelessWidget {
|
||||
final FocusNode node;
|
||||
@@ -22,7 +23,7 @@ class ListSearchActionListener extends StatelessWidget {
|
||||
autofocus: true,
|
||||
onKeyEvent: (kv) {
|
||||
final ch = kv.character;
|
||||
if (ch == null) {
|
||||
if (ch == null || LogicalKeyboardKey.isControlCharacter(ch)) {
|
||||
return;
|
||||
}
|
||||
final action = buffer.input(ch);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
|
||||
import 'package:flutter_hbb/common/widgets/setting_widgets.dart';
|
||||
import 'package:flutter_hbb/common/widgets/toolbar.dart';
|
||||
import 'package:get/get.dart';
|
||||
@@ -69,6 +70,8 @@ void showServerSettingsWithValue(
|
||||
ServerConfig serverConfig,
|
||||
OverlayDialogManager dialogManager,
|
||||
void Function(VoidCallback)? upSetState) async {
|
||||
const labelWidth = 120.0;
|
||||
const labelSpacing = 8.0;
|
||||
var isInProgress = false;
|
||||
final idCtrl = TextEditingController(text: serverConfig.idServer);
|
||||
final relayCtrl = TextEditingController(text: serverConfig.relayServer);
|
||||
@@ -112,10 +115,10 @@ void showServerSettingsWithValue(
|
||||
return Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 120,
|
||||
width: labelWidth,
|
||||
child: Text(label),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
SizedBox(width: labelSpacing),
|
||||
Expanded(
|
||||
child: serverSettingsTextFormField(
|
||||
label: label,
|
||||
@@ -175,6 +178,17 @@ void showServerSettingsWithValue(
|
||||
return null;
|
||||
},
|
||||
),
|
||||
Padding(
|
||||
padding: EdgeInsetsDirectional.only(
|
||||
start: isDesktop || isWeb ? labelWidth + labelSpacing : 0,
|
||||
),
|
||||
child: ApiServerWarning(
|
||||
controller: apiCtrl,
|
||||
idController: idCtrl,
|
||||
message: translate('api_server_connection_tip'),
|
||||
emptyMessage: translate('api_server_empty_tip'),
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
buildField('Key', keyCtrl, ''),
|
||||
if (isInProgress)
|
||||
|
||||
@@ -1928,6 +1928,11 @@ class RustdeskImpl {
|
||||
}
|
||||
|
||||
String mainGetCommonSync({required String key, dynamic hint}) {
|
||||
const prefix = 'resolve-api-server:';
|
||||
if (key.startsWith(prefix)) {
|
||||
return js.context
|
||||
.callMethod('getByName', ['api_server', key.substring(prefix.length)]);
|
||||
}
|
||||
throw UnimplementedError("mainGetCommonSync");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
|
||||
|
||||
void main() {
|
||||
test('warns only for remote HTTP endpoints', () {
|
||||
final cases = <String?, bool>{
|
||||
null: false,
|
||||
'': false,
|
||||
'https://api.example.com': false,
|
||||
'http://api.example.com': true,
|
||||
'http://192.168.1.13:13000': true,
|
||||
'http://localhost:21114': false,
|
||||
'http://127.0.0.1:21114': false,
|
||||
'http://[::1]:21114': false,
|
||||
};
|
||||
for (final entry in cases.entries) {
|
||||
expect(shouldWarnApiServer(entry.key), entry.value, reason: entry.key);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('warning follows API and ID changes using the resolved endpoint',
|
||||
(tester) async {
|
||||
final api = TextEditingController();
|
||||
final id = TextEditingController(text: 'id.example.com');
|
||||
addTearDown(api.dispose);
|
||||
addTearDown(id.dispose);
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: ApiServerWarning(
|
||||
controller: api,
|
||||
idController: id,
|
||||
message: 'HTTP warning',
|
||||
emptyMessage: 'Default HTTP warning',
|
||||
resolveApiServer: ({required api, required custom}) =>
|
||||
api.isNotEmpty ? api : 'http://$custom',
|
||||
),
|
||||
));
|
||||
expect(find.text('Default HTTP warning'), findsOneWidget);
|
||||
|
||||
id.text = 'localhost';
|
||||
await tester.pump();
|
||||
expect(find.text('Default HTTP warning'), findsNothing);
|
||||
|
||||
api.text = 'http://api.example.com';
|
||||
await tester.pump();
|
||||
expect(find.text('HTTP warning'), findsOneWidget);
|
||||
|
||||
api.text = 'https://api.example.com';
|
||||
await tester.pump();
|
||||
expect(find.text('HTTP warning'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('resolver failures are reported without breaking the server form',
|
||||
(tester) async {
|
||||
final api = TextEditingController();
|
||||
final id = TextEditingController();
|
||||
addTearDown(api.dispose);
|
||||
addTearDown(id.dispose);
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Column(children: [
|
||||
TextField(controller: api),
|
||||
Expanded(
|
||||
child: ApiServerWarning(
|
||||
controller: api,
|
||||
idController: id,
|
||||
message: 'HTTP warning',
|
||||
emptyMessage: 'Default HTTP warning',
|
||||
resolveApiServer: ({required api, required custom}) =>
|
||||
throw const FormatException('API preview failed'),
|
||||
)),
|
||||
]),
|
||||
),
|
||||
));
|
||||
expect(tester.takeException(), isA<FormatException>());
|
||||
expect(find.byType(ErrorWidget), findsNothing);
|
||||
expect(find.text('Default HTTP warning'), findsNothing);
|
||||
expect(find.byType(TextField), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_hbb/desktop/pages/file_manager_page.dart';
|
||||
import 'package:flutter_hbb/desktop/widgets/list_search_action_listener.dart';
|
||||
import 'package:flutter_hbb/models/file_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
List<Entry> _entries(int count) => [
|
||||
for (var i = 0; i < count; i++)
|
||||
Entry()
|
||||
..name = 'f$i'
|
||||
..path = '/f$i'
|
||||
];
|
||||
|
||||
List<String> _names(List<Entry> entries) =>
|
||||
entries.map((e) => e.name).toList()..sort();
|
||||
|
||||
void main() {
|
||||
test('navigation keys move the selection and stop at the ends', () {
|
||||
final entries = _entries(5);
|
||||
expect(_names(navigateSelection(entries, [], 1, false)), ['f0']);
|
||||
expect(_names(navigateSelection(entries, [], -1, false)), ['f4']);
|
||||
var selected = navigateSelection(entries, [entries[1]], 1, false);
|
||||
expect(_names(selected), ['f2']);
|
||||
selected = navigateSelection(entries, selected, -1, false);
|
||||
expect(_names(selected), ['f1']);
|
||||
expect(_names(navigateSelection(entries, selected, -3, false)), ['f0']);
|
||||
expect(_names(navigateSelection(entries, selected, 5, false)), ['f4']);
|
||||
});
|
||||
|
||||
test('shift extends and shrinks the range from the anchor', () {
|
||||
final entries = _entries(5);
|
||||
var selected = [entries[2]];
|
||||
selected = navigateSelection(entries, selected, 1, true);
|
||||
selected = navigateSelection(entries, selected, 1, true);
|
||||
expect(_names(selected), ['f2', 'f3', 'f4']);
|
||||
selected = navigateSelection(entries, selected, -1, true);
|
||||
selected = navigateSelection(entries, selected, -1, true);
|
||||
selected = navigateSelection(entries, selected, -1, true);
|
||||
expect(_names(selected), ['f1', 'f2']);
|
||||
selected = navigateSelection(entries, selected, 1, false);
|
||||
expect(_names(selected), ['f2']);
|
||||
});
|
||||
|
||||
test('page keys go to the visible edge before paging', () {
|
||||
// Rows 10..19 are fully visible.
|
||||
expect(pageDelta(12, 10, 19, true), 7);
|
||||
expect(pageDelta(19, 10, 19, true), 9);
|
||||
expect(pageDelta(12, 10, 19, false), -2);
|
||||
expect(pageDelta(10, 10, 19, false), -9);
|
||||
});
|
||||
|
||||
testWidgets('Enter does not reach type-to-search', (tester) async {
|
||||
final node = FocusNode();
|
||||
addTearDown(node.dispose);
|
||||
final searched = <String>[];
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: ListSearchActionListener(
|
||||
node: node,
|
||||
buffer: TimeoutStringBuffer(),
|
||||
onNext: searched.add,
|
||||
onSearch: searched.add,
|
||||
child: const SizedBox(),
|
||||
),
|
||||
));
|
||||
node.requestFocus();
|
||||
await tester.pump();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter, character: '\r');
|
||||
expect(searched, isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -25,6 +25,9 @@ use hwcodec::{
|
||||
},
|
||||
};
|
||||
|
||||
#[cfg(all(test, windows, feature = "vram"))]
|
||||
mod tests;
|
||||
|
||||
const DEFAULT_PIXFMT: AVPixelFormat = AVPixelFormat::AV_PIX_FMT_NV12;
|
||||
pub const DEFAULT_FPS: i32 = 30;
|
||||
const DEFAULT_GOP: i32 = i32::MAX;
|
||||
@@ -236,7 +239,7 @@ impl HwRamEncoder {
|
||||
data.append(v);
|
||||
Ok(data)
|
||||
}
|
||||
Err(_) => Ok(Vec::<EncodeFrame>::new()),
|
||||
Err(code) => Err(anyhow!("RAM encode failed: {}", code)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
use super::{CodecInfo, HwCodecConfig, CONFIG, CONFIG_SET_BY_IPC};
|
||||
use crate::{
|
||||
codec::enable_vram_option,
|
||||
vram::{VRamDecoder, VRamEncoder},
|
||||
AdapterDevice, CodecFormat,
|
||||
};
|
||||
use base::config::keys::{OPTION_ALLOW_D3D_RENDER, OPTION_ENABLE_HWCODEC};
|
||||
use hbb_common::config::{OVERWRITE_LOCAL_SETTINGS, OVERWRITE_SETTINGS};
|
||||
use hwcodec::{
|
||||
common::{DataFormat, Driver},
|
||||
vram::{DecodeContext, FeatureContext},
|
||||
};
|
||||
use std::{collections::HashMap, mem};
|
||||
|
||||
struct RestoreConfig {
|
||||
config: Option<HwCodecConfig>,
|
||||
set_by_ipc: bool,
|
||||
options: HashMap<String, String>,
|
||||
local_options: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Drop for RestoreConfig {
|
||||
fn drop(&mut self) {
|
||||
*CONFIG.lock().unwrap() = self.config.take();
|
||||
*CONFIG_SET_BY_IPC.lock().unwrap() = self.set_by_ipc;
|
||||
*OVERWRITE_SETTINGS.write().unwrap() = mem::take(&mut self.options);
|
||||
*OVERWRITE_LOCAL_SETTINGS.write().unwrap() = mem::take(&mut self.local_options);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_backend(config: &mut HwCodecConfig, driver: Driver, vendor: Driver, format: DataFormat) {
|
||||
let luid = match vendor {
|
||||
Driver::NV => 1,
|
||||
Driver::MFX => 2,
|
||||
Driver::AMF => 3,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
config.vram_encode.push(FeatureContext {
|
||||
driver: driver.clone(),
|
||||
vendor: vendor.clone(),
|
||||
luid,
|
||||
data_format: format,
|
||||
});
|
||||
config.vram_decode.push(DecodeContext {
|
||||
device: None,
|
||||
driver,
|
||||
vendor,
|
||||
luid,
|
||||
data_format: format,
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_sdk_entries_are_ignored_before_check_completes() {
|
||||
let _restore = RestoreConfig {
|
||||
config: CONFIG.lock().unwrap().take(),
|
||||
set_by_ipc: mem::replace(&mut *CONFIG_SET_BY_IPC.lock().unwrap(), false),
|
||||
options: mem::take(&mut *OVERWRITE_SETTINGS.write().unwrap()),
|
||||
local_options: mem::take(&mut *OVERWRITE_LOCAL_SETTINGS.write().unwrap()),
|
||||
};
|
||||
OVERWRITE_SETTINGS
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(OPTION_ENABLE_HWCODEC.into(), "Y".into());
|
||||
OVERWRITE_LOCAL_SETTINGS
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(OPTION_ALLOW_D3D_RENDER.into(), "Y".into());
|
||||
assert!(enable_vram_option(false));
|
||||
|
||||
let formats = [
|
||||
(CodecFormat::H264, DataFormat::H264),
|
||||
(CodecFormat::H265, DataFormat::H265),
|
||||
];
|
||||
let mut cached = HwCodecConfig::default();
|
||||
for (_, format) in formats {
|
||||
// A RAM fallback keeps this selection test independent of attached displays.
|
||||
cached.ram_encode.push(CodecInfo {
|
||||
format,
|
||||
..Default::default()
|
||||
});
|
||||
for vendor in [Driver::NV, Driver::MFX, Driver::AMF] {
|
||||
add_backend(&mut cached, vendor.clone(), vendor, format);
|
||||
}
|
||||
}
|
||||
*CONFIG.lock().unwrap() = Some(cached.clone());
|
||||
assert!(!HwCodecConfig::already_set());
|
||||
for (format, _) in formats {
|
||||
assert!(VRamEncoder::available(format).is_empty());
|
||||
for luid in 1..=3 {
|
||||
assert!(VRamDecoder::try_get(format, Some(luid)).is_none());
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
VRamDecoder::possible_available_without_check(),
|
||||
(false, false)
|
||||
);
|
||||
|
||||
for (index, &(format, data_format)) in formats.iter().enumerate() {
|
||||
for vendor in [Driver::NV, Driver::MFX, Driver::AMF] {
|
||||
add_backend(&mut cached, Driver::FFMPEG, vendor, data_format);
|
||||
}
|
||||
*CONFIG.lock().unwrap() = Some(cached.clone());
|
||||
let encoders = VRamEncoder::available(format);
|
||||
assert_eq!(encoders.len(), 3);
|
||||
for encoder in encoders {
|
||||
assert_eq!(encoder.driver, Driver::FFMPEG);
|
||||
let device = AdapterDevice {
|
||||
luid: encoder.luid,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(VRamEncoder::try_get(&device, format), Some(encoder.clone()));
|
||||
let decoder = VRamDecoder::try_get(format, Some(encoder.luid)).unwrap();
|
||||
assert_eq!(decoder.driver, Driver::FFMPEG);
|
||||
assert_eq!(decoder.vendor, encoder.vendor);
|
||||
assert_eq!(decoder.data_format, data_format);
|
||||
}
|
||||
assert!(VRamDecoder::available(format, Some(99)).is_empty());
|
||||
assert!(VRamDecoder::available(format, None).is_empty());
|
||||
assert_eq!(
|
||||
VRamDecoder::possible_available_without_check(),
|
||||
(true, index == 1)
|
||||
);
|
||||
}
|
||||
assert!(!HwCodecConfig::already_set());
|
||||
assert_eq!(
|
||||
HwCodecConfig::get().vram_encode.len(),
|
||||
cached.vram_encode.len()
|
||||
);
|
||||
}
|
||||
@@ -209,6 +209,8 @@ impl Frame<'_> {
|
||||
pub enum EncodeInput<'a> {
|
||||
YUV(&'a [u8]),
|
||||
Texture((*mut c_void, usize)),
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
Repeat,
|
||||
}
|
||||
|
||||
impl<'a> EncodeInput<'a> {
|
||||
|
||||
@@ -20,6 +20,17 @@ use std::{ptr, slice};
|
||||
generate_call_macro!(call_vpx, false);
|
||||
generate_call_ptr_macro!(call_vpx_ptr);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct VpxNoOutput;
|
||||
|
||||
impl std::fmt::Display for VpxNoOutput {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("no valid frame")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for VpxNoOutput {}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum VpxVideoCodecId {
|
||||
VP8,
|
||||
@@ -187,7 +198,7 @@ impl EncoderApi for VpxEncoder {
|
||||
if frames.len() > 0 {
|
||||
Ok(VpxEncoder::create_video_frame(self.id, frames))
|
||||
} else {
|
||||
Err(anyhow!("no valid frame"))
|
||||
Err(VpxNoOutput.into())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,9 @@ use hbb_common::{
|
||||
bytes::Bytes,
|
||||
log, ResultType,
|
||||
};
|
||||
pub use hwcodec::common::Driver;
|
||||
use hwcodec::{
|
||||
common::{DataFormat, Driver, MAX_GOP},
|
||||
common::{DataFormat, MAX_GOP},
|
||||
vram::{
|
||||
decode::{self, DecodeFrame, Decoder},
|
||||
encode::{self, EncodeFrame, Encoder},
|
||||
@@ -24,6 +25,9 @@ use hwcodec::{
|
||||
},
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod repeat_tests;
|
||||
|
||||
// https://www.reddit.com/r/buildapc/comments/d2m4ny/two_graphics_cards_two_monitors/
|
||||
// https://www.reddit.com/r/techsupport/comments/t2v9u6/dual_monitor_setup_with_dual_gpu/
|
||||
// https://cybersided.com/two-monitors-two-gpus/
|
||||
@@ -48,8 +52,6 @@ pub struct VRamEncoder {
|
||||
pub format: DataFormat,
|
||||
ctx: EncodeContext,
|
||||
bitrate: u32,
|
||||
last_frame_len: usize,
|
||||
same_bad_len_counter: usize,
|
||||
}
|
||||
|
||||
impl EncoderApi for VRamEncoder {
|
||||
@@ -83,8 +85,6 @@ impl EncoderApi for VRamEncoder {
|
||||
ctx,
|
||||
format: config.feature.data_format,
|
||||
bitrate,
|
||||
last_frame_len: 0,
|
||||
same_bad_len_counter: 0,
|
||||
}),
|
||||
Err(_) => Err(anyhow!(format!("Failed to create encoder"))),
|
||||
}
|
||||
@@ -98,7 +98,15 @@ impl EncoderApi for VRamEncoder {
|
||||
frame: EncodeInput,
|
||||
ms: i64,
|
||||
) -> ResultType<base::message_proto::VideoFrame> {
|
||||
let (texture, rotation) = frame.texture()?;
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
let repeated = matches!(&frame, EncodeInput::Repeat);
|
||||
#[cfg(not(all(windows, feature = "vram")))]
|
||||
let repeated = false;
|
||||
let (texture, rotation) = if repeated {
|
||||
(std::ptr::null_mut(), 0)
|
||||
} else {
|
||||
frame.texture()?
|
||||
};
|
||||
if rotation != 0 {
|
||||
// to-do: support rotation
|
||||
// Both the encoder and display(w,h) information need to be changed.
|
||||
@@ -106,10 +114,12 @@ impl EncoderApi for VRamEncoder {
|
||||
}
|
||||
let mut vf = VideoFrame::new();
|
||||
let mut frames = Vec::new();
|
||||
for frame in self
|
||||
.encode(texture, ms)
|
||||
.with_context(|| "Failed to encode")?
|
||||
{
|
||||
let result = if repeated {
|
||||
self.encode_repeat(ms)
|
||||
} else {
|
||||
self.encode(texture, ms)
|
||||
};
|
||||
for frame in result.with_context(|| "Failed to encode")? {
|
||||
frames.push(EncodedVideoFrame {
|
||||
data: Bytes::from(frame.data),
|
||||
pts: frame.pts,
|
||||
@@ -117,29 +127,10 @@ impl EncoderApi for VRamEncoder {
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if repeated && frames.is_empty() {
|
||||
return Ok(vf);
|
||||
}
|
||||
if frames.len() > 0 {
|
||||
// This kind of problem is occurred after a period of time when using the AMD SDK,
|
||||
// the encoding length is fixed at about 40, and the picture is still
|
||||
const MIN_BAD_LEN: usize = 100;
|
||||
const MAX_BAD_COUNTER: usize = 30;
|
||||
let this_frame_len = frames[0].data.len();
|
||||
if self.ctx.f.driver == Driver::AMF
|
||||
&& this_frame_len < MIN_BAD_LEN
|
||||
&& this_frame_len == self.last_frame_len
|
||||
{
|
||||
self.same_bad_len_counter += 1;
|
||||
if self.same_bad_len_counter >= MAX_BAD_COUNTER {
|
||||
log::info!(
|
||||
"{} times encoding len is {}, switch",
|
||||
self.same_bad_len_counter,
|
||||
self.last_frame_len
|
||||
);
|
||||
bail!(crate::codec::ENCODE_NEED_SWITCH);
|
||||
}
|
||||
} else {
|
||||
self.same_bad_len_counter = 0;
|
||||
}
|
||||
self.last_frame_len = this_frame_len;
|
||||
let frames = EncodedVideoFrames {
|
||||
frames: frames.into(),
|
||||
..Default::default()
|
||||
@@ -244,6 +235,7 @@ impl VRamEncoder {
|
||||
let v: Vec<_> = crate::hwcodec::HwCodecConfig::get()
|
||||
.vram_encode
|
||||
.drain(..)
|
||||
.filter(|c| c.driver == Driver::FFMPEG)
|
||||
.filter(|c| c.data_format == data_format)
|
||||
.collect();
|
||||
if crate::hwcodec::HwRamEncoder::try_get(format).is_some() {
|
||||
@@ -274,14 +266,21 @@ impl VRamEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(&mut self, texture: *mut c_void, ms: i64) -> ResultType<Vec<EncodeFrame>> {
|
||||
pub fn encode(
|
||||
&mut self,
|
||||
texture: *mut c_void,
|
||||
ms: i64,
|
||||
) -> ResultType<std::vec::Drain<'_, EncodeFrame>> {
|
||||
match self.encoder.encode(texture, ms) {
|
||||
Ok(v) => {
|
||||
let mut data = Vec::<EncodeFrame>::new();
|
||||
data.append(v);
|
||||
Ok(data)
|
||||
}
|
||||
Err(_) => Ok(Vec::<EncodeFrame>::new()),
|
||||
Ok(frames) => Ok(frames.drain(..)),
|
||||
Err(code) => Err(anyhow!("VRAM encode failed: {}", code)),
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_repeat(&mut self, ms: i64) -> ResultType<std::vec::Drain<'_, EncodeFrame>> {
|
||||
match self.encoder.encode_repeat(ms) {
|
||||
Ok(frames) => Ok(frames.drain(..)),
|
||||
Err(code) => Err(anyhow!("VRAM repeat encode failed: {}", code)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,6 +339,7 @@ impl VRamDecoder {
|
||||
crate::hwcodec::HwCodecConfig::get()
|
||||
.vram_decode
|
||||
.drain(..)
|
||||
.filter(|c| c.driver == Driver::FFMPEG)
|
||||
.filter(|c| c.data_format == data_format && c.luid == luid && luid != 0)
|
||||
.collect()
|
||||
}
|
||||
@@ -350,8 +350,10 @@ impl VRamDecoder {
|
||||
}
|
||||
let v = crate::hwcodec::HwCodecConfig::get().vram_decode;
|
||||
(
|
||||
v.iter().any(|d| d.data_format == DataFormat::H264),
|
||||
v.iter().any(|d| d.data_format == DataFormat::H265),
|
||||
v.iter()
|
||||
.any(|d| d.driver == Driver::FFMPEG && d.data_format == DataFormat::H264),
|
||||
v.iter()
|
||||
.any(|d| d.driver == Driver::FFMPEG && d.data_format == DataFormat::H265),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
use super::VRamEncoder;
|
||||
use crate::{codec::EncoderApi, EncodeInput};
|
||||
use base::message_proto::{video_frame, VideoFrame};
|
||||
use hwcodec::{
|
||||
common::{DataFormat, Driver, MAX_GOP},
|
||||
ffmpeg::AVHWDeviceType,
|
||||
ffmpeg_ram::decode::{DecodeContext, Decoder},
|
||||
vram::{encode::Encoder, DynamicContext, EncodeContext, FeatureContext},
|
||||
};
|
||||
use std::{mem, ptr};
|
||||
use winapi::{
|
||||
shared::{
|
||||
dxgi::{CreateDXGIFactory1, IDXGIFactory1},
|
||||
dxgiformat::DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
dxgitype::DXGI_SAMPLE_DESC,
|
||||
winerror::DXGI_ERROR_NOT_FOUND,
|
||||
},
|
||||
um::{d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown},
|
||||
Interface,
|
||||
};
|
||||
|
||||
struct Com<T>(*mut T);
|
||||
|
||||
impl<T> Drop for Com<T> {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe { (*(self.0 as *mut IUnknown)).Release() };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn texture(
|
||||
device: *mut ID3D11Device,
|
||||
width: u32,
|
||||
height: u32,
|
||||
shade: u8,
|
||||
) -> Com<ID3D11Texture2D> {
|
||||
let pixels = pixels(width, height, shade);
|
||||
let desc = D3D11_TEXTURE2D_DESC {
|
||||
Width: width,
|
||||
Height: height,
|
||||
MipLevels: 1,
|
||||
ArraySize: 1,
|
||||
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Usage: D3D11_USAGE_DEFAULT,
|
||||
BindFlags: D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
|
||||
CPUAccessFlags: 0,
|
||||
MiscFlags: D3D11_RESOURCE_MISC_SHARED,
|
||||
};
|
||||
let data = D3D11_SUBRESOURCE_DATA {
|
||||
pSysMem: pixels.as_ptr() as _,
|
||||
SysMemPitch: width * 4,
|
||||
SysMemSlicePitch: 0,
|
||||
};
|
||||
let mut raw = ptr::null_mut();
|
||||
assert_eq!((*device).CreateTexture2D(&desc, &data, &mut raw), 0);
|
||||
Com(raw)
|
||||
}
|
||||
|
||||
fn pixels(width: u32, height: u32, shade: u8) -> Vec<u8> {
|
||||
[shade, shade, shade, 255].repeat((width * height) as usize)
|
||||
}
|
||||
|
||||
fn check_picture(
|
||||
decoder: &mut Decoder,
|
||||
frame: VideoFrame,
|
||||
width: u32,
|
||||
height: u32,
|
||||
bright: bool,
|
||||
pts: i64,
|
||||
) {
|
||||
let frames = match frame.union.unwrap() {
|
||||
video_frame::Union::H264s(frames) | video_frame::Union::H265s(frames) => frames,
|
||||
_ => panic!("unexpected codec"),
|
||||
};
|
||||
let mut decoded = 0;
|
||||
for packet in frames.frames {
|
||||
assert_eq!(packet.pts, pts);
|
||||
for picture in decoder.decode(&packet.data).unwrap() {
|
||||
assert_eq!((picture.width, picture.height), (width as _, height as _));
|
||||
let center = (height as usize / 2) * picture.linesize[0] as usize + width as usize / 2;
|
||||
let y = picture.data[0][center];
|
||||
assert!(
|
||||
if bright { y > 160 } else { y < 90 },
|
||||
"stale or overwritten pixels: expected bright={}, got Y={}",
|
||||
bright,
|
||||
y
|
||||
);
|
||||
decoded += 1;
|
||||
}
|
||||
}
|
||||
assert!(decoded > 0, "encoder output did not decode to a picture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires hardware H.264/H.265 encoders; run explicitly on GPU hosts"]
|
||||
fn hardware_repeats_own_pixels_and_reset_on_recreation() {
|
||||
unsafe {
|
||||
let mut raw_factory = ptr::null_mut();
|
||||
assert_eq!(
|
||||
CreateDXGIFactory1(&IDXGIFactory1::uuidof(), &mut raw_factory),
|
||||
0
|
||||
);
|
||||
let factory = Com(raw_factory as *mut IDXGIFactory1);
|
||||
let mut tested = 0;
|
||||
for index in 0.. {
|
||||
let mut raw_adapter = ptr::null_mut();
|
||||
let result = (*factory.0).EnumAdapters1(index, &mut raw_adapter);
|
||||
if result == DXGI_ERROR_NOT_FOUND {
|
||||
break;
|
||||
}
|
||||
assert_eq!(result, 0);
|
||||
let adapter = Com(raw_adapter);
|
||||
let mut desc = mem::zeroed();
|
||||
assert_eq!((*adapter.0).GetDesc1(&mut desc), 0);
|
||||
let vendor = match desc.VendorId {
|
||||
0x10de => Driver::NV,
|
||||
0x1002 => Driver::AMF,
|
||||
0x8086 => Driver::MFX,
|
||||
_ => continue,
|
||||
};
|
||||
let luid = ((desc.AdapterLuid.HighPart as i64) << 32) | desc.AdapterLuid.LowPart as i64;
|
||||
let mut raw_device = ptr::null_mut();
|
||||
let mut raw_context = ptr::null_mut();
|
||||
assert_eq!(
|
||||
D3D11CreateDevice(
|
||||
adapter.0 as _,
|
||||
D3D_DRIVER_TYPE_UNKNOWN,
|
||||
ptr::null_mut(),
|
||||
D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
|
||||
ptr::null(),
|
||||
0,
|
||||
D3D11_SDK_VERSION,
|
||||
&mut raw_device,
|
||||
ptr::null_mut(),
|
||||
&mut raw_context,
|
||||
),
|
||||
0
|
||||
);
|
||||
let device = Com(raw_device);
|
||||
let context = Com(raw_context);
|
||||
for driver in [Driver::FFMPEG, vendor.clone()] {
|
||||
for format in [DataFormat::H264, DataFormat::H265] {
|
||||
for (width, height) in [(320, 240), (640, 360)] {
|
||||
let ctx = EncodeContext {
|
||||
f: FeatureContext {
|
||||
driver: driver.clone(),
|
||||
vendor: vendor.clone(),
|
||||
luid,
|
||||
data_format: format,
|
||||
},
|
||||
d: DynamicContext {
|
||||
device: Some(device.0 as _),
|
||||
width: width as _,
|
||||
height: height as _,
|
||||
kbitrate: 1000,
|
||||
framerate: 30,
|
||||
gop: MAX_GOP as _,
|
||||
},
|
||||
};
|
||||
let native = match Encoder::new(ctx.clone()) {
|
||||
Ok(encoder) => encoder,
|
||||
Err(()) => {
|
||||
eprintln!(
|
||||
"SKIP unavailable {:?} {:?} {:?} adapter={luid:#x}",
|
||||
vendor, driver, format
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut encoder = VRamEncoder {
|
||||
encoder: native,
|
||||
format,
|
||||
ctx,
|
||||
bitrate: 1000,
|
||||
};
|
||||
assert!(encoder.encode_to_message(EncodeInput::Repeat, 0).is_err());
|
||||
assert!(encoder
|
||||
.encode_to_message(EncodeInput::Texture((ptr::null_mut(), 0)), 0)
|
||||
.is_err());
|
||||
let mut decoder = Decoder::new(DecodeContext {
|
||||
name: if format == DataFormat::H264 {
|
||||
"h264"
|
||||
} else {
|
||||
"hevc"
|
||||
}
|
||||
.into(),
|
||||
device_type: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
|
||||
thread_count: 1,
|
||||
})
|
||||
.unwrap();
|
||||
let source = texture(device.0, width, height, 32);
|
||||
let frame = encoder
|
||||
.encode_to_message(EncodeInput::Texture((source.0 as _, 0)), 0)
|
||||
.unwrap();
|
||||
check_picture(&mut decoder, frame, width, height, false, 0);
|
||||
|
||||
// Overwrite and release the capture resource before any repeats.
|
||||
let overwritten = pixels(width, height, 224);
|
||||
(*context.0).UpdateSubresource(
|
||||
source.0 as _,
|
||||
0,
|
||||
ptr::null(),
|
||||
overwritten.as_ptr() as _,
|
||||
width * 4,
|
||||
0,
|
||||
);
|
||||
(*context.0).Flush();
|
||||
drop(source);
|
||||
for count in 1..=100 {
|
||||
let pts = count * 100;
|
||||
let frame =
|
||||
encoder.encode_to_message(EncodeInput::Repeat, pts).unwrap();
|
||||
check_picture(&mut decoder, frame, width, height, false, pts);
|
||||
}
|
||||
|
||||
let source = texture(device.0, width, height, 224);
|
||||
let frame = encoder
|
||||
.encode_to_message(EncodeInput::Texture((source.0 as _, 0)), 10100)
|
||||
.unwrap();
|
||||
check_picture(&mut decoder, frame, width, height, true, 10100);
|
||||
drop(source);
|
||||
encoder.encoder.set_bitrate(1500).unwrap();
|
||||
let frame = encoder
|
||||
.encode_to_message(EncodeInput::Repeat, 10200)
|
||||
.unwrap();
|
||||
check_picture(&mut decoder, frame, width, height, true, 10200);
|
||||
eprintln!(
|
||||
"PASS {:?} {:?} {:?} {width}x{height} adapter={luid:#x}",
|
||||
vendor, driver, format
|
||||
);
|
||||
tested += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(tested > 0, "no hardware encoders were tested");
|
||||
eprintln!("Validated {tested} encoder/codec/resolution combinations");
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,12 @@ use super::{Display, Rect, Server};
|
||||
|
||||
pub struct DisplayIter {
|
||||
outer: xcb_screen_iterator_t,
|
||||
inner: Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)>,
|
||||
// The monitor iterator points into the reply, so the reply is freed only when moving on.
|
||||
inner: Option<(
|
||||
xcb_randr_monitor_info_iterator_t,
|
||||
xcb_window_t,
|
||||
*mut xcb_randr_get_monitors_reply_t,
|
||||
)>,
|
||||
server: Rc<Server>,
|
||||
}
|
||||
|
||||
@@ -30,7 +35,11 @@ impl DisplayIter {
|
||||
fn next_screen(
|
||||
outer: &mut xcb_screen_iterator_t,
|
||||
server: &Server,
|
||||
) -> Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)> {
|
||||
) -> Option<(
|
||||
xcb_randr_monitor_info_iterator_t,
|
||||
xcb_window_t,
|
||||
*mut xcb_randr_get_monitors_reply_t,
|
||||
)> {
|
||||
if outer.rem == 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -48,10 +57,17 @@ impl DisplayIter {
|
||||
|
||||
let inner = xcb_randr_get_monitors_monitors_iterator(response);
|
||||
|
||||
libc::free(response as *mut _);
|
||||
xcb_screen_next(outer);
|
||||
|
||||
Some((inner, root))
|
||||
Some((inner, root, response))
|
||||
}
|
||||
}
|
||||
|
||||
fn free_reply(&mut self) {
|
||||
if let Some((_, _, response)) = self.inner.take() {
|
||||
unsafe {
|
||||
libc::free(response as *mut _);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,7 +77,7 @@ impl Iterator for DisplayIter {
|
||||
|
||||
fn next(&mut self) -> Option<Display> {
|
||||
loop {
|
||||
if let Some((ref mut inner, root)) = self.inner {
|
||||
if let Some((ref mut inner, root, _)) = self.inner {
|
||||
// If there is something in the current screen, return that.
|
||||
if inner.rem != 0 {
|
||||
unsafe {
|
||||
@@ -92,11 +108,18 @@ impl Iterator for DisplayIter {
|
||||
}
|
||||
|
||||
// The current screen was empty, so try the next screen.
|
||||
self.free_reply();
|
||||
self.inner = Self::next_screen(&mut self.outer, &self.server);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DisplayIter {
|
||||
fn drop(&mut self) {
|
||||
self.free_reply();
|
||||
}
|
||||
}
|
||||
|
||||
fn get_atom_name(conn: *mut xcb_connection_t, atom: xcb_atom_t) -> String {
|
||||
let empty = "".to_owned();
|
||||
if atom == 0 {
|
||||
|
||||
+28
-2
@@ -267,7 +267,13 @@ async fn race_transports_prefer_webrtc<'a, T: 'a>(
|
||||
}
|
||||
}
|
||||
match others_err.take() {
|
||||
Some(oe) => bail!("WebRTC failed: {}; fallback failed: {}", e, oe),
|
||||
// Report one error, as `select_ok` does: the UI matches and translates
|
||||
// the text whole (e.g. the offline auto-retry), and both legs often
|
||||
// carry the same rendezvous refusal anyway.
|
||||
Some(oe) => {
|
||||
log::warn!("fallback leg also failed: {}", oe);
|
||||
return Err(e);
|
||||
}
|
||||
None if others_fut.is_none() => bail!("WebRTC failed: {}", e),
|
||||
None => webrtc_err = Some(e),
|
||||
}
|
||||
@@ -308,7 +314,10 @@ async fn race_transports_prefer_webrtc<'a, T: 'a>(
|
||||
// it before failing the connection.
|
||||
Some(we) => match held.take() {
|
||||
Some(conn) => return Ok(conn),
|
||||
None => bail!("WebRTC failed: {}; fallback failed: {}", we, e),
|
||||
None => {
|
||||
log::warn!("WebRTC leg also failed: {}", we);
|
||||
return Err(e);
|
||||
}
|
||||
},
|
||||
None if webrtc_fut.is_none() => match held.take() {
|
||||
Some(conn) => return Ok(conn),
|
||||
@@ -5709,6 +5718,23 @@ mod webrtc_race_tests {
|
||||
assert_eq!(got, "ipv6");
|
||||
assert!(start.elapsed() < Duration::from_secs(5));
|
||||
}
|
||||
|
||||
// Both legs get the same rendezvous refusal; the UI needs the text verbatim, e.g. the
|
||||
// offline auto-retry matches it whole. Either leg may fail last.
|
||||
#[tokio::test]
|
||||
async fn same_failure_on_both_legs_reported_once() {
|
||||
for (webrtc_ms, fallback_ms) in [(10, 20), (20, 10)] {
|
||||
let err = race_transports_prefer_webrtc(
|
||||
err_after(webrtc_ms, "Remote desktop is offline"),
|
||||
vec![err_after(fallback_ms, "Remote desktop is offline")],
|
||||
60_000,
|
||||
NOT_P2P,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.to_string(), "Remote desktop is offline");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1251,6 +1251,11 @@ fn get_api_server_(api: String, custom: String) -> String {
|
||||
if !s0.is_empty() {
|
||||
let s = crate::increase_port(&s0, -2);
|
||||
if s == s0 {
|
||||
let s = if hbb_common::is_ipv6_str(&s) && !s.starts_with('[') {
|
||||
format!("[{s}]")
|
||||
} else {
|
||||
s
|
||||
};
|
||||
return format!("http://{}:{}", s, config::RENDEZVOUS_PORT - 2);
|
||||
} else {
|
||||
return format!("http://{}", s);
|
||||
@@ -3209,6 +3214,14 @@ mod tests {
|
||||
assert!(!is_public("https://rustdesk.com@evil.test"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_api_server_from_bare_ipv6_rendezvous_server() {
|
||||
assert_eq!(
|
||||
get_api_server_("".to_owned(), "2001:db8::1".to_owned()),
|
||||
"http://[2001:db8::1]:21114"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_use_tcp_proxy_for_api_url() {
|
||||
assert!(should_use_tcp_proxy_for_api_url(
|
||||
|
||||
@@ -2763,6 +2763,16 @@ pub fn main_get_common(key: String) -> String {
|
||||
}
|
||||
|
||||
pub fn main_get_common_sync(key: String) -> SyncReturn<String> {
|
||||
if let Some(args) = key.strip_prefix("resolve-api-server:") {
|
||||
let response = match serde_json::from_str::<(String, String)>(args) {
|
||||
Ok((api, custom)) => serde_json::json!({"url": crate::get_api_server(api, custom)}),
|
||||
Err(err) => {
|
||||
log::trace!("Invalid API server preview arguments: {err}");
|
||||
serde_json::json!({"error": err.to_string()})
|
||||
}
|
||||
};
|
||||
return SyncReturn(response.to_string());
|
||||
}
|
||||
// Metadata verification performs blocking network requests. Keep this key on
|
||||
// the asynchronous FFI path to avoid blocking the calling Flutter isolate.
|
||||
if key.starts_with("verified-download-url-") {
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", "“{}” 不能用作快捷键。"),
|
||||
("On", "开"),
|
||||
("Off", "关"),
|
||||
("api_server_connection_tip", "自定义服务器正在使用未加密的 HTTP。请联系管理员启用 HTTPS。"),
|
||||
("api_server_empty_tip", "API 服务器留空时,自定义服务器默认使用 HTTP。请联系管理员启用 HTTPS。"),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -288,5 +288,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-already-bound-to", "Already bound to"),
|
||||
("shortcut-mobile-physical-keyboard-tip", "Recording requires a physical keyboard. Soft keyboards are not supported."),
|
||||
("shortcut-key-not-supported", "\"{}\" can't be used as a shortcut."),
|
||||
("api_server_connection_tip", "Your custom server uses unencrypted HTTP. Contact your administrator to enable HTTPS."),
|
||||
("api_server_empty_tip", "With API Server empty, your custom server defaults to HTTP. Contact your administrator to enable HTTPS."),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", "'{}' non può essere usato come scorciatoia."),
|
||||
("On", "ON"),
|
||||
("Off", "OFF"),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", "Sneltoets wordt niet ondersteund"),
|
||||
("On", "Aan"),
|
||||
("Off", "Uit"),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", "Não é possível usar \"{}\" como atalho."),
|
||||
("On", "Ativado"),
|
||||
("Off", "Desativado"),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
+34
-32
@@ -781,37 +781,39 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Relay fallback delay in seconds", "Задержка перед переходом на ретранслятор в секундах"),
|
||||
("relay-fallback-delay-tip", "Сколько времени уже установленное соединение через ретранслятор ждёт прямое соединение WebRTC, прежде чем будет использовано вместо него. Увеличьте, чтобы дать медленному прямому соединению больше времени; уменьшите, чтобы быстрее переходить на ретранслятор в сетях, где прямое соединение невозможно. Оставьте пустым для значения по умолчанию 2.5 секунды."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Чтобы начать голосовой вызов, включите \"Захват аудио\" на странице \"Демонстрация экрана\"."),
|
||||
("Keyboard shortcuts", ""),
|
||||
("Configure shortcuts...", ""),
|
||||
("Enable keyboard shortcuts in remote session", ""),
|
||||
("shortcut-page-description", ""),
|
||||
("shortcut-passthrough-tip", ""),
|
||||
("Pass-through to remote", ""),
|
||||
("Reset to defaults", ""),
|
||||
("shortcut-reset-confirm-tip", ""),
|
||||
("Monitor", ""),
|
||||
("Keyboard", ""),
|
||||
("Toggle fullscreen", ""),
|
||||
("Switch to next display", ""),
|
||||
("Switch to previous display", ""),
|
||||
("Switch to next tab", ""),
|
||||
("Switch to previous tab", ""),
|
||||
("Toggle session recording", ""),
|
||||
("Close tab", ""),
|
||||
("Toggle toolbar", ""),
|
||||
("Toggle input source", ""),
|
||||
("Edit", ""),
|
||||
("Save", ""),
|
||||
("Set shortcut", ""),
|
||||
("shortcut-recording-instruction", ""),
|
||||
("shortcut-recording-press-keys-tip", ""),
|
||||
("shortcut-must-include-modifiers", ""),
|
||||
("shortcut-already-bound-to", ""),
|
||||
("Replace", ""),
|
||||
("Valid", ""),
|
||||
("shortcut-mobile-physical-keyboard-tip", ""),
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("Keyboard shortcuts", "Сочетания клавиш"),
|
||||
("Configure shortcuts...", "Настроить сочетания клавиш..."),
|
||||
("Enable keyboard shortcuts in remote session", "Использовать сочетания клавиш в удалённом сеансе"),
|
||||
("shortcut-page-description", "Привязка сочетаний клавиш к действиям в сеансе. Каждое назначение должно включать хотя бы один модификатор."),
|
||||
("shortcut-passthrough-tip", "Если включено, каждое настроенное сочетаний клавиш пересылается на удалённое устройство. Полезно, если настроенное сочетание клавиш конфликтует с чем-то нужным на удалённом устройстве."),
|
||||
("Pass-through to remote", "Отправлять на удалённое устройство"),
|
||||
("Reset to defaults", "Сбросить настройки по умолчанию"),
|
||||
("shortcut-reset-confirm-tip", "Все текущие настроенные сочетания клавиш будут заменены на настройки по умолчанию. Продолжить?"),
|
||||
("Monitor", "Монитор"),
|
||||
("Keyboard", "Клавиатура"),
|
||||
("Toggle fullscreen", "Переключить полноэкранный режим"),
|
||||
("Switch to next display", "Переключиться на следующий дисплей"),
|
||||
("Switch to previous display", "Переключиться на предыдущий дисплей"),
|
||||
("Switch to next tab", "Переключиться на следующую вкладку"),
|
||||
("Switch to previous tab", "Переключиться на предыдущую вкладку"),
|
||||
("Toggle session recording", "Переключить запись сеанса"),
|
||||
("Close tab", "Закрыть вкладку"),
|
||||
("Toggle toolbar", "Переключить панель инструментов"),
|
||||
("Toggle input source", "Переключить источник ввода"),
|
||||
("Edit", "Изменить"),
|
||||
("Save", "Сохранить"),
|
||||
("Set shortcut", "Настроить сочетание клавиш"),
|
||||
("shortcut-recording-instruction", "Нажмите сочетание клавиш, которое хотите использовать."),
|
||||
("shortcut-recording-press-keys-tip", "Нажмите сочетание клавиш..."),
|
||||
("shortcut-must-include-modifiers", "Необходимо использовать хотя бы один модификатор: {}"),
|
||||
("shortcut-already-bound-to", "Уже привязано к"),
|
||||
("Replace", "Заменить"),
|
||||
("Valid", "Допустимо"),
|
||||
("shortcut-mobile-physical-keyboard-tip", "Для записи требуется физическая клавиатура. Экранные клавиатуры не поддерживаются."),
|
||||
("shortcut-key-not-supported", "\"{}\" невозможно использовать как сочетание клавиш."),
|
||||
("On", "вкл"),
|
||||
("Off", "откл"),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", "自訂伺服器正在使用未加密的 HTTP。請聯絡管理員啟用 HTTPS。"),
|
||||
("api_server_empty_tip", "API 伺服器留空時,自訂伺服器預設使用 HTTP。請聯絡管理員啟用 HTTPS。"),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -813,6 +813,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
|
||||
@@ -813,5 +813,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("shortcut-key-not-supported", ""),
|
||||
("On", ""),
|
||||
("Off", ""),
|
||||
("api_server_connection_tip", ""),
|
||||
("api_server_empty_tip", ""),
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -891,6 +891,43 @@ fn get_all_term_values(uid: &str) -> Vec<String> {
|
||||
terms
|
||||
}
|
||||
|
||||
fn append_audio_latency_envs(
|
||||
envs: &mut Vec<(&'static str, String)>,
|
||||
get_var: impl Fn(&str) -> Option<String>,
|
||||
) {
|
||||
for key in ["PULSE_LATENCY_MSEC", "PIPEWIRE_LATENCY"] {
|
||||
if let Some(value) = get_var(key).filter(|value| !value.is_empty()) {
|
||||
envs.push((key, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod audio_latency_env_tests {
|
||||
use super::append_audio_latency_envs;
|
||||
|
||||
#[test]
|
||||
fn forwards_configured_values_without_creating_defaults() {
|
||||
let mut envs = Vec::new();
|
||||
append_audio_latency_envs(&mut envs, |key| match key {
|
||||
"PULSE_LATENCY_MSEC" => Some("60".to_owned()),
|
||||
"PIPEWIRE_LATENCY" => Some("1024/48000".to_owned()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(
|
||||
envs,
|
||||
vec![
|
||||
("PULSE_LATENCY_MSEC", "60".to_owned()),
|
||||
("PIPEWIRE_LATENCY", "1024/48000".to_owned()),
|
||||
]
|
||||
);
|
||||
|
||||
envs.clear();
|
||||
append_audio_latency_envs(&mut envs, |_| None);
|
||||
assert!(envs.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_start_server_(desktop: Option<&Desktop>) -> ResultType<Option<Child>> {
|
||||
match desktop {
|
||||
@@ -921,6 +958,9 @@ fn try_start_server_(desktop: Option<&Desktop>) -> ResultType<Option<Child>> {
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
append_audio_latency_envs(&mut envs, |key| std::env::var(key).ok());
|
||||
|
||||
envs.push((
|
||||
"TERM",
|
||||
get_cur_term(&desktop.uid).unwrap_or_else(|| suggest_best_term()),
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
mod directory;
|
||||
|
||||
use super::{
|
||||
installer_shell::{
|
||||
get_system_executable, path_for_cmd_assignment, path_for_cmd_environment,
|
||||
run_elevated_and_wait, trusted_install_environment,
|
||||
BATCH_SHORTCUT_DECODE_FAILURE_EXIT_CODE, CMD_RELATIVE_PATH,
|
||||
WIN7_SHELL_EXECUTE_MAX_PARAMETER_CHARS,
|
||||
},
|
||||
validate_install_app_name, ResultType,
|
||||
};
|
||||
use hbb_common::{
|
||||
anyhow::anyhow,
|
||||
bail, log,
|
||||
sha2::{Digest, Sha256},
|
||||
};
|
||||
@@ -99,10 +103,8 @@ fn verified_install_bootstrap(
|
||||
runner_directory: &Path,
|
||||
) -> ResultType<String> {
|
||||
let source = path_for_cmd_assignment(&script.path)?;
|
||||
let runner = runner_directory.join(format!(
|
||||
"rustdesk_install_{}.bat",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
let directory = path_for_cmd_assignment(runner_directory)?;
|
||||
let runner = runner_directory.join("install.bat");
|
||||
let runner = path_for_cmd_assignment(&runner)?;
|
||||
let cmd_path = get_system_executable(CMD_RELATIVE_PATH)?;
|
||||
let certutil_path = get_system_executable(CERTUTIL_RELATIVE_PATH)?;
|
||||
@@ -113,13 +115,13 @@ fn verified_install_bootstrap(
|
||||
// Short names preserve headroom under the Windows 7 ShellExecuteExW 2,048
|
||||
// UTF-16-character parameter limit. Paths are stored with delayed expansion
|
||||
// disabled, then expanded indirectly so literal `!` survives: S=source,
|
||||
// R=runner, Q=cmd.exe, H=certutil.exe, F=findstr.exe, C=created flag, E=exit code.
|
||||
// R=runner, Q=cmd.exe, H=certutil.exe, F=findstr.exe, D=directory, E=exit code.
|
||||
Ok(format!(
|
||||
"setlocal DisableDelayedExpansion & set \"S={source}\" & set \"R={runner}\" & \
|
||||
set \"Q={cmd}\" & set \"H={certutil}\" & set \"F={findstr}\" & \
|
||||
set \"C=0\" & set \"E=0\" & setlocal EnableDelayedExpansion & \
|
||||
set \"ERRORLEVEL=\" & set \"D={directory}\" & set \"E=0\" & setlocal EnableDelayedExpansion & \
|
||||
if exist \"!R!\" (set \"E={INSTALL_HANDOFF_RUNNER_EXISTS_EXIT_CODE}\") else (\
|
||||
set \"C=1\" & copy /Y \"!S!\" \"!R!\" > nul || \
|
||||
copy /Y \"!S!\" \"!R!\" > nul || \
|
||||
(set \"E={INSTALL_HANDOFF_COPY_FAILURE_EXIT_CODE}\") & \
|
||||
if \"!E!\"==\"0\" (\"!H!\" -hashfile \"!R!\" SHA256 > \"!R!.hash\" || \
|
||||
set \"E={INSTALL_HANDOFF_HASH_FAILURE_EXIT_CODE}\") & \
|
||||
@@ -127,26 +129,51 @@ fn verified_install_bootstrap(
|
||||
set \"E={INSTALL_HANDOFF_HASH_MISMATCH_EXIT_CODE}\") & \
|
||||
if \"!E!\"==\"0\" (\"!Q!\" /D /E:ON /V:OFF /C \"\"!R!\"\" & \
|
||||
set \"E=!errorlevel!\")) & \
|
||||
if \"!C!\"==\"1\" (rd /s /q \"!R!.dir\" > nul 2>&1 & \
|
||||
del /f /q \"!R!\" \"!R!.*\" > nul 2>&1) & exit /b !E!",
|
||||
rd /s /q \"!D!\" > nul 2>&1 & exit /b !E!",
|
||||
install_hash_pattern(&script.expected_hash),
|
||||
))
|
||||
}
|
||||
|
||||
fn verified_install_parameters(script: &InstallCommandScript) -> ResultType<String> {
|
||||
let system_directory = get_system_executable("")?;
|
||||
Ok(format!(
|
||||
fn verified_install_parameters(
|
||||
script: &InstallCommandScript,
|
||||
directory: &Path,
|
||||
) -> ResultType<String> {
|
||||
let parameters = format!(
|
||||
"/D /E:ON /V:ON /C {}",
|
||||
verified_install_bootstrap(script, &system_directory)?
|
||||
))
|
||||
verified_install_bootstrap(script, directory)?
|
||||
);
|
||||
let length = parameters.encode_utf16().count();
|
||||
if length >= WIN7_SHELL_EXECUTE_MAX_PARAMETER_CHARS {
|
||||
bail!("Elevated command is too long: {length} UTF-16 characters");
|
||||
}
|
||||
Ok(parameters)
|
||||
}
|
||||
|
||||
pub(super) fn run_cmds(cmds: String, show: bool, tip: &str) -> ResultType<()> {
|
||||
validate_install_app_name(&crate::get_app_name())?;
|
||||
let script = write_install_script(cmds)?;
|
||||
let cmd_path = get_system_executable(CMD_RELATIVE_PATH)?;
|
||||
let parameters = verified_install_parameters(&script)?;
|
||||
let exit_code = run_elevated_and_wait(&cmd_path, ¶meters, show)?;
|
||||
let directory = directory::path()?;
|
||||
let parameters = verified_install_parameters(&script, &directory)?;
|
||||
directory::create(&directory)?;
|
||||
let exit_code = run_elevated_and_wait(&cmd_path, ¶meters, show).map_err(|err| {
|
||||
anyhow!(
|
||||
"Installer handoff failed; protected directory may remain at {}: {err}",
|
||||
directory.display()
|
||||
)
|
||||
})?;
|
||||
// Cleanup must not change the result of an installation that already ran.
|
||||
match fs::symlink_metadata(&directory) {
|
||||
Ok(_) => log::warn!(
|
||||
"Protected installer directory may remain at {}",
|
||||
directory.display()
|
||||
),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(err) => log::warn!(
|
||||
"Protected installer directory may remain at {}: {err}",
|
||||
directory.display()
|
||||
),
|
||||
}
|
||||
if exit_code != 0 {
|
||||
bail!(
|
||||
"{tip} failed with elevated exit code {exit_code}: {}",
|
||||
@@ -208,7 +235,7 @@ mod tests {
|
||||
.expect("install script should be created");
|
||||
let bootstrap = verified_install_bootstrap(&script, &runner_dir)
|
||||
.expect("native verifier bootstrap should be generated");
|
||||
assert_native_handoff_structure(&script, &shortcut_commands, &bootstrap);
|
||||
assert_native_handoff_structure(&script, &shortcut_commands, &runner_dir);
|
||||
|
||||
let output = run_install_bootstrap_for_test(&bootstrap);
|
||||
assert!(
|
||||
@@ -218,15 +245,25 @@ mod tests {
|
||||
);
|
||||
assert!(marker.exists(), "verified install script must execute");
|
||||
std::fs::remove_file(&marker).expect("test marker should be removed");
|
||||
assert!(
|
||||
!runner_dir.exists(),
|
||||
"protected runner directory must be removed"
|
||||
);
|
||||
std::fs::create_dir(&runner_dir).expect("runner directory should be created");
|
||||
assert_replaced_install_script_is_rejected(&script, &runner_dir, &marker);
|
||||
std::fs::remove_dir(runner_dir).expect("runner directory should be empty");
|
||||
assert!(
|
||||
!runner_dir.exists(),
|
||||
"failed handoff directory must be removed"
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_native_handoff_structure(
|
||||
script: &InstallCommandScript,
|
||||
shortcut_commands: &str,
|
||||
bootstrap: &str,
|
||||
runner_dir: &Path,
|
||||
) {
|
||||
let bootstrap = verified_install_bootstrap(script, runner_dir)
|
||||
.expect("native verifier bootstrap should be generated");
|
||||
assert!(shortcut_commands.contains("certutil"));
|
||||
assert!(shortcut_commands.contains("-decode"));
|
||||
assert!(!shortcut_commands.to_ascii_lowercase().contains("cscript"));
|
||||
@@ -240,8 +277,8 @@ mod tests {
|
||||
.collect::<Vec<_>>()
|
||||
.join(" *");
|
||||
assert!(bootstrap.contains(&format!("/R /I /X /C:\"{win7_hash_pattern}\"")));
|
||||
let parameters =
|
||||
verified_install_parameters(script).expect("elevated parameters should be generated");
|
||||
let parameters = verified_install_parameters(script, runner_dir)
|
||||
.expect("elevated parameters should be generated");
|
||||
assert!(bootstrap.contains("certutil.exe"));
|
||||
assert!(bootstrap.contains("findstr.exe"));
|
||||
assert!(!bootstrap.to_ascii_lowercase().contains("powershell"));
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
use super::super::{
|
||||
installer_shell::{get_system_executable, path_for_cmd_environment},
|
||||
wide_string,
|
||||
};
|
||||
use hbb_common::{anyhow::anyhow, bail, ResultType};
|
||||
use std::{
|
||||
fs, mem,
|
||||
os::windows::fs::MetadataExt,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use windows::{
|
||||
core::{w, PCWSTR},
|
||||
Win32::{
|
||||
Foundation::{LocalFree, HLOCAL},
|
||||
Security::{
|
||||
Authorization::{
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
|
||||
},
|
||||
PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES,
|
||||
},
|
||||
Storage::FileSystem::{CreateDirectoryW, FILE_ATTRIBUTE_REPARSE_POINT},
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) fn path() -> ResultType<PathBuf> {
|
||||
let system = get_system_executable("")?;
|
||||
let windows = system
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow!("System directory has no parent"))?;
|
||||
let temporary = windows.join("Temp");
|
||||
for parent in temporary.ancestors() {
|
||||
let metadata = fs::symlink_metadata(parent).map_err(|err| {
|
||||
anyhow!(
|
||||
"Failed to inspect installer temporary parent {}: {err}",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
if !metadata.is_dir() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0 != 0 {
|
||||
bail!(
|
||||
"Installer temporary parent is not a regular directory: {}",
|
||||
parent.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(temporary.join(format!(
|
||||
"rustdesk-install-{}",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
)))
|
||||
}
|
||||
|
||||
pub(super) fn create(path: &Path) -> ResultType<()> {
|
||||
let wide_path = wide_string(path_for_cmd_environment(path)?);
|
||||
let mut descriptor = PSECURITY_DESCRIPTOR::default();
|
||||
// OWNER RIGHTS removes the ordinary creator's implicit WRITE_DAC permission.
|
||||
// The owner can inspect the ACL, but only Administrators/SYSTEM can modify contents.
|
||||
// https://learn.microsoft.com/windows-server/identity/ad-ds/manage/understand-special-identities-groups#owner-rights
|
||||
unsafe {
|
||||
ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
w!("D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;RC;;;OW)"),
|
||||
SDDL_REVISION_1,
|
||||
&mut descriptor,
|
||||
None,
|
||||
)?;
|
||||
}
|
||||
let attributes = SECURITY_ATTRIBUTES {
|
||||
nLength: mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor.0,
|
||||
bInheritHandle: false.into(),
|
||||
};
|
||||
let result = unsafe { CreateDirectoryW(PCWSTR(wide_path.as_ptr()), Some(&attributes)) };
|
||||
unsafe { LocalFree(Some(HLOCAL(descriptor.0))) };
|
||||
result.map_err(|err| {
|
||||
anyhow!(
|
||||
"Failed to create protected installer directory {}: {err}",
|
||||
path.display()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use winapi::um::winnt::MAXIMUM_ALLOWED;
|
||||
use windows::{
|
||||
core::{Owned, BOOL},
|
||||
Win32::{
|
||||
Foundation::HANDLE,
|
||||
Security::{
|
||||
AccessCheck,
|
||||
Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
||||
DuplicateToken, SecurityImpersonation, DACL_SECURITY_INFORMATION, GENERIC_MAPPING,
|
||||
GROUP_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION, PRIVILEGE_SET,
|
||||
TOKEN_DUPLICATE, TOKEN_QUERY,
|
||||
},
|
||||
Storage::FileSystem::{
|
||||
FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
|
||||
READ_CONTROL,
|
||||
},
|
||||
System::Threading::{GetCurrentProcess, OpenProcessToken},
|
||||
},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn protected_directory_enforces_creator_permissions() {
|
||||
let elevated =
|
||||
super::super::super::is_elevated(None).expect("creator elevation should be available");
|
||||
// The user-owned parent allows cleanup through DELETE_CHILD. AccessCheck
|
||||
// below checks the child's DACL, not that separate parent permission.
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"rustdesk_installer_acl_{}",
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
create(&directory).expect("production directory creation should succeed");
|
||||
let access = creator_directory_access(&directory);
|
||||
fs::remove_dir(&directory).expect("test directory should be removed");
|
||||
let expected = if elevated {
|
||||
FILE_ALL_ACCESS
|
||||
} else {
|
||||
READ_CONTROL
|
||||
};
|
||||
assert_eq!(
|
||||
access.expect("the created directory's access should be checked"),
|
||||
(true, expected.0),
|
||||
"only elevated administrators may modify the protected directory"
|
||||
);
|
||||
}
|
||||
|
||||
fn creator_directory_access(path: &Path) -> ResultType<(bool, u32)> {
|
||||
let wide_path = wide_string(path_for_cmd_environment(path)?);
|
||||
let mut descriptor = PSECURITY_DESCRIPTOR::default();
|
||||
unsafe {
|
||||
GetNamedSecurityInfoW(
|
||||
PCWSTR(wide_path.as_ptr()),
|
||||
SE_FILE_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&mut descriptor,
|
||||
)
|
||||
.ok()?;
|
||||
}
|
||||
let _descriptor = unsafe { Owned::new(HLOCAL(descriptor.0)) };
|
||||
let token = creator_impersonation_token()?;
|
||||
let mapping = GENERIC_MAPPING {
|
||||
GenericRead: FILE_GENERIC_READ.0,
|
||||
GenericWrite: FILE_GENERIC_WRITE.0,
|
||||
GenericExecute: FILE_GENERIC_EXECUTE.0,
|
||||
GenericAll: FILE_ALL_ACCESS.0,
|
||||
};
|
||||
let mut privileges = PRIVILEGE_SET::default();
|
||||
let mut privilege_size = mem::size_of::<PRIVILEGE_SET>() as u32;
|
||||
let mut granted = 0;
|
||||
let mut allowed = BOOL::default();
|
||||
unsafe {
|
||||
AccessCheck(
|
||||
descriptor,
|
||||
*token,
|
||||
MAXIMUM_ALLOWED,
|
||||
&mapping,
|
||||
Some(&mut privileges),
|
||||
&mut privilege_size,
|
||||
&mut granted,
|
||||
&mut allowed,
|
||||
)?;
|
||||
}
|
||||
Ok((allowed.as_bool(), granted))
|
||||
}
|
||||
|
||||
fn creator_impersonation_token() -> ResultType<Owned<HANDLE>> {
|
||||
let mut token = HANDLE::default();
|
||||
unsafe {
|
||||
OpenProcessToken(
|
||||
GetCurrentProcess(),
|
||||
TOKEN_QUERY | TOKEN_DUPLICATE,
|
||||
&mut token,
|
||||
)?
|
||||
};
|
||||
let token = unsafe { Owned::new(token) };
|
||||
let mut impersonation = HANDLE::default();
|
||||
unsafe { DuplicateToken(*token, SecurityImpersonation, &mut impersonation)? };
|
||||
Ok(unsafe { Owned::new(impersonation) })
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,8 @@ use std::{
|
||||
|
||||
pub const OPTION_REFRESH: &'static str = "refresh";
|
||||
|
||||
mod static_refresh;
|
||||
|
||||
#[cfg(windows)]
|
||||
const DXGI_RECOVERY_LIMIT: usize = 3;
|
||||
#[cfg(windows)]
|
||||
@@ -731,6 +733,16 @@ fn run(vs: VideoService) -> ResultType<()> {
|
||||
let mut encoder_warmed_up = false;
|
||||
let capture_width = c.width;
|
||||
let capture_height = c.height;
|
||||
let mut static_refresh = static_refresh::StaticRefresh::new(
|
||||
vs.source,
|
||||
codec_format,
|
||||
&encoder_cfg,
|
||||
&sp,
|
||||
&recorder,
|
||||
display_idx,
|
||||
capture_width,
|
||||
capture_height,
|
||||
);
|
||||
let (mut second_instant, mut send_counter) = (Instant::now(), 0);
|
||||
|
||||
while sp.ok() {
|
||||
@@ -855,7 +867,8 @@ fn run(vs: VideoService) -> ResultType<()> {
|
||||
}
|
||||
|
||||
let frame = frame.to(encoder.yuvfmt(), &mut yuv, &mut mid_data)?;
|
||||
let send_conn_ids = handle_one_frame(
|
||||
static_refresh.on_frame(&frame);
|
||||
let result = handle_one_frame(
|
||||
display_idx,
|
||||
&sp,
|
||||
frame,
|
||||
@@ -868,7 +881,8 @@ fn run(vs: VideoService) -> ResultType<()> {
|
||||
capture_width,
|
||||
capture_height,
|
||||
)?;
|
||||
frame_controller.set_send(now, send_conn_ids);
|
||||
static_refresh.on_frame_encoded(&result);
|
||||
frame_controller.set_send(now, result.send_conn_ids);
|
||||
send_counter += 1;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
@@ -932,11 +946,22 @@ fn run(vs: VideoService) -> ResultType<()> {
|
||||
&mut encoder_warmed_up,
|
||||
capture_width,
|
||||
capture_height,
|
||||
)?;
|
||||
)?
|
||||
.send_conn_ids;
|
||||
static_refresh.on_encoded(!send_conn_ids.is_empty());
|
||||
frame_controller.set_send(now, send_conn_ids);
|
||||
send_counter += 1;
|
||||
}
|
||||
}
|
||||
static_refresh.try_encode(
|
||||
&yuv,
|
||||
spf,
|
||||
quality,
|
||||
now,
|
||||
ms,
|
||||
&mut encoder,
|
||||
&mut frame_controller,
|
||||
)?;
|
||||
}
|
||||
Err(err) => {
|
||||
#[cfg(windows)]
|
||||
@@ -1261,7 +1286,7 @@ fn handle_one_frame(
|
||||
encoder_warmed_up: &mut bool,
|
||||
width: usize,
|
||||
height: usize,
|
||||
) -> ResultType<HashSet<i32>> {
|
||||
) -> ResultType<static_refresh::FrameEncodeResult> {
|
||||
sp.snapshot(|sps| {
|
||||
// so that new sub and old sub share the same encoder after switch
|
||||
if sps.has_subscribes() {
|
||||
@@ -1272,6 +1297,7 @@ fn handle_one_frame(
|
||||
})?;
|
||||
|
||||
let mut send_conn_ids: HashSet<i32> = Default::default();
|
||||
let mut vpx_no_output = false;
|
||||
let first = *first_frame;
|
||||
*first_frame = false;
|
||||
match encoder.encode_to_message(frame, ms) {
|
||||
@@ -1289,6 +1315,7 @@ fn handle_one_frame(
|
||||
send_conn_ids = sp.send_video_frame(msg);
|
||||
}
|
||||
Err(e) => {
|
||||
vpx_no_output = e.is::<scrap::VpxNoOutput>();
|
||||
*encode_fail_counter += 1;
|
||||
// Encoding errors are not frequent except on Android
|
||||
if !cfg!(target_os = "android") {
|
||||
@@ -1319,7 +1346,10 @@ fn handle_one_frame(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(send_conn_ids)
|
||||
Ok(static_refresh::FrameEncodeResult {
|
||||
send_conn_ids,
|
||||
vpx_no_output,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -0,0 +1,745 @@
|
||||
use super::{GenericService, VideoFrameController, VideoSource};
|
||||
use base::message_proto::Message;
|
||||
use hbb_common::{bail, ResultType};
|
||||
use scrap::{
|
||||
codec::{Encoder, EncoderCfg, BR_BALANCED, BR_BEST, BR_SPEED},
|
||||
record::Recorder,
|
||||
CodecFormat, EncodeInput,
|
||||
};
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const INITIAL_REPEAT_INTERVAL: Duration = Duration::from_millis(100);
|
||||
const MAX_REPEAT_FPS: u32 = 30;
|
||||
const MAX_REPEAT_FAILURES: usize = 3;
|
||||
const MAX_REPEAT_NO_OUTPUTS: usize = 100;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum HardwareBackend {
|
||||
Nvenc,
|
||||
Qsv,
|
||||
Amf,
|
||||
Vaapi,
|
||||
VideoToolbox,
|
||||
Other,
|
||||
}
|
||||
|
||||
fn max_repeat_frames(codec: CodecFormat, quality: f32, backend: HardwareBackend) -> usize {
|
||||
use HardwareBackend::*;
|
||||
// Measured entries sample quality 0.1, BR_SPEED, BR_BALANCED, and BR_BEST.
|
||||
// For measured entries, Original values come from AI-run tests. Active values
|
||||
// were adjusted by comparing 1080p screenshots captured every 10 repeat outputs.
|
||||
let (low, low_to_balanced, balanced_to_best, best) = match (codec, backend) {
|
||||
(CodecFormat::VP8, _) => (20, 20, 20, 30), // Original: (20, 20, 20, 30)
|
||||
(CodecFormat::VP9, _) => (40, 20, 20, 20), // Original: (40, 20, 20, 20)
|
||||
(CodecFormat::H264, Nvenc) => (80, 50, 60, 30), // Original: (270, 50, 60, 30)
|
||||
(CodecFormat::H264, Qsv) => (80, 70, 130, 110), // Original: (80, 70, 130, 110)
|
||||
(CodecFormat::H264, Amf) => (150, 150, 170, 110), // Original: (560, 150, 170, 110)
|
||||
(CodecFormat::H264, Vaapi) => (150, 100, 90, 60), // Original: (330, 100, 90, 60)
|
||||
(CodecFormat::H265, Nvenc) => (160, 90, 60, 30), // Original: (160, 90, 60, 30)
|
||||
(CodecFormat::H265, Qsv) => (150, 30, 30, 30), // Original: (150, 30, 30, 30)
|
||||
(CodecFormat::H265, Amf) => (200, 200, 200, 120), // Original: (580, 200, 200, 120)
|
||||
// The capture loop already repeats ten frames to drain VideoToolbox latency.
|
||||
(CodecFormat::H265, VideoToolbox) => (90, 90, 50, 90), // Original: (230, 90, 50, 90)
|
||||
(CodecFormat::H264, _) => (90, 60, 60, 30),
|
||||
(CodecFormat::H265, _) => (90, 60, 60, 30),
|
||||
(CodecFormat::AV1 | CodecFormat::Unknown, _) => return 0,
|
||||
};
|
||||
if quality >= BR_BEST {
|
||||
best
|
||||
} else if quality >= BR_BALANCED {
|
||||
balanced_to_best
|
||||
} else if quality >= BR_SPEED {
|
||||
low_to_balanced
|
||||
} else {
|
||||
low
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct FrameEncodeResult {
|
||||
pub(super) send_conn_ids: HashSet<i32>,
|
||||
pub(super) vpx_no_output: bool,
|
||||
}
|
||||
|
||||
pub(super) struct StaticRefresh<'a> {
|
||||
source: VideoSource,
|
||||
codec_format: CodecFormat,
|
||||
hardware_backend: HardwareBackend,
|
||||
sp: &'a GenericService,
|
||||
recorder: &'a Arc<Mutex<Option<Recorder>>>,
|
||||
display_idx: usize,
|
||||
width: usize,
|
||||
height: usize,
|
||||
last_encode: Instant,
|
||||
#[cfg(test)]
|
||||
elapsed_since_encode: Duration,
|
||||
repeat_output_counter: usize,
|
||||
repeat_no_outputs: usize,
|
||||
repeat_failures: usize,
|
||||
source_ready: bool,
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
has_texture: bool,
|
||||
}
|
||||
|
||||
impl<'a> StaticRefresh<'a> {
|
||||
pub(super) fn new(
|
||||
source: VideoSource,
|
||||
codec_format: CodecFormat,
|
||||
encoder_config: &EncoderCfg,
|
||||
sp: &'a GenericService,
|
||||
recorder: &'a Arc<Mutex<Option<Recorder>>>,
|
||||
display_idx: usize,
|
||||
width: usize,
|
||||
height: usize,
|
||||
) -> Self {
|
||||
let hardware_backend = match encoder_config {
|
||||
#[cfg(feature = "hwcodec")]
|
||||
EncoderCfg::HWRAM(config) => match config.name.as_str() {
|
||||
"h264_nvenc" | "hevc_nvenc" => HardwareBackend::Nvenc,
|
||||
"h264_qsv" | "hevc_qsv" => HardwareBackend::Qsv,
|
||||
"h264_amf" | "hevc_amf" => HardwareBackend::Amf,
|
||||
"h264_vaapi" => HardwareBackend::Vaapi,
|
||||
"hevc_videotoolbox" => HardwareBackend::VideoToolbox,
|
||||
_ => HardwareBackend::Other,
|
||||
},
|
||||
#[cfg(feature = "vram")]
|
||||
// The FFMPEG VRAM driver selects the encoder from the adapter vendor.
|
||||
EncoderCfg::VRAM(config) => match config.feature.vendor {
|
||||
scrap::vram::Driver::NV => HardwareBackend::Nvenc,
|
||||
scrap::vram::Driver::MFX => HardwareBackend::Qsv,
|
||||
scrap::vram::Driver::AMF => HardwareBackend::Amf,
|
||||
_ => HardwareBackend::Other,
|
||||
},
|
||||
_ => HardwareBackend::Other,
|
||||
};
|
||||
Self {
|
||||
source,
|
||||
codec_format,
|
||||
hardware_backend,
|
||||
sp,
|
||||
recorder,
|
||||
display_idx,
|
||||
width,
|
||||
height,
|
||||
last_encode: Instant::now(),
|
||||
#[cfg(test)]
|
||||
elapsed_since_encode: Duration::ZERO,
|
||||
repeat_output_counter: 0,
|
||||
repeat_no_outputs: 0,
|
||||
repeat_failures: 0,
|
||||
source_ready: false,
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
has_texture: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn on_frame(&mut self, _frame: &EncodeInput) {
|
||||
self.repeat_output_counter = 0;
|
||||
self.repeat_no_outputs = 0;
|
||||
self.source_ready = false;
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
{
|
||||
self.has_texture =
|
||||
matches!(_frame, EncodeInput::Texture((texture, 0)) if !texture.is_null());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn on_frame_encoded(&mut self, result: &FrameEncodeResult) {
|
||||
// VP8/VP9 rate control may drop a frame without an encoding error.
|
||||
// The latest input is still cached, so allow repeats even without output;
|
||||
// otherwise the final update may never be sent once capture becomes idle.
|
||||
self.on_encoded(
|
||||
!result.send_conn_ids.is_empty()
|
||||
|| (matches!(self.codec_format, CodecFormat::VP8 | CodecFormat::VP9)
|
||||
&& result.vpx_no_output),
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn on_encoded(&mut self, success: bool) {
|
||||
self.last_encode = Instant::now();
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.elapsed_since_encode = Duration::ZERO;
|
||||
}
|
||||
if success {
|
||||
self.source_ready = true;
|
||||
self.repeat_failures = 0;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn try_encode(
|
||||
&mut self,
|
||||
yuv: &[u8],
|
||||
spf: Duration,
|
||||
quality: f32,
|
||||
now: Instant,
|
||||
ms: i64,
|
||||
encoder: &mut Encoder,
|
||||
frame_controller: &mut VideoFrameController,
|
||||
) -> ResultType<()> {
|
||||
let spf = spf.max(Duration::from_secs(1) / MAX_REPEAT_FPS);
|
||||
if !self.source.is_monitor()
|
||||
|| self.codec_format == CodecFormat::AV1
|
||||
|| !self.source_ready
|
||||
|| (self.repeat_failures >= MAX_REPEAT_FAILURES
|
||||
&& !matches!(
|
||||
self.codec_format,
|
||||
CodecFormat::VP8 | CodecFormat::VP9 | CodecFormat::AV1
|
||||
))
|
||||
|| self.repeat_no_outputs >= MAX_REPEAT_NO_OUTPUTS
|
||||
|| self.repeat_output_counter
|
||||
>= max_repeat_frames(self.codec_format, quality, self.hardware_backend)
|
||||
|| {
|
||||
#[cfg(not(test))]
|
||||
let elapsed = self.last_encode.elapsed();
|
||||
#[cfg(test)]
|
||||
let elapsed = self.elapsed_since_encode;
|
||||
let interval = if matches!(self.codec_format, CodecFormat::VP8 | CodecFormat::VP9)
|
||||
|| (self.repeat_output_counter == 0 && self.repeat_no_outputs == 0)
|
||||
{
|
||||
INITIAL_REPEAT_INTERVAL.max(spf)
|
||||
} else {
|
||||
spf
|
||||
};
|
||||
elapsed < interval
|
||||
}
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let frame = if yuv.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(EncodeInput::YUV(yuv))
|
||||
};
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
let frame = frame.or_else(|| self.has_texture.then_some(EncodeInput::Repeat));
|
||||
if let Some(frame) = frame {
|
||||
self.sp.snapshot(|sps| {
|
||||
if sps.has_subscribes() {
|
||||
bail!("SWITCH");
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let result = encoder.encode_to_message(frame, ms);
|
||||
self.last_encode = if matches!(self.codec_format, CodecFormat::VP8 | CodecFormat::VP9) {
|
||||
Instant::now()
|
||||
} else {
|
||||
// Align with the capture loop so encoding time does not skip the next tick.
|
||||
now
|
||||
};
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.elapsed_since_encode = Duration::ZERO;
|
||||
}
|
||||
let mut vf = match result {
|
||||
Ok(vf) if vf.union.is_none() => {
|
||||
self.repeat_no_outputs += 1;
|
||||
return Ok(());
|
||||
}
|
||||
Ok(vf) => vf,
|
||||
Err(error) => {
|
||||
self.repeat_no_outputs += 1;
|
||||
self.repeat_failures += 1;
|
||||
if error.is::<scrap::VpxNoOutput>() {
|
||||
hbb_common::throttled_log!(
|
||||
Duration::from_secs(60),
|
||||
trace,
|
||||
"static refresh produced no output: {error:?}"
|
||||
);
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
Duration::from_secs(60),
|
||||
debug,
|
||||
"static refresh failed ({}): {error:?}",
|
||||
self.repeat_failures
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
self.repeat_output_counter += 1;
|
||||
self.repeat_failures = 0;
|
||||
vf.display = self.display_idx as _;
|
||||
let mut msg = Message::new();
|
||||
msg.set_video_frame(vf);
|
||||
self.recorder
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_mut()
|
||||
.map(|r| r.write_message(&msg, self.width, self.height));
|
||||
let send_conn_ids = self.sp.send_video_frame(msg);
|
||||
frame_controller.set_send(now, send_conn_ids);
|
||||
// Static refinement must not count as motion for adaptive bitrate.
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::server::{connection::ConnInner, service::Service};
|
||||
use base::message_proto::VideoFrame;
|
||||
use hbb_common::tokio::sync::mpsc;
|
||||
use scrap::{
|
||||
codec::{EncoderApi, EncoderCfg, BR_BALANCED},
|
||||
vpxcodec::{VpxEncoderConfig, VpxVideoCodecId},
|
||||
EncodeYuvFormat,
|
||||
};
|
||||
use std::{cell::Cell, rc::Rc};
|
||||
|
||||
pub(super) fn new_refresh<'a>(
|
||||
source: VideoSource,
|
||||
codec_format: CodecFormat,
|
||||
sp: &'a GenericService,
|
||||
recorder: &'a Arc<Mutex<Option<Recorder>>>,
|
||||
display_idx: usize,
|
||||
width: usize,
|
||||
height: usize,
|
||||
) -> StaticRefresh<'a> {
|
||||
// The mock encoders simulate each format without a hardware backend.
|
||||
let config = EncoderCfg::VPX(VpxEncoderConfig {
|
||||
width: width as _,
|
||||
height: height as _,
|
||||
quality: BR_BALANCED,
|
||||
codec: VpxVideoCodecId::VP9,
|
||||
keyframe_interval: None,
|
||||
});
|
||||
StaticRefresh::new(
|
||||
source,
|
||||
codec_format,
|
||||
&config,
|
||||
sp,
|
||||
recorder,
|
||||
display_idx,
|
||||
width,
|
||||
height,
|
||||
)
|
||||
}
|
||||
|
||||
struct CountingEncoder(Rc<Cell<usize>>);
|
||||
|
||||
impl EncoderApi for CountingEncoder {
|
||||
fn new(_: EncoderCfg, _: bool) -> ResultType<Self> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn encode_to_message(&mut self, frame: EncodeInput, _: i64) -> ResultType<VideoFrame> {
|
||||
match frame {
|
||||
EncodeInput::YUV(yuv) => assert_eq!(yuv, &[1]),
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
EncodeInput::Repeat => {}
|
||||
_ => panic!("unexpected encoder input"),
|
||||
}
|
||||
self.0.set(self.0.get() + 1);
|
||||
let mut vf = VideoFrame::new();
|
||||
vf.set_h264s(Default::default());
|
||||
Ok(vf)
|
||||
}
|
||||
|
||||
fn yuvfmt(&self) -> EncodeYuvFormat {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
#[cfg(feature = "vram")]
|
||||
fn input_texture(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn set_quality(&mut self, _: f32) -> ResultType<()> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn bitrate(&self) -> u32 {
|
||||
0
|
||||
}
|
||||
|
||||
fn support_changing_quality(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn latency_free(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn is_hardware(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn disable(&self) {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
fn attempt(
|
||||
refresh: &mut StaticRefresh<'_>,
|
||||
calls: &Rc<Cell<usize>>,
|
||||
yuv: &[u8],
|
||||
spf: Duration,
|
||||
) {
|
||||
let mut encoder = Encoder {
|
||||
codec: Box::new(CountingEncoder(Rc::clone(calls))),
|
||||
};
|
||||
refresh
|
||||
.try_encode(
|
||||
yuv,
|
||||
spf,
|
||||
BR_BALANCED,
|
||||
Instant::now(),
|
||||
0,
|
||||
&mut encoder,
|
||||
&mut VideoFrameController::new(0),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_network_waits_preserve_budget_and_new_frames_restart_it() {
|
||||
let sp = GenericService::new("static-refresh-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
let mut refresh = new_refresh(
|
||||
VideoSource::Monitor,
|
||||
CodecFormat::VP9,
|
||||
&sp,
|
||||
&recorder,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
);
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let spf = Duration::from_millis(100);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
let limit = max_repeat_frames(CodecFormat::VP9, BR_BALANCED, HardwareBackend::Other);
|
||||
for _ in 0..limit {
|
||||
refresh.elapsed_since_encode = Duration::from_secs(60);
|
||||
attempt(&mut refresh, &calls, &[1], spf);
|
||||
}
|
||||
assert_eq!(calls.get(), limit);
|
||||
|
||||
refresh.elapsed_since_encode = Duration::from_secs(600);
|
||||
attempt(&mut refresh, &calls, &[1], spf);
|
||||
assert_eq!(calls.get(), limit);
|
||||
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
refresh.elapsed_since_encode = Duration::from_secs(1);
|
||||
attempt(&mut refresh, &calls, &[1], spf);
|
||||
assert_eq!(calls.get(), limit + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_delay_repeat_interval_and_qos_limit_refresh_rate() {
|
||||
let sp = GenericService::new("static-refresh-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
let mut refresh = new_refresh(
|
||||
VideoSource::Monitor,
|
||||
CodecFormat::H264,
|
||||
&sp,
|
||||
&recorder,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
);
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_millis(10));
|
||||
assert_eq!(calls.get(), 0);
|
||||
|
||||
refresh.elapsed_since_encode = Duration::from_millis(50);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_millis(10));
|
||||
assert_eq!(calls.get(), 0);
|
||||
|
||||
refresh.elapsed_since_encode = Duration::from_millis(100);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_millis(10));
|
||||
assert_eq!(calls.get(), 1);
|
||||
|
||||
refresh.elapsed_since_encode = Duration::from_millis(33);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_millis(10));
|
||||
assert_eq!(calls.get(), 1);
|
||||
|
||||
refresh.elapsed_since_encode = Duration::from_secs(1) / 30;
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_millis(10));
|
||||
assert_eq!(calls.get(), 2);
|
||||
|
||||
refresh.elapsed_since_encode = Duration::from_millis(49);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_millis(50));
|
||||
assert_eq!(calls.get(), 2);
|
||||
refresh.elapsed_since_encode = Duration::from_millis(50);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_millis(50));
|
||||
assert_eq!(calls.get(), 3);
|
||||
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
refresh.elapsed_since_encode = Duration::from_millis(50);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_millis(10));
|
||||
assert_eq!(calls.get(), 3);
|
||||
|
||||
refresh.elapsed_since_encode = Duration::from_secs(1);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_secs(2));
|
||||
assert_eq!(calls.get(), 3);
|
||||
|
||||
refresh.elapsed_since_encode = Duration::from_secs(3);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_secs(2));
|
||||
assert_eq!(calls.get(), 4);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_secs(2));
|
||||
assert_eq!(calls.get(), 4);
|
||||
refresh.elapsed_since_encode = Duration::from_millis(1999);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_secs(2));
|
||||
assert_eq!(calls.get(), 4);
|
||||
refresh.elapsed_since_encode = Duration::from_millis(2000);
|
||||
attempt(&mut refresh, &calls, &[1], Duration::from_secs(2));
|
||||
assert_eq!(calls.get(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(all(windows, feature = "vram"))]
|
||||
fn texture_frames_request_repeats_without_accessing_capture_resources() {
|
||||
let sp = GenericService::new("static-refresh-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
let mut refresh = new_refresh(
|
||||
VideoSource::Monitor,
|
||||
CodecFormat::H264,
|
||||
&sp,
|
||||
&recorder,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
);
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
// Deliberately not a D3D resource: neither hook may dereference it.
|
||||
let texture = std::ptr::NonNull::<u8>::dangling().as_ptr() as _;
|
||||
for _ in 0..60 {
|
||||
refresh.on_frame(&EncodeInput::Texture((texture, 0)));
|
||||
}
|
||||
refresh.on_encoded(true);
|
||||
refresh.elapsed_since_encode = Duration::from_secs(1);
|
||||
attempt(&mut refresh, &calls, &[], Duration::from_millis(16));
|
||||
assert_eq!(calls.get(), 1);
|
||||
|
||||
for frame in [
|
||||
EncodeInput::YUV(&[1]),
|
||||
EncodeInput::Texture((texture, 90)),
|
||||
EncodeInput::Texture((std::ptr::null_mut(), 0)),
|
||||
] {
|
||||
refresh.on_frame(&frame);
|
||||
refresh.on_encoded(true);
|
||||
refresh.elapsed_since_encode = Duration::from_secs(1);
|
||||
attempt(&mut refresh, &calls, &[], Duration::from_millis(16));
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cameras_av1_and_missing_frames_are_not_refreshed() {
|
||||
let sp = GenericService::new("static-refresh-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
for (source, codec_format, yuv) in [
|
||||
(VideoSource::Camera, CodecFormat::VP9, &[1][..]),
|
||||
(VideoSource::Monitor, CodecFormat::AV1, &[1][..]),
|
||||
(VideoSource::Monitor, CodecFormat::VP9, &[][..]),
|
||||
] {
|
||||
let mut refresh = new_refresh(source, codec_format, &sp, &recorder, 0, 1, 1);
|
||||
refresh.on_frame(&EncodeInput::YUV(yuv));
|
||||
refresh.on_encoded(true);
|
||||
refresh.elapsed_since_encode = Duration::from_secs(60);
|
||||
attempt(&mut refresh, &calls, yuv, Duration::from_millis(100));
|
||||
}
|
||||
assert_eq!(calls.get(), 0);
|
||||
}
|
||||
|
||||
fn assert_output_budget(
|
||||
refresh: &mut StaticRefresh<'_>,
|
||||
sp: &GenericService,
|
||||
quality: f32,
|
||||
expected: usize,
|
||||
) {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
sp.on_subscribe(ConnInner::new(1, None, Some(tx)));
|
||||
let mut encoder = Encoder {
|
||||
codec: Box::new(CountingEncoder(Rc::new(Cell::new(0)))),
|
||||
};
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
for _ in 0..=expected {
|
||||
refresh.elapsed_since_encode = Duration::from_secs(1);
|
||||
refresh
|
||||
.try_encode(
|
||||
&[1],
|
||||
Duration::from_millis(33),
|
||||
quality,
|
||||
Instant::now(),
|
||||
0,
|
||||
&mut encoder,
|
||||
&mut VideoFrameController::new(0),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(rx.len(), expected);
|
||||
sp.on_unsubscribe(1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quality_bands_stop_each_backend_at_its_output_budget() {
|
||||
let sp = GenericService::new("repeat-quality-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
assert_eq!(
|
||||
[0.1, BR_SPEED, BR_BALANCED, BR_BEST]
|
||||
.map(|q| { max_repeat_frames(CodecFormat::H264, q, HardwareBackend::Vaapi) }),
|
||||
[150, 100, 90, 60]
|
||||
);
|
||||
for codec in [
|
||||
CodecFormat::VP8,
|
||||
CodecFormat::VP9,
|
||||
CodecFormat::H264,
|
||||
CodecFormat::H265,
|
||||
] {
|
||||
for backend in [
|
||||
HardwareBackend::Nvenc,
|
||||
HardwareBackend::Qsv,
|
||||
HardwareBackend::Amf,
|
||||
HardwareBackend::Vaapi,
|
||||
HardwareBackend::VideoToolbox,
|
||||
HardwareBackend::Other,
|
||||
] {
|
||||
let mut refresh = new_refresh(VideoSource::Monitor, codec, &sp, &recorder, 0, 1, 1);
|
||||
refresh.hardware_backend = backend;
|
||||
for quality in [
|
||||
0.1,
|
||||
BR_BEST,
|
||||
BR_SPEED,
|
||||
BR_BALANCED,
|
||||
BR_SPEED + 0.01,
|
||||
BR_BEST + 0.1,
|
||||
] {
|
||||
let limit = max_repeat_frames(codec, quality, backend);
|
||||
assert_output_budget(&mut refresh, &sp, quality, limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn speed_boundary_uses_the_speed_preset_for_all_backends() {
|
||||
for codec in [
|
||||
CodecFormat::VP8,
|
||||
CodecFormat::VP9,
|
||||
CodecFormat::H264,
|
||||
CodecFormat::H265,
|
||||
] {
|
||||
for backend in [
|
||||
HardwareBackend::Nvenc,
|
||||
HardwareBackend::Qsv,
|
||||
HardwareBackend::Amf,
|
||||
HardwareBackend::Vaapi,
|
||||
HardwareBackend::VideoToolbox,
|
||||
HardwareBackend::Other,
|
||||
] {
|
||||
assert_eq!(
|
||||
max_repeat_frames(codec, BR_SPEED, backend),
|
||||
max_repeat_frames(codec, BR_SPEED + 0.01, backend),
|
||||
"{codec:?} {backend:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "hwcodec")]
|
||||
fn ram_config_selects_the_actual_backend_and_preserves_other_encoders() {
|
||||
let sp = GenericService::new("repeat-backend-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
for (name, expected) in [
|
||||
("h264_nvenc", HardwareBackend::Nvenc),
|
||||
("hevc_nvenc", HardwareBackend::Nvenc),
|
||||
("h264_qsv", HardwareBackend::Qsv),
|
||||
("hevc_qsv", HardwareBackend::Qsv),
|
||||
("h264_amf", HardwareBackend::Amf),
|
||||
("hevc_amf", HardwareBackend::Amf),
|
||||
("h264_vaapi", HardwareBackend::Vaapi),
|
||||
("hevc_vaapi", HardwareBackend::Other),
|
||||
("hevc_videotoolbox", HardwareBackend::VideoToolbox),
|
||||
("h264_videotoolbox", HardwareBackend::Other),
|
||||
] {
|
||||
let config = EncoderCfg::HWRAM(scrap::hwcodec::HwRamEncoderConfig {
|
||||
name: name.to_owned(),
|
||||
mc_name: None,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
quality: BR_BALANCED,
|
||||
keyframe_interval: None,
|
||||
});
|
||||
let codec_format = if name.starts_with("hevc_") {
|
||||
CodecFormat::H265
|
||||
} else {
|
||||
CodecFormat::H264
|
||||
};
|
||||
let mut refresh = StaticRefresh::new(
|
||||
VideoSource::Monitor,
|
||||
codec_format,
|
||||
&config,
|
||||
&sp,
|
||||
&recorder,
|
||||
0,
|
||||
1920,
|
||||
1080,
|
||||
);
|
||||
for quality in [0.1, BR_SPEED, BR_BALANCED, BR_BEST] {
|
||||
let limit = max_repeat_frames(codec_format, quality, expected);
|
||||
assert_output_budget(&mut refresh, &sp, quality, limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "vram")]
|
||||
fn vram_config_resolves_ffmpeg_to_the_actual_hardware_backend() {
|
||||
let sp = GenericService::new("repeat-vram-backend-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
for (vendor, expected) in [
|
||||
("NV", HardwareBackend::Nvenc),
|
||||
("MFX", HardwareBackend::Qsv),
|
||||
("AMF", HardwareBackend::Amf),
|
||||
("FFMPEG", HardwareBackend::Other),
|
||||
] {
|
||||
let config = EncoderCfg::VRAM(scrap::vram::VRamEncoderConfig {
|
||||
device: Default::default(),
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
quality: BR_BALANCED,
|
||||
keyframe_interval: None,
|
||||
feature: serde_json::from_value(serde_json::json!({
|
||||
"driver": "FFMPEG",
|
||||
"vendor": vendor,
|
||||
"luid": 0,
|
||||
"data_format": "H264",
|
||||
}))
|
||||
.unwrap(),
|
||||
});
|
||||
let mut refresh = StaticRefresh::new(
|
||||
VideoSource::Monitor,
|
||||
CodecFormat::H264,
|
||||
&config,
|
||||
&sp,
|
||||
&recorder,
|
||||
0,
|
||||
1920,
|
||||
1080,
|
||||
);
|
||||
for quality in [0.1, BR_SPEED, BR_BALANCED, BR_BEST] {
|
||||
let limit = max_repeat_frames(CodecFormat::H264, quality, expected);
|
||||
assert_output_budget(&mut refresh, &sp, quality, limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod error_tests;
|
||||
@@ -0,0 +1,579 @@
|
||||
use super::{tests::new_refresh, *};
|
||||
use crate::server::{connection::ConnInner, service::Service};
|
||||
use base::message_proto::VideoFrame;
|
||||
use hbb_common::tokio::sync::mpsc;
|
||||
use scrap::{
|
||||
codec::{EncoderApi, EncoderCfg, BR_BALANCED},
|
||||
EncodeYuvFormat,
|
||||
};
|
||||
use std::{cell::RefCell, collections::VecDeque, rc::Rc};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Outcome {
|
||||
Frame,
|
||||
Empty,
|
||||
Dropped,
|
||||
Error,
|
||||
}
|
||||
|
||||
struct State {
|
||||
outcomes: VecDeque<Outcome>,
|
||||
calls: usize,
|
||||
disabled: usize,
|
||||
inputs: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
struct ScriptedEncoder(Rc<RefCell<State>>);
|
||||
|
||||
impl EncoderApi for ScriptedEncoder {
|
||||
fn new(_: EncoderCfg, _: bool) -> ResultType<Self> {
|
||||
unreachable!()
|
||||
}
|
||||
fn encode_to_message(&mut self, input: EncodeInput, _: i64) -> ResultType<VideoFrame> {
|
||||
let mut state = self.0.borrow_mut();
|
||||
state.calls += 1;
|
||||
if let EncodeInput::YUV(yuv) = input {
|
||||
state.inputs.push(yuv.to_vec());
|
||||
}
|
||||
match state.outcomes.pop_front().expect("unexpected encode") {
|
||||
Outcome::Frame => {
|
||||
let mut vf = VideoFrame::new();
|
||||
vf.set_h264s(Default::default());
|
||||
Ok(vf)
|
||||
}
|
||||
Outcome::Empty => Ok(VideoFrame::new()),
|
||||
Outcome::Dropped => Err(scrap::VpxNoOutput.into()),
|
||||
Outcome::Error => bail!("injected encoding error"),
|
||||
}
|
||||
}
|
||||
fn yuvfmt(&self) -> EncodeYuvFormat {
|
||||
unreachable!()
|
||||
}
|
||||
#[cfg(feature = "vram")]
|
||||
fn input_texture(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn set_quality(&mut self, _: f32) -> ResultType<()> {
|
||||
unreachable!()
|
||||
}
|
||||
fn bitrate(&self) -> u32 {
|
||||
0
|
||||
}
|
||||
fn support_changing_quality(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn latency_free(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn is_hardware(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn disable(&self) {
|
||||
self.0.borrow_mut().disabled += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn encoder(outcomes: &[Outcome]) -> (Encoder, Rc<RefCell<State>>) {
|
||||
let state = Rc::new(RefCell::new(State {
|
||||
outcomes: outcomes.iter().copied().collect(),
|
||||
calls: 0,
|
||||
disabled: 0,
|
||||
inputs: Vec::new(),
|
||||
}));
|
||||
(
|
||||
Encoder {
|
||||
codec: Box::new(ScriptedEncoder(Rc::clone(&state))),
|
||||
},
|
||||
state,
|
||||
)
|
||||
}
|
||||
|
||||
fn attempt(refresh: &mut StaticRefresh<'_>, encoder: &mut Encoder) {
|
||||
refresh.elapsed_since_encode = Duration::from_secs(1);
|
||||
refresh
|
||||
.try_encode(
|
||||
&[1],
|
||||
Duration::from_millis(100),
|
||||
BR_BALANCED,
|
||||
Instant::now(),
|
||||
0,
|
||||
encoder,
|
||||
&mut VideoFrameController::new(0),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failures_pause_refresh_until_a_real_frame_succeeds() {
|
||||
use Outcome::*;
|
||||
let sp = GenericService::new("repeat-errors-test".to_owned(), false);
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
sp.on_subscribe(ConnInner::new(1, None, Some(tx)));
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
let mut refresh = new_refresh(
|
||||
VideoSource::Monitor,
|
||||
CodecFormat::H264,
|
||||
&sp,
|
||||
&recorder,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
);
|
||||
let (mut encoder, state) = encoder(&[Error, Error, Empty, Frame, Error, Error, Error, Frame]);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
refresh
|
||||
.try_encode(
|
||||
&[1],
|
||||
Duration::from_millis(100),
|
||||
BR_BALANCED,
|
||||
Instant::now(),
|
||||
0,
|
||||
&mut encoder,
|
||||
&mut VideoFrameController::new(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
state.borrow().calls,
|
||||
1,
|
||||
"failure must retain the rate limit"
|
||||
);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(rx.len(), 0);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(rx.len(), 1, "empty output must not stop further refreshes");
|
||||
for _ in 0..3 {
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
}
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(state.borrow().calls, 7);
|
||||
assert_eq!(rx.len(), 1);
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(false);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(
|
||||
state.borrow().calls,
|
||||
7,
|
||||
"a failed real frame must not restart refresh"
|
||||
);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(state.borrow().calls, 8);
|
||||
assert_eq!(rx.len(), 2);
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_outputs_exhaust_the_no_output_budget_without_disabling_the_encoder() {
|
||||
let sp = GenericService::new("repeat-empty-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
let mut refresh = new_refresh(
|
||||
VideoSource::Monitor,
|
||||
CodecFormat::H264,
|
||||
&sp,
|
||||
&recorder,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
);
|
||||
let (mut encoder, state) = encoder(&[Outcome::Empty; 100]);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
for _ in 0..101 {
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
}
|
||||
assert_eq!(state.borrow().calls, 100);
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vpx_drops_exhaust_the_no_output_budget_without_disabling_the_encoder() {
|
||||
let sp = GenericService::new("repeat-vpx-drops-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
for codec in [CodecFormat::VP8, CodecFormat::VP9] {
|
||||
let mut refresh = new_refresh(VideoSource::Monitor, codec, &sp, &recorder, 0, 1, 1);
|
||||
let limit = MAX_REPEAT_NO_OUTPUTS;
|
||||
let (mut encoder, state) = encoder(&vec![Outcome::Dropped; limit]);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
for _ in 0..=limit {
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
}
|
||||
assert_eq!(state.borrow().calls, limit, "{codec:?}");
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vpx_dropped_capture_repeats_the_latest_frame() {
|
||||
use super::super::handle_one_frame;
|
||||
use Outcome::*;
|
||||
let sp = GenericService::new("repeat-dropped-capture-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
for codec in [CodecFormat::VP8, CodecFormat::VP9] {
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
sp.on_subscribe(ConnInner::new(1, None, Some(tx)));
|
||||
let mut refresh = new_refresh(VideoSource::Monitor, codec, &sp, &recorder, 0, 1, 1);
|
||||
let (mut encoder, state) = encoder(&[Frame, Dropped, Dropped, Frame]);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert!(rx.try_recv().unwrap().1.has_video_frame());
|
||||
|
||||
let latest_yuv = [2];
|
||||
refresh.on_frame(&EncodeInput::YUV(&latest_yuv));
|
||||
let mut normal_failures = 0;
|
||||
let mut first_frame = false;
|
||||
let mut encoder_warmed_up = false;
|
||||
let result = handle_one_frame(
|
||||
0,
|
||||
&sp,
|
||||
EncodeInput::YUV(&latest_yuv),
|
||||
100,
|
||||
&mut encoder,
|
||||
recorder.clone(),
|
||||
&mut normal_failures,
|
||||
&mut first_frame,
|
||||
&mut encoder_warmed_up,
|
||||
1,
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.send_conn_ids.is_empty());
|
||||
assert!(result.vpx_no_output);
|
||||
refresh.on_frame_encoded(&result);
|
||||
assert_eq!(rx.len(), 0);
|
||||
for (elapsed_ms, expected_calls, expected_outputs) in
|
||||
[(99, 2, 0), (100, 3, 0), (100, 4, 1)]
|
||||
{
|
||||
refresh.elapsed_since_encode = Duration::from_millis(elapsed_ms);
|
||||
refresh
|
||||
.try_encode(
|
||||
&latest_yuv,
|
||||
Duration::from_nanos(33_333_333),
|
||||
BR_BALANCED,
|
||||
Instant::now(),
|
||||
expected_calls as i64 * 100,
|
||||
&mut encoder,
|
||||
&mut VideoFrameController::new(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(state.borrow().calls, expected_calls, "{codec:?}");
|
||||
assert_eq!(rx.len(), expected_outputs);
|
||||
}
|
||||
assert_eq!(state.borrow().inputs, vec![vec![1], vec![2], vec![2], vec![2]]);
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
sp.on_unsubscribe(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_frame_errors_do_not_enable_repeat() {
|
||||
use super::super::handle_one_frame;
|
||||
let sp = GenericService::new("repeat-capture-error-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
for (codec, outcome, vpx_no_output) in [
|
||||
(CodecFormat::VP8, Outcome::Error, false),
|
||||
(CodecFormat::VP9, Outcome::Error, false),
|
||||
(CodecFormat::H264, Outcome::Dropped, true),
|
||||
(CodecFormat::H265, Outcome::Dropped, true),
|
||||
] {
|
||||
let mut refresh = new_refresh(VideoSource::Monitor, codec, &sp, &recorder, 0, 1, 1);
|
||||
let (mut encoder, state) = encoder(&[outcome, Outcome::Frame]);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
let mut normal_failures = 0;
|
||||
let mut first_frame = false;
|
||||
let mut encoder_warmed_up = false;
|
||||
let result = handle_one_frame(
|
||||
0,
|
||||
&sp,
|
||||
EncodeInput::YUV(&[1]),
|
||||
0,
|
||||
&mut encoder,
|
||||
recorder.clone(),
|
||||
&mut normal_failures,
|
||||
&mut first_frame,
|
||||
&mut encoder_warmed_up,
|
||||
1,
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.send_conn_ids.is_empty());
|
||||
assert_eq!(result.vpx_no_output, vpx_no_output);
|
||||
refresh.on_frame_encoded(&result);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(state.borrow().calls, 1, "{codec:?}");
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsuccessful_repeats_preserve_the_frame_budget() {
|
||||
let sp = GenericService::new("repeat-frame-budget-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
for codec in [CodecFormat::VP8, CodecFormat::VP9] {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
sp.on_subscribe(ConnInner::new(1, None, Some(tx)));
|
||||
let mut refresh = new_refresh(VideoSource::Monitor, codec, &sp, &recorder, 0, 1, 1);
|
||||
let limit = max_repeat_frames(codec, BR_BALANCED, HardwareBackend::Other);
|
||||
let mut outcomes = vec![Outcome::Dropped; 40];
|
||||
outcomes.extend(vec![Outcome::Empty; 40]);
|
||||
outcomes.extend(vec![Outcome::Frame; limit + 1]);
|
||||
let (mut encoder, state) = encoder(&outcomes);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
for _ in 0..80 {
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
}
|
||||
assert_eq!(rx.len(), 0, "{codec:?}");
|
||||
for _ in 0..=limit {
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
}
|
||||
assert_eq!(state.borrow().calls, 80 + limit, "{codec:?}");
|
||||
assert_eq!(rx.len(), limit);
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
sp.on_unsubscribe(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_intervals_are_codec_specific_after_the_first_attempt() {
|
||||
let sp = GenericService::new("repeat-interval-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
for (codec, spf_ms, first_interval_ms, repeat_interval_ms) in [
|
||||
(CodecFormat::VP8, 10, 100, 100),
|
||||
(CodecFormat::VP9, 10, 100, 100),
|
||||
(CodecFormat::VP8, 200, 200, 200),
|
||||
(CodecFormat::VP9, 200, 200, 200),
|
||||
(CodecFormat::H264, 10, 100, 34),
|
||||
(CodecFormat::H265, 10, 100, 34),
|
||||
(CodecFormat::H264, 16, 100, 34),
|
||||
(CodecFormat::H265, 16, 100, 34),
|
||||
(CodecFormat::H264, 50, 100, 50),
|
||||
(CodecFormat::H265, 50, 100, 50),
|
||||
(CodecFormat::H264, 200, 200, 200),
|
||||
(CodecFormat::H265, 200, 200, 200),
|
||||
] {
|
||||
for first in [
|
||||
Outcome::Frame,
|
||||
Outcome::Empty,
|
||||
Outcome::Dropped,
|
||||
Outcome::Error,
|
||||
] {
|
||||
let mut refresh = new_refresh(VideoSource::Monitor, codec, &sp, &recorder, 0, 1, 1);
|
||||
let (mut encoder, state) = encoder(&[first, Outcome::Frame]);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
for (elapsed_ms, expected_calls) in [
|
||||
(first_interval_ms - 1, 0),
|
||||
(first_interval_ms, 1),
|
||||
(repeat_interval_ms - 1, 1),
|
||||
(repeat_interval_ms, 2),
|
||||
] {
|
||||
refresh.elapsed_since_encode = Duration::from_millis(elapsed_ms);
|
||||
refresh
|
||||
.try_encode(
|
||||
&[1],
|
||||
Duration::from_millis(spf_ms),
|
||||
BR_BALANCED,
|
||||
Instant::now(),
|
||||
0,
|
||||
&mut encoder,
|
||||
&mut VideoFrameController::new(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(state.borrow().calls, expected_calls, "{codec:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_timing_uses_the_capture_loop_start() {
|
||||
let sp = GenericService::new("repeat-loop-clock-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
let spf = Duration::from_nanos(33_333_333);
|
||||
let clock_start = Instant::now() + Duration::from_secs(1);
|
||||
for first in [
|
||||
Outcome::Frame,
|
||||
Outcome::Empty,
|
||||
Outcome::Dropped,
|
||||
Outcome::Error,
|
||||
] {
|
||||
let mut refresh = new_refresh(
|
||||
VideoSource::Monitor,
|
||||
CodecFormat::H264,
|
||||
&sp,
|
||||
&recorder,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
);
|
||||
let (mut encoder, state) = encoder(&[first, Outcome::Frame]);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
refresh.last_encode = clock_start;
|
||||
for (index, loop_start) in [
|
||||
clock_start + INITIAL_REPEAT_INTERVAL,
|
||||
clock_start + INITIAL_REPEAT_INTERVAL + spf,
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
// Capture processing finishes partway through the current loop.
|
||||
let capture_end = loop_start + Duration::from_millis(5);
|
||||
refresh.elapsed_since_encode = capture_end.duration_since(refresh.last_encode);
|
||||
refresh
|
||||
.try_encode(
|
||||
&[1],
|
||||
spf,
|
||||
BR_BALANCED,
|
||||
loop_start,
|
||||
0,
|
||||
&mut encoder,
|
||||
&mut VideoFrameController::new(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(state.borrow().calls, index + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_output_budget_is_cumulative_and_restarts_with_a_new_frame() {
|
||||
let sp = GenericService::new("repeat-no-output-budget-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
for codec in [CodecFormat::VP8, CodecFormat::VP9] {
|
||||
let mut refresh = new_refresh(VideoSource::Monitor, codec, &sp, &recorder, 0, 1, 1);
|
||||
let mut outcomes = Vec::new();
|
||||
for _ in 0..10 {
|
||||
outcomes.push(Outcome::Frame);
|
||||
for _ in 0..5 {
|
||||
outcomes.extend([Outcome::Empty, Outcome::Dropped]);
|
||||
}
|
||||
}
|
||||
outcomes.push(Outcome::Empty);
|
||||
outcomes.push(Outcome::Frame);
|
||||
let (mut encoder, state) = encoder(&outcomes);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
for _ in 0..111 {
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
}
|
||||
assert_eq!(state.borrow().calls, 110, "{codec:?}");
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(false);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(state.borrow().calls, 110);
|
||||
refresh.on_encoded(true);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(state.borrow().calls, 111);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(state.borrow().calls, 112);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_error_limits_are_codec_specific() {
|
||||
let sp = GenericService::new("repeat-codec-errors-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
for (codec, expected_calls) in [
|
||||
(CodecFormat::VP8, 100),
|
||||
(CodecFormat::VP9, 100),
|
||||
(CodecFormat::AV1, 0),
|
||||
(CodecFormat::H264, 3),
|
||||
(CodecFormat::H265, 3),
|
||||
] {
|
||||
let mut refresh = new_refresh(VideoSource::Monitor, codec, &sp, &recorder, 0, 1, 1);
|
||||
let limit = MAX_REPEAT_NO_OUTPUTS;
|
||||
let (mut encoder, state) = encoder(&vec![Outcome::Error; limit]);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
for _ in 0..=limit {
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
}
|
||||
assert_eq!(state.borrow().calls, expected_calls, "{codec:?}");
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeats_leave_normal_failure_tracking_and_switching_intact() {
|
||||
use super::super::handle_one_frame;
|
||||
use Outcome::*;
|
||||
let sp = GenericService::new("repeat-normal-errors-test".to_owned(), false);
|
||||
let recorder = Arc::new(Mutex::new(None));
|
||||
let mut refresh = new_refresh(
|
||||
VideoSource::Monitor,
|
||||
CodecFormat::H264,
|
||||
&sp,
|
||||
&recorder,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
);
|
||||
let normal_limit = if cfg!(target_os = "android") { 9 } else { 3 };
|
||||
let mut outcomes = vec![Error, Error, Frame];
|
||||
outcomes.extend(vec![Error; normal_limit - 1]);
|
||||
let (mut encoder, state) = encoder(&outcomes);
|
||||
refresh.on_frame(&EncodeInput::YUV(&[1]));
|
||||
refresh.on_encoded(true);
|
||||
let mut normal_failures = 0;
|
||||
let mut first_frame = false;
|
||||
let mut encoder_warmed_up = false;
|
||||
handle_one_frame(
|
||||
0,
|
||||
&sp,
|
||||
EncodeInput::YUV(&[1]),
|
||||
0,
|
||||
&mut encoder,
|
||||
recorder.clone(),
|
||||
&mut normal_failures,
|
||||
&mut first_frame,
|
||||
&mut encoder_warmed_up,
|
||||
1,
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
attempt(&mut refresh, &mut encoder);
|
||||
assert_eq!(state.borrow().disabled, 0);
|
||||
for _ in 2..normal_limit {
|
||||
handle_one_frame(
|
||||
0,
|
||||
&sp,
|
||||
EncodeInput::YUV(&[1]),
|
||||
0,
|
||||
&mut encoder,
|
||||
recorder.clone(),
|
||||
&mut normal_failures,
|
||||
&mut first_frame,
|
||||
&mut encoder_warmed_up,
|
||||
1,
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let result = handle_one_frame(
|
||||
0,
|
||||
&sp,
|
||||
EncodeInput::YUV(&[1]),
|
||||
0,
|
||||
&mut encoder,
|
||||
recorder.clone(),
|
||||
&mut normal_failures,
|
||||
&mut first_frame,
|
||||
&mut encoder_warmed_up,
|
||||
1,
|
||||
1,
|
||||
);
|
||||
assert_eq!(result.unwrap_err().to_string(), "SWITCH");
|
||||
assert_eq!(state.borrow().disabled, 1);
|
||||
}
|
||||
Reference in New Issue
Block a user