Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions app/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- When an Android emulator does not confirm that a recording stopped, the
recording stays active and shows the error, so stopping it again
retries instead of starting a new recording.
- Closing an Android stream or quitting SimUtil while the stream is still
starting no longer leaves adb running.
- Quitting SimUtil while an Android emulator is streamed no longer hangs.
- Closing an Android emulator's stream while its recording is being
stopped no longer converts the recording twice.

## [0.6.1] - 2026-11-21

### Fixed
Expand Down
43 changes: 43 additions & 0 deletions app/test/streams_cubit_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,29 @@ class _FakeSession implements DeviceSession {
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}

/// A session whose recording stop fails until [stopWorks] is set.
class _RecordingSession extends _FakeSession {
_RecordingSession(super.deviceId);

bool recording = false;
bool stopWorks = false;
int stops = 0;

@override
bool get isRecording => recording;

@override
Future<void> startRecording(String path) async => recording = true;

@override
Future<String?> stopRecording() async {
stops++;
if (!stopWorks) throw StateError('Recording did not stop: offline');
recording = false;
return '/rec/done.mp4';
}
}

void main() {
Device sim(DeviceState state) => Device.ios(
id: 'UDID',
Expand Down Expand Up @@ -259,4 +282,24 @@ void main() {
expect(cubit.stateValue.isOpen('UDID'), isTrue);
await cubit.close();
});

test('a recording whose stop fails stays recording for a retry', () async {
final session = _RecordingSession('UDID')..gate.complete();
final saved = <String>[];
final cubit = StreamsCubit((_) async => session, onSaved: saved.add);
await cubit.open(sim(DeviceState.booted));
await cubit.toggleRecording('UDID', '/rec');
bool recording() => cubit.stateValue.entries.single.recordingSince != null;
expect(recording(), isTrue);

await expectLater(cubit.toggleRecording('UDID', '/rec'), throwsStateError);
expect(recording(), isTrue);
expect(saved, isEmpty);

session.stopWorks = true;
expect(await cubit.toggleRecording('UDID', '/rec'), '/rec/done.mp4');
expect(recording(), isFalse);
expect(saved, ['/rec/done.mp4']);
expect(session.stops, 2);
});
}
22 changes: 22 additions & 0 deletions packages/simutil_adb/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
# Changelog

## 1.5.1

- `EmulatorGrpcSession.stopRecording` throws a `StateError` when the
emulator does not confirm `screenrecord stop` (adb fails, times out or
answers `KO`), and keeps the recording active so the caller can retry;
it returned null and dropped the recording, although the emulator could
still be recording. `stop()` still ends the session in that case.
- `ScrcpySession` releases its server, control socket and `adb forward`
when the video stream ends before the session went live; only a failed
live session gets closed by its owner.
- `ScrcpySession.stop()` cancels a video handshake still in progress
instead of waiting for its 10 s timeout.
- A second `EmulatorGrpcSession.stopRecording()` while one is running
waits for it and returns its result, instead of stopping, converting
and deleting the same file again.
- `EmulatorGrpcSession.stop()` ends running gRPC calls instead of waiting
for them, so it no longer hangs while a frame stream is still listened
to (the app quitting with a stream open).
- `ScrcpySession.stop()` during `start()` waits (up to 3 s) until the
start has released the `adb forward` and server process it was still
creating, so nothing outlives `stop()`; it returned before that.

## 1.5.0

- `AndroidDeviceService.launchDevice` returns once the emulator is up
Expand Down
37 changes: 28 additions & 9 deletions packages/simutil_adb/lib/src/emulator/emulator_grpc_session.dart
Original file line number Diff line number Diff line change
Expand Up @@ -282,19 +282,32 @@ class _EmulatorGrpcSession implements EmulatorGrpcSession {
_recordingPath = path;
}

/// The stop in progress: a second [stopRecording] (closing the stream
/// while the record button's stop runs) joins it instead of stopping
/// and converting the same file again.
Future<String?>? _stoppingRecording;

