Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ internal class AccessoryAttachment<T> : Closeable {
@Synchronized fun generation(): Long = epoch
@Synchronized fun isCurrent(generation: Long): Boolean = !closed && epoch == generation
@Synchronized fun contains(device: T): Boolean = current?.first == device
val live: Boolean @Synchronized get() = current != null

fun install(device: T, generation: Long, lease: Closeable): Boolean {
val accepted = synchronized(this) {
Expand All @@ -34,6 +35,16 @@ internal class AccessoryAttachment<T> : Closeable {
return previous != null
}

/** Drops the lease installed at [generation] when its streams ended; a newer lease is kept. */
fun release(generation: Long): Boolean {
val previous = synchronized(this) {
if (current == null || epoch != generation) null
else { epoch++; current.also { current = null } }
}
previous?.second?.close()
return previous != null
}

override fun close() {
synchronized(this) { closed = true }
clear()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,39 @@ import org.openxplay.stream.carlife.CarlifeOutput
import java.io.BufferedInputStream
import java.io.Closeable
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

/** Schedules the next inventory sweep; the returned handle cancels it. */
internal fun interface CarlifeSweepTimer {
fun schedule(task: Runnable): Closeable
}

/** Android supplies the accessory role; Stream owns all CarLife bytes and channel multiplexing. */
class AndroidCarlifeAccessory(
class AndroidCarlifeAccessory internal constructor(
context: Context,
private val output: CarlifeOutput,
private val report: (String) -> Unit = {},
private val attach: (InputStream, OutputStream, Closeable) -> Closeable,
sweepTimer: CarlifeSweepTimer?,
private val report: (String) -> Unit,
) : Closeable {
constructor(context: Context, output: CarlifeOutput, report: (String) -> Unit = {}) :
this(context, output::attachAccessory, null, report)

private val context = context.applicationContext
private val manager = this.context.getSystemService(UsbManager::class.java)
private val worker = Executors.newSingleThreadExecutor { task ->
private val worker: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor { task ->
Thread(task, "carlife-accessory").apply { isDaemon = true }
}
// Attach intents reach only a foreground activity, and a head unit can restart CarLife
// without a detach, so the inventory is swept again while no lease is live.
private val timer = sweepTimer ?: CarlifeSweepTimer { task ->
val future = worker.schedule(task, SWEEP_INTERVAL_MS, TimeUnit.MILLISECONDS)
Closeable { future.cancel(false) }
}
@Volatile private var sweep: Closeable? = null
private val lifecycle = AccessoryAttachment<UsbAccessory>()
private val permissionAction = "${this.context.packageName}.CARLIFE_USB_PERMISSION"
private var registered = false
Expand All @@ -41,6 +60,7 @@ class AndroidCarlifeAccessory(
// The detach extra identifies the old lease. A new open still requires live inventory and permission.
when (intent.action) {
permissionAction -> refresh(permissionResult = true)
UsbManager.ACTION_USB_ACCESSORY_ATTACHED -> refresh(permissionResult = false, attached = true)
UsbManager.ACTION_USB_ACCESSORY_DETACHED -> refresh(permissionResult = false, detached = detachedAccessory(intent))
}
}
Expand All @@ -52,6 +72,7 @@ class AndroidCarlifeAccessory(
if (registered || lifecycle.closed) return
val filter = IntentFilter().apply {
addAction(permissionAction)
addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED)
addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED)
}
if (Build.VERSION.SDK_INT >= 33) context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
Expand All @@ -72,26 +93,49 @@ class AndroidCarlifeAccessory(
else intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY)

@Synchronized
private fun refresh(permissionResult: Boolean, detached: UsbAccessory? = null) {
private fun refresh(permissionResult: Boolean, detached: UsbAccessory? = null, attached: Boolean = false) {
if (!registered || lifecycle.closed) return
submit {
if (attached) observe("usb_attached")
if (detached != null) {
if (requested == detached) requested = null
if (lifecycle.contains(detached) && lifecycle.clear()) report("usb_detached")
}
reconcile(permissionResult)
}
}

/** The streams of the lease opened at [generation] closed: the session ended with or without a detach. */
private fun streamsClosed(generation: Long) {
// Wait for the next sweep instead of reopening at once, so a head unit that ends every
// session immediately is retried at the sweep interval rather than in a tight loop.
submit(scan = false) {
if (lifecycle.release(generation)) {
lastObservation = "usb_lease_lost"
report("usb_lease_lost")
}
}
}

private fun submit(scan: Boolean = true, work: () -> Unit) {
try {
worker.execute {
if (lifecycle.closed) return@execute
runCatching {
if (detached != null) {
if (requested == detached) requested = null
if (lifecycle.contains(detached) && lifecycle.clear()) report("usb_detached")
}
reconcile(permissionResult)
}.onFailure { failure ->
runCatching { work() }.onFailure { failure ->
observe("usb_error:${failure.javaClass.simpleName}")
}
if (scan || !lifecycle.live) rearm()
}
} catch (_: RejectedExecutionException) {
// A detach or permission broadcast can race shutdown.
// A broadcast or stream teardown can race shutdown.
}
}

private fun rearm() {
sweep?.close()
sweep = if (lifecycle.closed || lifecycle.live) null else timer.schedule { refresh() }
}

private fun observe(message: String) {
if (lastObservation != message) {
lastObservation = message
Expand Down Expand Up @@ -124,18 +168,23 @@ class AndroidCarlifeAccessory(
return
}
val generation = lifecycle.generation()
val descriptor = usb.openAccessory(accessory) ?: run {
val descriptor = try { usb.openAccessory(accessory) } catch (_: SecurityException) {
// A detach revoked the grant while the old entry is still listed; ask again next sweep.
requested = null
observe("usb_permission_revoked")
return
} ?: run {
observe("usb_unavailable")
return
}
val streams = try { AccessoryStreams(descriptor) }
val streams = try { AccessoryStreams(descriptor) { streamsClosed(generation) } }
catch (failure: Exception) { descriptor.close(); throw failure }
try {
if (!lifecycle.isCurrent(generation)) {
streams.close()
return
}
val attachment = output.attachAccessory(streams.input, streams.output, streams)
val attachment = attach(streams.input, streams.output, streams)
val lease = Closeable {
runCatching { attachment.close() }
streams.close()
Expand All @@ -153,6 +202,8 @@ class AndroidCarlifeAccessory(
@Synchronized
override fun close() {
lifecycle.close()
sweep?.close()
sweep = null
if (registered) runCatching { context.unregisterReceiver(receiver) }
registered = false
permission?.cancel()
Expand All @@ -161,14 +212,19 @@ class AndroidCarlifeAccessory(
}
}

private const val SWEEP_INTERVAL_MS = 3_000L

internal fun carlifeAccessoryMatches(manufacturer: String?, model: String?): Boolean =
manufacturer == "Baidu" && model == "CarLife"

// Android drops a transfer's unread remainder; framing must consume a buffered byte stream.
internal fun bufferAccessoryInput(input: InputStream): InputStream = BufferedInputStream(input, 16_384)

/** Each direction owns a duplicate, so closing a stream cannot close a reused descriptor number. */
private class AccessoryStreams(private val descriptor: ParcelFileDescriptor) : Closeable {
private class AccessoryStreams(
private val descriptor: ParcelFileDescriptor,
private val onClosed: () -> Unit,
) : Closeable {
val input = bufferAccessoryInput(
ParcelFileDescriptor.AutoCloseInputStream(ParcelFileDescriptor.dup(descriptor.fileDescriptor)))
val output = try {
Expand All @@ -177,13 +233,14 @@ private class AccessoryStreams(private val descriptor: ParcelFileDescriptor) : C
input.close()
throw failure
}
private var closed = false
@Synchronized
private val closed = java.util.concurrent.atomic.AtomicBoolean(false)

// No monitor is held while closing: the reader thread can end the session during this teardown.
override fun close() {
if (closed) return
closed = true
if (!closed.compareAndSet(false, true)) return
runCatching { descriptor.close() }
runCatching { input.close() }
runCatching { output.close() }
onClosed()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,25 @@ class AccessoryAttachmentTest {
lifecycle.close()
assertEquals(2, second)
}

@Test fun releaseDropsOnlyTheLeaseOfItsGeneration() {
val lifecycle = AccessoryAttachment<String>()
var first = 0
var second = 0
val opened = lifecycle.generation()
assertTrue(lifecycle.install("first", opened, Closeable { first++ }))
assertTrue(lifecycle.live)
assertTrue(lifecycle.release(opened))
assertFalse(lifecycle.live)
assertEquals(1, first)
assertFalse(lifecycle.release(opened))

val reopened = lifecycle.generation()
assertTrue(lifecycle.install("second", reopened, Closeable { second++ }))
assertFalse(lifecycle.release(opened))
assertTrue(lifecycle.contains("second"))
assertEquals(0, second)
lifecycle.close()
assertEquals(1, second)
}
}
Loading
Loading