MediaPipe Tasks: vision, text and audio

MediaPipe Tasks on Android: vision, text and audio tasks from .tflite models, running modes, LIVE_STREAM with CameraX, and memory and timestamp bugs. About 25 minutes.

Why it matters

  • MediaPipe Tasks (com.google.mediapipe:tasks-vision, tasks-text, tasks-audio) is part of Google AI Edge. Each task is a ready-made pipeline (pre- and post-processing included) that runs a .tflite model, either one Google provides or a compatible custom one. It sits between ML Kit (fully ready-made) and LiteRT (bring any model, write your own processing).
  • LIVE_STREAM mode with CameraX is the pattern behind real-time gesture, face, and object features; getting the timestamp and backpressure wrong causes errors, frozen overlays, or a stalled camera.
  • Interviewers at product companies ask how you wire a MediaPipe detector into a CameraX pipeline, how you free native memory, and what happens when the model is not yet downloaded.
  • Tasks run on LiteRT (the renamed TensorFlow Lite) under the hood. For on-device LLMs, the old MediaPipe LLM Inference API is deprecated; new work uses LiteRT-LM, which is a separate API.

The simple explanation

  • A MediaPipe Task is a specialised kitchen appliance: you plug in a recipe (.tflite model) and it does one job (detect, classify, landmark).
  • IMAGE mode is a single photo on the counter; VIDEO mode is a pre-recorded clip; LIVE_STREAM is a live feed from a window.
  • The monotonic timestamp is a ticket number: each frame gets a higher number, and the kitchen refuses tickets that go backwards.
  • STRATEGY_KEEP_ONLY_LATEST is a single-plate tray: if the cook is busy, the old plate is thrown away and only the newest one waits.
  • Forgetting to call close() is like leaving the appliance plugged in: the native memory stays allocated until the process dies.

MediaPipe Tasks is part of Google AI Edge. Three modules cover the main modalities:

ModuleExample classesInput
tasks-visionObjectDetector, ImageClassifier, HandLandmarker, FaceLandmarkerMPImage (from android.media.Image or bitmap)
tasks-textTextClassifier, TextEmbedderString
tasks-audioAudioClassifierAudioData (samples + AudioDataFormat)

Every task is created from a .tflite model file via BaseOptions. The model lives in assets/ for small files or is downloaded at runtime for large ones (Play Asset Delivery, Play for On-device AI, or your own WorkManager download). Check the current docs for supported models and devices.

Running modes control how frames are fed in:

ModeUse caseTimestamp
IMAGEOne still image, detect(image)Not needed
VIDEODecoded video frames, detectForVideo(image, ms)Required, increasing
LIVE_STREAMCamera feed, detectAsync(image, ms)Required, increasing, in milliseconds

These modes are for vision tasks. Text tasks have no running mode: you just call classify(text). Audio tasks use their own modes, AUDIO_CLIPS (classify) and AUDIO_STREAM (classifyAsync with a listener).

In LIVE_STREAM you set a result listener (and an error listener) on the options builder, before the task is created. Each detectAsync() call passes an MPImage and a timestamp in milliseconds that must increase every frame (the docs use SystemClock.uptimeMillis()). Results arrive on the listener; if the task is still busy when the next frame arrives, it drops the frame rather than queuing. With CameraX you pair this with ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST so the camera side also discards stale frames. Every ImageProxy must be closed, and the task itself must be closed when you are done to free native memory.

Create the task and run IMAGE, VIDEO, text, and clip calls off the main thread (Dispatchers.Default or a dedicated Executor); they are synchronous. Measure on a low-end device, not just a flagship.

Notes

  • Three modules: com.google.mediapipe:tasks-vision, tasks-text, tasks-audio. Each task class (e.g. ObjectDetector, TextClassifier, AudioClassifier) is created with createFromOptions(context, options) from a .tflite file set via BaseOptions.builder().setModelAssetPath(...).
  • Vision running modes: IMAGE (detect, synchronous), VIDEO (detectForVideo, synchronous, every frame, needs timestamps), LIVE_STREAM (detectAsync, results on a listener). VIDEO and LIVE_STREAM need an increasing timestamp in milliseconds on every call.
  • In LIVE_STREAM the detector drops frames when busy; it does not queue them. Pair with CameraX STRATEGY_KEEP_ONLY_LATEST so the camera side also discards stale frames instead of backing up.
  • Every ImageProxy from CameraX must be closed, so put close() in a finally block. The task itself must be closed (detector.close()) when the screen or ViewModel is done; skipping this leaks native memory.
  • Small task models usually live in assets/. Very large ones can be downloaded after install (Play Asset Delivery or a WorkManager fetch) and loaded with setModelAssetPath pointing at the file, or a buffer.
  • Run synchronous calls (detect, detectForVideo, classify) off the main thread. Use Dispatchers.Default or a dedicated single-thread Executor.
  • The MediaPipe LLM Inference API (tasks-genai, .task files) is deprecated on Android. The replacement for on-device LLMs is LiteRT-LM with .litertlm model files. LiteRT-LM is a separate API, not a MediaPipe task.
  • BaseOptions lets you pick Delegate.CPU or Delegate.GPU. GPU support varies by device and model, so be ready to recreate the task on CPU if GPU setup fails.
  • Text tasks take a String and have no running mode. Audio tasks take AudioData and use AUDIO_CLIPS or AUDIO_STREAM (continuous mic feed with classifyAsync).

