From e23900a7049838a40b97e42cf1e599559cc120b9 Mon Sep 17 00:00:00 2001 From: JKook <10250087+JKook-Plus@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:09:58 +1100 Subject: [PATCH] Fix black preview when the phone refuses USB transfers (0.1.1) On a Pixel 7 Pro short of memory the kernel refused libuvc's 96 KB isochronous transfers with ENOMEM. libuvc freed each refused transfer, and even reported success when the first one failed, so the stream lost its transfers and went black while the app still said "streaming". - New libuvc patch: transfers of 32 KB at most, refused or failed transfers are parked and queued again from the event thread, parked transfers are freed on stop, and a submit hook for tests. - usbcam.cpp: retries parked transfers, resets the video interface to alt 0 before negotiating, and resets the USB port once if the camera still refuses to start with an I/O error (seen after the app was killed mid-stream). Debug builds read debug.hardline.usbfail to fail a share of submissions on purpose. - CameraController: restarts a stream that delivers no frames for 5 s, and shows an error after 3 restarts in a minute. - Version 0.1.1 (versionCode 2), changelog and docs. Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 4 +- .../cpp/patches/libuvc-0.0.8-transfers.patch | 343 ++++++++++++++++++ app/src/main/cpp/usbcam.cpp | 116 +++++- .../dev/hardline/service/CameraController.kt | 59 +++ docs/BUILDING.md | 14 +- docs/TESTING.md | 6 + .../metadata/android/en-US/changelogs/2.txt | 1 + 7 files changed, 527 insertions(+), 16 deletions(-) create mode 100644 app/src/main/cpp/patches/libuvc-0.0.8-transfers.patch create mode 100644 fastlane/metadata/android/en-US/changelogs/2.txt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 053f7c4..bbb2fd5 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -21,8 +21,8 @@ android { applicationId = "dev.hardline" minSdk = 26 targetSdk = 34 - versionCode = 1 - versionName = "0.1.0" + versionCode = 2 + versionName = "0.1.1" ndk { abiFilters += listOf("arm64-v8a", "x86_64") } externalNativeBuild { cmake { arguments += "-DANDROID_STL=c++_static" } } } diff --git a/app/src/main/cpp/patches/libuvc-0.0.8-transfers.patch b/app/src/main/cpp/patches/libuvc-0.0.8-transfers.patch new file mode 100644 index 0000000..a9807b4 --- /dev/null +++ b/app/src/main/cpp/patches/libuvc-0.0.8-transfers.patch @@ -0,0 +1,343 @@ +Keep video transfers small and never drop one the kernel refuses. + +libuvc 0.0.8 queues 100 isochronous transfers of up to 32 packets each, about 96 KB per transfer +for a typical USB 2 camera. The kernel needs one physically contiguous buffer per transfer, and a +phone that is short of memory refuses blocks that large with ENOMEM. libuvc then freed the refused +transfer, or, if the very first one failed, all of them while still reporting success. The stream +lost its transfers one by one and went quiet with no error. + +This caps each transfer at 32 KB, parks a refused or failed transfer instead of freeing it, adds +uvc_retry_parked_transfers() for the event thread to queue parked transfers again, and frees parked +transfers when the stream stops. uvc_submit_hook lets tests make submissions fail. + +--- a/include/libuvc/libuvc.h ++++ b/include/libuvc/libuvc.h +@@ -643,6 +643,16 @@ + + void uvc_stop_streaming(uvc_device_handle_t *devh); + ++/* Transfers the kernel refused to queue (phones short of memory answer ENOMEM) are kept rather ++ * than freed. Call this regularly from the thread that handles libusb events; it queues them ++ * again, at most every 20 ms. Returns how many are still waiting. */ ++int uvc_retry_parked_transfers(uvc_device_handle_t *devh); ++ ++struct libusb_transfer; ++/* When set, libuvc submits its video transfers through this function instead of ++ * libusb_submit_transfer. Meant for tests that need submissions to fail. */ ++extern int (*uvc_submit_hook)(struct libusb_transfer *transfer); ++ + uvc_error_t uvc_stream_open_ctrl(uvc_device_handle_t *devh, uvc_stream_handle_t **strmh, uvc_stream_ctrl_t *ctrl); + uvc_error_t uvc_stream_ctrl(uvc_stream_handle_t *strmh, uvc_stream_ctrl_t *ctrl); + uvc_error_t uvc_stream_get_current_ctrl(uvc_stream_handle_t *strmh, uvc_stream_ctrl_t *ctrl); +--- a/include/libuvc/libuvc_internal.h ++++ b/include/libuvc/libuvc_internal.h +@@ -259,6 +259,12 @@ + void *user_ptr; + struct libusb_transfer *transfers[LIBUVC_NUM_TRANSFER_BUFS]; + uint8_t *transfer_bufs[LIBUVC_NUM_TRANSFER_BUFS]; ++ /* transfers the kernel refused, waiting for uvc_retry_parked_transfers(); guarded by cb_mutex */ ++ uint8_t parked[LIBUVC_NUM_TRANSFER_BUFS]; ++ int num_parked; ++ uint32_t submit_failures; ++ /* only touched by the event thread */ ++ struct timespec last_retry; + struct uvc_frame frame; + enum uvc_frame_format frame_format; + struct timespec capture_time_finished; +--- a/src/stream.c ++++ b/src/stream.c +@@ -39,6 +39,7 @@ + #include "libuvc/libuvc.h" + #include "libuvc/libuvc_internal.h" + #include "errno.h" ++#include + + #ifdef _MSC_VER + +@@ -834,10 +835,59 @@ + * + * @param transfer Active transfer + */ ++int (*uvc_submit_hook)(struct libusb_transfer *transfer) = NULL; ++ ++static int _uvc_submit(struct libusb_transfer *transfer) { ++ return uvc_submit_hook ? uvc_submit_hook(transfer) : libusb_submit_transfer(transfer); ++} ++ ++/* Frees a transfer for good. Call with cb_mutex held. */ ++static void _uvc_free_transfer_locked(uvc_stream_handle_t *strmh, struct libusb_transfer *transfer) { ++ int i; ++ for (i = 0; i < LIBUVC_NUM_TRANSFER_BUFS; i++) { ++ if (strmh->transfers[i] == transfer) { ++ free(transfer->buffer); ++ libusb_free_transfer(transfer); ++ strmh->transfers[i] = NULL; ++ if (strmh->parked[i]) { ++ strmh->parked[i] = 0; ++ strmh->num_parked--; ++ } ++ break; ++ } ++ } ++ if (i == LIBUVC_NUM_TRANSFER_BUFS) ++ UVC_DEBUG("transfer %p not found; not freeing!", transfer); ++ pthread_cond_broadcast(&strmh->cb_cond); ++} ++ ++/* Keeps a transfer the kernel would not queue, for uvc_retry_parked_transfers(). Call with ++ * cb_mutex held. */ ++static void _uvc_park_transfer_locked(uvc_stream_handle_t *strmh, struct libusb_transfer *transfer) { ++ int i; ++ strmh->submit_failures++; ++ for (i = 0; i < LIBUVC_NUM_TRANSFER_BUFS; i++) { ++ if (strmh->transfers[i] == transfer) { ++ if (!strmh->parked[i]) { ++ strmh->parked[i] = 1; ++ strmh->num_parked++; ++ } ++ break; ++ } ++ } ++ pthread_cond_broadcast(&strmh->cb_cond); ++} ++ ++/* ++ * Every finished transfer is queued again while the stream runs. A transfer is freed only when ++ * the stream stops or the device is gone. One the kernel refuses (ENOMEM when a phone is short of ++ * memory) or that failed as a whole is parked and queued again by uvc_retry_parked_transfers(); ++ * stock libuvc freed it, so a stream could lose every transfer and go quiet without an error. ++ */ + void LIBUSB_CALL _uvc_stream_callback(struct libusb_transfer *transfer) { + uvc_stream_handle_t *strmh = transfer->user_data; +- +- int resubmit = 1; ++ enum { RESUBMIT, PARK, FREE } next = RESUBMIT; ++ int r; + + switch (transfer->status) { + case LIBUSB_TRANSFER_COMPLETED: +@@ -865,88 +915,72 @@ + } + } + break; +- case LIBUSB_TRANSFER_CANCELLED: +- case LIBUSB_TRANSFER_ERROR: +- case LIBUSB_TRANSFER_NO_DEVICE: { +- int i; ++ case LIBUSB_TRANSFER_CANCELLED: ++ case LIBUSB_TRANSFER_NO_DEVICE: + UVC_DEBUG("not retrying transfer, status = %d", transfer->status); +- pthread_mutex_lock(&strmh->cb_mutex); +- +- /* Mark transfer as deleted. */ +- for(i=0; i < LIBUVC_NUM_TRANSFER_BUFS; i++) { +- if(strmh->transfers[i] == transfer) { +- UVC_DEBUG("Freeing transfer %d (%p)", i, transfer); +- free(transfer->buffer); +- libusb_free_transfer(transfer); +- strmh->transfers[i] = NULL; +- break; +- } +- } +- if(i == LIBUVC_NUM_TRANSFER_BUFS ) { +- UVC_DEBUG("transfer %p not found; not freeing!", transfer); +- } +- +- resubmit = 0; +- +- pthread_cond_broadcast(&strmh->cb_cond); +- pthread_mutex_unlock(&strmh->cb_mutex); +- ++ next = FREE; ++ break; ++ case LIBUSB_TRANSFER_ERROR: ++ UVC_DEBUG("transfer failed, parking it, status = %d", transfer->status); ++ next = PARK; + break; +- } + case LIBUSB_TRANSFER_TIMED_OUT: + case LIBUSB_TRANSFER_STALL: + case LIBUSB_TRANSFER_OVERFLOW: + UVC_DEBUG("retrying transfer, status = %d", transfer->status); + break; + } +- +- if ( resubmit ) { +- if ( strmh->running ) { +- int libusbRet = libusb_submit_transfer(transfer); +- if (libusbRet < 0) +- { +- int i; +- pthread_mutex_lock(&strmh->cb_mutex); + +- /* Mark transfer as deleted. */ +- for (i = 0; i < LIBUVC_NUM_TRANSFER_BUFS; i++) { +- if (strmh->transfers[i] == transfer) { +- UVC_DEBUG("Freeing failed transfer %d (%p)", i, transfer); +- free(transfer->buffer); +- libusb_free_transfer(transfer); +- strmh->transfers[i] = NULL; +- break; +- } +- } +- if (i == LIBUVC_NUM_TRANSFER_BUFS) { +- UVC_DEBUG("failed transfer %p not found; not freeing!", transfer); +- } ++ pthread_mutex_lock(&strmh->cb_mutex); ++ if (next == FREE || !strmh->running) { ++ _uvc_free_transfer_locked(strmh, transfer); ++ } else if (next == PARK) { ++ _uvc_park_transfer_locked(strmh, transfer); ++ } else { ++ r = _uvc_submit(transfer); ++ if (r == LIBUSB_ERROR_NO_DEVICE) ++ _uvc_free_transfer_locked(strmh, transfer); ++ else if (r < 0) ++ _uvc_park_transfer_locked(strmh, transfer); ++ } ++ pthread_mutex_unlock(&strmh->cb_mutex); ++} + +- pthread_cond_broadcast(&strmh->cb_cond); +- pthread_mutex_unlock(&strmh->cb_mutex); +- } +- } else { +- int i; +- pthread_mutex_lock(&strmh->cb_mutex); ++int uvc_retry_parked_transfers(uvc_device_handle_t *devh) { ++ uvc_stream_handle_t *strmh; ++ struct timespec now; ++ int left = 0; + +- /* Mark transfer as deleted. */ +- for(i=0; i < LIBUVC_NUM_TRANSFER_BUFS; i++) { +- if(strmh->transfers[i] == transfer) { +- UVC_DEBUG("Freeing orphan transfer %d (%p)", i, transfer); +- free(transfer->buffer); +- libusb_free_transfer(transfer); +- strmh->transfers[i] = NULL; ++ clock_gettime(CLOCK_MONOTONIC, &now); ++ DL_FOREACH(devh->streams, strmh) { ++ int i, r; ++ long long elapsed_ms = (now.tv_sec - strmh->last_retry.tv_sec) * 1000LL + ++ (now.tv_nsec - strmh->last_retry.tv_nsec) / 1000000; ++ ++ pthread_mutex_lock(&strmh->cb_mutex); ++ if (strmh->running && strmh->num_parked > 0 && elapsed_ms >= 20) { ++ strmh->last_retry = now; ++ for (i = 0; i < LIBUVC_NUM_TRANSFER_BUFS && strmh->running && strmh->num_parked > 0; i++) { ++ if (!strmh->parked[i] || !strmh->transfers[i]) ++ continue; ++ r = _uvc_submit(strmh->transfers[i]); ++ if (r == 0) { ++ strmh->parked[i] = 0; ++ strmh->num_parked--; ++ } else if (r == LIBUSB_ERROR_NO_DEVICE) { ++ _uvc_free_transfer_locked(strmh, strmh->transfers[i]); ++ } else { ++ /* still no room: try again next time rather than hammering the kernel now */ ++ strmh->submit_failures++; + break; + } + } +- if(i == LIBUVC_NUM_TRANSFER_BUFS ) { +- UVC_DEBUG("orphan transfer %p not found; not freeing!", transfer); +- } +- +- pthread_cond_broadcast(&strmh->cb_cond); +- pthread_mutex_unlock(&strmh->cb_mutex); + } ++ if (strmh->running) ++ left += strmh->num_parked; ++ pthread_mutex_unlock(&strmh->cb_mutex); + } ++ return left; + } + + /** Begin streaming video from the camera into the callback function. +@@ -1213,9 +1247,18 @@ + packets_per_transfer = (ctrl->dwMaxVideoFrameSize + + endpoint_bytes_per_packet - 1) / endpoint_bytes_per_packet; + +- /* But keep a reasonable limit: Otherwise we start dropping data */ +- if (packets_per_transfer > 32) +- packets_per_transfer = 32; ++ /* But keep each transfer at 32 KiB or less. The kernel needs one physically ++ * contiguous buffer per transfer, and a phone short of memory refuses anything bigger ++ * (ENOMEM). More, smaller transfers keep the same amount of data queued. */ ++ { ++ size_t cap = 32768 / endpoint_bytes_per_packet; ++ if (cap < 1) ++ cap = 1; ++ if (cap > 32) ++ cap = 32; ++ if (packets_per_transfer > cap) ++ packets_per_transfer = cap; ++ } + + total_transfer_size = packets_per_transfer * endpoint_bytes_per_packet; + break; +@@ -1275,23 +1318,32 @@ + pthread_create(&strmh->cb_thread, NULL, _uvc_user_caller, (void*) strmh); + } + ++ /* A transfer the kernel refuses now is parked and queued later by ++ * uvc_retry_parked_transfers(), so a moment of memory pressure cannot leave the stream ++ * with few or no transfers. */ ++ ret = UVC_SUCCESS; ++ pthread_mutex_lock(&strmh->cb_mutex); ++ memset(strmh->parked, 0, sizeof(strmh->parked)); ++ strmh->num_parked = 0; + for (transfer_id = 0; transfer_id < LIBUVC_NUM_TRANSFER_BUFS; + transfer_id++) { +- ret = libusb_submit_transfer(strmh->transfers[transfer_id]); +- if (ret != UVC_SUCCESS) { +- UVC_DEBUG("libusb_submit_transfer failed: %d",ret); ++ int r = _uvc_submit(strmh->transfers[transfer_id]); ++ if (r == LIBUSB_ERROR_NO_DEVICE) { ++ UVC_DEBUG("libusb_submit_transfer failed: %d", r); + break; + } ++ if (r < 0) ++ _uvc_park_transfer_locked(strmh, strmh->transfers[transfer_id]); + } +- +- if ( ret != UVC_SUCCESS && transfer_id >= 0 ) { +- for ( ; transfer_id < LIBUVC_NUM_TRANSFER_BUFS; transfer_id++) { +- free ( strmh->transfers[transfer_id]->buffer ); +- libusb_free_transfer ( strmh->transfers[transfer_id]); +- strmh->transfers[transfer_id] = 0; ++ if (transfer_id < LIBUVC_NUM_TRANSFER_BUFS) { ++ /* the device is gone: free what was never queued */ ++ int i; ++ for (i = 0; i < LIBUVC_NUM_TRANSFER_BUFS; i++) { ++ if (strmh->transfers[i] && (i >= transfer_id || strmh->parked[i])) ++ _uvc_free_transfer_locked(strmh, strmh->transfers[i]); + } +- ret = UVC_SUCCESS; + } ++ pthread_mutex_unlock(&strmh->cb_mutex); + + UVC_EXIT(ret); + return ret; +@@ -1537,13 +1589,18 @@ + * necessarily completed but they will be free'd in _uvc_stream_callback(). + */ + for(i=0; i < LIBUVC_NUM_TRANSFER_BUFS; i++) { +- if(strmh->transfers[i] != NULL) ++ if(strmh->transfers[i] != NULL && !strmh->parked[i]) + libusb_cancel_transfer(strmh->transfers[i]); + } + +- /* Wait for transfers to complete/cancel */ ++ /* Wait for transfers to complete/cancel. Parked ones are not queued, so nothing will ever ++ * complete them: free them here (a callback may park one while we wait). */ + do { + for(i=0; i < LIBUVC_NUM_TRANSFER_BUFS; i++) { ++ if(strmh->transfers[i] != NULL && strmh->parked[i]) ++ _uvc_free_transfer_locked(strmh, strmh->transfers[i]); ++ } ++ for(i=0; i < LIBUVC_NUM_TRANSFER_BUFS; i++) { + if(strmh->transfers[i] != NULL) + break; + } diff --git a/app/src/main/cpp/usbcam.cpp b/app/src/main/cpp/usbcam.cpp index 3291259..7f13e74 100644 --- a/app/src/main/cpp/usbcam.cpp +++ b/app/src/main/cpp/usbcam.cpp @@ -5,6 +5,9 @@ // optional USB Audio Class capture stream on the same device handle. #include #include +#ifndef NDEBUG +#include +#endif #include #include @@ -74,6 +77,11 @@ struct Session { std::mutex listenerLock; // the button reports on the event thread, whatever the stream is doing std::atomic streaming{false}; int streamInterface = -1; + // Held while a stream starts or stops. The event thread only try_locks it to queue parked + // transfers again: stopping waits for callbacks that only the event thread delivers. + std::mutex videoLock; + int parkedLogged = 0; + std::chrono::steady_clock::time_point parkedLoggedAt{}; std::vector audioAlts; AudioAlt audio; @@ -280,7 +288,10 @@ void button_cb(int button, int state, void *user) { } void stop_video(Session *s, JNIEnv *env) { - if (s->streaming.exchange(false) && s->devh) uvc_stop_streaming(s->devh); + if (s->streaming.exchange(false) && s->devh) { + std::lock_guard v(s->videoLock); + uvc_stop_streaming(s->devh); + } std::lock_guard l(s->listenerLock); if (s->videoListener) { env->DeleteGlobalRef(s->videoListener); @@ -308,6 +319,45 @@ bool is_bulk(Session *s, int ifaceNumber) { return bulk; } +// Notes in the log when the kernel refuses video transfers and when they are all queued again, +// at most once a second. +void log_parked(Session *s, int parked) { + if ((parked > 0) == (s->parkedLogged > 0)) return; + auto now = std::chrono::steady_clock::now(); + if (parked > 0 && now - s->parkedLoggedAt < std::chrono::seconds(1)) return; + if (parked > 0) LOGW("%d video transfers refused by the kernel, retrying", parked); + else LOGI("video transfers queued again"); + s->parkedLogged = parked; + s->parkedLoggedAt = now; +} + +#ifndef NDEBUG +// Debug builds only: `adb shell setprop debug.hardline.usbfail N` makes N percent of video +// transfer submissions fail the way they do on a phone that is short of memory. 0 turns it off. +std::atomic g_fail_percent{0}; +std::atomic g_fail_checked{0}; +std::atomic g_fail_seed{12345}; + +int debug_submit(libusb_transfer *t) { + long long now = std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + if (now - g_fail_checked > 500) { + g_fail_checked = now; + char value[PROP_VALUE_MAX] = {}; + __system_property_get("debug.hardline.usbfail", value); + g_fail_percent = atoi(value); + } + int percent = g_fail_percent; + if (percent > 0) { + uint32_t x = g_fail_seed; + x ^= x << 13; x ^= x >> 17; x ^= x << 5; + g_fail_seed = x; + if (static_cast(x % 100) < percent) return LIBUSB_ERROR_IO; + } + return libusb_submit_transfer(t); +} +#endif + // ---------------------------------------------------------------- JNI jlong n_open(JNIEnv *, jclass, jint fd, jboolean video) { @@ -349,6 +399,10 @@ jlong n_open(JNIEnv *, jclass, jint fd, jboolean video) { while (s->running) { timeval tv{0, 100000}; libusb_handle_events_timeout_completed(s->usb, &tv, nullptr); + if (s->streaming && s->videoLock.try_lock()) { + if (s->streaming && s->devh) log_parked(s, uvc_retry_parked_transfers(s->devh)); + s->videoLock.unlock(); + } } }); return reinterpret_cast(s); @@ -494,16 +548,15 @@ jstring n_describe(JNIEnv *env, jclass, jlong h) { return env->NewStringUTF(j.c_str()); } -jint n_start_video(JNIEnv *env, jclass, jlong h, jint iface, jint format, jint frame, jint interval, jobject listener) { - auto *s = reinterpret_cast(h); - if (!s || !s->devh) return UVC_ERROR_NO_DEVICE; - stop_video(s, env); - uvc_streaming_interface_t *sif = stream_interface(s, iface); - if (!sif) return UVC_ERROR_INVALID_PARAM; - +// Negotiates the format and starts the stream. Leaves the listener set even on failure. +uvc_error_t start_stream(Session *s, JNIEnv *env, uvc_streaming_interface_t *sif, jint format, jint frame, + jint interval, jobject listener) { uvc_stream_ctrl_t ctrl{}; ctrl.bInterfaceNumber = sif->bInterfaceNumber; uvc_claim_if(s->devh, ctrl.bInterfaceNumber); + // Stop any stream the camera still thinks is running, as the kernel's uvcvideo driver does: + // an app killed mid-stream never sets alternate setting 0 again. + libusb_set_interface_alt_setting(s->usbh, ctrl.bInterfaceNumber, 0); uvc_query_stream_ctrl(s->devh, &ctrl, 1, UVC_GET_MAX); ctrl.bInterfaceNumber = sif->bInterfaceNumber; ctrl.bmHint = 1; @@ -523,14 +576,50 @@ jint n_start_video(JNIEnv *env, jclass, jlong h, jint iface, jint format, jint f s->videoListener = env->NewGlobalRef(listener); } s->streamInterface = sif->bInterfaceNumber; - s->streaming = true; - e = uvc_start_streaming(s->devh, &ctrl, frame_cb, s, 0); + { + std::lock_guard v(s->videoLock); + s->streaming = true; + e = uvc_start_streaming(s->devh, &ctrl, frame_cb, s, 0); + } if (e != UVC_SUCCESS) { stop_video(s, env); set_error(std::string("start stream: ") + uvc_strerror(e)); - return e; } - return 0; + return e; +} + +// A reset kills the transfer that carries the camera button, and libuvc does not queue it again +// after an error. Queue it once the event thread has seen it end. +void restart_status(Session *s) { + if (!s->devh || !s->devh->status_xfer) return; + for (int i = 0; i < 50; i++) { + int r = libusb_submit_transfer(s->devh->status_xfer); + if (r != LIBUSB_ERROR_BUSY) { + if (r != 0) LOGW("button transfer after reset: %s", libusb_error_name(r)); + return; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } +} + +jint n_start_video(JNIEnv *env, jclass, jlong h, jint iface, jint format, jint frame, jint interval, jobject listener) { + auto *s = reinterpret_cast(h); + if (!s || !s->devh) return UVC_ERROR_NO_DEVICE; + stop_video(s, env); + uvc_streaming_interface_t *sif = stream_interface(s, iface); + if (!sif) return UVC_ERROR_INVALID_PARAM; + uvc_error_t e = start_stream(s, env, sif, format, frame, interval, listener); + if (e == UVC_ERROR_IO) { + // Some cameras (349c:8319) left streaming by an app that was killed answer every request + // to start with an I/O error until they are re-plugged. A port reset does the same. + int r = libusb_reset_device(s->usbh); + LOGW("camera refused to start (%s), USB reset %s", uvc_strerror(e), r == 0 ? "done" : libusb_error_name(r)); + if (r == LIBUSB_SUCCESS) { + restart_status(s); + e = start_stream(s, env, sif, format, frame, interval, listener); + } + } + return e == UVC_SUCCESS ? 0 : e; } void n_stop_video(JNIEnv *env, jclass, jlong h) { @@ -636,6 +725,9 @@ const JNINativeMethod kMethods[] = { JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *) { g_vm = vm; +#ifndef NDEBUG + uvc_submit_hook = debug_submit; +#endif JNIEnv *env = nullptr; if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) return JNI_ERR; jclass cls = env->FindClass("dev/hardline/usb/UsbNative"); diff --git a/app/src/main/java/dev/hardline/service/CameraController.kt b/app/src/main/java/dev/hardline/service/CameraController.kt index 0ca262f..017875b 100644 --- a/app/src/main/java/dev/hardline/service/CameraController.kt +++ b/app/src/main/java/dev/hardline/service/CameraController.kt @@ -22,6 +22,7 @@ import android.net.nsd.NsdServiceInfo import android.os.BatteryManager import android.os.Build import android.os.PowerManager +import android.os.SystemClock import android.os.VibrationEffect import android.os.Vibrator import android.util.Log @@ -151,6 +152,8 @@ class CameraController(val app: Application) { private var settingsListener: Any? = null private val ejected = HashSet() private var cameraButtonDown = false + private var stallWatch: Job? = null + private val stallRestarts = ArrayDeque() private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { @@ -278,6 +281,9 @@ class CameraController(val app: Application) { setMotionDetection(false) stopPush() setServer(false) + stallWatch?.cancel() + stallWatch = null + stallRestarts.clear() session.value = null selection.value = null audioNotice.value = false @@ -365,6 +371,8 @@ class CameraController(val app: Application) { error.value = "${s.displayName} does not offer a video format this app can show." return } + stallWatch?.cancel() + stallWatch = null val failure = withContext(Dispatchers.IO) { s.stopVideo() ingest?.close() @@ -389,6 +397,7 @@ class CameraController(val app: Application) { return } selection.value = sel + ingest?.let { watchForStall(s, sel, it) } saveState(s) { put("stream", sel.stream.number); put("fourcc", sel.format.fourcc) put("width", sel.frame.width); put("height", sel.frame.height); put("interval", sel.interval) @@ -397,6 +406,51 @@ class CameraController(val app: Application) { updateNotification() } + /** + * Restarts the stream when the camera stops delivering frames, and says so when restarting + * does not help. Without this a stream that lost its USB transfers stayed black while the app + * still showed it as streaming. + */ + private fun watchForStall(s: UsbSession, sel: Selection, watched: VideoIngest) { + // At least STALL_MS, and three frame times for very slow frame rates (interval is in 100 ns). + val limitMs = maxOf(STALL_MS, 3L * sel.interval / 10_000) + stallWatch = scope.launch { + var seen = watched.frames.get() + var changedAt = SystemClock.elapsedRealtime() + while (true) { + delay(1000) + val now = SystemClock.elapsedRealtime() + val count = watched.frames.get() + if (count != seen) { + seen = count + changedAt = now + } else if (now - changedAt >= limitMs) { + break + } + } + onStall(s, sel, seen == 0L) + } + } + + private fun onStall(s: UsbSession, sel: Selection, neverStarted: Boolean) = scope.launch { + lock.withLock { + if (session.value !== s || selection.value != sel) return@withLock + val now = SystemClock.elapsedRealtime() + while (stallRestarts.isNotEmpty() && now - stallRestarts.first() > STALL_WINDOW_MS) stallRestarts.removeFirst() + if (stallRestarts.size >= STALL_RESTARTS) { + Log.w(TAG, "no video after ${stallRestarts.size} restarts, giving up") + stallRestarts.clear() + error.value = "${s.displayName} stopped sending video and restarting the stream did not help.\n" + + "Unplug the camera and plug it in again. If it keeps happening, close other apps or pick a lower resolution." + return@withLock + } + stallRestarts.addLast(now) + Log.w(TAG, if (neverStarted) "no video since the stream started, restarting it" else "video stopped, restarting the stream") + messages.tryEmit("No video from the camera, restarting it") + startStreamLocked(s, sel) + } + } + fun decoderName(): String? = ingest?.decoderName fun addCompressedListener(l: (PixelKind, ByteArray, Int, Long) -> Unit) { compressedListeners += l } fun removeCompressedListener(l: (PixelKind, ByteArray, Int, Long) -> Unit) { compressedListeners -= l } @@ -913,6 +967,11 @@ class CameraController(val app: Application) { companion object { private const val TAG = "CameraController" + /** How long without a frame before the stream counts as stalled. */ + private const val STALL_MS = 5_000L + /** Restarts allowed within [STALL_WINDOW_MS] before the app gives up and says so. */ + private const val STALL_RESTARTS = 3 + private const val STALL_WINDOW_MS = 60_000L const val ACTION_PERMISSION = "dev.hardline.USB_PERMISSION" } } diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 7df5dc9..508bf31 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -34,8 +34,18 @@ libusb and libuvc are not in the repository. Before the native build, Gradle run It does nothing when the sources are already there, so only the first build needs a network connection. To change a version, edit the URL and checksum in the script. -There is one patch. It adds the H.265 format identifiers to libuvc so that cameras with an H.265 -stream have a usable format. +There are two patches, both for libuvc: + +- `libuvc-0.0.8-h265.patch` adds the H.265 format identifiers, so that cameras with an H.265 + stream have a usable format. +- `libuvc-0.0.8-transfers.patch` keeps each video transfer at 32 KB or less and keeps a transfer + the kernel refuses instead of freeing it. The event thread in `usbcam.cpp` queues those again. + Phones that are short of memory refuse large transfers, and stock libuvc then lost them one by + one until the picture went black. + +`usbcam.cpp` also sets the video interface back to alternate setting 0 before it negotiates a +format, and resets the USB port once if the camera still answers the start request with an I/O +error. Both undo what an app killed in the middle of a stream leaves behind. If you open the project in Android Studio before building once, run `scripts/fetch-deps.sh` yourself first. Studio configures CMake during sync, before any Gradle task has run. diff --git a/docs/TESTING.md b/docs/TESTING.md index 0e1eaea..e17ed0b 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -81,6 +81,12 @@ Two things are driven from outside while it runs: - `touch /tmp/vcam-still` freezes the picture and `rm /tmp/vcam-still` lets it move again. Use it to test motion detection. +Debug builds can also make video transfers fail the way they do on a phone that is short of +memory. `adb shell setprop debug.hardline.usbfail 30` fails 30 percent of transfer submissions, +`100` fails all of them and `0` turns it off. The app logs `video transfers refused by the kernel, +retrying` (tag `usbcam`) while transfers wait, and restarts the stream if no frame arrives for 5 +seconds (tag `CameraController`). + ### Driving the app | Script | Purpose | diff --git a/fastlane/metadata/android/en-US/changelogs/2.txt b/fastlane/metadata/android/en-US/changelogs/2.txt new file mode 100644 index 0000000..f3eac05 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/2.txt @@ -0,0 +1 @@ +Fixes a black picture on phones that are short of memory: the app now uses smaller USB transfers and retries any the phone refuses. If a camera stops sending video, HardLine restarts the stream, and says so if that does not help. A camera left stuck by an app that was closed mid-stream is reset instead of failing with an I/O error.