diff --git a/app/src/main/java/space/bloggin/scribe/ListenService.kt b/app/src/main/java/space/bloggin/scribe/ListenService.kt new file mode 100644 index 0000000..582af82 --- /dev/null +++ b/app/src/main/java/space/bloggin/scribe/ListenService.kt @@ -0,0 +1,267 @@ +package space.bloggin.scribe + +import android.Manifest +import android.annotation.SuppressLint +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ServiceInfo +import android.media.AudioFormat +import android.media.AudioManager +import android.media.AudioRecord +import android.media.MediaRecorder +import android.media.ToneGenerator +import android.os.Build +import android.os.IBinder +import android.os.PowerManager +import android.os.VibrationEffect +import android.os.Vibrator +import org.json.JSONObject +import org.vosk.Model +import org.vosk.Recognizer + +class ListenService : Service() { + companion object { + const val ACTION_STOP = "space.bloggin.scribe.STOP" + private const val CHANNEL = "listen" + private const val NOTE_ID = 7 + + fun start(ctx: Context) { + val i = Intent(ctx, ListenService::class.java) + if (Build.VERSION.SDK_INT >= 26) ctx.startForegroundService(i) else ctx.startService(i) + } + + fun stop(ctx: Context) { + ctx.stopService(Intent(ctx, ListenService::class.java)) + } + } + + @Volatile private var stopFlag = false + private var worker: Thread? = null + private var wakeLock: PowerManager.WakeLock? = null + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent?.action == ACTION_STOP) { + Prefs.setWanted(this, false) + stopSelf() + return START_NOT_STICKY + } + if (worker?.isAlive == true) return START_STICKY + startInForeground("Starting up") + if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { + setState("Microphone permission is missing. Open Hey Dumby and allow it.") + stopSelf() + return START_NOT_STICKY + } + Store.init(this) + Prefs.setWanted(this, true) + Bus.running = true + stopFlag = false + if (Prefs.cpu(this)) { + val pm = getSystemService(Context.POWER_SERVICE) as PowerManager + wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "scribe:listen").also { it.acquire() } + } + worker = Thread({ runLoop() }, "scribe-listen").also { it.start() } + return START_STICKY + } + + override fun onDestroy() { + stopFlag = true + try { worker?.join(1500) } catch (_: Exception) {} + try { wakeLock?.let { if (it.isHeld) it.release() } } catch (_: Exception) {} + Bus.running = false + Bus.partial = "" + Bus.activeNoteId = null + Bus.state = "Not listening" + Bus.changed() + super.onDestroy() + } + + private fun startInForeground(text: String) { + val nm = getSystemService(NotificationManager::class.java) + if (Build.VERSION.SDK_INT >= 26) { + nm.createNotificationChannel(NotificationChannel(CHANNEL, "Listening", NotificationManager.IMPORTANCE_LOW)) + } + val n = buildNotification(text) + if (Build.VERSION.SDK_INT >= 29) { + startForeground(NOTE_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + } else startForeground(NOTE_ID, n) + } + + private fun buildNotification(text: String): Notification { + val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE) + val stop = PendingIntent.getService( + this, 1, Intent(this, ListenService::class.java).setAction(ACTION_STOP), PendingIntent.FLAG_IMMUTABLE + ) + return Notification.Builder(this, CHANNEL) + .setSmallIcon(R.drawable.ic_stat) + .setContentTitle("Hey Dumby") + .setContentText(text) + .setContentIntent(open) + .setOngoing(true) + .addAction(Notification.Action.Builder(null, "Stop listening", stop).build()) + .build() + } + + private fun setState(s: String) { + Bus.state = s + Bus.changed() + try { + getSystemService(NotificationManager::class.java).notify(NOTE_ID, buildNotification(s)) + } catch (_: Exception) {} + } + + private fun beep(kind: Int) { + if (Prefs.vibrate(this)) { + try { + @Suppress("DEPRECATION") + val v = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator + v.vibrate(VibrationEffect.createOneShot(60, VibrationEffect.DEFAULT_AMPLITUDE)) + } catch (_: Exception) {} + } + if (Prefs.beep(this)) { + try { + val t = ToneGenerator(AudioManager.STREAM_NOTIFICATION, 70) + t.startTone(kind, 120) + Thread.sleep(170) + t.release() + } catch (_: Exception) {} + } + } + + @SuppressLint("MissingPermission") + private fun runLoop() { + var model: Model? = null + var wake: Recognizer? = null + var free: Recognizer? = null + var rec: AudioRecord? = null + try { + val phrase = Prefs.wake(this) + val shown = Prefs.wakeShown(this) + val silenceMs = Prefs.silence(this) * 1000L + setState("Loading speech model (first run takes a few seconds)") + model = Model(ModelFiles.ensure(this).absolutePath) + wake = Recognizer(model, 16000f, "[\"" + phrase.replace("\"", "") + "\", \"[unk]\"]") + free = Recognizer(model, 16000f) + + val min = AudioRecord.getMinBufferSize(16000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) + rec = AudioRecord( + MediaRecorder.AudioSource.VOICE_RECOGNITION, 16000, + AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, 32000) + ) + if (rec.state != AudioRecord.STATE_INITIALIZED) { + setState("The microphone could not be opened. Another app may be using it.") + return + } + rec.startRecording() + val buf = ShortArray(2000) + var dictating = false + var lastSpeech = 0L + var lastPartial = "" + var noteId: String? = null + val segments = ArrayList() + setState("Listening for “$shown”") + + fun endDictation(cancelled: Boolean) { + if (cancelled) noteId?.let { Store.delete(it) } + dictating = false + noteId = null + segments.clear() + lastPartial = "" + Bus.activeNoteId = null + Bus.partial = "" + beep(ToneGenerator.TONE_PROP_BEEP2) + // Drop whatever the beep leaked into the microphone. + rec.read(buf, 0, buf.size) + wake.reset() + free.reset() + setState("Listening for “$shown”") + } + + while (!stopFlag) { + val n = rec.read(buf, 0, buf.size) + if (n <= 0) { Thread.sleep(20); continue } + val now = System.currentTimeMillis() + if (!dictating) { + val text = if (wake.acceptWaveForm(buf, n)) { + JSONObject(wake.result).optString("text") + } else JSONObject(wake.partialResult).optString("partial") + if (text.contains(phrase)) { + wake.reset() + free.reset() + dictating = true + lastSpeech = now + lastPartial = "" + Bus.partial = "" + beep(ToneGenerator.TONE_PROP_ACK) + rec.read(buf, 0, buf.size) + lastSpeech = System.currentTimeMillis() + setState("Taking a note. Say “end note” when done") + } + continue + } + var finalText: String? = null + if (free.acceptWaveForm(buf, n)) { + finalText = JSONObject(free.result).optString("text") + } else { + val p = JSONObject(free.partialResult).optString("partial") + if (p != lastPartial) { + lastPartial = p + if (p.isNotEmpty()) lastSpeech = now + Bus.partial = p + Bus.changed() + } + } + if (finalText != null) { + lastPartial = "" + Bus.partial = "" + if (finalText.isNotBlank()) { + lastSpeech = now + val p = Speech.parse(finalText) + if (p.cancel) { endDictation(true); continue } + if (p.scratch) { + val id = noteId + if (id != null && segments.isNotEmpty()) { + val last = segments.removeAt(segments.size - 1) + val cur = Store.get(id)?.text ?: "" + val idx = cur.lastIndexOf(last) + if (idx >= 0) Store.setText(id, cur.substring(0, idx).trimEnd(' ')) + } + } + if (p.text.isNotEmpty()) { + if (noteId == null) { + val note = Store.create() + noteId = note.id + Bus.activeNoteId = note.id + } + val id = noteId!! + val cur = Store.get(id)?.text ?: "" + val joined = Speech.join(cur, p.text) + segments.add(joined.substring(cur.length).trimStart(' ')) + Store.setText(id, joined) + } + Bus.changed() + if (p.end) { endDictation(false); continue } + } + if (noteId == null) Bus.changed() + } + if (now - lastSpeech > silenceMs) endDictation(false) + } + } catch (t: Throwable) { + setState("Stopped: " + (t.message ?: t.javaClass.simpleName)) + } finally { + try { rec?.stop() } catch (_: Exception) {} + try { rec?.release() } catch (_: Exception) {} + try { wake?.close() } catch (_: Exception) {} + try { free?.close() } catch (_: Exception) {} + try { model?.close() } catch (_: Exception) {} + } + } +}