Code example

This shows a LIVE_STREAM ObjectDetector wired to a CameraX ImageAnalysis use case, with the three things that cause the most bugs: the result listener, the increasing timestamp, and closing every proxy and the detector itself.

// MediaPipe Tasks LIVE_STREAM wired to CameraX
val baseOptions = BaseOptions.builder()
    .setModelAssetPath("efficientdet_lite0.tflite") // in src/main/assets
    .setDelegate(Delegate.GPU)
    .build()
 
val options = ObjectDetector.ObjectDetectorOptions.builder()
    .setBaseOptions(baseOptions)
    .setRunningMode(RunningMode.LIVE_STREAM)
    .setMaxResults(5)
    // LIVE_STREAM results arrive here, on a background thread
    .setResultListener { result, _ ->
        detections.value = result.detections() // e.g. a MutableStateFlow
    }
    .setErrorListener { error -> Log.e("Detector", error.message.orEmpty()) }
    .build()
 
val detector = ObjectDetector.createFromOptions(context, options)
 
// CameraX: keep only the latest frame, RGBA_8888 so toBitmap() is cheap
val analysis = ImageAnalysis.Builder()
    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
    .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
    .build()
 
analysis.setAnalyzer(cameraExecutor) { imageProxy ->
    try {
        val mpImage = BitmapImageBuilder(imageProxy.toBitmap()).build()
        // timestamp in milliseconds, increasing every frame
        detector.detectAsync(mpImage, SystemClock.uptimeMillis())
    } finally {
        imageProxy.close() // always return the buffer to the camera
    }
}
 
// When the screen or ViewModel is done
analysis.clearAnalyzer()
detector.close()
  • setResultListener lives on the options builder; LIVE_STREAM mode requires it. It runs on a background thread, so push results into a StateFlow (thread-safe) or post to the main thread.
  • SystemClock.uptimeMillis() never goes backwards and is in milliseconds, which is what the docs use. A timestamp that does not increase makes the call fail.
  • imageProxy.close() sits in finally, so an exception never leaks the camera buffer. toBitmap() copies the pixels, so closing the proxy right away is safe.
  • detector.close() frees the native model and buffers; without it, each new screen leaks native memory until the process is killed. Real code also rotates the bitmap by imageProxy.imageInfo.rotationDegrees, as the official sample does.

Run the idea in plain Kotlin

class FrameQueue {
  private var busy = false
  fun submit(): Boolean {
      if (busy) return false
      return true
  }
  fun startWork() { busy = true }
  fun finishWork() { busy = false }
}

class TimestampValidator {
  private var last = 0L
  fun check(ts: Long): Boolean {
      if (ts <= last) return false
      last = ts
      return true
  }
}

fun main() {
  val queue = FrameQueue()
  val validator = TimestampValidator()
  var accepted = 0
  var dropped = 0

  // Simulate 6 frames while the detector is busy for the first 4
  queue.startWork()
  for (i in 1..6) {
      val ts = i * 1000L
      if (!validator.check(ts)) {
          println("Frame " + i + ": rejected (non-monotonic timestamp)")
          dropped++
      } else if (!queue.submit()) {
          println("Frame " + i + ": dropped (detector busy)")
          dropped++
      } else {
          println("Frame " + i + ": accepted")
          accepted++
      }
  }
  queue.finishWork()

  // Frame 7 arrives after the detector is free
  val ts7 = 7000L
  if (validator.check(ts7) && queue.submit()) {
      println("Frame 7: accepted after detector freed")
      accepted++
  }

  // Demonstrate a non-monotonic timestamp
  val tsBad = 3000L
  if (!validator.check(tsBad)) {
      println("Timestamp " + tsBad + " rejected: not greater than last (" + 7000L + ")")
  }

  println("---")
  println("Accepted: " + accepted + "  Dropped: " + dropped)
}