/// Throws a [StateError] when the emulator does not confirm the stop: it
/// may still be recording, so the recording stays active (and the
/// `.webm` untouched) for the caller to retry.
@override
Future<String?> stopRecording() async {
Future<String?> stopRecording() => _stoppingRecording ??= _stopRecording()
.whenComplete(() => _stoppingRecording = null);

Future<String?> _stopRecording() async {
final path = _recordingPath;
_recordingPath = null;
if (path == null) return null;
// Until the emulator confirms the stop it may still be writing the
// file: then report nothing saved and leave the `.webm` as it is.
final String? failure;
try {
final stopped = await _emu(['screenrecord', 'stop']);
if (!stopped.success || stopped.stdout.contains('KO')) return null;
} catch (_) {
return null;
failure = !stopped.success || stopped.stdout.contains('KO')
? (stopped.stdout + stopped.stderr).trim()
: null;
} catch (e) {
throw StateError('Recording did not stop: $e');
}
if (failure != null) throw StateError('Recording did not stop: $failure');
_recordingPath = null;
final converted = await runFfmpeg(_exec, [
'-y',
'-loglevel',
Expand Down Expand Up @@ -325,10 +338,16 @@ class _EmulatorGrpcSession implements EmulatorGrpcSession {
@override
Future<void> stop() async {
if (_stopped) return;
await stopRecording();
try {
await stopRecording();
} on StateError {
// The session goes away anyway; the emulator keeps the `.webm`.
}
_stopped = true;
unawaited(_input?.close());
await _channel.shutdown();
// Not shutdown(): it waits for running calls, and a frame stream whose
// listener is not cancelled (the app quitting) never ends.
await _channel.terminate();
await _statusController.close();
}
}
34 changes: 31 additions & 3 deletions packages/simutil_adb/lib/src/scrcpy/scrcpy_session.dart
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ class _ScrcpySession implements ScrcpySession {

/// Set once the video worker reports the stream's end.
bool _videoEnded = false;

/// Completes on [stop], cancelling a video handshake still in progress.
final _stopRequested = Completer<void>();
late final _frames = StreamController<(Uint8List, bool)>.broadcast(
onListen: () => _video?.forward(true),
onCancel: () => _video?.forward(false),
Expand Down Expand Up @@ -187,20 +190,30 @@ class _ScrcpySession implements ScrcpySession {

@override
Future<void> start() async {
final done = _startDone = Completer<void>();
_emit(const SessionConnecting());
try {
await _startServer();
if (!_stopped) await _connect();
} catch (e) {
// Emit before stop(): it closes the status stream.
// Emit before stopping: it closes the status stream.
_emit(SessionFailed('$e'));
await stop();
await _shutDown();
} finally {
// stop() during the start only released what existed by then.
if (_stopped) await _release();
done.complete();
}
}

/// Completes when the running [start] is done, including releasing what
/// it created after a [stop].
Completer<void>? _startDone;

/// How long [stop] waits for a running [start] to release what it is
/// still creating (an `adb forward`, the server's `adb shell`).
static const _startSettle = Duration(seconds: 3);

/// Polls `sys.boot_completed` with short commands, so a booting device
/// does not hold a [CommandExec] slot for minutes and [stop] ends the
/// wait.
Expand Down Expand Up @@ -328,8 +341,14 @@ class _ScrcpySession implements ScrcpySession {
onKeyFrameNeeded: requestKeyFrame,
onEnded: () {
_videoEnded = true;
if (!_stopped) _emit(const SessionFailed('Stream ended'));
if (_stopped) return;
final wasLive = _status is SessionLive;
_emit(const SessionFailed('Stream ended'));
// Only a failed live stream gets closed by its owner; one that never
// went live would keep its server and forward until then.
if (!wasLive) unawaited(stop());
},
cancel: _stopRequested.future,
);

/// Live only with a control socket, so a view's key-frame request on
Expand Down Expand Up @@ -425,7 +444,16 @@ class _ScrcpySession implements ScrcpySession {

@override
Future<void> stop() async {
await _shutDown();
// A start in flight may still be creating the forward or the server
// process; it releases them once it sees the stop. Wait for that, so
// nothing outlives stop() (an app quitting right after it).
await _startDone?.future.timeout(_startSettle, onTimeout: () {});
}

Future<void> _shutDown() async {
if (_stopped) return;
if (!_stopRequested.isCompleted) _stopRequested.complete();
await stopRecording();
_stopped = true;
_keyFrameTimer?.cancel();
Expand Down
16 changes: 14 additions & 2 deletions packages/simutil_adb/lib/src/scrcpy/scrcpy_video_worker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,15 @@ class ScrcpyVideoWorker {
/// [onSize] gets each session header, [onFrame] every access unit (key
/// frames prefixed with SPS/PPS) while [forward] is on, [onKeyFrameNeeded]
/// an attached decoder dropping frames, and [onEnded] the socket closing.
/// When [cancel] completes before the handshake does, the worker is
/// killed (its socket goes with it) and this throws.
static Future<ScrcpyVideoWorker> connect(
int port, {
required void Function(int width, int height) onSize,
required void Function(Uint8List frame, bool keyFrame) onFrame,
required void Function() onKeyFrameNeeded,
required void Function() onEnded,
Future<void>? cancel,
}) async {
final events = ReceivePort();
final exit = ReceivePort();
Expand All @@ -55,8 +58,10 @@ class ScrcpyVideoWorker {
});
events.listen((message) {
switch (message) {
// Cancelled first: the port may still be queued; the worker is
// already being killed.
case final SendPort port:
commands.complete(port);
if (!commands.isCompleted) commands.complete(port);
case (final int width, final int height):
onSize(width, height);
case (final Uint8List frame, final bool keyFrame):
Expand All @@ -73,13 +78,20 @@ class ScrcpyVideoWorker {
onEnded();
}
});
await Isolate.spawn(
final isolate = await Isolate.spawn(
_main,
(events.sendPort, port),
onExit: exit.sendPort,
onError: events.sendPort,
debugName: 'scrcpy video',
);
unawaited(
cancel?.then((_) {
if (commands.isCompleted) return;
fail(StateError('scrcpy video connection cancelled'));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
isolate.kill(priority: Isolate.immediate);
}),
);
return ScrcpyVideoWorker._(await commands.future, exited.future);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/simutil_adb/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: simutil_adb
description: Android emulator and device APIs for SimUtil via adb.
version: 1.5.0
version: 1.5.1
homepage: https://github.com/dungngminh/simutil
repository: https://github.com/dungngminh/simutil/tree/main/packages/simutil_adb
issue_tracker: https://github.com/dungngminh/simutil/issues
Expand Down
29 changes: 27 additions & 2 deletions packages/simutil_adb/test/emulator/emulator_grpc_session_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ import 'package:test/test.dart';

/// An emulator whose display answers [screenshot] in turn.
class _FakeEmulator extends EmulatorControllerServiceBase {
_FakeEmulator(this.screenshot);
_FakeEmulator(this.screenshot, {this.frames = const Stream.empty()});

final Future<Image> Function(int call) screenshot;

/// What `streamScreenshot` sends; the emulator's never ends.
final Stream<Image> frames;
var calls = 0;

@override
Expand All @@ -22,7 +25,7 @@ class _FakeEmulator extends EmulatorControllerServiceBase {

@override
Stream<Image> streamScreenshot(ServiceCall call, ImageFormat request) =>
const Stream.empty();
frames;

@override
Future<Empty> streamInputEvent(
Expand Down Expand Up @@ -87,4 +90,26 @@ void main() {
]);
expect(emulator.calls, 1);
});

test('stop() ends a frame stream that is still running', () async {
final frames = StreamController<Image>();
addTearDown(frames.close);
final emulator = _FakeEmulator(
(_) async => _display(1080, 2424),
frames: frames.stream,
);
final session = await sessionFor(emulator);
await session.start();
final received = Completer<void>();
// Like the app's frame pump during a quit: nobody cancels it.
session.frames(path: '/tmp/frames', width: 1080, height: 2424).listen((_) {
if (!received.isCompleted) received.complete();
}, onError: (Object _) {});
frames.add(_display(1080, 2424));
await received.future.timeout(const Duration(seconds: 5));

final clock = Stopwatch()..start();
await session.stop().timeout(const Duration(seconds: 5));
expect(clock.elapsed, lessThan(const Duration(seconds: 2)));
});
}
Loading
Loading