MediaPipe Tasks: vision, text and audio
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.tflitemodel, 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 (
.tflitemodel) 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:
| Module | Example classes | Input |
|---|---|---|
tasks-vision | ObjectDetector, ImageClassifier, HandLandmarker, FaceLandmarker | MPImage (from android.media.Image or bitmap) |
tasks-text | TextClassifier, TextEmbedder | String |
tasks-audio | AudioClassifier | AudioData (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:
| Mode | Use case | Timestamp |
|---|---|---|
IMAGE | One still image, detect(image) | Not needed |
VIDEO | Decoded video frames, detectForVideo(image, ms) | Required, increasing |
LIVE_STREAM | Camera 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 withcreateFromOptions(context, options)from a.tflitefile set viaBaseOptions.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_LATESTso the camera side also discards stale frames instead of backing up. - Every
ImageProxyfrom CameraX must be closed, so putclose()in afinallyblock. The task itself must be closed (detector.close()) when the screen orViewModelis 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 aWorkManagerfetch) and loaded withsetModelAssetPathpointing at the file, or a buffer. - Run synchronous calls (
detect,detectForVideo,classify) off the main thread. UseDispatchers.Defaultor a dedicated single-threadExecutor. - The MediaPipe LLM Inference API (
tasks-genai,.taskfiles) is deprecated on Android. The replacement for on-device LLMs is LiteRT-LM with.litertlmmodel files. LiteRT-LM is a separate API, not a MediaPipe task. BaseOptionslets you pickDelegate.CPUorDelegate.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
Stringand have no running mode. Audio tasks takeAudioDataand useAUDIO_CLIPSorAUDIO_STREAM(continuous mic feed withclassifyAsync).
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()setResultListenerlives on the options builder; LIVE_STREAM mode requires it. It runs on a background thread, so push results into aStateFlow(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 infinally, 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 byimageProxy.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
- Memory tracking showed native heap rising with each screen rotation, ending with the process killed on low-RAM devices.
- The
ObjectDetectorwas created inonCreateof the Activity, butclose()was never called. - Each rotation destroyed the Activity and created a new detector without releasing the previous one.
- Moved detector creation into a
ViewModel(which survives rotation) withonCleared()callingdetector.close(). - Wrapped
imageProxy.close()in atry/finallyso a thrown exception during frame conversion ordetectAsync()no longer leaked the proxy. - Added a debug check that compares native heap (
Debug.getNativeHeapAllocatedSize()) before and after repeated rotations.
- 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.
- 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.Defaultor a dedicatedExecutor. - 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. UseSystemClock.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 intry/finallyand close the proxy in thefinallyblock. - 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_LATESTso 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)
-
Add
com.google.mediapipe:tasks-texttobuild.gradle(check the current docs for the latest version). Download a text-classification model from the MediaPipe Text Classifier docs and place it inapp/src/main/assets/. -
In a
ViewModel, create the classifier:- Build
BaseOptionswithsetModelAssetPath("text_classifier.tflite"). - Build
TextClassifier.TextClassifierOptionswithsetBaseOptions(...). Text tasks have no running mode. - Call
TextClassifier.createFromOptions(context, options)and store the result.
- Build
-
Add a
classify(text: String)method that callsclassifier.classify(text)onDispatchers.Default(insideviewModelScope.launch) and reads the top label withresult.classificationResult().classifications()[0].categories()[0].categoryName(). Put it in aStateFlow. -
In the Compose UI, add a
TextFieldand aButton. On click, callviewModel.classify(text)and show the label from theStateFlowin aTextcomposable. Show aCircularProgressIndicatorwhile the call is in flight. -
In
onCleared(), callclassifier.close(). -
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
ViewModelsurvives rotation). A log line inonCleared()confirmsclose()runs when you leave the screen.