In production

Native memory leak after screen rotation
  • Memory tracking showed native heap rising with each screen rotation, ending with the process killed on low-RAM devices.
  • The ObjectDetector was created in onCreate of the Activity, but close() was never called.
  • Each rotation destroyed the Activity and created a new detector without releasing the previous one.
The fix
  • Moved detector creation into a ViewModel (which survives rotation) with onCleared() calling detector.close().
  • Wrapped imageProxy.close() in a try/finally so a thrown exception during frame conversion or detectAsync() no longer leaked the proxy.
  • Added a debug check that compares native heap (Debug.getNativeHeapAllocatedSize()) before and after repeated rotations.
Frozen overlay from bad timestamps
  • Users on a specific camera hardware reported the detection overlay freezing every few seconds.
  • The team used System.currentTimeMillis() for the timestamp. Wall-clock time can jump backwards when the system clock is adjusted.
  • Calls with a non-increasing timestamp failed and went to the error listener, which only logged them, so the overlay stopped updating.
The fix
  • Switched to SystemClock.uptimeMillis(), which never goes backwards.
  • Wrapped the timestamp in a small helper that guarantees each value is larger than the last, with a unit test.
  • Added a frame-drop counter exposed in a debug overlay so the issue is visible during QA.

Common mistakes

  • Not calling detector.close(). The native model stays allocated. After a few screen navigations the process runs out of native memory and is killed. Always close in ViewModel.onCleared() or when the screen is done.
  • Running detect() or classify() on the main thread. These calls are synchronous and take time depending on model and device. On the main thread this causes jank and ANRs. Use Dispatchers.Default or a dedicated Executor.
  • Bad timestamps in LIVE_STREAM. Using System.currentTimeMillis(), nanoseconds instead of milliseconds, or a counter that resets breaks the increasing-timestamp rule and calls fail. Use SystemClock.uptimeMillis().
  • Bundling a very large .tflite in the base module. A large model inflates every install. Download it after install via Play Asset Delivery or WorkManager, and show a loading state until it is ready.
  • Forgetting imageProxy.close() on the exception path. If conversion or detectAsync() throws, the proxy is never closed and the camera pipeline backs up. Wrap the body in try/finally and close the proxy in the finally block.
  • Using STRATEGY_BLOCK_PRODUCER with LIVE_STREAM. Frames queue up behind slow analysis, so results lag further and further behind the preview. Use STRATEGY_KEEP_ONLY_LATEST so stale frames are discarded instead of queued.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“Explain the difference between IMAGE, VIDEO and LIVE_STREAM running modes in MediaPipe Tasks.”

“How do you wire a MediaPipe ObjectDetector into a CameraX pipeline?”

“What happens if you forget to call close() on a MediaPipe detector?”

“How do you handle a large .tflite model that cannot be bundled in the APK?”

Quiz

In LIVE_STREAM mode, what does the detector do when it is still processing a previous frame and a new detectAsync() call arrives?

Which timestamp source fits LIVE_STREAM detectAsync() calls?

What must you do with an ImageProxy after building an MPImage from it?

A 60 MB .tflite model is needed for an ObjectDetector. What is the recommended approach?

0 of 4 answered

Mini task

Hands-on: wire a TextClassifier to a button tap (15 min)

  1. Add com.google.mediapipe:tasks-text to build.gradle (check the current docs for the latest version). Download a text-classification model from the MediaPipe Text Classifier docs and place it in app/src/main/assets/.

  2. In a ViewModel, create the classifier:

    • Build BaseOptions with setModelAssetPath("text_classifier.tflite").
    • Build TextClassifier.TextClassifierOptions with setBaseOptions(...). Text tasks have no running mode.
    • Call TextClassifier.createFromOptions(context, options) and store the result.
  3. Add a classify(text: String) method that calls classifier.classify(text) on Dispatchers.Default (inside viewModelScope.launch) and reads the top label with result.classificationResult().classifications()[0].categories()[0].categoryName(). Put it in a StateFlow.

  4. In the Compose UI, add a TextField and a Button. On click, call viewModel.classify(text) and show the label from the StateFlow in a Text composable. Show a CircularProgressIndicator while the call is in flight.

  5. In onCleared(), call classifier.close().

  6. Done condition: tapping the button with a sample sentence shows the predicted label quickly on a mid-range device. Rotating the screen and tapping again still works without creating a second classifier (the ViewModel survives rotation). A log line in onCleared() confirms close() runs when you leave the screen.